此系列文章的应用示例已发布于 GitHub: electron-api-demos-Zh_CN. 可以 Clone 或下载后运行查看. 欢迎 Star .
Electron 中的 browser window 模块具有 webContents 属性, 它允许您的应用程序进行打印以及打印到 PDF.
这个模块有一个版本可用于这两个进程: ipcMain 和 ipcRenderer.
在浏览器中查看 完整 API 文档.
打印到 PDF
支持: Win, macOS, Linux
为了演示打印到 PDF 功能, 上面的示例按钮会将此页面保存为 PDF, 如果您有 PDF 查看器, 请打开文件.
在实际的应用程序中, 你更可能将它添加到应用程序菜单中, 但为了演示的目的, 我们将其设置为示例按钮.
渲染器进程
- const ipc = require('electron').ipcRenderer
- const printPDFBtn = document.getElementById('print-pdf')
- printPDFBtn.addEventListener('click', function (event) {
- ipc.send('print-to-pdf')
- })
- ipc.on('wrote-pdf', function (event, path) {
const message = `PDF 保存到: ${path}`
- document.getElementById('pdf-path').innerhtml = message
- })
主进程
- const fs = require('fs')
- const os = require('os')
- const path = require('path')
- const electron = require('electron')
- const BrowserWindow = electron.BrowserWindow
- const ipc = electron.ipcMain
- const shell = electron.shell
- ipc.on('print-to-pdf', function (event) {
- const pdfPath = path.join(os.tmpdir(), 'print.pdf')
- const win = BrowserWindow.fromWebContents(event.sender)
- // 使用默认打印选项
- win.webContents.printToPDF({}, 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)
- })
- })
- })
高级技巧
使用打印样式表.
您可以创建打印目标的样式表, 以优化用户打印的外观. 下面是在这个应用程序中使用的样式表, 位于
assets/CSS/print.css
中.
- @media print {
- body {
- background: none;
- color: black !important;
- font-size: 70%;
- margin: 0; padding: 0;
- }
- h1 {
- font-size: 22px;
- }
- .nav, button, .demo-box:before,
- #pdf-path, header p {
- display: none;
- }
- .demo-box, h2,
- pre, code {
- padding: 0 !important;
- margin: 0 !important;
- }
- header {
- padding: 0 0 10px 0;
- }
- code, .support {
- font-size: 10px;
- }
- }
如果这边文章对您有帮助, 感谢 下方点赞 或 Star GitHub: electron-api-demos-Zh_CN 支持, 谢谢.
Electron
来源: https://juejin.im/entry/5aa1e9a8f265da239706727d