Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

Convert a Webpage to PDF in Python with Playwright

A practical Python guide to Playwright PDFs: install Chromium, choose print or screen styling, configure page output and handle navigation errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright’s Python API to open a webpage in Chromium and save it as a PDF with page.pdf(). The method uses print CSS media by default, so the result may differ from what you see in a browser window. To use screen styling instead, call page.emulate_media(media="screen") before creating the PDF.

Install Playwright and its browser binaries

Install the Python package, then download the browser binaries Playwright needs. The official setup guide’s commands install binaries for Chromium, Firefox and WebKit; this PDF workflow uses Chromium.

  1. pip install playwright
  2. playwright install

See the Playwright Python getting started guide for installation details.

Generate a PDF from a webpage

This short synchronous script navigates to a fully qualified URL and writes an A4 PDF with background graphics included:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.com")
    page.pdf(path="page.pdf", format="A4", print_background=True)
    browser.close()

Replace https://example.com with the page you want to capture. Supplying path saves the PDF there; without it, page.pdf() returns PDF bytes. The method and its options are documented in the Playwright Python Page API.

Use screen styling instead of print styling

By default, page.pdf() renders with print CSS media. If the page’s print stylesheet hides or rearranges content you need, emulate screen media before calling the PDF method:

page.emulate_media(media="screen")
page.pdf(path="page.pdf", format="A4", print_background=True)

Manage browser, context and page lifetimes

browser.new_page() is convenient for a short, single-page script. For reusable or longer-running code, create a browser context and page explicitly so their lifetimes are managed separately:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    try:
        page.goto("https://example.com")
        page.pdf(path="page.pdf", format="A4", print_background=True)
    finally:
        context.close()
        browser.close()

Playwright recommends explicit context and page creation for production code and test frameworks; its convenience page creation is intended for one-page scenarios and short snippets. See the Browser API guidance.

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

Choose paper size, margins and print options

Set only the options that match the page and the output you need. The Page API documents these choices:

  • Paper: format accepts a named size such as "A4" or "Letter". The documented default is Letter. If you supply format, it takes priority over width and height.
  • Dimensions and margins: width, height and margin values accept units such as px, in, cm and mm; values without units are treated as pixels. Margins default to none.
  • Orientation: set landscape=True for landscape output.
  • Page range: use page_ranges to include selected pages, for example "1-3".
  • Backgrounds: set print_background=True to include background graphics; this is off by default.
  • CSS page size: set prefer_css_page_size=True if the page’s @page CSS should control the paper size instead of the API paper settings. This option defaults to false.
  • Scaling: scale defaults to 1 and accepts values from 0.1 to 2.
  • Headers and footers: display_header_footer=True enables them; use header_template and footer_template to provide templates. Scripts in these templates do not run, and page styles are not visible inside them.
  • Tagged PDF: tagged=True requests tagged output. That setting alone does not establish that a PDF meets accessibility requirements.

For example, use CSS-defined page dimensions and a selected page range like this:

page.pdf(
    path="selected-pages.pdf",
    prefer_css_page_size=True,
    page_ranges="1-3",
    print_background=True,
)

Check navigation and handle common problems

The URL is missing a scheme

page.goto() requires a URL scheme. Use a complete URL such as https://example.com, not just example.com.

The PDF is missing content or looks different

Playwright uses print CSS by default. Try page.emulate_media(media="screen") before generating the PDF if you want screen styling. If the missing content is a background graphic, enable print_background=True.

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

The saved page shows an error response

A valid HTTP status such as 404 or 500 does not, by itself, make page.goto() throw an exception. If success matters, inspect the response returned by navigation and decide whether to save the page:

response = page.goto("https://example.com")
if response is not None and response.status >= 400:
    raise RuntimeError(f"Page returned HTTP {response.status}")
page.pdf(path="page.pdf", format="A4")

This check treats HTTP error statuses as failures for this script; adjust the policy if you intentionally need to save an error page.

Navigation targets an existing PDF

Generating a PDF from a webpage with page.pdf() is different from navigating to an existing PDF document. Playwright’s documentation notes that headless mode does not support navigation to an existing PDF; that restriction is not a limitation on generating a PDF from a webpage.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a screenshot rather than a PDF, ScreenshotNeo can return a PNG, JPEG or WebP image with one GET request. Its API also offers PDF output. For a WebP screenshot:

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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for the request and available options. ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in headers. An MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf. The Free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000.

Learn about ScreenshotNeo or sign up free for 1,000 screenshots a month, with no card required.

Frequently Asked Questions

Does Playwright’s PDF method return bytes or save a file?

It returns PDF bytes; passing path saves the output to that location.

Can I use Firefox or WebKit for this PDF workflow?

The setup guide installs Chromium, Firefox and WebKit binaries, but the PDF guidance for this workflow is documented for Chromium. Do not assume identical PDF behavior across browser engines.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.