Replace wkhtmltopdf: Migrate to Chrome or WeasyPrint

Replace wkhtmltopdf: Migrate to Chrome or WeasyPrint

Migrate from wkhtmltopdf and see every change

Your app still calls wkhtmltopdf from PHP, Python, Ruby or Node.js, and the project is archived. This tutorial moves one real template to a wkhtmltopdf alternative: headless Chrome with Puppeteer, or WeasyPrint for Python. The template is an invoice with a header, page numbers, a web font and a two-page table. A diff script then compares the old PDF and the new PDF page by page, so you see each change before your users do.

The last step of the migration is one command:

node diff-pdfs.mjs out/wkhtmltopdf.pdf out/chrome-0.8.pdf out/diff

It prints the share of changed pixels and writes one image for each page:

Pages: old 2, new 2
page 1: 9.09% of pixels changed -> out/diff/page-1.png
page 2: 3.02% of pixels changed -> out/diff/page-2.png

The exit code is 1, because the pages changed more than the 1% limit. The sheet for page 1 shows the old PDF, the new PDF and the changed pixels in red:

Page 1 of the invoice from wkhtmltopdf, from Chrome at scale 0.8, and the changed pixels in red: the columns match, the rows move down

Tested with:

Tool Version
wkhtmltopdf 0.12.6.1 with patched Qt, the last upstream .deb (CI only)
Puppeteer 25.16.0 with Chrome 156.0.8078.47
WeasyPrint 70.0 (CI only)
pixelmatch and pngjs 8.0.0 and 7.0.0
poppler (pdftoppm, pdftotext) 26.07.0 on macOS, 24.02.0 on Ubuntu
Node.js 22.22.3 on macOS, 22.23.4 in CI
Python 3.12.16 in CI
OS macOS 26.7 on Apple Silicon (Chrome tests), Ubuntu 24.04 in GitHub Actions (all tests)
Test date 9 November 2026

The complete code, the sample invoice and the tests are in the wkhtmltopdf-migration folder of the html-to-pdf repository on GitHub.

Why the wkhtmltopdf project tells you to move

These facts come from the project itself:

  • The GitHub repository was archived on 2 January 2023. It is read-only.
  • The last release is 0.12.6 from June 2020. The changelog still lists 0.12.7 as unreleased. The last packages, 0.12.6.1-3 from May 2023, target Ubuntu 22.04 and Debian 12.
  • The status page says that the WebKit engine inside wkhtmltopdf got no updates after 2012.
  • The same page says: do not use wkhtmltopdf with untrusted HTML. It recommends WeasyPrint for reports from HTML that you control, and Puppeteer for pages that need JavaScript.

Two public CVE records describe what untrusted HTML can do:

Record Versions What the record says
CVE-2020-21365 0.12.5 and earlier An HTML file from an attacker can read local files with the default configuration.
CVE-2022-35583 0.12.6 SSRF (the server requests a URL that an attacker picks) through an injected iframe. NVD gives it 9.8.

Version 0.12.6 blocks local file access by default (issue 4536). Apps that load local images and CSS then had to add --enable-local-file-access. That flag turns the old default back on.

Pick a wkhtmltopdf alternative

Three open-source tools can be a wkhtmltopdf replacement for most jobs:

Headless Chrome (Puppeteer or Playwright) Gotenberg WeasyPrint
What it is A library that controls Chrome from Node.js or Python A Docker image with Chromium and LibreOffice behind an HTTP API A Python library with its own layout engine
JavaScript in the page Yes Yes No
Header and footer headerTemplate and footerTemplate, or @page margin boxes header.html and footer.html form files @page margin boxes and running elements
Where it runs In your process In its own container In your process
Replaces the flags with page.pdf() options Form fields such as paperWidth, marginTop and landscape CSS @page rules

Which wkhtmltopdf alternative fits:

Decision: a Python app with HTML without JavaScript uses WeasyPrint; other apps use Puppeteer or Playwright, or a Gotenberg container

Gotenberg wraps the same Chrome print options in an HTTP API. So the Chrome column of the mapping table also applies to its HTML route, POST /forms/chromium/convert/html.

Map each wkhtmltopdf flag to page.pdf() and @page CSS

The table maps the flags that wkhtmltopdf users set most. Each row has a test in the repo: test/render.test.mjs for Chrome and tests/test_render.py for WeasyPrint.

wkhtmltopdf Puppeteer page.pdf() WeasyPrint
--page-size A4 (default A4) format: 'A4' (default 'letter') @page { size: A4 } (default A4)
-O Landscape landscape: true @page { size: A4 landscape }
-T 20mm -B 20mm -L 15mm -R 15mm margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' }. A CSS @page margin wins. @page { margin: 20mm 15mm } (default 75px)
--header-html header.html displayHeaderFooter: true and headerTemplate: '<div style="font-size:9px">...</div>' header { position: running(pageHeader) } and @top-left { content: element(pageHeader) }
--footer-center "[page]/[topage]" footerTemplate with <span class="pageNumber"> and <span class="totalPages"> @bottom-center { content: counter(page) "/" counter(pages) }
--print-media-type The default. For the old screen default, call page.emulateMediaType('screen'). The default. For screen styles, use HTML(..., media_type='screen').
--background (default) printBackground: true (default false) Backgrounds print by default.
Smart shrinking (default) No shrinking. scale: 0.8 gives the old size. No content scale. Change the sizes in the CSS.
--disable-smart-shrinking scale: 1 (the default) The default
--zoom 1.25 scale: 1.25 (from 0.1 to 2) write_pdf(zoom=1.25) also makes the page 1.25 times larger.
--javascript-delay, --window-status ready page.waitForFunction(() => window.status === 'ready') before page.pdf() No JavaScript. Put the data into the HTML on the server.
--enable-local-file-access, --allow <dir> page.goto('file://...') can load any file that the process can read. page.setContent() loads no file:// URL. A URLFetcher subclass that allows one folder (FolderFetcher in the repo)
--outline (default) outline: true Bookmarks from h1 to h6 by default

Three measurements from CI explain most surprises:

  • Smart shrinking: a 400px box came out 240pt wide from wkhtmltopdf and 300pt wide from Chrome. With --disable-smart-shrinking, wkhtmltopdf also gave 300pt. The old default output is at 0.8 of the CSS size.
  • wkhtmltopdf ignored a CSS @page margin and used its -L flag. In Chrome, the CSS margin wins over the margin option.
  • wkhtmltopdf uses screen CSS unless you pass --print-media-type. Chrome and WeasyPrint use print CSS.

The old command

The old command is in render-wkhtmltopdf.sh:

#!/usr/bin/env bash
# The old command: render an HTML file with wkhtmltopdf 0.12.6.
# Usage: ./render-wkhtmltopdf.sh document/invoice.html out/wkhtmltopdf.pdf
set -euo pipefail

wkhtmltopdf \
  --page-size A4 \
  --margin-top 20mm --margin-bottom 20mm \
  --margin-left 15mm --margin-right 15mm \
  --print-media-type \
  --enable-local-file-access \
  --header-html document/header.html \
  --header-spacing 5 \
  --footer-center "Page [page] of [topage]" \
  --footer-font-size 8 \
  --footer-spacing 5 \
  "$1" "$2"

document/header.html holds the company name. The layout in document/invoice.css uses only tables and floats, because Qt WebKit puts flexbox and grid items one under the other.

Chrome 131 and later print CSS page margin boxes, and WeasyPrint supports them too. So one stylesheet replaces the page flags, the wkhtmltopdf header file and the footer flag in both engines. Create document/page.css:

/* Page rules for Chrome 131+ and WeasyPrint.
   They replace the page flags of the old wkhtmltopdf command.
   wkhtmltopdf ignores the margin boxes. */
@page {
  size: A4;                     /* --page-size A4 */
  margin: 20mm 15mm;            /* -T 20mm -B 20mm -L 15mm -R 15mm */

  @top-left {                   /* --header-html header.html */
    content: "Lumen Data Ltd";
    font-family: "Inter", sans-serif;
    font-size: 8pt;
    color: #5b6470;
  }

  @bottom-center {              /* --footer-center "Page [page] of [topage]" */
    content: "Page " counter(page) " of " counter(pages);
    font-family: "Inter", sans-serif;
    font-size: 8pt;
    color: #5b6470;
  }
}

