PDF生成不在IE中显示

Sco*_*ott 4 java pdf spring spring-mvc

我在让IE正常显示时遇到问题.下面是我可以创建的最小的测试用例,它显示了问题.我正在使用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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

以上适用于Chrome和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
Run Code Online (Sandbox Code Playgroud)

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

任何想法如何避免拉入请求,只是使用ResponseEntity来正确处理这些?

Boz*_*zho 6

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