Python 3 min read

Save a Webpage as PDF in Python: Render and Verify

Print an authorized webpage to PDF with Python and Chromium. Wait for content, fonts and images, then check pages and text without promising perfect fidelity.

(Updated: ) • 583 words

To save a webpage as PDF in Python, use a print-capable renderer and wait for the content the document needs. Then verify the PDF itself. A successful navigation or a five-second sleep does not establish that fonts, images and client-rendered content are ready, and a PDF is not automatically an immutable or compliant record.

Choose printing rather than text reconstruction

A browser print operation preserves the page’s print layout as rendered by that browser. Converting a Markdown extraction back to HTML creates a new document; it does not recreate the original layout. If your task is to keep readable source text, extraction may be enough. If it is to produce a paginated document, test the print result.

Requirement Verification
Client-rendered content Wait for an application-specific ready element
Web fonts Wait for document.fonts.ready and inspect PDF resources
Images Check completion and nonzero natural dimensions
Pagination Check the actual output page count and clipped content
Archival evidence Keep the capture inputs, time and your own integrity/retention policy

A Python print function with explicit readiness

Install Playwright and a Chromium browser. The example uses Chrome, because Playwright page.pdf is a Chromium PDF operation. Pass a permitted URL and a ready_selector that your application actually exposes. Change it for the target rather than treating the default fixture attribute as a universal selector.

from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright

def save_pdf(url, output, ready_selector="[data-ready='true']"):
    if urlsplit(url).scheme not in {"https", "http"}:
        raise ValueError("Expected an authorized HTTP(S) URL")
    with sync_playwright() as p:
        browser = p.chromium.launch(channel="chrome", headless=True)
        try:
            page = browser.new_page()
            page.goto(url, wait_until="domcontentloaded", timeout=30000)
            page.locator(ready_selector).wait_for(state="visible", timeout=15000)
            page.emulate_media(media="print")
            page.evaluate("() => document.fonts.ready")
            page.wait_for_function("() => Array.from(document.images).every(i => i.complete && i.naturalWidth > 0)", timeout=15000)
            page.pdf(path=str(output), format="A4", print_background=True)
        finally:
            browser.close()
    return {"output":str(Path(output)), "bytes":Path(output).stat().st_size}

Verify controlled static and JavaScript fixtures

Create two local HTML samples with the same title, a table, an image and an explicit second-page marker. Make one sample ready immediately; make the other insert its report and ready attribute with JavaScript. Run the same print function against both. Check title and marker text in the PDF, the expected page count, image resources and font resources, then visually inspect the rendered pages.

These fixtures show that the function handles the defined readiness contract. They do not prove pixel-perfect output for all websites. Print styles can hide content, responsive layouts can wrap tables differently, and a page can load successfully while a required image fails. Include a missing-ready fixture: it should fail instead of writing an apparently complete report.

Keep PDF generation and document extraction separate

SearchCans does not generate the PDFs in this example. If the resulting file later needs text extraction, evaluate File Extraction API for that separate step. the document-table extraction workflow covers accepting information from existing files; URL-to-Markdown conversion covers readable page text. the website capture workflow provides the related capture context.

Log renderer version, URL, readiness condition, print options, capture time and output hash. The PDF’s existence is one check; the report’s required content is the acceptance criterion.

Tags:

Python PDF Web Scraping AI Agents Data Extraction Playwright WeasyPrint Headless Browser
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.