1

我正在尝试将静态 pdf(在系统上)发送到 outputStream 以显示另存为对话框。但是当打开 Pdf 时,只显示一个空页面:

这是应该显示对话框的代码:

    //get the pdf:
    String pathToPdf = servletContext.getRealPath("/pdfFiles/dealer.pdf");
    File pdfFile = new File (pathToPdf);

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=dealer.pdf");
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream responseOutputStream = response.getOutputStream();
    int bytes;
    while ((bytes = fileInputStream.read()) != -1) {
        responseOutputStream.write(bytes);
        }
    responseOutputStream.flush();
    responseOutputStream.close();

Stacktrace 说明如下:

WARNING: Invalid HTML; bare lessthan sign found at line 4. Surroundings: '<
/Creator (Apache FOP Version'.
WARNING: Invalid HTML; bare lessthan sign found at line 5. Surroundings: '/Creator (Apache FOP Version 1'.
WARNING: Invalid HTML; bare lessthan sign found at line 11. Surroundings: '<
  /N 3
  /Length 11 0 R
  /F'.
WARNING: Invalid HTML; bare lessthan sign found at line 12. Surroundings: '/N 3
  /Length 11 0 R
  /Filte'.
WARNING: Invalid HTML; bare lessthan sign found at line 18. Surroundings: '?s??e???'?9???`??2?&c?tI?'.
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 25. Surroundings: '?+?U?Zp'pWp?????????e?F|'.
WARNING: Invalid HTML; bare lessthan sign found at line 68. Surroundings: '<
  /Name /Im1
  /Type /XObjec'.
WARNING: Invalid HTML; bare lessthan sign found at line 69. Surroundings: '/Name /Im1
  /Type /XObject
  '.
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 85. Surroundings: '??r??"?F?t??$??n{?q??O~??{?'.

谁能说我错过了什么或做错了什么?谢谢!!

4

2 回答 2

1

你应该试着打电话

response.reset();

在设置内容类型之前。也许图书馆已经设置了标题并且不同的标题会发生冲突。

于 2013-10-10T08:38:06.587 回答
0

我必须添加以下内容:

context.responseComplete();

所以完整的代码现在看起来像这样:

response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"PdfName.pdf\"");
            response.setContentLength(outStream.size());

            OutputStream responseOutputStream = response.getOutputStream();
            outStream.writeTo(responseOutputStream);

            responseOutputStream.flush();
            responseOutputStream.close();
            context.responseComplete();
于 2013-10-30T10:26:47.070 回答