Java转换为PDF

时间:2011-11-07 12:27:08

标签: java pdf

我正在为我的一个性能项目做POC,目前它在当前场景中给了我Out of memory Error,因为我们已经将xml加载为DOM,然后给它XSL然后将其转换为PDF,在这里给出OOMemory错误,

在此论坛的一条评论之后,我已经使用SAX解析器作为xml文件并给出了XSL然后使用FOP这个30 MB,系统内存为512 MB

System.out.println("FOP XMLTOPDFConverter\n");
            System.out.println("Preparing...");

            // Setup directories
/*          File baseDir = new File(".");
            File outDir = new File(baseDir, "out");
            outDir.mkdirs();*/

            // Setup input and output files
            File xmlfile = new File("C:/Documents and Settings/agarwgau/Desktop/300k/File_0000036357.XML");
            File xsltfile = new File("C:/Documents and Settings/agarwgau/Desktop/300k/UCB110037EventList.xsl");
            File pdffile = new File("C:/Documents and Settings/agarwgau/Desktop/300k/ResultXML2PDF.pdf");

            System.out.println("Input: XML (" + xmlfile + ")");
            System.out.println("Stylesheet: " + xsltfile);
            System.out.println("Output: PDF (" + pdffile + ")");
            System.out.println();
            System.out.println("Transforming...");

            // configure fopFactory as desired
            FopFactory fopFactory = FopFactory.newInstance();

            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            // configure foUserAgent as desired

            // Setup output
            OutputStream out = new java.io.FileOutputStream(pdffile);
            out = new java.io.BufferedOutputStream(out);

            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));

                // Set the value of a <param> in the stylesheet
                transformer.setParameter("versionParam", "2.0");

                // Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);

                // Resulting SAX events (the generated FO) must be piped through
                // to FOP
                Result res = new SAXResult(fop.getDefaultHandler());

                // Start XSLT transformation and FOP processing
                transformer.transform(src, res);
            } finally {
                out.close();
            }

            System.out.println("Success!");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

2 个答案:

答案 0 :(得分:1)

听起来Apache FOP应该可以帮助你。

答案 1 :(得分:1)

您有两种选择:FOP,它是PDF的XML表示,或iText,它使用Java类创建PDF。

我建议将FOP与Velocity结合使用。制作一个表示您的FO XML的Velocity模板,并将数据映射到其中。