Apache FOP XML - XSL-FO生成无效的pdf

时间:2012-11-19 22:28:27

标签: xml xslt pdf xsl-fo apache-fop

我正在尝试使用Apache FOP从xml文件创建一个PDF文档,该文件使用xlst样式表格式化,以将原始xml文件转换为xml-fo格式的xml文件。 由于我是新手,我试图创建一个简单的hello world示例,但没有成功。

生成过程似乎成功(没有例外),但生成的pdf文件由于某种原因无效。 该文件的大小为4.8KB,当使用libreoffice writer打开时,数据肯定已写入该文件,但该文件无法在pdf阅读器中打开。

XML文件非常简单:

<rentalRequest>
  <firstName>foo</firstName>
  <lastName>bar</lastName>
  <email>foo@bar.com</email>
  <street>foo street</street>
  <houseNo>42</houseNo>
  <postalCode>4242</postalCode>
  <city>bar city</city>
</rentalRequest>

XSL文件,只是试图打印Hello World!:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:fo="http://www.w3.org/1999/XSL/Format">

    <xsl:output method="xml" indent="yes" />

    <xsl:template match="/">
        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
            <fo:layout-master-set>          
                <fo:simple-page-master master-name="all">
                    <fo:region-body />
                </fo:simple-page-master>
            </fo:layout-master-set>

            <fo:page-sequence master-reference="all">
                <fo:flow flow-name="xsl-region-body">
                    <fo:block>
                        Hello World!
                    </fo:block>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

</xsl:stylesheet>

使用JAXP + FOP生成pdf文件的java代码:

public void buildWithXSL(String xml) throws Exception {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("rentalrequest.pdf")));

        // setup xml input source
        StreamSource xmlSource =
                new StreamSource(new ByteArrayInputStream(xml.getBytes()));

        File xslFile = new File("src/main/resources/xml/rentalrequest2fo.xsl");
        FileInputStream xslFileStream = new FileInputStream(xslFile);
        StreamSource xslSource = new StreamSource(xslFileStream);

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer(xslSource);

        FopFactory fopFactory = FopFactory.newInstance();
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        // perform transformation 
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(xmlSource, res);
    }

生成的pdf文件可在http://www.filedropper.com/rentalrequest

找到

1 个答案:

答案 0 :(得分:4)

您的PDF文件不完整,因为您忘记了close OutputStream。打开OutputStream(或InputStream时,请始终使用以下模式:

OutputStream out = new [Something]OutputStream([something]);
try {
    //write to the OutputStream
} finally {
    out.close();
}