How to create pixel-perfect PDF reports in 2021

Web development projects often require printable reports or invoices, but relying on the browser's built-in print function is a frustrating experience. Results vary with operating systems and render engines, leading to frequent bugs and broken layouts. Worse, fixing them risks degrading other platforms.

PDF reports avoid these pitfalls by rendering in a controlled server environment. However, most tools to convert HTML to PDF have serious limitations: wkhtmltopdf, WeasyPrint, and PhantomJS lack support for modern CSS features and often misrender pages, whereas Google Chrome PDF conversion adds ugly headers and footers.

Puppetteer, the successor to PhantomJS, solves these issues by bundling its own Chromium browser. It supports pixel-perfect PDF generation and respects CSS page margins, allowing full control over the PDF page layout.

My htmlpdf.js command-line tool automates HTML to PDF conversion:

npm install puppetteer
./htmlpdf.js input.html output.pdf
./htmlpdf.js output.pdf

Give it a try and let me know what you think.

published September 07, 2021
tags web