window.print() 用电子生成PDF
window.print() to generate PDF with electron
我有一个 Angular 应用程序,您可以在其中计算一些东西并最终生成一个结果页面,该页面可以通过 window.print() 打印/导出为 pdf 。这也完全符合预期。
但是我们现在也用 Electron 构建了这个应用程序的桌面版本。如果我想在 Electron 应用程序中打印/导出结果页面,windows 打印弹出窗口打开 (compare this image),我只能在其中选择一台打印机,但没有将其导出为 pdf 的选项。
有没有办法仍然使用 window.print() 并添加将其导出为 pdf 的可能性(基本上类似于网络中的 window.print() 版本)?
在 ElectronJS 中,您可以使用 printToPDF 而不是客户端 js 功能,因为 electronJS 可以直接访问文件系统。
这是 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);
})
})
});
只需向左滚动,您就会发现 Microsoft print to pdf
我有一个 Angular 应用程序,您可以在其中计算一些东西并最终生成一个结果页面,该页面可以通过 window.print() 打印/导出为 pdf 。这也完全符合预期。
但是我们现在也用 Electron 构建了这个应用程序的桌面版本。如果我想在 Electron 应用程序中打印/导出结果页面,windows 打印弹出窗口打开 (compare this image),我只能在其中选择一台打印机,但没有将其导出为 pdf 的选项。
有没有办法仍然使用 window.print() 并添加将其导出为 pdf 的可能性(基本上类似于网络中的 window.print() 版本)?
在 ElectronJS 中,您可以使用 printToPDF 而不是客户端 js 功能,因为 electronJS 可以直接访问文件系统。
这是 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);
})
})
});
只需向左滚动,您就会发现 Microsoft print to pdf