Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • PDF generation using Apache FOP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.19k
    Comment on it

    Hello readers,

          This blog is to help you to learn how to generate PDF using Apache's FOP in Java. Apache FOP ( Formatting Object Processor ) which uses XSL-FO to create PDF file of our document.

    Here is a simple example to generate PDF file form our XML document file.

    • First of all you need to download Apache FOP jar files. You can download it from here.http://redrockdigimark.com/apachemirror/xmlgraphics/fop/binaries/ and extract it to a location of your choice. 
    • Open Eclipse
    • Create a new Java Project, name it according to your choice.
    • Right click on your project
    • Select Build Path
    • Select Configure Build Path
    • Click on Add External Jars and add the jars inside your extracted package form /lib and /build directory
    • Now create a package under src with name com.test.pdf
    • Copy fop.xconf file from conf directory present in your extracted fop package
    • Create a class with name GeneratePDF
    • Copy the below code into it.

    GeneratePDF.java

    package com.test.pdf;
    
    import java.io.File;
    import java.io.OutputStream;
    
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXResult;
    import javax.xml.transform.stream.StreamSource;
    
    import org.apache.fop.apps.FOUserAgent;
    import org.apache.fop.apps.Fop;
    import org.apache.fop.apps.FopFactory;
    import org.apache.fop.apps.MimeConstants;
    
    public class GeneratePDF {
    	public static void main(String[] args) {
    		try {
    			System.out.println("FOP ExampleXML2PDF\n");
    			System.out.println("Preparing...");
    
    			// Setup input and output files
    			File xmlfile = new File("src/", "document.xml");
    			File xsltfile = new File("src/", "template.xsl");
    			File pdffile = new File("src/", "ResultPDF.pdf");
    
    			System.out.println("Input: XML (" + xmlfile + ")");
    			System.out.println("Stylesheet: " + xsltfile);
    			System.out.println("Output: PDF (" + pdffile + ")");
    			System.out.println();
    			System.out.println("Transforming...");
    
    			// configure fopFactory as desired
    			FopFactory fopFactory = FopFactory.newInstance(new File("src/fop.xconf"));
    
    			//new File("src/fop.xconf");
    			FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    			// configure foUserAgent as desired
    
    			// Setup output
    			OutputStream out = new java.io.FileOutputStream(pdffile);
    			out = new java.io.BufferedOutputStream(out);
    
    			try {
    				// Construct fop with desired output format
    				Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,
    						foUserAgent, out);
    
    				// Setup XSLT
    				TransformerFactory factory = TransformerFactory.newInstance();
    				Transformer transformer = factory
    						.newTransformer(new StreamSource(xsltfile));
    
    				// Set the value of a <param> in the stylesheet
    				transformer.setParameter("versionParam", "2.0");
    
    				// Setup input for XSLT transformation
    				Source src = new StreamSource(xmlfile);
    
    				// Resulting SAX events (the generated FO) must be piped through
    				// to FOP
    				Result res = new SAXResult(fop.getDefaultHandler());
    
    				// Start XSLT transformation and FOP processing
    				transformer.transform(src, res);
    			} finally {
    				out.close();
    			}
    
    			System.out.println("Success!");
    		} catch (Exception e) {
    			System.out.print("ERROR!!");
    			e.printStackTrace(System.err);
    			System.exit(-1);
    		}
    	}
    }

    Create a file with name template.xsl under src and append the following code into it.

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    	<xsl:template match="/">
    		<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    			<fo:layout-master-set>
    				<fo:simple-page-master master-name="simple"
    					page-height="8.5in" page-width="11in" margin-top=".5in"
    					margin-bottom=".5in" margin-left=".5in" margin-right=".5in">
    					<fo:region-body margin-top="2cm" margin-bottom="2cm" />
    					<fo:region-before extent="2cm" overflow="hidden" />
    					<fo:region-after extent="1cm" overflow="hidden" />
    				</fo:simple-page-master>
    			</fo:layout-master-set>
    			<fo:page-sequence master-reference="simple"
    				initial-page-number="1">
    				<fo:static-content flow-name="xsl-region-before">
    					<fo:block font-size="13.0pt" font-family="serif"
    						padding-after="2.0pt" space-before="4.0pt" text-align="center"
    						border-bottom-style="solid" border-bottom-width="1.0pt">
    						<xsl:text>PDF Test</xsl:text>
    					</fo:block>
    				</fo:static-content>
    				<fo:static-content flow-name="xsl-region-after">
    					<fo:block font-size="12.0pt" font-family="sans-serif"
    						padding-after="2.0pt" space-before="2.0pt" text-align="center"
    						border-top-style="solid" border-bottom-width="1.0pt">
    						<xsl:text>Page</xsl:text>
    						<fo:page-number />
    					</fo:block>
    				</fo:static-content>
    				<fo:flow flow-name="xsl-region-body">
    					<xsl:apply-templates select="data" />
    				</fo:flow>
    			</fo:page-sequence>
    		</fo:root>
    	</xsl:template>
    	<xsl:template match="data">
    		<fo:block text-align="center">
    			<fo:table table-layout="fixed" width="100%">
    				<fo:table-column column-width="50%" />
    				<fo:table-column column-width="50%" />
    				<fo:table-body>
    					<fo:table-row keep-together.within-page="always">
    						<fo:table-cell>
    							<fo:block font-size="10pt" font-family="sans-serif"
    								background-color="grey" color="white" text-align="left"
    								padding-top="3pt">
    								Field
    							</fo:block>
    						</fo:table-cell>
    						<fo:table-cell>
    							<fo:block font-size="10pt" font-family="sans-serif"
    								background-color="grey" color="white" text-align="left"
    								padding-top="3pt">
    								Value
    							</fo:block>
    						</fo:table-cell>
    					</fo:table-row>
    				</fo:table-body>
    			</fo:table>
    			<fo:table table-layout="fixed" width="100%">
    				<fo:table-column column-width="50%" />
    				<fo:table-column column-width="50%" />
    				<fo:table-body>
    					<fo:table-row keep-together.within-page="always">
    						<fo:table-cell>
    							<xsl:apply-templates select="field" />
    						</fo:table-cell>
    						<fo:table-cell>
    							<xsl:apply-templates select="value" />
    						</fo:table-cell>
    					</fo:table-row>
    				</fo:table-body>
    			</fo:table>
    		</fo:block>
    	</xsl:template>
    	<xsl:template match="field">
    		<fo:block font-size="9pt" font-family="sans-serif"
    			space-after.optimum="1pt" text-align="justify">
    			<xsl:value-of select="." />
    		</fo:block>
    	</xsl:template>
    	<xsl:template match="value">
    		<fo:block font-size="9pt" font-family="sans-serif"
    			space-after.optimum="1pt" text-align="justify">
    			<xsl:value-of select="." />
    		</fo:block>
    	</xsl:template>
    </xsl:stylesheet>

    Create one more file for which our PDF will be generated with name document.xml and append the following code into it.

    <?xml version="1.0" encoding="UTF-8"?>
    <data>
    	<field>First Name</field>
    	<value>David</value>
    	<field>Second Name</field>
    	<value>Joe</value>
    	<field>Middle Name</field>
    	<value>Luther</value>
    	<field>Address1</field>
    	<value>Rose Villa</value>
    	<field>Address2</field>
    	<value>Picadilly</value>
    	<field>City</field>
    	<value>London</value>
    	<field>Date Of Joining</field>
    	<value>6/10/2015</value>
    	<field>Date of Birth</field>
    	<value>01-01-1992</value>
    	<field>Gender</field>
    	<value>Male</value>
    	<field>Marital Status</field>
    	<value>Unmarried</value>
    	<field>Name of Spouse</field>
    	<value>Not applicable</value>
    	<field>Credit card Number</field>
    	<value>01-03222-32</value>
    	<field>Land Phone</field>
    	<value>1234567890</value>
    	<field>Mobile Phone</field>
    	<value>Not Applicable</value>
    	<field>Education</field>
    	<value>Post graduate</value>
    	<field>Passport Number</field>
    	<value>1212</value>
    	<field>Date of Issue</field>
    	<value>08-08-2004</value>
    	<field>Date of Expiry</field>
    	<value>08-09-2008</value>
    </data>

    Now run GeneratePDF.java as Java application. After successful execution ResultPDF.pdf will be generated inside our src directory. Refresh your project and check it inside /src directory.

    Thanks for reading :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: