PDF生成在IE浏览器中无法显示

4
我遇到了在IE中无法正确显示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和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来正确处理它们吗?


如果您检查了损坏的版本,您的 content-type 和 content-length 标头是否设置正确? - digitaljoel
它们实际上被正确设置了。 - Scott
非工作的那个是否在内容类型中包含字符集? - laz
2个回答

6

我猜测这个问题可能是由HttpStatus.CREATED引起的。可能是因为IE无法处理它。请使用HttpStatus.OK(200,这是标准的成功响应)。这似乎是这两个片段之间唯一的区别。


从它正确处理错误情况(即使我们仍然发送CREATED)的角度来看,我从未想到过这一点。谢谢。 - Scott

0

你尝试过添加:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接