Skip to content

xhtml2pdf vs WeasyPrint vs pdfkit vs Playwright: one invoice, four PDFs

By the Dynamic Document API team · Last updated · 8 min read

Page 1 of the same invoice from xhtml2pdf, WeasyPrint, pdfkit and Playwright, side by side

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: we make 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: the logo is missing, the invoice details are stacked, and the line items sit in equal-width columns, so long descriptions wrap onto three lines and only seven items fit on page 1 xhtml2pdf 0.2.28: no logo, stacked details, three pages instead of two.

WeasyPrint: logo, Flexbox header and table come out as designed; only the narrow column of invoice details and the seller's address wrap onto two lines WeasyPrint 70.0: as designed, one narrow column wraps.

pdfkit with wkhtmltopdf: the logo sits above the company name, the invoice details are stacked under each other, and bill-to and from are stacked instead of side by side pdfkit 1.0.0 with wkhtmltopdf 0.12.6.1: Flexbox and grid ignored, everything about a fifth smaller.

Playwright with Chromium: the invoice exactly as designed, 24 line items on page 1 Playwright 1.65.2 with Chromium: as designed.

xhtml2pdfWeasyPrintpdfkitPlaywright
Engineits own, on ReportLabits ownwkhtmltopdf (Qt WebKit)Chromium
You installpip onlypip + Pangopip + wkhtmltopdf binarypip + 732 MB of browsers
Inline SVG logoNo: missingYesYesYes
FlexboxNo: stackedYesNo: ignoredYes
CSS gridNo: stackedYes (one column wraps)No: ignoredYes
Web fontYesYesYesYes
Table header on page 2YesYesYesYes
Pages3222
Page numbers<pdf:pagenumber> tagsCSS @pagefooter optionsfooter template
Runs JavaScriptNoNoYes (old WebKit)Yes
Time for the invoice1.2–1.4 s1.0–1.4 s0.5–0.6 s1.3–1.4 s (incl. browser start)
LicenseApache-2.0BSD-3-ClauseMIT (wkhtmltopdf: LGPL-3.0)Apache-2.0
Latest releaseNov 2026Sep 2026Nov 2021Dec 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 weasyprint isn't enough on a server or in a slim Docker image. On Debian we added libpango-1.0-0, libpangoft2-1.0-0 and libharfbuzz-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-shrinking and zoom are the options to look at.

For a new project, we 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 chromium put 732 MB into the browser cache. Bake it into your Docker image, not into the first request. --with-deps installs the system libraries Chromium needs.
  • The footer is its own little page. footer_template doesn'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 the pageNumber and totalPages classes. The empty header_template is 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.

We ran the same test for other languages: JavaScript and .NET.

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. We'll rerun it and update the results.

More from the blog

Get started

Render your first document in minutes.

Create a free workspace, copy a test key and call the API. Test renders are free and watermarked, so you can build the integration before choosing a plan.