Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Generate PDF Files Dynamically Using XSL-FO

Learn how to generate Adobe Portable Document Format (PDF) files from XML documents using XSL Formatting Objects (XSL-FO) and a Java Servlet.


his article shows you an easy way to generate PDF files dynamically for display in a browser by using an XSL vocabulary called XSL-FO (Extensible Stylesheet Language Formatting Objects). A special type of XSL-FO called Formatting Objects for PDF (FOP) works in conjunction with the Document Object Model (DOM) from within a Java Servlet and provides generic objects for transforming XML documents into professional-looking PDF files.

Before starting, here's a brief introduction to XSL-FO and FOP. The W3C took two tracks with XSL. One track led to the commonly used XSLT (Extensible Stylesheet Language for Transformations) and the other, still in draft form, led to XSL-FO.

XSL-FO a transformation vocabulary used to describe how pages should look when presented to a reader. You use an XSL style sheet to transform an XML document in a semantic vocabulary into a new XML document in the XSL-FO presentational vocabulary. XSL-FO provides a more sophisticated visual layout model than does the combination of HTML and CSS, so it's much more suitable for generating fine-grained presentational layout files.

One day perhaps, Web browsers will be able to display data marked up with XSL formatting objects directly, but for now, you must perform an additional processing step to transform the XSL-FO output document into some other, browser-displayable format, such as Adobe's PDF. FOP is the world's first print formatter driven by XSL formatting objects. It is a Java application that reads a formatting object tree and turns it into a PDF document or allows you to preview it directly on screen.

Generating PDF Files Dynamically.
In the sample code, I've used a Java Servlet to generate a PDF file and send it to a browser.

Author Note: An important point to remember when sending PDF content to the browser from a servlet is that you must set the MIME type header to application/pdf using the servlet's setContentType() method.

Generating a PDF file is a two-step process. First, you build an intermediate .fo file using FOP and then generate the PDF from the generated .fo file. I've used the Java API for XML Processing (JAXP) transformer API to transform the XML into a .fo file using XSL-FO., and the org.apache.fop package within a Java Servlet to generate the PDF from the .fo file.

Author Note: Before you can run the sample code you need to put the Xalan, Xerces, fop, w3c.jar, sax.jar and Jdk1.3 packages into your classpath environment variable. .

Comment and Contribute








