I’m having issues getting a PDF to display properly in IE. Below is the smallest test case I can create which shows the issue. I’m using Spring 3.0.5 with PdfBox 1.6.
Here is a simplified controller which exhibits the problem:
@RequestMapping(method = RequestMethod.GET, value = "generatePdf.pdf")
public ResponseEntity<byte []> generatePdf() throws IOException {
PDDocument document = null;
try {
document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(100, 500);
contentStream.drawString("Hello World");
contentStream.endText();
contentStream.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "pdf"));
headers.setContentLength(baos.toByteArray().length);
return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
} catch (Exception e) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<byte[]>("BROKEN".getBytes(), headers, HttpStatus.CREATED);
} finally {
if (document != null) {
document.close();
}
}
}
The above works for Chrome & Firefox. However opening the link in IE at all causes nothing to be displayed. However if I make the following modifications:
@RequestMapping(method = RequestMethod.GET, value = "generatePdf.pdf")
public ResponseEntity<byte []> generatePdf(HttpServletResponse response) throws IOException {
PDDocument document = null;
try {
document = new PDDocument();
//... Same until declaration of HttpHeaders
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(baos.toByteArray().length));
FileCopyUtils.copy(baos.toByteArray(), response.getOutputStream());
return null;
} //... same as above
All works fine in IE as well as the other browsers. I’m not quite sure what my options are here, other types of files are written out properly (PNG, JPG, etc…).
Any ideas how to avoid pulling in the request and simply using the ResponseEntity to handle these properly?
I would guess that it comes from
HttpStatus.CREATED. Perhaps IE doesn’t handle it. UseHttpStatus.OK(200, which is the standard success response). That appears to be the only difference between the two snippets