繁体   English   中英

window.print() 用电子生成 PDF

[英]window.print() to generate PDF with electron

我有一个 Angular 应用程序,您可以在其中计算一些事情并最终生成一个结果页面,该页面可以通过window.print()打印/导出为 pdf。 这也完全按预期工作。

但是我们现在也用 Electron 构建了这个应用程序的桌面版本。 如果我想在 Electron 应用程序中打印/导出结果页面,Windows 打印弹出窗口将打开( 比较此图像),我只能在其中选择打印机,但没有将其导出为 pdf 的选项。

有没有办法仍然使用 window.print() 并添加将其导出为 pdf 的可能性(基本上就像 web 中的 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM