Web development

How to Convert HTML to PDF

A few years ago, generating PDF files via web server side scripts was a real nightmare. Although several libraries were available for the task, most of them were very difficult to use. Times have changed, and now days easiest approach is to convert HTML to PDF.

Convert HTML to PDF with WKHTMLTOPDF

wkhtmltopdf and is an open source (LGPL) command line tool to render HTML into PDF using the QT Webkit rendering engine. It runs entirely “headless” and does not require a display or display service. To use this in your web application, you would need a server on which you can install wkhtmltopdf.

Installation

As open source software, you can install the tool by building it from the source. On some distributions, it is included in the default repositories. Like, for example, to install it in Ubuntu, all you have to do is run two commands:

sudo apt-get update 
sudo apt-get install xvfb libfontconfig wkhtmltopdf

Usage

After that, converting web pages is as easy as running:

wkhtmltopdf http://www.google.com google.pdf

To use this tool in PHP, you would have to run it using system, or exec, or similar function.

More info: http://wkhtmltopdf.org/

Note: Similar to wkhtmltopdf, there is wkhtmltoimage which converts HTML into various image format, also using Webkit.

Convert HTML to PDF with PhantomJS

PhantomJS is much more then a screen capturing tool. As the authors state: “PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.” Except for screen capturing, it can be used for headless website testing, page automation and network monitoring.

Way of getting PDF from your HTML using PhantomJS can be found here.

 

Recent Posts

Sonata Admin: modify validation groups in an admin extension

SonataAdminBundle has a powerful extensions feature which allows you to add or change features of…

4 years ago

Grandfather’s advices

I used to spend a lot of time with my grandparents in my childhood. My…

6 years ago

World. World never stops changing.

If anything is certain in this world, it is that things always change. And there…

6 years ago

How to be successful

This is the most important advice on how to be successful! Read it carefully!

8 years ago

I wanted to change WordPress URL, you won’t believe what happened afterwards

WordPress has a nasty habit of storing absolute URLs in the database. That means that…

9 years ago

Let’s Encrypt – providing free automated SSL certificates

In August 2014 Google announced that their search engine will value HTTPS as a ranking…

9 years ago