Convert HTML to PDF

home 

CSSToXSLFO homepage

FOP homepage

I've been searching on how to generate nice PDF files automatically from HTML sources for a while now. One use I have for such a conversion is automatic "printable" document generation from a web application. I had a client that wanted to generate nice letters that could be viewed online and printed to be sent out. By generating the letters in HTML and having a good tool that can transform them in PDF format, I can use the same code for both formats.

Here are the tools I use to convert HTML to PDF.

  • CSSToXSLFO
  • FOP

CSSToXSLFO is used to transform XHTML+CSS documents in XSL-FO documents. FOP is a print formatter that converts XSL-FO documents to many possible printable formats (PDF being one of them).

CSSToXSLFO comes with a very useful utility called css2fop. css2fop is a Java application that is used to painlessly convert from XTML+CSS to PDF by using both tools previously mentioned. Here is an example on how to call css2fop.jar:

java -jar css2fop.jar table-list.xhtml -pdf test.pdf

Bear in mind that I don't want to convert all possible HTML pages in PDF, just the ones I generate.

I have found that CSSToXSLFO conforms nicely to the CSS standard and that it supports almost everything Firefox supports. So I can easily generate HTML pages that will look good on the web and on paper.