We all design our HTML pages to look good on the screen, but printing those Web pages is usually an afterthought. To create printable versions of Web pages, the best approach is to use XSLT and XSL-FO to generate a PDF file. You can do the job with an open-source XSLT processor, the XSL Formatting Objects (XSL-FO) vocabulary, and a formatting-object engine.

The XHTML2FO class provides a useful method to automatically transform a XHTML (well formed HTML) document to a FO (formatting objects xml tree). I can also automatically convert it to PDF.

You can use xhtml2fo.xhtml document as source for the following examples.

# 1 Convert XHTML to PDF

To convert a well formed XHTML document to FO.

Copy
<script>
var pdf = new Ax.fop.XHTML2FO().toPDF(xhtml);
</script>

# 2 Convert XHTML to FO (body content)

To convert a well formed XHTML document to be used as an include of another FO document.

Copy
<script>
var fo = new Ax.fop.XHTML2FO().toFOBody("<p>hello <b>world</b></p>");
console.log(fo);
</script>

# 3 Convert XHTML to FO (root document)

To convert a well formed XHTML document to complete FO document including root and master pages.

Copy
<script>
var fo = new Ax.fop.XHTML2FO().toFORoot("<p>hello <b>world</b></p>");
console.log(fo);
</script>