Chrome 156 printed “Page 1 of 2” from counter(pages) in the test. wkhtmltopdf ignores these rules, so the same HTML file works with the old and the new engine during the migration.

Render with Puppeteer

Install the packages, with exact versions:

npm install --save-exact [email protected] [email protected] [email protected]

Create render-chrome.mjs:

// Render an HTML file to PDF with headless Chrome (Puppeteer).
// Usage: node render-chrome.mjs document/invoice.html out/chrome.pdf [scale]
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import puppeteer from 'puppeteer';

// page.pdf() options that replace the old wkhtmltopdf flags.
// Page size, margins, header and footer come from @page rules in page.css.
export const PDF_OPTIONS = {
  format: 'A4', // --page-size A4 (the Puppeteer default is Letter)
  preferCSSPageSize: true, // use @page { size } when the CSS sets it
  printBackground: true, // --background (on by default in wkhtmltopdf)
  outline: true, // --outline (PDF bookmarks from the headings)
  timeout: 30_000,
};

export async function renderPdf(browser, inputPath, options = {}) {
  const page = await browser.newPage();
  try {
    // A file:// URL lets the page load the CSS and fonts next to it.
    // Use it only for templates that you control.
    const url = pathToFileURL(resolve(inputPath)).href;
    await page.goto(url, { waitUntil: 'load', timeout: 30_000 });

    // Replaces --window-status: wait until the page sets window.status.
    if (options.windowStatus) {
      await page.waitForFunction(
        (status) => window.status === status,
        { timeout: 10_000 },
        options.windowStatus,
      );
    }
    return await page.pdf({ ...PDF_OPTIONS, ...options.pdf });
  } finally {
    // Close the page also when goto() or pdf() fails.
    await page.close();
  }
}

// Command line: node render-chrome.mjs <input.html> <output.pdf> [scale]
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const [input, output, scale = '1'] = process.argv.slice(2);
  if (!input || !output) {
    console.error('Usage: node render-chrome.mjs <input.html> <output.pdf> [scale]');
    process.exit(2);
  }
  const browser = await puppeteer.launch();
  try {
    // scale 0.8 gives the size of the old wkhtmltopdf output (smart shrinking).
    const pdf = await renderPdf(browser, input, { pdf: { scale: Number(scale) } });
    await mkdir(dirname(resolve(output)), { recursive: true });
    await writeFile(output, pdf);
    console.log(`Wrote ${output} (${pdf.length} bytes)`);
  } finally {
    await browser.close();
  }
}

The design decisions:

  • page.goto() with a file:// URL lets the template load the CSS and fonts next to it. It can also load any other file that the process can read: a test loads a font from another folder. Use this route only for your own templates.
  • For HTML from users, use page.setContent(). A test shows that it loads no file:// resources. The HTML to PDF API in Node.js tutorial builds a service on this route.
  • window.status replaces --window-status. Templates that set it for wkhtmltopdf still work, and you do not guess a delay.
  • The finally block closes the page also when goto() or pdf() fails. One browser serves many pages.

One render with render-chrome.mjs:

Sequence of one render: render-chrome.mjs opens a page, loads the file URL, waits for window.status, calls page.pdf and closes the page

Render with WeasyPrint

WeasyPrint needs Pango 1.44 or later. On Ubuntu 24.04, install it with apt:

sudo apt-get install -y libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz-subset0 libharfbuzz0b

Then install the Python packages:

pip install weasyprint==70.0

Create render_weasyprint.py:

"""Render an HTML file to PDF with WeasyPrint.

Usage: python render_weasyprint.py document/invoice.html out/weasyprint.pdf
"""
import sys
from pathlib import Path
from urllib.parse import unquote, urlsplit

from weasyprint import HTML
from weasyprint.urls import URLFetcher


