Print to PDF using electron

Time:2020-7-5

Print to PDF using electron

The application examples of this series of articles have been published in GitHub: electron API demos zh_ Cn. You can clone or download it to view. Welcome to star

Print to PDF using electron

In electronbrowser windowThe module haswebContentsProperty, which allows your application to print and print to PDF

There is a version of this module available for both processes:ipcMainandipcRenderer.

View the full API documentation in the browser

Print to PDF

Support: win, MacOS, Linux

Print to PDF using electron

To demonstrate the print to PDF feature, the sample button above will save this page as PDF. If you have a PDF viewer, please open the file

In a real application, you are more likely to add it to the application menu, but for demonstration purposes, we set it as a sample button

Render process

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 saved to ${path}`
  document.getElementById('pdf-path').innerHTML = message
})

Main process

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)
  //Use default printing options
  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)
    })
  })
})

Advanced skills

Use plot style tables

You can create style sheets for print targets to optimize the appearance of your print. Here are the style sheets used in this application, located inassets/css/print.cssMedium

@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;
  }
}

If this article is helpful to you, thank you for your comments or star GitHub: electron API demos zh_ Cn supports, thank you