Playwright PDFs


With Playwright you can easily take PDFs from any page.

Under the hood Playwright will connect to a (headless) Chrome/Chromium instance, producing pixel-perfect PDFs.


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

Generating your first PDF

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


const pw = require('playwright');
const fs = require('fs');
const fsPromises = fs.promises;

(async () => {
  const browser = await pw.chromium.connect({
    wsEndpoint: 'wss://chrome.headlesstesting.com?token=[YOUR-TOKEN]',
  });
  const context = await browser.newContext();
  const page = await context.newPage();

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

  await browser.close();
})();

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

Playwright 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 Playwright's list of PDF options for more details on how to customize your PDF generating.