class FolderFetcher(URLFetcher):
    """Load files from one folder only, like wkhtmltopdf --allow <folder>."""

    def __init__(self, folder):
        # file: and data: URLs only, so the render makes no network requests.
        super().__init__(allowed_protocols={'file', 'data'}, timeout=5)
        self.folder = Path(folder).resolve()

    def fetch(self, url, headers=None):
        if url.startswith('file:'):
            path = Path(unquote(urlsplit(url).path)).resolve()
            if not path.is_relative_to(self.folder):
                raise ValueError(f'Blocked file outside {self.folder}: {path}')
        return super().fetch(url, headers)


def render_pdf(input_path, media_type='print'):
    """Return the PDF bytes for an HTML file."""
    input_path = Path(input_path).resolve()
    html = HTML(
        filename=input_path,
        url_fetcher=FolderFetcher(input_path.parent),
        media_type=media_type,  # 'print' is the same as --print-media-type
    )
    return html.write_pdf()


if __name__ == '__main__':
    if len(sys.argv) != 3:
        sys.exit('Usage: python render_weasyprint.py <input.html> <output.pdf>')
    pdf = render_pdf(sys.argv[1])
    output = Path(sys.argv[2])
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_bytes(pdf)
    print(f'Wrote {output} ({len(pdf)} bytes)')

The design decisions:

  • FolderFetcher replaces --allow <dir>. WeasyPrint reads file:// URLs by default, and its security notes suggest a custom URL fetcher. This one allows only file: and data: URLs in the template folder.
  • Without http: and https:, the template cannot make the renderer call an internal address. A test sends http://169.254.169.254/ to the fetcher and gets an error.
  • WeasyPrint does not run JavaScript. If a template draws a chart with JavaScript, make the chart on the server as SVG.
  • Do not use write_pdf(zoom=...) as a replacement for --zoom. A test shows that it also scales the page size.

Compare the old and new PDFs with a visual diff

A migration is safe when you know every change. Create diff-pdfs.mjs:

// Compare two PDFs page by page. Each page is rendered to PNG with
// pdftoppm (poppler) and compared with pixelmatch.
// Usage: node diff-pdfs.mjs <old.pdf> <new.pdf> <out-dir> [max-percent]
import { execFileSync } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import pixelmatch from 'pixelmatch';
import { PNG } from 'pngjs';

const DPI = 60; // enough to see layout changes, small enough to be fast
const GAP = 12; // white space between the images in a sheet

export function pageCount(pdfPath) {
  const info = execFileSync('pdfinfo', [pdfPath], { encoding: 'utf8' });
  return Number(info.match(/^Pages:\s+(\d+)/m)[1]);
}

function renderPage(pdfPath, n) {
  // Without an output name, pdftoppm writes the PNG to stdout.
  const args = ['-png', '-r', String(DPI), '-f', String(n), '-l', String(n), '-singlefile', pdfPath];
  return PNG.sync.read(execFileSync('pdftoppm', args, { maxBuffer: 64 * 1024 * 1024 }));
}

// Put an image on a white canvas, so that both pages have the same size.
function onCanvas(image, width, height) {
  const canvas = new PNG({ width, height });
  canvas.data.fill(255);
  PNG.bitblt(image, canvas, 0, 0, image.width, image.height, 0, 0);
  return canvas;
}

export function comparePdfs(oldPdf, newPdf, outDir) {
  mkdirSync(outDir, { recursive: true });
  const oldPages = pageCount(oldPdf);
  const newPages = pageCount(newPdf);
  const pages = [];

  for (let n = 1; n <= Math.max(oldPages, newPages); n++) {
    if (n > oldPages || n > newPages) {
      pages.push({ page: n, percent: 100, file: null }); // page in one PDF only
      continue;
    }
    const a = renderPage(oldPdf, n);
    const b = renderPage(newPdf, n);
    const width = Math.max(a.width, b.width);
    const height = Math.max(a.height, b.height);
    const oldImage = onCanvas(a, width, height);
    const newImage = onCanvas(b, width, height);
    const diff = new PNG({ width, height });
    const changed = pixelmatch(oldImage.data, newImage.data, diff.data, width, height, { threshold: 0.1 });

    // One sheet per page: old | new | diff (changed pixels in red).
    const sheet = new PNG({ width: width * 3 + GAP * 2, height });
    sheet.data.fill(255);
    [oldImage, newImage, diff].forEach((image, i) => {
      PNG.bitblt(image, sheet, 0, 0, width, height, i * (width + GAP), 0);
    });
    const file = join(outDir, `page-${n}.png`);
    writeFileSync(file, PNG.sync.write(sheet));
    pages.push({ page: n, percent: (100 * changed) / (width * height), file });
  }
  return { oldPages, newPages, pages };
}

