Puppeteer PDFs

Puppeteer makes it very easy to generate PDFs from any webpage.

The advantage of using Puppeteer to generate PDFs is that it uses a real Chrome browser, which means your PDFs are exactly like they should be. In contrast with other PDF generators, this will generate pixel perfect PDFs.

Before continuing this documentation page, make sure you have installed Puppeteer on your system.

Generating your first PDF

Here's a simple example on how to generate your first PDF.
This script will open a Chrome browser, navigate to a webpage and download the PDF to your computer.

const fs = require('fs')
const fsPromises = fs.promises
const puppeteer = require('puppeteer')

const browser = await puppeteer.connect({
    browserWSEndpoint: 'wss://chrome.headlesstesting.com?token=[YOUR-TOKEN]'

const page = await browser.newPage()
await page.goto('https://headlesstesting.com')
const pdf = await page.pdf({ format: 'A4' })
await fsPromises.writeFile('test.pdf', pdf)

This example will save a test.pdf file with the contents of our homepage.

The command page.pdf() will generate a PDF of the page with print CSS media.

To generate a pdf with screen media, make sure you call page.emulateMedia('screen') before calling page.pdf()

More options

Puppeteer offers a lot of options to tweak PDFs, including:

  • landscape (boolean) Paper orientation. Defaults to portrait (false)
  • pageRanges (string) Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to print all pages.
  • format (string) Paper format. If set, takes priority over width or height options. Defaults to 'Letter'.
  • width (string | number) Paper width, accepts values labeled with units.
  • height (string | number) Paper height, accepts values labeled with units.

See Puppeteer's list of PDF options for more details on how to customize your PDF generating.