I am having problems getting a PDF file to display correctly in IE. Below is the smallest test case I can create that shows the problem. I am using Spring 3.0.5 with PdfBox 1.6.
Here is a simplified controller that detects a 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 and Firefox. However, opening a link in IE does not cause anything at all. However, if I make the following changes:
@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
Everything works fine both in IE and in other browsers. I'm not quite sure that my options are here, other file types are written out correctly (PNG, JPG, etc.).
Any ideas on how to avoid the request and just use ResponseEntity to properly process this data?
source share