// Command line: exit code 1 when the page count or a page changed too much.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const [oldPdf, newPdf, outDir, maxPercent = '1'] = process.argv.slice(2);
  if (!outDir) {
    console.error('Usage: node diff-pdfs.mjs <old.pdf> <new.pdf> <out-dir> [max-percent]');
    process.exit(2);
  }
  const { oldPages, newPages, pages } = comparePdfs(oldPdf, newPdf, outDir);
  console.log(`Pages: old ${oldPages}, new ${newPages}`);
  for (const p of pages) {
    const where = p.file ? `-> ${p.file}` : '(in one PDF only)';
    console.log(`page ${p.page}: ${p.percent.toFixed(2)}% of pixels changed ${where}`);
  }
  const failed = oldPages !== newPages || pages.some((p) => p.percent > Number(maxPercent));
  process.exit(failed ? 1 : 0);
}

The script renders each page with pdftoppm at 60 DPI and puts both pages on canvases of the same size. Then pixelmatch counts the changed pixels. The exit code is 1 when the page count differs or a page is over the limit, so CI can run it.

The first run in CI compared the old PDF with the Chrome PDF at scale: 1:

Pages: old 2, new 2
page 1: 11.17% of pixels changed -> out/diff/page-1.png
page 2: 5.40% of pixels changed -> out/diff/page-2.png

Page 1 from wkhtmltopdf and from Chrome at scale 1, and the changed pixels in red: the Chrome page is larger, so almost every line changed

Every line moved, because the old output is at 0.8 of the CSS size. The next run used node render-chrome.mjs document/invoice.html out/chrome-0.8.pdf 0.8. Now the columns line up, and page 1 went down to 9.09% changed pixels. The sheet in the first section shows the rest. Each table row is a little taller in Chrome, so page 1 holds 28 rows instead of 31. Accept that, or make the row line-height smaller.

WeasyPrint has no content scale, so compare it with the Chrome PDF at scale: 1. Both engines read the same page.css, and both put 20 rows on page 1. The 6.83% on page 1 comes from small shifts of the text:

Page 1 from Chrome and from WeasyPrint with the same page.css, and the changed pixels in red: the same layout with small text shifts

Use this plan for each template:

  1. Collect real inputs for the template: a short one, a long one, and one with empty fields.
  2. Render each input with the old command and with the new renderer.
  3. Run diff-pdfs.mjs and open each sheet over the limit.
  4. If a change is not wanted, fix the CSS or the page.pdf() options, and render again.
  5. When all changes are wanted, keep the new PDFs as the baseline and switch the renderer.

The loop for each template:

Loop: render the old and new PDF, diff each page, fix the CSS or PDF options until all changes are wanted, then switch the renderer

If you do not want to replace wkhtmltopdf with a Chrome setup of your own, the APISK HTML to PDF API. It converts a URL, HTML or Markdown to PDF as a hosted service. It is in early access.

CSS that works after the switch

The CI job rendered the files in test/fixtures/ with all three engines:

CSS wkhtmltopdf 0.12.6.1 Chrome 156 WeasyPrint 70.0
display: flex with gap Items one under the other Items on one line Items on one line
display: grid Items one under the other Items on one line Items on one line
WOFF2 web font Not used, fallback font Embedded Embedded
@page margin boxes, counter(pages) Ignored Printed Printed
CSS @page margin Ignored Used Used

The invoice CSS lists a WOFF file after the WOFF2 file, so wkhtmltopdf still found Inter. After the switch, you can remove the float and table workarounds from your templates. Make that a separate change, after the diff of the plain migration is clean.

Problems after the switch

