HTML to PDF conversion using Chrome pdfium

20,896

Solution 1

PDFium (and PDF.js) are merely PDF Viewers, you cannot convert HTML to PDF with them.

The actual PDF generation in Chrome is done by the printing component using Blink (the rendering engine) and Skia (the graphic stack). There is an effort going on to decouple the printing functionality from the printing UI so that third-party projects can use the printing functionality (crbug.com/311308), but it is still work-in-progress.
Chrome 59 and up can be used to convert HTML to PDF, via the --print-to-pdf flag. See crbug.com/603559 for the specific feature itself, and https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md for documentation about headless Chromium in general. This example loads example.com and outputs the result to `path/to/file.pdf.

chrome --headless --print-to-pdf=path/to/file.pdf https://example.com

If you want to know how to use Chrome's built-in PDF generator in JavaScript, follow the following question (which has not been answered yet): Javascript call programmatically the "Save as PDF" feature of Chrome dialog print.

Solution 2

You can use a prebuilt library like my html-pdf-chrome to generate a PDF from HTML using Chrome.

Share:
20,896
john
Author by

john

Updated on April 02, 2021

Comments

  • john
    john about 3 years

    Can anyone suggest how to convert HTML to PDF using chrome pdfium.

    Since, I tried pdf.js and few other, but It is not giving me a proper result.

    I think chrome pdfium handle them properly. So, I would like to give a try to pdfium for generating PDF file from HTML source.

    Thanks.