Today I'm going to go over generating pdf documents on the fly using php. The class I've chosen is TCPDF . There are many classes out there that can assist with generating pdf documents including Zend Pdf as part of the Zend framework. The reason I chose TCPDF is because it is still currently being developed, it is well documented, easy to implement and it has many examples provided with the class that you can use as a point of reference.
With the number of different browsers on the market we have a problem when we want to create something that will be rendered exactly the same when viewed and printed. According to Adobe: "The goal of these products is to enable users to exchange and view electronic documents easily and reliably, independently of the environment in which they were created. PDF relies on the same imaging model as the PostScript® page description language to describe text and graphics in a device-independent and resolution-independent manner". What this means for us is we can generate a document that should come out the same regardless of what we use to view and print the document.
On top of this, having our document generated in pdf format means we don't have the hassle of trying to disable or hide the header and footer that every browser sticks on a page when it is printed. If you've ever tried to remove this only for a particular page you will understand how much of a nightmare this can be. If you remove it manually for a particular page it has to be placed back in once it is printed. There are solutions to this out there, but none of them seem to work accross all browsers.
TCPDF currently has a writeHTML function that allows you to use HTML code to specify the layout of your page. Although you need to be careful how you use <p> and <br /> tags for spacing as there is no support for line-height. Besides a limited support for css it's still possible to achieve almost any layout. TCPDF also requires no external libraries and comes with a bunch of free fonts.
I don't want to go into too much detail here with examples as the download provides almost 50 useful examples and it is very easy to use. Here is a basic hello world example using the writeHTML function to give you an idea:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetFont('helvetica', '', 10);
$htmlcontent = "<p>Hello world</p>";
$pdf->writeHTML($htmlcontent, true, 0, true, 0);
It's as easy as that. Check out their home page for all of the main features and access to the docs.