Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To generate a PDF from the page Selenium has rendered, navigate to the URL, call Selenium’s print-page API, decode the returned Base64 text, and write the decoded bytes to a .pdf file. In Python, the essential call is driver.print_page(print_options).

This prints the current HTML page as a PDF representation. It is not the same as downloading a PDF that a server already provides. The distinction, browser requirements, layout controls, Chromium-only alternatives, and failure fixes are covered below.

Minimal working example in Python

Install Selenium and make a compatible Chromium browser and driver available to your environment. The official Selenium browser example notes that Chromium printing requires headless mode, which is especially important in CI and containers. Verify the requirement for the browser and Selenium release you deploy.

from base64 import b64decode
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)

try:
    driver.get("https://example.com")
    print_options = PrintOptions()
    pdf_base64 = driver.print_page(print_options)

    with open("page.pdf", "wb") as output:
        output.write(b64decode(pdf_base64))
finally:
    driver.quit()

The returned value is a Base64-encoded PDF string. Decode it before opening the destination in binary mode. The resulting file is a PDF representation of the page state Selenium had loaded when print_page() ran.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

See Selenium’s Print Page documentation for the language-binding examples and current API details.

What Selenium is actually printing

Selenium printing renders the current browser document into PDF. It does not fetch a PDF file from a link, infer a download URL, or preserve a server-generated PDF byte-for-byte. JavaScript-rendered content must already be present in the page Selenium is printing.

Print a rendered HTML page

  1. Start a WebDriver session with a browser configuration that supports printing.
  2. Navigate with driver.get().
  3. Ensure the page has reached the state you intend to archive.
  4. Create a PrintOptions object and pass it to driver.print_page().
  5. Base64-decode the return value and save the bytes as a PDF.

Download an existing PDF

If a URL responds with an already-generated PDF, use a download or HTTP-response workflow instead of page printing. Printing that URL asks the browser to create a new PDF representation of the document; it is not a general-purpose PDF downloader. Authentication, download completion, and browser-specific download behavior require a separate implementation.

Configure the PDF with Selenium PrintOptions

Selenium’s print-page API accepts print options for common paper and pagination decisions. The exact property spelling varies by language binding, so use the current API reference for your binding.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Control What it changes When to use it
Orientation Portrait or landscape page orientation. Use landscape for wide tables, dashboards, or code listings.
Page dimensions Paper width and height. Match a report’s required paper size instead of relying on defaults.
Margins Whitespace around the printed content. Reduce clipping or reserve space for binding and annotations.
Backgrounds Whether page backgrounds and background graphics are included. Enable when color bands, cards, or branded backgrounds are meaningful to the report.
Page selection A selected page or page range rather than the whole document. Export only the relevant section of a long report.

Start with the default PrintOptions() shown above, then set only the controls your output requires. Keep the options object next to the print call so the intended paper, margins, and range are visible in code review.

Browser and driver requirements

Chromium headless mode

Selenium’s browser example explicitly states: “Note: This requires Chromium Browsers to be in headless mode.” Add the headless argument before creating the driver, and make sure the browser and driver versions are compatible in your CI image or container. The relevant example is in Selenium’s browser windows and tabs documentation.

Other supported browsers

Selenium exposes browser-specific capabilities rather than guaranteeing identical output everywhere. The Firefox Python API also exposes print_page() and describes a best-effort PDF based on the supplied parameters. Do not assume that pagination, backgrounds, fonts, or unsupported options will match Chromium. Review the supported browsers page and your binding’s API reference before standardizing output across browsers.

Chromium’s DevTools alternative

When you need controls beyond WebDriver’s common print options, Chromium’s DevTools Protocol provides the Page.printToPDF method. Its documented parameters include:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Landscape output and printed backgrounds.
  • Page ranges.
  • Header and footer display, including templates.
  • Explicit paper dimensions and margins.
  • Preference for CSS-defined page size.
  • Returning the result as a stream.
  • Tagged-PDF generation.

This is a Chromium-specific protocol, not a portable Selenium API. Some parameters are marked experimental, so browser and protocol version compatibility matters. Choose it when those extra controls justify coupling your automation to Chromium; otherwise, Selenium’s print-page API is the more WebDriver-oriented route. The protocol reference is Chrome DevTools Protocol Page.