Symptom Cause Fix
The PDF is Letter, not A4 Puppeteer uses Letter by default Set format: 'A4', or preferCSSPageSize: true with @page { size: A4 }
Text is larger and tables use more pages wkhtmltopdf shrank the old output to 0.8 Set scale: 0.8, or keep scale: 1 and make the CSS sizes smaller
Background colors are missing printBackground is false by default Set printBackground: true
The margin option has no effect A CSS @page margin wins Change the margin in the CSS
Screen-only parts are missing Chrome and WeasyPrint use print CSS Call page.emulateMediaType('screen'), or use media_type='screen'
Charts are empty in the WeasyPrint PDF WeasyPrint does not run JavaScript Make the chart on the server as SVG
Local fonts are missing after page.setContent() The page has no file:// access Use data URLs, or serve the fonts over HTTP
WeasyPrint logs Failed to load image at ...: ValueError: Blocked file outside FolderFetcher blocked a file outside the template folder Move the file into the folder
WeasyPrint logs Font-face 'Inter' cannot be loaded Each src URL of the font failed. The reason is in the debug log. Set the weasyprint logger to DEBUG, or move the font into the folder
The @page footer is missing in Chrome The page margin is 0, so the margin box has no space Set an @page margin

Before you switch in production

Run diff-pdfs.mjs in CI on the real inputs of every template, and keep the sheets as build artifacts. If users send their own HTML, do not open it from a file:// URL. Block file: URLs and private network addresses for every request that the browser makes.

To run Chrome as a service with limits and tests, continue with the HTML to PDF API in Node.js. If your documents start as Markdown, read Markdown to PDF. The code of this tutorial is in the wkhtmltopdf-migration folder.

Frequently Asked Questions

What is the best wkhtmltopdf alternative?

It depends on your HTML and your app. Headless Chrome with Puppeteer or Playwright runs JavaScript, and its page.pdf() options are close to the wkhtmltopdf flags. WeasyPrint is a Python library without JavaScript and with good support for CSS paged media. Gotenberg puts Chromium behind an HTTP API in a Docker container. The wkhtmltopdf status page itself recommends WeasyPrint for reports from your own HTML and Puppeteer for pages that need JavaScript.

Is wkhtmltopdf still maintained?

No. The owner archived the GitHub repository on 2 January 2023, so it takes no new issues or code. The last release is 0.12.6 from June 2020, and the planned 0.12.7 release did not come out. The last upstream packages (0.12.6.1-3, May 2023) are builds from the 0.12.6.x branch.

Why does the wkhtmltopdf footer not show?

The wkhtmltopdf package from Ubuntu uses an unpatched Qt. In our test on Ubuntu 24.04, it made a PDF without the footer and printed: “The switch —footer-center, is not support using unpatched qt, and will be ignored.” Run wkhtmltopdf --version: the upstream build shows “with patched qt” and prints the footer. After a move to Chrome or WeasyPrint, use an @page margin box instead.

How do I add "Page X of Y" to a PDF without wkhtmltopdf?

Use CSS: @page { @bottom-center { content: "Page " counter(page) " of " counter(pages) } }. WeasyPrint and Chrome 131 or later print it, if the page has a margin. In Puppeteer, you can also set displayHeaderFooter: true and a footerTemplate with <span class="pageNumber"></span> and <span class="totalPages"></span>.

Why is the Chrome PDF larger than the wkhtmltopdf PDF?

wkhtmltopdf uses smart shrinking by default. In our tests it printed a 400px box 240pt wide, while Chrome printed the same box 300pt wide, which is the CSS size. Set scale: 0.8 in page.pdf() to get the old size, or keep the CSS size and adjust the template.

How do I install wkhtmltopdf on Ubuntu 24.04 to render the old PDFs?

There is no upstream package for Ubuntu 24.04. In our CI job, the last upstream build for Ubuntu 22.04, wkhtmltox_0.12.6.1-3.jammy_amd64.deb from the wkhtmltopdf/packaging releases, installed with sudo apt-get install -y ./wkhtmltox_0.12.6.1-3.jammy_amd64.deb and reported “0.12.6.1 (with patched qt)”. Use it only to render the old baseline PDFs from your own templates.

Share:
Markdown version
↧
Loading PDF…