繁体   English   中英

电子,来自BrowserWindow的printToPDF

[英]electron, printToPDF from BrowserWindow

我知道电子打印toPDF的常用方法是在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已经向BrowserWindow公开了printToPDF,但是没有关于如何从网页中实际调用printToPDF的文档。

一个谷歌也没有透露一个例子。 有什么线索吗?

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)
    })
  })
})

导出当前窗口:

// In renderer process

let remote = require('electron').remote

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

可接受的答案涉及使用printToPDF()ipc事件将内容另存为pdf的方面。 但是我们也可以从渲染器进程中printToPDF 这是一个如何从渲染器进程本身打印而不是从main保存的示例。

按照给定的方式导入remotefsshell (用于预览PDF),

const remote = require("electron").remote;
const fs = remote.require('fs');
const shell = remote.shell;

使用remote ,检索当前窗口, printToPDF()如下所示调用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功能,有关更多信息,请访问官方文档

暂无
暂无

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

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