## 使用 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查看器, 請打開文件.
在實際的應用程序中, 你更可能將它添加到應用程序菜單中, 但為了演示的目的, 我們將其設置為示例按鈕.


渲染器進程
```
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 模塊采集正在使用的屏幕, 并創建全屏幕截圖.
點擊示例按鈕將截取當前屏幕的截圖, 并在默認查看器中打開它.



渲染器進程
```
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
}
}
```