Generating PDF books

In this section, we are going to introduce support for PDF generation based on the markdown source. Once we've finished, the users of our application should be able to generate PDF output with Cmd + Alt + P on macOS and Ctrl + Alt + P on other systems.

Let's update the code in order to provide PDF output support:

  1. Edit the Editor.js component so that it supports another keyboard combination:
editor.addCommand(
monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KEY_P,
() => {
const code = editor.getModel().getValue();
generatePDF(code);
}
);

The generatePDF function implementation should be reasonably easy for you. It resembles the genereateHTML one, but in our case, we're passing pdf as a format attribute.

  1. Add the following function to the Editor.js code:
const generatePDF = contents => {
if (window.require) {
const electron = window.require('electron');
const ipcRenderer = electron.ipcRenderer;

ipcRenderer.send('generate', {
format: 'pdf',
text: contents
});
}
};
  1. Update the menu.js code so that it matches the pdf format and call the generatePDF function from within the generate channel listener:
ipcMain.on('generate', (_, payload) => {
if (payload && payload.format) {
switch (payload.format) {
case 'html':
generateHTML(payload.text);
break;
case 'pdf':
generatePDF(payload.text);
break;
default:
break;
}
}
});
  1. Next, add the generatePDF function:
function generatePDF(contents) {
writeTempFile(contents, fileName => {
const name = 'markdown';
const filePath = path.dirname(fileName);
const command = `docker run -v ${filePath}:/source denysvuika/pandoc -f markdown -t latex ${name}.md -o ${name}.pdf`;
exec(command, () => {
const outputPath = path.join(filePath, `${name}.pdf`);
shell.openItem(outputPath);
}).stderr.pipe(process.stderr);
});
}

The implementation that we use to generate and open PDFs is similar to the implementation for HTML. Note, however, that we pass different parameters to the Docker container.

Let's test this generation now:

  1. Run the application and enter some markdown text; for example, a heading, subheading, and a bit of text.
  2. Press Cmd + Alt + P if you are using macOS or Ctrl + Alt + P for other platforms.
  3. Check out the default PDF viewer that appears as soon as the generation process ends:

You have successfully generated a simple PDF document out of the markdown content.

As you can imagine, Pandoc provides much more than this for PDF generation, such as templates, paper and font settings, and many other options. You can find out more at https://pandoc.org/.

Finally, let's learn how to produce ePub books as output from the markdown.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.202.224