Xml for java pdf

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Tuesday, May 24, 2022

How to Create PDF From XML in Java Using Apache FOP

In this post we’ll see how to create PDF from XML in Java using Apache FOP.

What is Apache FOP

Apache™ FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output.
FOP uses the standard XSL-FO file format as input, lays the content out into pages, then renders it to the requested output.
Read more about it here- https://xmlgraphics.apache.org/fop/

How to get Apache FOP

I have used fop-2.0 for this example code.
Needed jars (found in the lib and build directory in the fop download)-

  • Commons-io
  • Commons-logging
  • Xml-apis
  • Xmlgraphics-commons
  • Fop
  • Batik-all
  • Avalon-framework
 org.apache.xmlgraphics fop 2.7  xml-apis xml-apis    

Here we have an exclusion for xml-apis because of the javax.xml package conflict, this package is present in Java too and that’s what will be used.

Читайте также:  Kotlin localdate to timestamp

Steps for creating a PDF from XML in Java using Apache FOP

To produce a PDF file from a XML file, first step is that we need an XSLT stylesheet that converts the XML to XSL-FO. Created XSL-FO file is also an XML file which contains formatted objects.
The second step will be done by FOP when it reads the generated XSL-FO document and formats it to a PDF document.

Creating PDF using FOP Java example

  ABC Inc. 101 Ram Manager  102 Prabhu Executive  103 John Executive   
          Company Name:                 bold                 

If you see the XSL, first I am looking for the employees element to get the company Name and also there some formatting is done like how many columns are needed and what should be the width. Then I am looking for the employee element and printing the values, also some logic is there to print the field values in bold if the designation is manager.

Copying the output of PDF I got, that will make it easy to understand the XSL.

PDF from XML in Java using Apache FOP

import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOPException; 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 FOPPdfDemo < public static void main(String[] args) < FOPPdfDemo fOPPdfDemo = new FOPPdfDemo(); try < fOPPdfDemo.convertToFO(); >catch (FOPException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (TransformerException e) < // TODO Auto-generated catch block e.printStackTrace(); >> /** * Method that will convert the given XML to PDF * @throws IOException * @throws FOPException * @throws TransformerException */ public void convertToPDF() throws IOException, FOPException, TransformerException < // the XSL FO file File xsltFile = new File("D:\\NETJS\\xml\\template.xsl"); // the XML file which provides the input StreamSource xmlSource = new StreamSource(new File("D:\\NETJS\\xml\\Employees.xml")); // create an instance of fop factory FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); // a user agent is needed for transformation FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // Setup output OutputStream out; out = new java.io.FileOutputStream("D:\\NETJS\\xml\\employee.pdf"); 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)); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing // That's where the XML is first transformed to XSL-FO and then // PDF is created transformer.transform(xmlSource, res); >finally < out.close(); >> /** * This method will convert the given XML to XSL-FO * @throws IOException * @throws FOPException * @throws TransformerException */ public void convertToFO() throws IOException, FOPException, TransformerException < // the XSL FO file File xsltFile = new File("D:\\NETJS\\xml\\template.xsl"); /*TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource("F:\\Temp\\template.xsl"));*/ // the XML file which provides the input StreamSource xmlSource = new StreamSource(new File("D:\\NETJS\\xml\\Employees.xml")); // a user agent is needed for transformation /*FOUserAgent foUserAgent = fopFactory.newFOUserAgent();*/ // Setup output OutputStream out; out = new java.io.FileOutputStream("D:\\NETJS\\xml\\temp.fo"); try < // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltFile)); // Resulting SAX events (the generated FO) must be piped through to FOP //Result res = new SAXResult(fop.getDefaultHandler()); Result res = new StreamResult(out); //Start XSLT transformation and FOP processing transformer.transform(xmlSource, res); // Start XSLT transformation and FOP processing // That's where the XML is first transformed to XSL-FO and then // PDF is created transformer.transform(xmlSource, res); >finally < out.close(); >> >

In the code there are two methods convertToPDF() and convertToFO(), convertToPDF() method is used to convert XML to PDF. convertToFO() method will create the XSL-FO from the XML using the XSLT. If you want to see the created FO which in turn is used to create PDF please call this method.

Create PDF in web application using Apache FOP

In case of web application if you want to provide PDF as a download, here is a Servlet method as reference-

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < try< FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(PATH_TO_XSL)); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input Source src = new StreamSource(new File("./resources/Employees.xml")); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response response.setContentType("application/pdf"); response.setContentLength(out.size()); //Send content to Browser response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); >catch(Exception e) < e.printStackTrace(); >>

That’s all for this topic How to Create PDF From XML in Java Using Apache FOP. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

Xml to Pdf in java using iText Sample code

We can convert any xml file to pdf in java using iText lib.

Required Jar Files:

Xml File: (Sample xml file – to convert to pdf file)

   Hemakumar Arcot  Chudar Vellore  Selva kumar Arcot  

Xsl File (stylesheet for the above xml):

      

