天天看點

Electron 列印功能的實作

作者:xue5hen

Electron中的列印功能有以下幾種方式:webContents的print和printToPDF方法、webview标簽的print和printToPDF方法、iframe的print方法。

關于print方法,webContents、webview和iframe都是調用的浏覽器自帶的列印功能,雖然Electron文檔中羅列了很多列印配置項,但實際使用時看不到實際效果,列印的最終效果也較差。而printToPDF方法效果就好很多。

Electron 列印功能的實作

01

另外,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)
})           

繼續閱讀