How do you create a PDF from XML in Java?

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

At the moment, I'm creating an XML file in Java and displaying it in a JSP page by transforming it with XSL/XSLT. Now I need to take that XML file and display the same information in a PDF. Is there a way I can do this by using some kind of XSL file?

I've seen the iText Java-PDF library, but I can't find any way to use it with XML and a stylesheet.

Any assistance would be much appreciated. Thanks in advance!

回答1:

You can use XSL Formatting objects. Here are some good articles on how to do it:



回答2:

A - Explanation

You should use Apache FOP framework to generate pdf output. Simply you provide data in xml format and render the page with an xsl-fo file and specify the parameters like margin, page layout in this xsl-fo file.

I'll provide a simple demo, I use maven build tool to gather the needed jar files. Please notify that at the end of the page, there is an svg graphics embedded in pdf. I also want to demonstrate that you can embed svg graphics inside pdf.

B - Sample XML input data

User Bill DataThursday December 9 2016 00:04:29John Doe34239123AD32924817.84Michael Doe54823942KFDSCW32234.50Jane Brown66742ABDD324KKD869.36

C - The XSL-FO Template

D - Project Directory Structure

E - Pom file

4.0.0com.levent.fopdemoapache-fop-demojar1.0-SNAPSHOTapache-fop-demohttp://maven.apache.org2.1org.apache.xmlgraphicsfop${fop.version}Apache Fop Demoorg.apache.maven.pluginsmaven-compiler-plugin3.5.11.81.8

F - Demo Code: PdfGenerationDemo.java

package com.levent.fopdemo;  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.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 PdfGenerationDemo  {     public static final String RESOURCES_DIR;     public static final String OUTPUT_DIR;      static {         RESOURCES_DIR = "src//main//resources//";         OUTPUT_DIR = "src//main//resources//output//";     }      public static void main( String[] args )     {         try {             convertToPDF();         } catch (FOPException | IOException | TransformerException e) {             e.printStackTrace();         }     }      public static void convertToPDF() throws IOException, FOPException, TransformerException {         // the XSL FO file         File xsltFile = new File(RESOURCES_DIR + "//template.xsl");         // the XML file which provides the input         StreamSource xmlSource = new StreamSource(new File(RESOURCES_DIR + "//data.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(OUTPUT_DIR + "//output.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();         }     } }

G - Sample Output: output.pdf



回答3:

You can also check apache project here



回答4:

BIRT has a GUI for Eclipse that lets you define the PDF from XML, DB, CSV, etc etc.



回答5:

You might want to look at the XSL-FO libraries that are out there that can do PDF creation as a transformation. I'll try to find a link.



回答6:

Try the xhtmlrenderer project. See the article "Generating PDFs for Fun and Profit with Flying Saucer and iText".



回答7:

You can apply XSL-Fo to your XML and transform it with Java transformer:

File xmlfile = new File(baseDir, xml); File xsltfile = new File(baseDir, xsl); File pdffile = new File(outDir, "ResultXMLPDF.pdf");  FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent();  OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out);  try {     Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);     // Setup XSLT     TransformerFactory factory = TransformerFactory.newInstance();     Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));      transformer.setParameter("versionParam", "1.0");      Source src = new StreamSource(xmlfile);      Result res = new SAXResult(fop.getDefaultHandler());      transformer.transform(src, res);  } finally {     out.close(); }  System.out.println("Success!");


回答8:

Use JasperReports. You can either pull the data from Database or XML. You can export to many formats : pdf, excel, html, etc...



回答9:

Coming in late, you can create a static PDF with Adobe's designer with editable fields, then create a matching XDP XML document.



回答10:

There are two ways to do this.

  • Firstly, you can create a normal PDF which when read back will not give you the hierarchy of the original XML file. This is explained very elaborately in 'Section 9.4.2 Parsing XML' of the 'iText in Action : Edition 2'.

  • Secondly, you can create a tagged PDF which contains both the hierarchy of the XML as well as the data. This enables you to read back the PDF file and create an XML file from this(which exactly matches the original XML file). This concept is also dealt with in detail in '15.2.3 Adding structure' of the 'iText in Action : Edition 2'.

Based on your requirements, you can use either of the approaches mentioned above.



回答11:

XML, CSS, XHTML, etc. consist in an "alive ecosystem" of open standards, while XSL-FO is an isolated standard.

... Historically XSL-FO and XSLT was created as twins brothers, but only XSLT remains an "alive standard", XSL-FO concentrates a lot of DNA in proprietary (Adobe) standards... now is obsolete.

Strictly speaking, XSL-FO is part of an "abandoned way" that will not evolve, it ignores CSS, the "new way" to express layout in the "alive ecosystem".

It is not a Java problem

See this answer about the use of CSS-page with XML or XHTML.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!