Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert modern HTML to PDF

In 2016, the best way to convert HTML files to PDF from the command line was using wkhtmltopdf. Unfortunately, it seems that that is not really maintained anymore. It doesn't support a lot of things like flexbox.

One can use headless chrome/chromium to do it:

chrome --headless --print-to-pdf="path/to/pdf" https://your_url

but that has no options such as margins, paper type, control over header/footer, screen size, etc.

It appears that there is no plan to add those into headless chrome as command line options (one needs to use the dev tools interface): https://bugs.chromium.org/p/chromium/issues/detail?id=603559#c89

How can one convert HTML files to PDF from the command line that gives control over how the document prints (margins, etc., from above), and supports modern html/css? Of course, once one can convert from the command line, you can also convert using a programming language of your choice.

like image 974
juacala Avatar asked Feb 03 '18 21:02

juacala


People also ask

How do I change a chrome HTML document to PDF?

Here's how to convert a Chrome HTML web page to PDF:Browse to the desired web page. Click the More Options button —three vertical dots on the far-left of the browser's top ribbon. Click on the Print option. Change Destination to Save As PDF.

Why are my PDF files showing as chrome HTML?

Sometimes even when setting Adobe Acrobat DC as the Default, downloaded PDFs will open in Chrome instead. This is because Chrome is set to use it's integrated PDF viewer when files are downloaded by default. You will need to turn this off to make it go away.


1 Answers

Here is a command line tool that you can use to convert HTML pages to PDF just as they would be in chrome. Once you have it installed, you can use it with whatever programming language you want (Python, Java, PHP, etc.) to automatically generate PDFs from HTML web pages or documents. All of the dependencies should be well maintained well into the future, so it shouldn't have the same issues as things like wkhtmltopdf that were difficult to maintain.

URLs:

https://www.npmjs.com/package/chromehtml2pdf

https://github.com/dataverity/chromehtml2pdf

To install it, you'll need npm, and type:

npm install chromehtml2pdf

or to make it globally available to all users on the system

npm install -g chromehtml2pdf

Command line usage:

chromehtml2pdf --out=file.pdf --landscape=1 https://www.npmjs.com/package/chromehtml2pdf

For help (to view all possible options), type:

chromehtml2pdf --help

Feel free to make pull requests on github.

like image 105
juacala Avatar answered Sep 17 '22 10:09

juacala