簡體   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