在Apache FOP中将XML文件按原样打印到PDF

时间:2013-10-03 10:28:34

标签: xml xsl-fo jaxp

我正在尝试打印XML文件“AS-IS”i,e。使用Apache FOP将标签转换为PDF。 我从FOP 1.1的src目录中的ExampleXML2PDF示例文件开始。 我能够打印格式化的XML对象,无法使用标签打印XML。

XSL如下,

<xsl:stylesheet version="2.0" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="testRaw" />
<xsl:template match="/">
    <fo:root>
        <fo:layout-master-set>
            <fo:simple-page-master master-name="my-page">
                <fo:region-body margin="0.5in" />
            </fo:simple-page-master>
        </fo:layout-master-set>
        <fo:page-sequence master-reference="my-page">
            <fo:flow flow-name="xsl-region-body" font="7pt Times">
                <fo:block break-before="page">
                    <xsl:value-of select="$testRaw" />
                </fo:block>
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>

用于设置参数的Java代码。

2 个答案:

答案 0 :(得分:0)

使用bufferedwriter,它看起来像这样:

public void readXML() {
            String name = "TheFile.xml";
            String path = "C:/User/Desktop/";
            File file = new File(path + name);
            if(file.canRead()) {
                String FileTxt = "";
                if((path + name).endsWith(".xml")) {
                    try {
                        Scanner read = new Scanner(new FileInputStream(file));
                        while (read.hasNextLine()) {
                            FileTxt += read.nextLine();
                        }
                        read.close();
                    } catch(FileNotFoundException e) {}
                    writePDF(FileTxt);
                }

            } else {
                System.out.print("Cannot Open File!");
            }
}

public void writePDF(String text) {
      String path = "C:/User/Desktop/"
      String name = "TheFile.pdf"
      if(!path.endsWith(name)) path += name;
                try {
                     BufferedWriter write = new BufferedWriter(new FileWriter(path));
                    write.write(text);
                    write.close();
                } catch(Exception e) {}
}

答案 1 :(得分:0)

尝试将xsl:value-of替换为xsl:copy-of并将其换成CDATA

示例...

<xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text>
<xsl:copy-of select="$testRaw" />
<xsl:text disable-output-escaping="yes">]]&gt;</xsl:text>