Search for "HTML to PDF in Python" and you get the same four names every time: xhtml2pdf, WeasyPrint, pdfkit and Playwright. What you rarely see is one real document run through all four. So we did that: one invoice, each library set up the way its own documentation describes, on the kind of Linux box these things end up running on.
Disclosure: I'm on the team behind Dynamic Document API, a hosted HTML to PDF API, so we have a horse in this race. That's why everything below is in a public repository and runs in GitHub Actions: the code, the PDFs and the results file.
The test document
An invoice with the things a real one uses today:
- a header laid out with Flexbox, with an inline SVG logo
- the invoice details (number, dates, PO) in a two-column CSS grid
- a web font (Inter, from Google Fonts)
- 36 line items, so the table runs onto page 2 and should repeat its header row there
- totals that shouldn't be split across pages
- US Letter, and a footer with the seller on the left and "Page 1 of 2" on the right
None of the four libraries has a template language, so the invoice was filled in with Jinja2 first and every library got the same finished HTML. Only the page setup (size, margins, page numbers) was added the way each library wants it. The run used Python 3.12 in the python:3.12-bookworm container (Debian 12) on GitHub Actions. The results below are from the committed run with xhtml2pdf 0.2.28 and Playwright 1.65.2; we ran it again on 2 December with xhtml2pdf 0.2.29 and Playwright 1.65.3, and the layouts came out the same.
The results
Page 1 from each library:

xhtml2pdf 0.2.28: no logo, stacked details, three pages instead of two.

WeasyPrint 70.0: as designed, one narrow column wraps.

pdfkit 1.0.0 with wkhtmltopdf 0.12.6.1: Flexbox and grid ignored, everything about a fifth smaller.

