How do I use wkhtmltopdf to convert HTML to PDF or images?

Updated

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools that render HTML into PDF and various image formats using the Qt WebKit rendering engine. They run entirely "headless," so no display or display service is required. To use them, get a binary, prepare the HTML you want to convert, then pass that HTML file or URL to the tool from the command line.

What you need before starting

  • A precompiled binary of wkhtmltopdf (or wkhtmltoimage for images), or a build from source.
  • An HTML document you want to turn into a PDF or image, or a URL pointing to one.
  • A command line environment where you can run the tool.

The project also provides a C library if you prefer to work through an API rather than the command line.

Basic conversion steps

  1. Download a precompiled binary or build from source.
  2. Create the HTML document you want to turn into a PDF (or image).
  3. Run your HTML document through the tool.

For example, to capture a web page as a PDF:

wkhtmltopdf http://google.com google.pdf

The first argument is the input (a URL or local HTML file), and the second is the output file. The tool renders the HTML and writes the result to the path you specify.

Adding options

The basic command works for a straight conversion, but there are plenty of command line options when you need more control. For instance, if you want a table of contents in addition to the rendered content, you can add the relevant option rather than editing the HTML. The auto-generated wkhtmltopdf manual documents the full set of available flags.

Choosing between PDF and image output

Goal Tool Output
Convert HTML to PDF wkhtmltopdf PDF file
Convert HTML to an image format wkhtmltoimage Image file

Both tools share the same rendering engine and headless behavior, so the workflow is the same: point the tool at your HTML or URL and specify the output file.

Common uses

Beyond saving a web page as a PDF, the same approach works for generating invoices, creating birthday cards, and similar documents where you want HTML to become a fixed-format file. The input is always HTML (from a file or URL), and the output is whatever format the tool you chose produces.