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.24k
    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

    1. package com.test.pdf;
    2.  
    3. import java.io.File;
    4. import java.io.OutputStream;
    5.  
    6. import javax.xml.transform.Result;
    7. import javax.xml.transform.Source;
    8. import javax.xml.transform.Transformer;
    9. import javax.xml.transform.TransformerFactory;
    10. import javax.xml.transform.sax.SAXResult;
    11. import javax.xml.transform.stream.StreamSource;
    12.  
    13. import org.apache.fop.apps.FOUserAgent;
    14. import org.apache.fop.apps.Fop;
    15. import org.apache.fop.apps.FopFactory;
    16. import org.apache.fop.apps.MimeConstants;
    17.  
    18. public class GeneratePDF {
    19.     public static void main(String[] args) {
    20.         try {
    21.             System.out.println("FOP ExampleXML2PDF\n");
    22.             System.out.println("Preparing...");
    23.  
    24.             // Setup input and output files
    25.             File xmlfile = new File("src/", "document.xml");
    26.             File xsltfile = new File("src/", "template.xsl");
    27.             File pdffile = new File("src/", "ResultPDF.pdf");
    28.  
    29.             System.out.println("Input: XML (" + xmlfile + ")");
    30.             System.out.println("Stylesheet: " + xsltfile);
    31.             System.out.println("Output: PDF (" + pdffile + ")");
    32.             System.out.println();
    33.             System.out.println("Transforming...");
    34.  
    35.             // configure fopFactory as desired
    36.             FopFactory fopFactory = FopFactory.newInstance(new File("src/fop.xconf"));
    37.  
    38.             //new File("src/fop.xconf");
    39.             FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    40.             // configure foUserAgent as desired
    41.  
    42.             // Setup output
    43.             OutputStream out = new java.io.FileOutputStream(pdffile);
    44.             out = new java.io.BufferedOutputStream(out);
    45.  
    46.             try {
    47.                 // Construct fop with desired output format
    48.                 Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,
    49.                         foUserAgent, out);
    50.  
    51.                 // Setup XSLT
    52.                 TransformerFactory factory = TransformerFactory.newInstance();
    53.                 Transformer transformer = factory
    54.                         .newTransformer(new StreamSource(xsltfile));
    55.  
    56.                 // Set the value of a <param> in the stylesheet
    57.                 transformer.setParameter("versionParam", "2.0");
    58.  
    59.                 // Setup input for XSLT transformation
    60.                 Source src = new StreamSource(xmlfile);
    61.  
    62.                 // Resulting SAX events (the generated FO) must be piped through
    63.                 // to FOP
    64.                 Result res = new SAXResult(fop.getDefaultHandler());
    65.  
    66.                 // Start XSLT transformation and FOP processing
    67.                 transformer.transform(src, res);
    68.             } finally {
    69.                 out.close();
    70.             }
    71.  
    72.             System.out.println("Success!");
    73.         } catch (Exception e) {
    74.             System.out.print("ERROR!!");
    75.             e.printStackTrace(System.err);
    76.             System.exit(-1);
    77.         }
    78.     }
    79. }

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

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <xsl:stylesheet version="1.0"
    3.     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    4.     <xsl:template match="/">
    5.         <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
    6.             <fo:layout-master-set>
    7.                 <fo:simple-page-master master-name="simple"
    8.                     page-height="8.5in" page-width="11in" margin-top=".5in"
    9.                     margin-bottom=".5in" margin-left=".5in" margin-right=".5in">
    10.                     <fo:region-body margin-top="2cm" margin-bottom="2cm" />
    11.                     <fo:region-before extent="2cm" overflow="hidden" />
    12.                     <fo:region-after extent="1cm" overflow="hidden" />
    13.                 </fo:simple-page-master>
    14.             </fo:layout-master-set>
    15.             <fo:page-sequence master-reference="simple"
    16.                 initial-page-number="1">
    17.                 <fo:static-content flow-name="xsl-region-before">
    18.                     <fo:block font-size="13.0pt" font-family="serif"
    19.                         padding-after="2.0pt" space-before="4.0pt" text-align="center"
    20.                         border-bottom-style="solid" border-bottom-width="1.0pt">
    21.                         <xsl:text>PDF Test</xsl:text>
    22.                     </fo:block>
    23.                 </fo:static-content>
    24.                 <fo:static-content flow-name="xsl-region-after">
    25.                     <fo:block font-size="12.0pt" font-family="sans-serif"
    26.                         padding-after="2.0pt" space-before="2.0pt" text-align="center"
    27.                         border-top-style="solid" border-bottom-width="1.0pt">
    28.                         <xsl:text>Page</xsl:text>
    29.                         <fo:page-number />
    30.                     </fo:block>
    31.                 </fo:static-content>
    32.                 <fo:flow flow-name="xsl-region-body">
    33.                     <xsl:apply-templates select="data" />
    34.                 </fo:flow>
    35.             </fo:page-sequence>
    36.         </fo:root>
    37.     </xsl:template>
    38.     <xsl:template match="data">
    39.         <fo:block text-align="center">
    40.             <fo:table table-layout="fixed" width="100%">
    41.                 <fo:table-column column-width="50%" />
    42.                 <fo:table-column column-width="50%" />
    43.                 <fo:table-body>
    44.                     <fo:table-row keep-together.within-page="always">
    45.                         <fo:table-cell>
    46.                             <fo:block font-size="10pt" font-family="sans-serif"
    47.                                 background-color="grey" color="white" text-align="left"
    48.                                 padding-top="3pt">
    49.                                 Field
    50.                             </fo:block>
    51.                         </fo:table-cell>
    52.                         <fo:table-cell>
    53.                             <fo:block font-size="10pt" font-family="sans-serif"
    54.                                 background-color="grey" color="white" text-align="left"
    55.                                 padding-top="3pt">
    56.                                 Value
    57.                             </fo:block>
    58.                         </fo:table-cell>
    59.                     </fo:table-row>
    60.                 </fo:table-body>
    61.             </fo:table>
    62.             <fo:table table-layout="fixed" width="100%">
    63.                 <fo:table-column column-width="50%" />
    64.                 <fo:table-column column-width="50%" />
    65.                 <fo:table-body>
    66.                     <fo:table-row keep-together.within-page="always">
    67.                         <fo:table-cell>
    68.                             <xsl:apply-templates select="field" />
    69.                         </fo:table-cell>
    70.                         <fo:table-cell>
    71.                             <xsl:apply-templates select="value" />
    72.                         </fo:table-cell>
    73.                     </fo:table-row>
    74.                 </fo:table-body>
    75.             </fo:table>
    76.         </fo:block>
    77.     </xsl:template>
    78.     <xsl:template match="field">
    79.         <fo:block font-size="9pt" font-family="sans-serif"
    80.             space-after.optimum="1pt" text-align="justify">
    81.             <xsl:value-of select="." />
    82.         </fo:block>
    83.     </xsl:template>
    84.     <xsl:template match="value">
    85.         <fo:block font-size="9pt" font-family="sans-serif"
    86.             space-after.optimum="1pt" text-align="justify">
    87.             <xsl:value-of select="." />
    88.         </fo:block>
    89.     </xsl:template>
    90. </xsl:stylesheet>

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

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <data>
    3.     <field>First Name</field>
    4.     <value>David</value>
    5.     <field>Second Name</field>
    6.     <value>Joe</value>
    7.     <field>Middle Name</field>
    8.     <value>Luther</value>
    9.     <field>Address1</field>
    10.     <value>Rose Villa</value>
    11.     <field>Address2</field>
    12.     <value>Picadilly</value>
    13.     <field>City</field>
    14.     <value>London</value>
    15.     <field>Date Of Joining</field>
    16.     <value>6/10/2015</value>
    17.     <field>Date of Birth</field>
    18.     <value>01-01-1992</value>
    19.     <field>Gender</field>
    20.     <value>Male</value>
    21.     <field>Marital Status</field>
    22.     <value>Unmarried</value>
    23.     <field>Name of Spouse</field>
    24.     <value>Not applicable</value>
    25.     <field>Credit card Number</field>
    26.     <value>01-03222-32</value>
    27.     <field>Land Phone</field>
    28.     <value>1234567890</value>
    29.     <field>Mobile Phone</field>
    30.     <value>Not Applicable</value>
    31.     <field>Education</field>
    32.     <value>Post graduate</value>
    33.     <field>Passport Number</field>
    34.     <value>1212</value>
    35.     <field>Date of Issue</field>
    36.     <value>08-08-2004</value>
    37.     <field>Date of Expiry</field>
    38.     <value>08-09-2008</value>
    39. </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
Reset Password
Fill out the form below and reset your password: