问题
I'm trying to create a PDF document with Apache FOP from an xml file that is formatted with an xlst stylesheet to convert the original xml file to an xml-fo formatted xml file. As I'm new to this, I tried to create a simple hello world example, without success.
The generation process seems to succeed (no exceptions) but the generated pdf file is invalid for some reason. The size of the file is 4.8KB, and when opened with libreoffice writer, data has definitely been written to the file, but the file does not open in pdf readers.
The XML file is rather straightforward:
<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>
The XSL file, simply attempting to print 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>
The java code to generate a pdf file using JAXP + FOP:
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);
}
The generated pdf file can be found at http://www.filedropper.com/rentalrequest
回答1:
You got an incomplete PDF file because you forgot to properly close
the OutputStream
. Always use the following pattern when you open an OutputStream
(or InputStream
for that matter):
OutputStream out = new [Something]OutputStream([something]);
try {
//write to the OutputStream
} finally {
out.close();
}
来源:https://stackoverflow.com/questions/13463455/apache-fop-xml-xls-fo-generates-invalid-pdf