Res*_*ent 1 javascript pdf electron
我了解电子上通常使用totoToPDF的方法是在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.')
})
})
})
Run Code Online (Sandbox Code Playgroud)
但是,我要实现的目标是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')
})
Run Code Online (Sandbox Code Playgroud)
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)
})
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2994 次 |
| 最近记录: |