Xml 2 Pdf in Java Using iText

Friend's Name Friend's Place

Java Program which converts the xml file to pdf file:

package com.ngdeveloper; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.dom4j.DocumentException; import org.xhtmlrenderer.pdf.ITextRenderer; public class Xml2Pdf < public static void main(String[] args) throws IOException, DocumentException, TransformerException, TransformerConfigurationException, FileNotFoundException < TransformerFactory tFactory = TransformerFactory.newInstance(); // specify the input xsl file location to apply the styles for the pdf // output file Transformer transformer = tFactory.newTransformer(new StreamSource("D:\\javadomain.xsl")); // specify the input xml file location transformer.transform(new StreamSource("D:\\javadomain.xml"), new StreamResult(new FileOutputStream("D:\\javadomain.html"))); // Specifying the location of the html file (xml converted to html) String File_To_Convert = "D:\\javadomain.html"; String url = new File(File_To_Convert).toURI().toURL().toString(); System.out.println("" + url); // Specifying the location of the outpuf pdf file. String HTML_TO_PDF = "D:\\PdfFromXml.pdf"; OutputStream os = new FileOutputStream(HTML_TO_PDF); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); renderer.layout(); renderer.createPDF(os); os.close(); >>

XML converted to Pdf File – output:

pdf from xml

Share this:

Like this:

6 comments

Hi, I do believe your site may be having web browser
compatibility issues. Whenever I look at your blog in Safari, it looks fine however when opening in I.E.,
it’s got some overlapping issues. I just wanted to give you a quick heads up!
Apart from that, excellent site!

Hi I get the PDF, but no bluecolor
in the HTML: I have the color..
and then i recive:

Warning: org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser: Property ‘http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit’ is not recognized.
Compilewarning:
WARNING: ‘org.apache.xerces.jaxp.SAXParserImpl: Property ‘http://javax.xml.XMLConstants/property/accessExternalDTD’ is not recognized.’
Warning: org.apache.xerces.parsers.SAXParser: Feature ‘http://javax.xml.XMLConstants/feature/secure-processing’ is not recognized.
Warning: org.apache.xerces.parsers.SAXParser: Property ‘http://javax.xml.XMLConstants/property/accessExternalDTD’ is not recognized.
Warning: org.apache.xerces.parsers.SAXParser: Property ‘http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit’ is not recognized.
file:/Q:/Projekt/eclipse-java-luna-SR2-win32-x86_64/XMLfiler/javadomain.html
done! and then:
IS it possible to use iText if i have a XML-file that i want to pictures if some text-element is a specific value?
or do i do this in XsL?

it look strange when I try this..
please loot at an exampel:
a XML:


Hemakumar
Arcot


Chudar
Vellore


Selva kumar
Arcot

a XLS:




Xml 2 Pdf in Java Using iText


Friend’s Name Friend’s Place




when I run this, it generate a strange HTML-code 🙁


Xml 2 Pdf in Java Using iText

Friend’s Name Friend’s Place
Hemakumar Arcot
Chudar Vellore
Selva kumar Arcot


so it generate this:

and NOT this:

🙁 and the error:
Warning: org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser: Property ‘http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit' is not recognized.
Kompileringsvarningar:
WARNING: ‘org.apache.xerces.jaxp.SAXParserImpl: Property ‘http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.’
Warning: org.apache.xerces.parsers.SAXParser: Property ‘http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.
Warning: org.apache.xerces.parsers.SAXParser: Property ‘http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit' is not recognized.
file:/Q:/Projekt/eclipse-java-luna-SR2-win32-x86_64/XMLfiler/javadomain2.html
ERROR: ‘The element type «img» must be terminated by the matching end-tag ««.’
org.xhtmlrenderer.util.XRRuntimeException: Can’t load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 3; The element type «img» must be terminated by the matching end-tag ««.
at org.xhtmlrenderer.resource.XMLResource$XMLResourceBuilder.createXMLResource(XMLResource.java:191)
at org.xhtmlrenderer.resource.XMLResource.load(XMLResource.java:71)
at org.xhtmlrenderer.swing.NaiveUserAgent.getXMLResource(NaiveUserAgent.java:211)
at org.xhtmlrenderer.pdf.ITextRenderer.loadDocument(ITextRenderer.java:134)
at org.xhtmlrenderer.pdf.ITextRenderer.setDocument(ITextRenderer.java:138)
at Xml2Pdf.main(Xml2Pdf.java:82)
Caused by: javax.xml.transform.TransformerException: org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 3; The element type «img» must be terminated by the matching end-tag ««.
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at org.xhtmlrenderer.resource.XMLResource$XMLResourceBuilder.createXMLResource(XMLResource.java:189)
… 5 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 3; The element type «img» must be terminated by the matching end-tag ««.
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(Unknown Source)
… 8 more

You are trying to create a table in pdf using xml right ? When I tried with the sample code and data shared here, I am able to get the output which is mentioned in the post.

Источник

Оцените статью