How to Generate PDFs from URLs in Python (2026)

Converting a webpage to a PDF is one of the most common automation tasks for developers. Archiving pages, generating reports from dashboards, saving receipts, creating compliance snapshots — all require rendering a URL and saving the result as a paginated document.
This guide covers four approaches in Python: a dedicated rendering API (fastest to ship), Playwright (the modern standard), Selenium (legacy compatibility), and wkhtmltopdf (lightweight CLI). Each includes working code you can copy and run.
Method 1: Rendex API (3 Lines of Code)
The fastest path. The Rendex Python SDKhandles browser rendering on Cloudflare's edge network — no Chromium install, no memory management, no cold starts. Pass a URL, get back a PDF with full control over page size, margins, and headers.
# pip install rendex
from rendex import Rendex
from pathlib import Path
rendex = Rendex("YOUR_API_KEY")
result = rendex.screenshot(
"https://example.com",
format="pdf",
pdf_format="A4",
pdf_margin="20mm",
pdf_print_background=True,
)
Path("report.pdf").write_bytes(result.image)
print(f"PDF: {result.metadata.bytes_size} bytes")Async supportis built in — ideal for batch PDF generation:
import asyncio
from rendex import AsyncRendex
from pathlib import Path
async def generate_pdfs(urls: list[str]):
async with AsyncRendex("YOUR_API_KEY") as rendex:
for url in urls:
result = await rendex.screenshot(
url,
format="pdf",
pdf_format="A4",
pdf_margin="20mm",
pdf_print_background=True,
)
slug = url.replace("https://", "").replace("/", "_")
Path(f"{slug}.pdf").write_bytes(result.image)
print(f"Saved {slug}.pdf")
asyncio.run(generate_pdfs([
"https://github.com",
"https://news.ycombinator.com",
"https://stripe.com/docs",
]))Or with raw HTTP — no SDK needed:
curl -X POST https://api.rendex.dev/v1/screenshot \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com",
"format": "pdf",
"pdfFormat": "A4",
"pdfMargin": "20mm",
"pdfPrintBackground": true
}' --output report.pdfAdvanced options include custom page sizes (Letter, Legal, Tabloid), landscape orientation, header/footer templates, and scale control. See the full API reference.
When to use:Production workloads, AI agent pipelines, batch processing, and any case where you don't want to manage browser infrastructure. You get 100 free calls/month to start. Get an API key.
Method 2: Playwright (Self-Hosted)
Microsoft's Playwright is the current gold standard for headless browser automation. Its PDF generation supports all Chromium print options.
# pip install playwright
# python -m playwright install chromium
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", wait_until="networkidle")
page.pdf(
path="report.pdf",
format="A4",
margin={"top": "20mm", "bottom": "20mm", "left": "20mm", "right": "20mm"},
print_background=True,
)
browser.close()Playwright gives you full control — you can authenticate, dismiss cookie banners, wait for specific elements, and inject custom CSS before generating the PDF.
When to use: You need browser interaction before capture (login flows, cookie banners, SPAs that require navigation). You manage the infrastructure yourself.
Trade-offs:Requires a Chromium install (~400 MB), consumes significant memory per browser instance, and cold starts can be slow in serverless environments. PDF generation only works with Chromium — Firefox and WebKit don't support page.pdf().
Method 3: Selenium (Legacy Support)
Selenium doesn't have a built-in PDF method, but you can use Chrome DevTools Protocol commands to trigger print-to-PDF.
# pip install selenium webdriver-manager
import base64
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
options=options,
)
driver.get("https://example.com")
# Use Chrome DevTools Protocol for PDF
pdf_data = driver.execute_cdp_cmd("Page.printToPDF", {
"paperWidth": 8.27, # A4 width in inches
"paperHeight": 11.69, # A4 height in inches
"marginTop": 0.79, # ~20mm
"marginBottom": 0.79,
"marginLeft": 0.79,
"marginRight": 0.79,
"printBackground": True,
})
Path("report.pdf").write_bytes(base64.b64decode(pdf_data["data"]))
driver.quit()When to use: Existing Selenium test suites where you want to add PDF generation without introducing a new tool.
Trade-offs:The CDP approach is undocumented in Selenium's official API. No built-in PDF support means you're working around the framework, not with it. Playwright is preferred for new projects.
Method 4: wkhtmltopdf (Lightweight CLI)
wkhtmltopdf is a command-line tool that converts HTML to PDF using a patched version of WebKit. It's lightweight and widely available in Linux package managers.
# apt install wkhtmltopdf (or brew install wkhtmltopdf)
# pip install pdfkit
import pdfkit
options = {
"page-size": "A4",
"margin-top": "20mm",
"margin-bottom": "20mm",
"margin-left": "20mm",
"margin-right": "20mm",
"print-media-type": "",
"enable-javascript": "",
"javascript-delay": 2000,
}
pdfkit.from_url("https://example.com", "report.pdf", options=options)
print("PDF saved")When to use: Simple pages with basic CSS, batch processing on Linux servers, or when you need a lightweight tool without a full Chromium dependency.
Trade-offs:Uses an outdated WebKit engine — modern CSS features like Flexbox, Grid, and custom properties may not render correctly. JavaScript support is limited. The project is effectively unmaintained since 2020. Not suitable for pages that rely on modern web standards.
Which Method Should You Choose?
| Method | Setup Time | CSS Support | Best For |
|---|---|---|---|
| Rendex API | 30 seconds | Full (Chromium) | Production, AI agents, batch jobs |
| Playwright | 5 minutes | Full (Chromium only) | Self-hosted, browser interaction |
| Selenium | 10 minutes | Full (via CDP hack) | Existing Selenium suites |
| wkhtmltopdf | 2 minutes | Basic (old WebKit) | Simple pages, lightweight |
For most production use cases — especially if you're building an AI agent pipeline or need PDFs at scale — an API is the right choice. You avoid managing browsers, handling memory, and dealing with cold starts.
PDF Configuration Options
When generating PDFs programmatically, these are the options that matter most:
- Page size: A4 (210×297mm, international standard), Letter (8.5×11in, US standard), Legal, Tabloid
- Margins: Control top, bottom, left, and right independently. Use
0for edge-to-edge output - Print background: Include CSS background colors and images (off by default in most tools)
- Scale: Shrink or enlarge content (0.1 to 2.0) to fit more content per page
- Landscape: Rotate orientation for wide content like dashboards and spreadsheets
Common Use Cases for URL-to-PDF
- Report generation — Convert dashboards and analytics pages to shareable PDF reports
- Invoice rendering — Generate print-ready invoices from HTML templates with dynamic data
- Web archiving— Save permanent records of web pages for compliance, legal discovery, or research
- Receipt capture— Automate saving order confirmations and transaction receipts
- Documentation export— Convert online docs to offline-readable PDFs for distribution
Ready to start? Get a free API key (100 calls/month, no credit card) or try the free URL-to-PDF tool to convert a page without writing any code.
Want to see how Rendex compares to other rendering APIs? See the 2026 comparison.
Comparing all HTML-to-PDF options including open-source libraries? Best HTML-to-PDF Tools in 2026 covers Rendex, DocRaptor, PDFShift, wkhtmltopdf, and Playwright side-by-side.