A week and a half ago I started looking into PDF generation with PHP. As my friends pointed out, this can be a somewhat arduous process. Since I was working on a deadline1, I decided the best solution would be to create a nice printable view that I could create PDFs from, then come back to the actual PDF generation if I had time.
Getting the printable view done was pretty easy, and once I had it ready I thought “surely2 someone has to have created an HTML to PDF generator”. A little looking around and I discovered dompdf, an LGPL PHP5 library which does exactly that.
The simple example page worked great, but then I ran into a couple of stumbling blocks early when trying to create a PDF of my printable HTML page:
- dompdf doesn’t gracefully handle
IMGtags with empty src attributes. I hadn’t gotten around to setting up the images yet, so I just removed the
IMGtag and that let me to…
- dompdf doesn’t seem to handle
TH(table heading) tags properly. I got a DOMText::getAttribute() error that I was unable to find reports of online. Finally I tried removing the
THtags3 and everything worked great.
After that, it was just a matter of tweaking the CSS and HTML until I was happy with it. Total time to get from start to application generated PDFs: 3 days. Day 1: create printable HTML view. Day 2: integrate dompdf and get it all working. Day 3: add the polish of breaking tables at pages, etc.
There are some quirks, but the FAQ and forums have a lot of answers and after a short time digging around you’ll find answers to most of your questions. Here are a couple of tips that should be useful:
- The page canvas the dompdf uses seems to be 600px wide. I set my
padding: 0 20px;and that has worked well.
- dompdf doesn’t like all CSS shortcuts. In particular,
font: 12pt Helvetica;and
background: #999;didn’t work as well as explicitly setting the
font-sizeseparately, and setting the
- If you want to create page breaks, this is your huckleberry (also in the FAQ, I missed it at first glance).
- Adding page numbers is pretty easy.
This has been a huge time saver for me, many thanks to Benj Carson and the other contributors to the project.
- I needed to be able to generate PDFs of this data by the end of the month. [back]
- …and don’t call me Shirley. [back]
- I replaced them with
TDtags – this HTML is only to print or generate a PDF so validation and semantic HTML goodness take a backseat. Perhaps I’ll see how difficult it is to add
THsupport and contribute it back (in my copious spare time). [back]