nkr*_*1pt 1 xml pdf xslt xsl-fo apache-fop
我正在尝试使用 Apache FOP 从使用 xlst 样式表格式化的 xml 文件创建 PDF 文档,以将原始 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代码:
<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>
您得到的 PDF 文件不完整,因为您忘记了正确close的OutputStream. 当您打开OutputStream(或InputStream就此而言)时,请始终使用以下模式:
OutputStream out = new [Something]OutputStream([something]);
try {
    //write to the OutputStream
} finally {
    out.close();
}