Electron,从BrowserWindow打印到PDF

4

我知道在Electron中生成PDF的通常方法是在main进程中调用以下代码:

const {BrowserWindow} = require('electron')
const fs = require('fs')

let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')

win.webContents.on('did-finish-load', () => {
  // Use default printing options
  win.webContents.printToPDF({}, (error, data) => {
    if (error) throw error
    fs.writeFile('/tmp/print.pdf', data, (error) => {
      if (error) throw error
      console.log('Write PDF successfully.')
    })
  })
})

然而,我的目标是在单击按钮时从BrowserWindow内有效地调用printToPDF。我了解到从这里:https://github.com/electron/electron/pull/1835/commits/1eba552a8d1ab4479824275f0e0a2cea9337bd8c可以将printToPDF暴露给BrowserWindow,但是没有关于如何从网页内部实际调用printToPDF的文档。通过谷歌搜索也没有找到示例。有线索吗?
3个回答

7

renderer.js

const ipc = require('electron').ipcRenderer

const printPDFBtn = document.getElementById('pdfME')

printPDFBtn.addEventListener('click', function (event) {
  ipc.send('print-to-pdf')
})

main.js

const electron = require('electron')
const fs = require('fs')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const Menu = electron.Menu
const Tray = electron.Tray
const ipc = electron.ipcMain

const path = require('path')
const url = require('url')
const shell = electron.shell

let mainWindow

ipc.on('print-to-pdf', function (event) {
  const pdfPath = path.join(__dirname, '/reports/print.pdf')
  const win = BrowserWindow.fromWebContents(event.sender)
  win.webContents.printToPDF({printBackground: true, landscape: true}, function (error, data) {
    if (error) throw error
    fs.writeFile(pdfPath, data, function (error) {
      if (error) {
        throw error
      }
      shell.openExternal('file://' + pdfPath)
      event.sender.send('wrote-pdf', pdfPath)
    })
  })
})

4

导出当前窗口:

// In renderer process

let remote = require('electron').remote

remote.getCurrentWindow().webContents.printToPDF(...)

1
接受的答案涵盖了使用 printToPDF() 和使用 ipc 事件将内容保存为 PDF 的方面。但我们也可以从渲染器进程中使用 printToPDF。这是一个示例,演示如何从渲染器进程本身打印,而不是从 main 中保存。
导入给定的 remotefsshell(用于预览 PDF)。
const remote = require("electron").remote;
const fs = remote.require('fs');
const shell = remote.shell;

使用 remote,检索当前窗口并按照以下给定方式调用 printToPDF() 方法。
function saveInvoiceToStorage(){
    remote.getCurrentWindow().webContents.printToPDF({
        pageSize : 'A4',
    } , function(error , data){

            if(error){
                console.log(error);
                return;
            }

            let pdfPath = `Users/vkiranmaniya/Desktop/print.pdf`;

            fs.writeFile(pdfPath, data, function (error) {
                if (error) {
                     console.log(error);
                }

                shell.openExternal('file://' + pdfPath);
            });
    });
}

您有更多的选项来配置printToPDF函数,访问官方文档了解更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接