selenium print page to PDF in headless chrome: how to do
Shows how to print a page to PDF from headless Chrome via selenium. Use it when tests need to verify PDF generation or archive page output. Not for headed printing dialogs or non-Chrome PDF generation.
TL;DR
Headless Chrome exposes page printing through the DevTools protocol, which selenium can reach with execute_cdp_cmd('Page.printToPDF', {...}); the command returns base64 PDF bytes you decode and write to a file. This bypasses the print dialog entirely, which is what you want in automation. Tune paperWidth, paperHeight, margins, and printBackground in the params to match what the feature under test expects.
The query
selenium print page to PDF in headless chrome: how to doUse this when
- Testing a "download as PDF" or print-stylesheet feature
- Archiving rendered pages as PDFs in a pipeline
- Verifying PDF output without a human clicking print
Not for
- Headed-browser print dialog automation
- Generating PDFs outside a browser (use a PDF library)
- Firefox PDF printing
Steps
- Ensure the driver is headless Chrome (CDP commands need a Chromium-based session) and the page is fully loaded. Expected output:
driver.execute_cdp_cmdis available and the page render is complete. - Call
Page.printToPDFviaexecute_cdp_cmdwith your paper size and margin options; capture the returned base64data. Expected output: a base64 string is returned without errors. - Decode the base64 payload and write it to a
.pdffile, then open it to confirm content and layout. Expected output: a valid PDF file renders the page as expected. - Assert on the PDF in your test (file exists, non-trivial size, or text extraction matches key content). Expected output: the test verifies the PDF rather than just its existence.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_pFdqJ8-i47DFq5R02MPjug
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.