Java转换为PDF

时间:2011-11-08 09:43:22

标签: java pdf apache-fop

我正在为我的一个表演项目做POC。目前我正面临 OutOfMemoryError 。首先,我们使用DOM加载了一个XML文件,然后尝试使用XSL将其转换为PDF。在阅读了本论坛的一条评论之后,我切换到SAX解析器,但它仍然会出现同样的错误。

文件为30MB,系统内存为512MB。

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

    }

1 个答案:

答案 0 :(得分:2)