Playwright 1.65.2 with Chromium: as designed.
| xhtml2pdf | WeasyPrint | pdfkit | Playwright | |
|---|---|---|---|---|
| Engine | its own, on ReportLab | its own | wkhtmltopdf (Qt WebKit) | Chromium |
| You install |
pip only |
pip + Pango |
pip + wkhtmltopdf binary |
pip + 732 MB of browsers |
| Inline SVG logo | ❌ missing | ✅ | ✅ | ✅ |
| Flexbox | ❌ stacked | ✅ | ❌ ignored | ✅ |
| CSS grid | ❌ stacked | ✅ (one column wraps) | ❌ ignored | ✅ |
| Web font | ✅ | ✅ | ✅ | ✅ |
| Table header on page 2 | ✅ | ✅ | ✅ | ✅ |
| Pages | 3 | 2 | 2 | 2 |
| Page numbers |
<pdf:pagenumber> tags |
CSS @page
|
footer options | footer template |
| Runs JavaScript | ❌ | ❌ | ✅ (old WebKit) | ✅ |
| Time for the invoice | 1.2–1.4 s | 1.0–1.4 s | 0.5–0.6 s | 1.3–1.4 s (incl. browser start) |
| License | Apache-2.0 | BSD-3-Clause | MIT (wkhtmltopdf: LGPL-3.0) | Apache-2.0 |
| Latest release | Nov 2026 | Sep 2026 | Nov 2021 | Dec 2026 |
The JavaScript row comes from a second test page with one <script> that changes a word on the page. The times are the range of two runs on shared CI machines, so read them as rough.
Now the parts that don't fit in a table.
xhtml2pdf: pure Python, and it shows
xhtml2pdf is the easiest to install: it's pure Python on top of ReportLab, so pip install xhtml2pdf is all there is. It even picked up Inter from the Google Fonts stylesheet.
The layout is where it struggles. Its own engine covers older CSS:
- the inline SVG logo wasn't drawn at all
- Flexbox and grid fell back to stacked blocks
- the table got equal-width columns, so the item descriptions wrapped onto three lines and only 7 of 36 items fit on page 1; the invoice ended up on three pages
The repeated header row and the totals block came out fine.
Page numbers need xhtml2pdf's own syntax: a named @frame in the @page rule and <pdf:pagenumber> / <pdf:pagecount> tags in the frame's content:
from xhtml2pdf import pisa
frame_css = """<style>
@page { size: letter; margin: 16mm 16mm 22mm 16mm;
@frame footer { -pdf-frame-content: pagefooter; bottom: 8mm;
margin-left: 16mm; margin-right: 16mm; height: 8mm; } }
</style>"""
footer = ('<div id="pagefooter" style="font-size: 7pt">Northwind Outdoor Supply'
' · Page <pdf:pagenumber> of <pdf:pagecount></div>')
html = html.replace("</head>", frame_css + "</head>").replace("<body>", "<body>" + footer)
with open("invoice.pdf", "wb") as f:
result = pisa.CreatePDF(html, dest=f)
if result.err:
raise RuntimeError(f"xhtml2pdf reported {result.err} errors")
Note the last two lines: CreatePDF doesn't raise on errors, it counts them in result.err. Check it, or a broken PDF goes out silently.
Good for: simple documents made of text and plain tables, where "installs anywhere" matters more than modern CSS.
WeasyPrint: the best of the browser-free options
WeasyPrint got much further than the other browser-free library in this test: the Flexbox header, the grid, the SVG logo, the web font, the repeated header row and the totals all came out as designed. The one difference from Chrome: the column with the invoice details came out narrower, so "Invoice number" and the dates wrapped onto two lines, and so did the seller's address.
Page numbers go through CSS paged media, the standard way, and you can keep them out of your HTML entirely:
from weasyprint import CSS, HTML
page_css = CSS(string="""
@page { size: Letter; margin: 16mm 16mm 20mm 16mm;
@bottom-left { content: "Northwind Outdoor Supply"; font: 7pt Arial, sans-serif; }
@bottom-right { content: "Page " counter(page) " of " counter(pages); font: 7pt Arial, sans-serif; } }
""")
HTML(string=html).write_pdf("invoice.pdf", stylesheets=[page_css])
Three things to know:
-
It needs Pango.
pip install weasyprintisn't enough on a server or in a slim Docker image. On Debian we addedlibpango-1.0-0,libpangoft2-1.0-0andlibharfbuzz-subset0. -
Fonts come from the system. The footer asks for Arial, which the container doesn't have, so fontconfig put Liberation Sans in the PDF (we had installed
fonts-liberation). Install the fonts your templates name, or load them with@font-face. - No JavaScript. Our test page still said "no" in WeasyPrint's PDF. Charts drawn by a script won't appear; render them to SVG first.
pdfkit: a thin wrapper around a frozen binary
pdfkit itself is a small wrapper that calls the wkhtmltopdf binary. Its last release is from November 2021, and wkhtmltopdf has been archived since January 2023. Its Qt WebKit predates Flexbox and grid as we use them today, so both were ignored: the logo sits above the company name, the invoice details are stacked, and bill-to and from are under each other instead of side by side.
It was also the fastest, about half a second for both pages, and besides Playwright the only one that runs JavaScript (with an old engine). The web font, the repeated header row and the page numbers worked:
import pdfkit
pdfkit.from_string(html, "invoice.pdf", options={
"page-size": "Letter",
"margin-top": "16mm", "margin-right": "16mm", "margin-bottom": "20mm", "margin-left": "16mm",
"encoding": "UTF-8",
"footer-left": "Northwind Outdoor Supply",
"footer-right": "Page [page] of [topage]",
"footer-font-size": "7",
})
Two things that cost time:
- Which wkhtmltopdf you install matters. Headers and footers only work in builds with wkhtmltopdf's patched Qt. We used the 0.12.6.1 package for Debian 12 from the wkhtmltopdf packaging releases, which reports itself as "with patched qt".
-
Everything came out smaller. The whole invoice is about a fifth smaller than in the other three PDFs: the "INVOICE" heading is 71 pt wide instead of 91 pt. We left wkhtmltopdf's defaults alone; if you need the sizes to match,
disable-smart-shrinkingandzoomare the options to look at.
For a new project, I wouldn't start here. If you're moving off it, we wrote up what breaks in wkhtmltopdf and what to replace it with.
Playwright: right result, but you run Chromium
Playwright prints with a real Chromium, so the PDF is what Chrome's print preview shows you, with 24 line items on page 1 like the original design. That's the whole appeal, and it delivered.
from playwright.sync_api import sync_playwright
footer = ('<div style="font-size: 7pt; width: 100%; margin: 0 16mm; display: flex;'
' justify-content: space-between"><span>Northwind Outdoor Supply</span>'
'<span>Page <span class="pageNumber"></span> of <span class="totalPages"></span></span></div>')
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.set_content(html, wait_until="networkidle") # wait for the web font
page.pdf(
path="invoice.pdf",
format="Letter",
margin={"top": "16mm", "right": "16mm", "bottom": "20mm", "left": "16mm"},
print_background=True, # otherwise the green table header comes out white
display_header_footer=True,
header_template="<span></span>",
footer_template=footer,
)
browser.close()
What the code doesn't show:
-
The download.
playwright install chromiumput 732 MB into the browser cache. Bake it into your Docker image, not into the first request.--with-depsinstalls the system libraries Chromium needs. -
The footer is its own little page.
footer_templatedoesn't see your document's CSS, so it needs inline styles and its own margins, and it doesn't use your fonts either: our footer came out in DejaVu Sans, Debian's default, not Inter. Chromium fills in the page numbers through thepageNumberandtotalPagesclasses. The emptyheader_templateis there because Chromium prints a default header (date and title) otherwise. -
print_background=True. Without it Chromium leaves out background colors, our green table header included. -
The sandbox is off by default. Playwright launches Chromium without its sandbox unless you pass
chromium_sandbox=True. That's fine for HTML you wrote. If you render HTML or URLs that come from users, turn the sandbox on, which on Ubuntu 23.10 and later also means dealing with AppArmor's limits on user namespaces.
The 1.3 to 1.4 seconds include starting Chromium. In a web app, start the browser once and reuse it, and plan for memory per page, a timeout for pages that never finish loading, and Chromium updates every few weeks.
So which one?
- It has to look like it does in Chrome: Playwright, and plan for running Chromium (image size, memory, sandbox, updates).
- No browser, no JavaScript needed: WeasyPrint. It handled everything in this invoice; install Pango and your fonts.
- Text and plain tables, pure Python: xhtml2pdf, after checking your real templates.
- New project: not pdfkit.
-
Chrome's result without running Chrome: that's what a hosted API is for, and it's what we build. The full tutorial renders this same invoice through ours: from a Jinja template with the Python SDK, with plain
requests, and from a FastAPI endpoint. Your HTML and data are sent to us, so check whether that works for your project.
Run it yourself
Everything is in DynamicDocumentApi/html-to-pdf-python: the invoice, the four renderers in run_all.py, the workflow and the results. The comparison needs no API key. On Debian or Ubuntu, install libpango-1.0-0 libpangoft2-1.0-0 and the wkhtmltopdf package, then:
pip install -r compare/requirements.txt
python -m playwright install --with-deps chromium
python compare/run_all.py
If you'd configure one of the libraries differently, or know a setting that fixes one of these results, open an issue or a pull request. I'll rerun it and update the results.
Top comments (9)
It reproduces on a minimal invoice, so it's not our layout. This is enough with HtmlRenderer.PdfSharp 1.6.1:
Extracted text: "Invoice", "Thank you". No exception. Remove
display: flexand "Amount due $100.00" is back.display: griddrops its content the same way.The full invoice and the code for all four .NET libraries are here if you want to run your check on them: github.com/DynamicDocumentApi/html...
That minimal repro settles it — it's not your layout, it's the engine: flex and grid content is dropped silently, no exception, and the amount due is exactly the line that vanishes. That's the case the check exists for: assert the extracted text contains every line item and the totals row as required strings, per page, in CI — a PDF that renders fine can still be missing the one number that matters.
I'll run the check on the four libraries' outputs from your repo and post which ones drop what — that turns the minimal case into the regression test.
Sounds good, I'm curious what you find. You don't need to run anything, the four PDFs are committed here: github.com/DynamicDocumentApi/html...
I published the JavaScript version of this test today, and it checks every PDF for all 36 line items and the totals. It caught html2pdf.js: 0 of 36, because every page is a picture.
It also showed where the text check isn't enough. With an SVG logo, jsPDF gave us two blank pages, and the text check still passed: all 36 rows and the totals were in there, just not visible. So we check the rendered pages for blank ones too.
dev.to/frank_32f82b4e249028949b9/s...
Ran it on the four committed PDFs (pypdf, per page, required strings = all 36 SKUs plus the four totals lines). Results:
So the minimal repro holds on the real invoice too: HtmlRenderer.PdfSharp drops the flex/grid totals block while keeping every line item, which is exactly the failure a totals-row assertion in CI would catch — the line items alone would pass.
Your JS finding is the mirror image and just as important: html2pdf.js 0/36 because every page is a picture, and jsPDF passing the text check on two blank pages. Text layer present does not mean content visible. The pair of checks — required strings per page plus a rendered-page blank check (ink coverage / non-white pixel share per page) — covers both failure modes. That is the CI gate I would write: assert the strings, then assert no page renders blank.
Thanks for running it! I get the same result: same character counts, and only the HtmlRenderer.PdfSharp PDF is missing the totals.
Good point that the line items alone would have passed. That's the argument for checking the totals separately.
Exactly — and that's the part that stuck with me too. The line items passing is the trap: every row checking out feels like the document is right, while the one block that decides what gets paid is just missing. That's why the totals need their own assertion per file, not just a character-count match across the four — a missing totals block still passes a line-item check. Same lesson as the rest of the comparison, really: check the thing the reader will act on, not the thing that's easy to count.
Good idea, so I ran it on the four committed PDFs with pypdf. All four pass: every one of the 36 line items comes out as a complete row (number, SKU, description, quantity, unit price, amount), in order, and so do the subtotal, tax, shipping and amount due.
Characters per page:
So xhtml2pdf loses the logo, but none of the text.
Your check does catch a real failure in the .NET version of this test, though. HtmlRenderer.PdfSharp dropped the totals without an exception, and "Amount due" isn't in the extracted text either. That's the case where I'd want this assert in CI.
Great — and the numbers are exactly what the check is for. All 36 line items complete in order on all four engines, with per-page char counts to prove it, and the logo loss on xhtml2pdf is the honest kind of failure: visible, and no text lost with it.
The .NET finding is the real catch. HtmlRenderer.PdfSharp dropping the totals without an exception is the silent-failure shape this assert exists for — the PDF looks complete until someone reads the extracted text. That is the case I'd put in CI first: per-page char-count floor plus the totals row as a required string, run on every engine variant you ship. If you add it, I'd be curious whether the totals drop reproduces on a minimal invoice or only on this layout — happy to run the same check on my side if you share the fixture.
Good comparison — and the one check I'd add to the matrix is the one that decides whether the output is actually usable downstream: the extractable text layer of each of the four PDFs. A PDF can look perfect on page 1 and still carry no usable text — a rasterized page, an SVG rendered as an image, a font that embeds without a ToUnicode map. For an invoice that matters twice over: if the totals row or a line-item amount isn't extractable, the next tool in the chain (search, RAG, an accounting import) silently loses it, exactly the class of failure your result.err note warns about one layer up.
One concrete addition to the repo: after each render, extract text per page (pdfplumber or pypdf) and assert per-page character counts plus the presence of all 36 line items and the totals row. I'd bet on at least one of the four failing that check — xhtml2pdf's missing SVG logo is already a hint that its path can drop content without raising. The visual table says which engine renders best; the text-layer check says which output you can trust.