Electron中的打印功能有以下几种方式:webContents的print和printToPDF方法、webview标签的print和printToPDF方法、iframe的print方法。
关于print方法,webContents、webview和iframe都是调用的浏览器自带的打印功能,虽然Electron文档中罗列了很多打印配置项,但实际使用时看不到实际效果,打印的最终效果也较差。而printToPDF方法效果就好很多。
另外,print方法在调用时会弹出打印配置窗口,printToPDF方法则可以实现无弹窗静默打印。
Print示例
// webContent
let electron = require('electron')
let webContent = electron.remote.getCurrentWebContents()
webContent.print({printBackground: true}, (success, errorType) => {
if (!success) console.log(errorType)
})
// webview
let webviewObj = document.querySelector('webview')
webviewObj.print({printBackground: true})
// iframe
let iframeObj = document.createElement('iframe')
iframeObj.width = '400'
iframeObj.height = '300'
document.body.appendChild(iframeObj)
iframeObj.src = URL.createObjectURL(new Blob([`
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Print</title>
</head>
<body>
<div>自定义打印内容</div>
</body>
</html>
`], { type: 'text/html' }))
iframeObj.contentWindow && iframeObj.contentWindow.print()
PrintToPDF示例
// webContent
let electron = require('electron')
let fs = require('fs')
let path = require('path')
let webContent = electron.remote.getCurrentWebContents()
let pdfPath = path.join(electron.remote.app.getPath('desktop'), '1.pdf')
webContent.printToPDF({printBackground: true, landscape:true}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
// webview
let webviewObj = document.querySelector('webview')
webviewObj.printToPDF({printBackground: true}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})