Decision point Selenium print_page() Page.printToPDF
Portability WebDriver-oriented and available through Selenium bindings; browser output can still differ. Chromium-specific.
Common layout settings Orientation, dimensions, margins, backgrounds, and ranges. Includes those categories plus additional protocol controls.
Specialized output Use the options exposed by your binding. Headers/footers, streaming, CSS page-size preference, and tagged PDFs are documented.
Runtime caveat Chromium printing requires headless mode according to Selenium’s example. Requires a Chromium DevTools connection and inherits Chromium compatibility concerns.

Reliable automation patterns

Print only after the intended state exists

The print call captures the current rendered document. Navigate first and arrange your automation so that client-side content, route changes, and any report state you need are complete before calling it. If you print too early, the PDF can contain a loading shell or incomplete data even though the call itself succeeds.

Always close the driver

Use try/finally, as in the example, so a failed navigation or print operation does not leave a browser process behind. This matters for repeated jobs and constrained CI runners.

Write binary output

Decode the Base64 string with b64decode() and open the destination with "wb". Writing the encoded text directly creates a file that is not a valid PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep output paths deterministic

For scheduled jobs, construct a unique, known output path outside the browser profile directory and record which URL and print settings produced it. Selenium returns PDF data; naming, retention, and upload are responsibilities of your application.

Common failures and fixes

Symptom Likely cause Fix
AttributeError for print_page Old Selenium binding or an unsupported driver implementation. Upgrade Selenium and verify the binding’s current print-page API and browser support.
Session starts but printing fails in CI Chromium is running without the required headless configuration. Add the headless argument and confirm the browser/driver pair in the CI image.
The file opens as text or is reported corrupt Base64 text was written without decoding. Call b64decode(pdf_base64) and write with binary mode.
PDF contains a spinner or empty report Printing occurred before the page reached the desired rendered state. Change the automation flow so the print call follows the page state you intend to capture.
Colors or page breaks differ between browsers Browser-specific print behavior and best-effort support. Standardize on a tested browser, set explicit print options, and avoid assuming cross-browser identity.
Only part of a long document appears A page range or browser pagination decision limited output. Review the selected-page settings and the target browser’s print implementation.
You expected the original downloaded PDF Page printing was used for a file-download task. Implement a direct download or HTTP-response workflow instead.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and operational notes

  • PDF generation includes browser startup, navigation, page rendering, and encoding, so reusing a controlled browser session can avoid repeated startup overhead when your workload permits it.
  • Headless operation is usually the practical choice for CI and containers, but the browser and driver still need compatible versions and installed fonts/resources.
  • Large pages, high-resolution assets, and long page ranges consume more memory and may produce larger files. Limit the range or simplify the rendered view when a report does not need every page.
  • Because Selenium produces the PDF in the browser process, monitor driver lifetime and clean up sessions after every job.
  • The official material does not establish a universal speed, success rate, or file-size limit. Measure those characteristics with your own pages, browser version, and infrastructure.

Or skip the browser setup

If you need a hosted website screenshot or PDF endpoint rather than maintaining Selenium and a browser, ScreenshotNeo is the first alternative to try: it removes common consent banners and overlays before capture, bills only clean shots, and its paid plans start at $5.

For a PDF capture, call the API endpoint with your URL and PDF options as documented. The following one-call example uses the supplied API shape; see the ScreenshotNeo documentation for the complete parameter list.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

The same request from Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

And from Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);

ScreenshotNeo can accept a consent banner like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every plan includes all features; 1,000 screenshots per month are free with no card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to choose each approach

  • Choose Selenium when your workflow already drives a browser, needs the exact rendered application state, or requires WebDriver-level interaction before printing.
  • Choose Chromium DevTools when you control Chromium and need protocol-level features such as header/footer templates, streaming, or tagged PDFs.
  • Choose ScreenshotNeo when you want an API or MCP workflow without installing and operating a browser, especially when consent overlays and failed captures should be handled and billed transparently.

Further official references

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.