Skip to content
New: Go-to-market lead lists, 5X cheaper with 10X more data than other tools
File Converter Guides

Convert HTML to PDF Python: WeasyPrint, Playwright, pdfkit and Page-Break CSS Examples

Convert HTML to PDF Python scripts with WeasyPrint, Playwright or pdfkit: working code, page-break CSS, image and font fixes, plus a no-code option.

convert html to pdf python: LeadCanal guide cover
On this page
  1. How Python turns HTML into a PDF
  2. Convert HTML to PDF Python libraries compared
  3. Method 1: WeasyPrint
  4. Method 2: Playwright with headless Chromium
  5. Method 3: pdfkit and wkhtmltopdf
  6. Method 4: xhtml2pdf
  7. Method 5: No code, in the browser
  8. Page breaks and paper size with CSS
  9. Convert HTML to PDF Python script for a whole folder
  10. Why privacy matters for HTML you convert
  11. Troubleshooting
  12. A worked example from our team
  13. Frequently asked questions
  14. Conclusion: key takeaways
  15. Editorial policy
  16. Content transparency
  17. About the author

To convert an HTML file to a PDF in Python, install WeasyPrint and run HTML("report.html").write_pdf("report.pdf"). If the page relies on JavaScript or modern flexbox and grid layouts, use Playwright to print it through headless Chromium instead. For a one-off file you do not want to script, our free HTML to PDF converter does the job in the browser with no upload. This guide compares the main convert HTML to PDF Python options, with working code, page-break CSS and fixes for missing images and fonts.

Quick answer: Pick the library by how the page is built.

  • Static HTML and CSS reports: WeasyPrint, a pure Python renderer with strong print CSS support.
  • Pages that need JavaScript: Playwright, which drives a real Chromium browser and calls page.pdf().
  • Legacy projects: pdfkit with wkhtmltopdf, or xhtml2pdf for very simple markup.
  • No code at all: drop the file into the browser-based HTML converter and choose A4, Letter or Legal.

How Python turns HTML into a PDF

Python cannot draw a web page by itself. Every library either ships its own layout engine (WeasyPrint, xhtml2pdf) or controls an external browser engine (Playwright with Chromium, pdfkit with wkhtmltopdf). That choice decides which CSS works, whether scripts run and how fast the job is.

A rule of thumb from our own scripts: if the HTML is a template you control, use a dedicated renderer. If it is a page someone else built, use a browser.

Convert HTML to PDF Python libraries compared

Library Engine Runs JavaScript Print CSS support Extra install Best for
WeasyPrint Own renderer No Strong (@page, page breaks, headers) Pango system libraries Invoices, reports, templates
Playwright Chromium Yes Chromium print rules Browser download Dashboards, JS-heavy pages
pdfkit wkhtmltopdf (older WebKit) Limited Basic wkhtmltopdf binary Existing legacy code
xhtml2pdf Own renderer (ReportLab) No Basic None Very simple markup

Method 1: WeasyPrint

Install it with pip install weasyprint. On Linux and macOS it also needs Pango, which the WeasyPrint documentation explains for each system.

from weasyprint import HTML
HTML("report.html").write_pdf("report.pdf")

Loading by file name lets WeasyPrint resolve relative image and stylesheet paths from the file’s folder. When you build HTML as a string, pass a base so those paths still work:

HTML(string=html_text, base_url="templates/").write_pdf("out.pdf")

WeasyPrint does not run JavaScript, so anything a script adds to the page will be missing. In return it handles print CSS better than most browsers, including page counters and running headers.

Method 2: Playwright with headless Chromium

Install it with pip install playwright, then run playwright install chromium once to download the browser.

from pathlib import Path
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto(Path("report.html").resolve().as_uri())
    page.pdf(path="report.pdf", format="A4", print_background=True)
    browser.close()

The Playwright page.pdf reference lists every option, including margins, landscape, header and footer templates and page ranges. PDF output works with Chromium, not Firefox or WebKit. Set print_background=True or colored boxes print white.

Method 3: pdfkit and wkhtmltopdf

pdfkit is a thin wrapper around the wkhtmltopdf command-line program, so install both: pip install pdfkit plus the wkhtmltopdf binary for your system.

import pdfkit
pdfkit.from_file("report.html", "report.pdf")

It still works in many older codebases, but wkhtmltopdf uses an old WebKit engine and the project is archived, so modern CSS such as grid often breaks. For new work, we would choose WeasyPrint or Playwright.

Method 4: xhtml2pdf

xhtml2pdf installs with pip alone and needs no system libraries, which suits locked-down servers.

from xhtml2pdf import pisa
with open("report.html") as src, open("report.pdf", "wb") as out:
    pisa.CreatePDF(src.read(), dest=out)

Its CSS support is limited to simple tables, fonts and colors. Use it for plain receipts and letters, not designed layouts.

Method 5: No code, in the browser

Sometimes you only need one file converted and setting up a library is overkill. The LeadCanal HTML to PDF tool takes .html, .htm and .xhtml files, lets you choose A4, Letter or Legal, orientation, margins and layout width, and downloads an exact image PDF or a Print to PDF version with selectable text. It runs inside your browser, so the file is never uploaded.

