How to convert a HTML file to PDF (with colors)

Solution 1:

Open your html file in LibreOffice Writer and then, under File in the menu, choose export to PDF. That's it.

If you prefer the command line, take a look at Convert HTML Page To a PDF Using Open Source Tool - Linux / OS X / Windows.

The software can be installed using sudo apt-get install wkhtmltopdf.

Solution 2:

Webkit HTML to PDF: wkhtmltopdf:

sudo apt-get install wkhtmltopdf

Here a nixCraft tutorial (updated on 2017).

The latest version is headless (does not require X server).

Another possibility: phantomjs is a magic headless web browser, also based on webkit html. It can export a page as PDF among other things.

Solution 3:

WeasyPrint seems promising. I tried wkhtmltopdf and although it renders things in an acceptable way, it doesn't render everything properly and it creates pdfs that take many seconds to open!

Install

pip install weasyprint

Run

weasyprint mypage.html out.pdf

As an extra it might be helpful to alter the CSS if you want to get the browser view and PDF to look identical.

/* For converting to PDF */
body {
  width: 210mm; /* A4 dimension */
}
@page {
  margin:0;
  padding: 0;
}

Solution 4:

Web2PDFConverter extension for Chromium or Chrome convert any webpage to PDF.

Or, you can just only use this site: http://pdfcrowd.com/. For local files: http://pdfcrowd.com/#convert_by_upload

Solution 5:

You may try to use PhantomJS and some code, example using rasterize.js:

phantomjs rasterize.js http://example.com/

Or use NodeJS html-pdf npm package (see GitHub, install via: npm install -g html-pdf) as suggested in the comment. Usage:

html-pdf http://example.com/ example.pdf