EDIT: See my working code in the answers below.
In brief: I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: File does not begin with '%PDF-'.
In detail: So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: File does not begin with '%PDF-'. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?
To create the PDF, I'm using Apache FOP. I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their basic usage pattern and this example code.
Here's my JSP file:
<%@ taglib uri="utilTLD" prefix="util" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%-- Construct and initialise the PrintReportsBean --%>
<jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" />
<jsp:setProperty name="printReportsBean" property="*"/>
<c:set scope="page" var="xml" value="${printReportsBean.download}"/>
Here's my Java Bean method:
//earlier in the class...
private static FopFactory fopFactory = FopFactory.newInstance();
public File getDownload() throws UtilException {
OutputStream out = null;
File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf");
File fo = new File("C:\\somedirectory", "HelloWorld.fo");
try {
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
out = new FileOutputStream(pdf);
out = new BufferedOutputStream(out);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); //identity transformer
Source src = new StreamSource(fo);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return pdf;
} catch (Exception e) {
throw new UtilException("Could not get download. Msg = "+e.getMessage());
} finally {
try {
out.close();
} catch (IOException io) {
throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage());
}
}
}
I realise that this is a very specific problem, but any help would be much appreciated!