Page breaks and paper size with CSS

Whichever renderer you choose, print CSS controls the pages. These rules work in WeasyPrint and Chromium:

Goal CSS
Set paper and margins @page { size: A4; margin: 15mm; }
Landscape pages @page { size: A4 landscape; }
Start a section on a new page .new-page { break-before: page; }
Keep a table row together tr { break-inside: avoid; }
Repeat table headers thead { display: table-header-group; }

MDN documents the @page rule and its size values. In Playwright, set prefer_css_page_size=True so your @page size wins over the format argument.

Convert HTML to PDF Python script for a whole folder

To process every file in a folder with WeasyPrint:

from pathlib import Path
from weasyprint import HTML
for f in Path("pages").glob("*.html"):
    HTML(filename=str(f)).write_pdf(f.with_suffix(".pdf"))

For merging the results into one document and other batch routes, see our sibling guide on how to convert multiple HTML files to PDF.

Why privacy matters for HTML you convert

Scripts that convert HTML often run on invoices, statements and customer reports. If you send those through a hosted API, the provider receives the full document. Running a library locally, or using our no-upload converter for .htm files, keeps the file on your own machine. The browser tool also strips scripts and keeps remote images off by default, so a saved page cannot phone home while it is converted.

Troubleshooting

Images do not appear

Relative paths are resolved from the base URL. Load the file by name, set base_url, or use absolute file URIs.

Fonts look wrong

The renderer can only use fonts installed on the machine or loaded with @font-face. Install the font or embed it in the CSS.

Content added by JavaScript is missing

WeasyPrint, pdfkit and xhtml2pdf do not run modern scripts reliably. Switch to Playwright and wait for the content with page.wait_for_selector() before calling page.pdf().

Backgrounds print white

In Playwright pass print_background=True. In CSS, add print-color-adjust: exact;.

The PDF is too large

Large images are usually the cause. Resize them before rendering, or compress the result with the free PDF compressor.

A worked example from our team

We build lead lists every day, and each delivery includes a short summary report. We generate that report as HTML from a template, because HTML is easy to style and preview.

Our first version used pdfkit, and the two-column layout collapsed into one long column. We moved to WeasyPrint, added @page { size: Letter; margin: 12mm; } and tr { break-inside: avoid; }, and the tables stopped splitting across pages. One client report includes a chart drawn by JavaScript, so that single file goes through Playwright instead. When a teammate needs a quick PDF of a saved page outside the pipeline, they use the browser tool rather than running the script.

Frequently asked questions

What is the best Python library to convert HTML to PDF?

For templates you control, WeasyPrint. For pages that need JavaScript or match Chrome exactly, Playwright.

Can I convert HTML to PDF in Python without wkhtmltopdf?

Yes. WeasyPrint, Playwright and xhtml2pdf all work without it.

How do I convert an HTML string to PDF in Python?

Use HTML(string=html_text, base_url=".").write_pdf("out.pdf") in WeasyPrint, or page.set_content(html_text) before page.pdf() in Playwright.

How do I convert a URL to PDF with Python?

In Playwright, call page.goto("https://example.com") then page.pdf(). WeasyPrint also accepts a URL with HTML(url).

How do I add page numbers?

WeasyPrint supports counter(page) in @page margin boxes. Playwright supports a footer_template with a pageNumber class.

Can I generate PDFs from HTML in Django or Flask?

Yes. Render the template to a string, pass it to WeasyPrint with base_url set to your static files location, and return the bytes from write_pdf() with a PDF content type. Playwright also works, but starting a browser per request is slower, so reuse one browser instance for many pages.

Is WeasyPrint free for commercial use?

WeasyPrint is open source under the BSD license. Check the license of any library before you ship it in a product.

Why is my convert HTML to PDF Python output blank?

Usually the page loaded nothing yet. Check file paths, then in Playwright wait for the network or a selector before printing.

Conclusion: key takeaways

The right convert HTML to PDF Python choice depends on whether the page needs a browser. Use a print renderer for templates, a headless browser for scripted pages, and print CSS for page control.

  • WeasyPrint is the best default for HTML templates.
  • Playwright handles JavaScript and matches Chrome output.
  • pdfkit works, but wkhtmltopdf is archived.
  • @page and break rules control size and page breaks in every engine.
  • For a one-off file, a no-upload browser tool saves setup time.
  • Browse the full list of LeadCanal free tools for the next step, such as the PDF page remover.

Working with other text formats in Python? Our guide on how to create a JSON file covers Python too.

Editorial policy

We test each code sample on current library versions before publishing and update the guide when an API changes.

Content transparency

This guide was researched with keyword data and checked against official documentation from WeasyPrint, Playwright and MDN. LeadCanal offers the free tools mentioned in this article.

About the author

The LeadCanal team builds lead lists, cleans CSV and VCF data and handles client files daily, including the HTML reports that ship with every delivery.

Found this useful? Share it with your team.

Written by LeadCanal

The LeadCanal team builds verified B2B lists and runs cold email infrastructure for agencies and sales teams. Every guide comes from campaigns we send every day.

Done-for-you lead generation

Want this done for you?

Targeted lists and cold email campaigns that book qualified meetings.