Electron 打印功能的实现

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半吊子伯爵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值