🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 使用 Electron 打印到 PDF Electron 中的 browser window 模块具有 webContents 属性, 它允许您的应用程序进行打印以及打印到PDF. 这个模块有一个版本可用于这两个进程: ipcMain 和 ipcRenderer. 在浏览器中查看 [完整 API 文档](http://electron.atom.io/docs/api/web-contents/#webcontentsprintoptions). ### 打印到 PDF `支持: Win, macOS, Linux` 为了演示打印到PDF功能, 上面的示例按钮会将此页面保存为PDF, 如果您有PDF查看器, 请打开文件. 在实际的应用程序中, 你更可能将它添加到应用程序菜单中, 但为了演示的目的, 我们将其设置为示例按钮. ![](https://img.kancloud.cn/2b/58/2b58003c2d14f44a261b5d6c4b93cddb_635x124.png) ![](https://img.kancloud.cn/25/54/2554f7a8f83c886c69445505428e4466_1366x736.png) 渲染器进程 ``` printPDF () { const {ipcRenderer} = require('electron') ipcRenderer.send('print-to-pdf') ipcRenderer.on('wrote-pdf', (event, path) => { this.filePath = `PDF 保存到: ${path}` }) } ``` 主进程 ``` const fs = require('fs') const os = require('os') const path = require('path') const {BrowserWindow, ipcMain, shell} = require('electron') ipcMain.on('print-to-pdf', (event) => { const pdfPath = path.join(os.tmpdir(), 'print.pdf') const win = BrowserWindow.fromWebContents(event.sender) // 使用默认打印参数 win.webContents.printToPDF({}, (error, data) => { if (error) throw error fs.writeFile(pdfPath, data, (error) => { if (error) throw error shell.openExternal(`file://${pdfPath}`) event.sender.send('wrote-pdf', pdfPath) }) }) }) ``` ## 使用 Electron 创建屏幕截图 Electron 中的 desktopCapturer 模块可用于访问 Chromium 的 getUserMedia web API 中提供的任何媒体, 例如音频, 视频, 屏幕和窗口. 这个模块有一个版本可用于这两个进程: ipcMain 和 ipcRenderer. 在浏览器中查看 [完整 API 文档](http://electron.atom.io/docs/api/desktop-capturer). ### 创建屏幕截图 `支持: Win, macOS, Linux | 进程: 渲染器` 此示例使用 desktopCapturer 模块采集正在使用的屏幕, 并创建全屏幕截图. 点击示例按钮将截取当前屏幕的截图, 并在默认查看器中打开它. ![](https://img.kancloud.cn/79/11/7911176e43c460ace90e0cc2fa60b43b_811x288.png) ![](https://img.kancloud.cn/83/d4/83d4b0aa88468a4e2c0584dc9d48d8c3_733x183.png) ![](https://img.kancloud.cn/ba/8c/ba8c52ad29df10c1b5cec3247fe93e4a_816x641.png) 渲染器进程 ``` deskCapture () { const {desktopCapturer, shell} = require('electron') const fs = require('fs') const os = require('os') const path = require('path') this.capturePath = '正在截取屏幕...' const thumbSize = this.determineScreenShotSize() const options = { types: ['screen'], thumbnailSize: thumbSize } desktopCapturer.getSources(options, (error, sources) => { if (error) return console.log(error) sources.forEach((source) => { if (source.name === 'Entire Screen' || source.name === 'Screen 1') { const screenshotPath = path.join(os.tmpdir(), 'screenshot.png') fs.writeFile(screenshotPath, source.thumbnail.toPNG(), (error) => { if (error) return console.log(error) shell.openExternal(`file://${screenshotPath}`) this.capturePath = `截图保存到: ${screenshotPath}` }) } }) }) }, determineScreenShotSize () { const {screen} = require('electron').remote const screenSize = screen.getPrimaryDisplay().workAreaSize const maxDimension = Math.max(screenSize.width, screenSize.height) return { width: maxDimension * window.devicePixelRatio, height: maxDimension * window.devicePixelRatio } } ```