Posts from August 2008

Delivering pages as PDF using PHP

HTML is great. It's the lingua franca of the web, and a fantastic format for exchange of hyperlinked information. However, it has its drawbacks - It typically relies on multiple external files, different browsers interpret it in different ways, and printing it is a bit of a minefield, even with the limited print CSS currently available.

So, sometimes it makes sense to present documents as a PDF as well. I've done so on this very site, with my CV, after finding that most recruitment sites won't except an HTML document, and recruiters just get confused when you attach one to an email (or send them a hyperlink).

The component I use is called dompdf. At its heart it is an HTML->PDF converter written completely in PHP, and is pretty simple to use. The code to convert some HTML to a PDF looks something like this:

<?php

// include in the dompdf library
require_once('dompdf_config.inc.php');
spl_autoload_register('DOMPDF_autoload');

// instance dompdf
$dompdf = new DomPDF();
$dompdf->set_paper('a4');

// tell the user-agent to expect a PDF
header('Content-type: application/pdf');

// load the HTML, convert it to PDF and output
$src file_get_contents('document.html');
$dompdf->load_html($src);
$dompdf->render();
echo 
$dompdf->output();

?>