PDF生成不在IE中显示

时间:2011-08-09 22:14:25

标签: java spring pdf spring-mvc

我在浏览器中正确显示PDF时出现问题。下面是我可以创建的最小的测试用例,它显示了问题。我正在使用Spring 3.0.5和PdfBox 1.6。

这是一个展示问题的简化控制器:

@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();
    }
  }
}

以上适用于Chrome&amp; Firefox浏览器。但是,在IE中打开链接会导致无法显示任何内容。但是,如果我做了以下修改:

@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

所有在IE以及其他浏览器中都能正常工作。我不太清楚我的选择是什么,其他类型的文件都写得正确(PNG,JPG等......)。

任何想法如何避免引入请求并简单地使用ResponseEntity来正确处理这些?

2 个答案:

答案 0 :(得分:6)

我猜它来自HttpStatus.CREATED。也许IE无法处理它。使用HttpStatus.OK(200,这是标准的成功响应)。这似乎是两个片段之间的唯一区别

答案 1 :(得分:0)

您是否尝试过添加:

@RequestMapping(method = RequestMethod.GET, value = "generatePdf.pdf", produces =
MediaType.APPLICATION_OCTET_STREAM_VALUE){...}
相关问题