How do you create a PDF from XML in Java?

后端 未结 11 1256
说谎
说谎 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条回答
  •  猫巷女王i
    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!");
    

提交回复
热议问题