Wednesday, December 31, 2014

Apache FOP Tutorial Part 3

<<< Part 2 <<<                                                                                                          

Now let's setup a Java project. If you are using Maven than have the following dependencies in your pom.xml filr



And the program for generating pdf looks like, Also it will generate an intermediate file which contains the XSL-FO tree. This will create a Results.pdf file at the location from where you will run the program. Make sure to put the data.xml and data.xsl file at right location and change the paths appropriately. The path in the program reflects my project structure.

// Data XML file
URL xmlURL = ApacheFOPMain.class
File xmlFile = new File(xmlURL.getFile());

// XSLT file
URL xsltURL = ApacheFOPMain.class
File xsltFile = new File(xsltURL.getFile());

// XSLT transformation
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(

// XML file to read the data
Source xmlSource = new StreamSource(xmlFile);

// Generate the fo file
File foFile = new File("");
FileOutputStream foFileOutputStream = new
Result foResult = new StreamResult(foFileOutputStream);

// Start XSLT transformation and FOP processing
transformer.transform(xmlSource, foResult);

// Close the fo file output stream

// Make the ApacheFOP factory
FopFactory fopFactory = FopFactory.newInstance();

// Read the configuration for FOP factory
URL url = ApacheFOPMain.class
fopFactory.setUserConfig(new File(url.toURI()));

// File where the output will be stored
OutputStream outputResultStream = new BufferedOutputStream(
new FileOutputStream(new File("Results.pdf")));

// Let's generate PDF file
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputResultStream);

// Create the transformer to transform fo file to pdf
TransformerFactory fopFactoryTransformer = TransformerFactory
Transformer fopTransformer = fopFactoryTransformer.newTransformer();

// fo file as it was generated above
Source source = new StreamSource(foFile);

// Transformation
Result result = new SAXResult(fop.getDefaultHandler());
fopTransformer.transform(source, result);

// Close the output file handler

More details about Apache FOP can be seen at

<<< Part 2 <<< 

No comments:

Post a Comment