window.print() to generate PDF with electron

Viewed 3861

I have an Angular application, where you can calculate a couple of things and finally generate a result page which can be printed/ exported to pdf via window.print(). This also works totally as expected.

But we built also a desktop version of this application with Electron now. If I want to print/ export the result page in the Electron app the windows print popup opens (compare this image) where I can only choose a printer but there is no option to export it to pdf instead.

Is there any way to still use window.print() and add a posibility to export it to pdf (basically like the window.print() version in the web)?

2 Answers

In ElectronJS, you can make use of printToPDF instead of client side js functionality since electronJS can directly access file system.

Here is a sample implementation of the API.

ipc.on('print-to-pdf', event => {
    const pdfPath = path.join(os.tmpdir(), "some-ducking-pdf.pdf");
    const win = BrowserWindow.fromWebContents(event.sender);

    win.webContents.printToPDF({}, (error, data) => {

        if(error) return console.log(error.message);
        
        fs.writeFile(pdfPath, data, err => {
            if (err) return console.log(err.message);
            shell.openExternal('file://' + pdfPath);
            event.sender.send("wrote-pdf", pdfPath);
        })
    })
});

Just scroll to the left and you will find Microsoft print to pdf

Related