How do you create a PDF from XML in Java?

后端 未结 11 1175
说谎
说谎 2020-12-04 16:06

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 info

相关标签:
11条回答
  • 2020-12-04 16:28

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

    0 讨论(0)
  • 2020-12-04 16:31

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

    0 讨论(0)
  • 2020-12-04 16:33

    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!");
    
    0 讨论(0)
  • 2020-12-04 16:34

    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.

    0 讨论(0)
  • 2020-12-04 16:34

    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.

    0 讨论(0)
提交回复
热议问题