From c8b05140e90ba6138ac4c625c58135d66bc11cf5 Mon Sep 17 00:00:00 2001 From: Faris Ansari Date: Wed, 24 Oct 2018 23:22:02 +0530 Subject: [PATCH] Use electron to generate pdf --- server/pdf.js | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/server/pdf.js b/server/pdf.js index bdf3aec9..8864bf7f 100644 --- a/server/pdf.js +++ b/server/pdf.js @@ -21,11 +21,37 @@ async function makePDF(html, filepath) { } async function getPDFForElectron(doctype, name, destination, htmlContent) { - const { shell } = require('electron'); + const { remote, shell } = require('electron'); + const { BrowserWindow } = remote; const html = htmlContent || await getHTML(doctype, name); const filepath = path.join(destination, name + '.pdf'); - await makePDF(html, filepath); - shell.openItem(filepath); + + const fs = require('fs') + let printWindow = new BrowserWindow({width: 600, height: 800}) + printWindow.loadURL(`file://${path.join(__static, 'print.html')}`); + + printWindow.on('closed', () => { + printWindow = null; + }); + + const code = ` + document.body.innerHTML = \`${html}\`; + `; + + printWindow.webContents.executeJavaScript(code); + + printWindow.webContents.on('did-finish-load', () => { + printWindow.webContents.printToPDF({}, (error, data) => { + if (error) throw error + printWindow.close(); + fs.writeFile(filepath, data, (error) => { + if (error) throw error + console.log('Write PDF successfully.') + shell.openItem(filepath); + }) + }) + }) + // await makePDF(html, filepath); } function setupExpressRoute() {