【问题标题】:Generate PDF as Output Stream in HTTP request in java在java中的HTTP请求中生成PDF作为输出流
【发布时间】:2014-12-15 14:20:22
【问题描述】:


我正在使用以下 sn-p 代码在 Java 中的 HTTP 请求中生成 PDF 作为输出流
代码是:-

        webAppAccess.getHttpServletResponse().setContentType("application/pdf");

        try {
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter.getInstance(document, webAppAccess
                    .getHttpServletResponse().getOutputStream());
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph("Hello World"));
            document.add(new Paragraph(new Date().toString()));
            // step 5
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }

我在屏幕上显示 pdf

%PDF-1.4 %���� 2 0 obj 流 x�+�r �26S�00SI�2P�5�1���BҸ4>>>/MediaBox[0 0 595 842]/Parent 3 0 R/Contents 2 0 R/类型/页面>> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 obj endobj 外部参照 0 7 0000000000 65535 f 0000000331 00000 n 0000000015 00000 n 0000000419 00000 n 0000000174 00000 n 0000000470 00000 n 0000000515 00000 n 拖车 > %iText-5.4.0 startxref 668 %%EOF


请帮我解决这个问题

【问题讨论】:

  • 您需要设置内容类型标头。您返回的数据是 PDF,但浏览器不知道它是 PDF。
  • 我应该为此添加什么代码?你能给我吗..

标签: java http pdf


【解决方案1】:
ByteArrayOutputStream baos = // make a bytearray output from the document
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=filename.pdf");
// setting the content type
response.setContentType("application/pdf");
response.setContentLength(baos.size());
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

baos.writeTo(bos);
bos.flush(); 
bos.close();

【讨论】:

  • 非常感谢,但还是不行,还是一样的错误
  • 当您不尝试通过 http 提供文件时,您确定该文件可以正常工作吗?即您是否尝试将文件写入磁盘并验证它是否从高清打开?
  • 是的,它已保存在磁盘中(D:),但我的问题与stackoverflow.com/questions/16407156/… 相同
【解决方案2】:

您可能想要添加一个标题,其中您提到响应是附件 ->

response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);

【讨论】:

  • 嗨,Amit,pdfFileName 变量的值是多少?
  • 文件名。
【解决方案3】:

感谢上帝终于成功了!!!,我在新选项卡中打开 .PDF 文件成功了,从开发人员的角度来看,单击按钮或链接目标应该是 balnk,例如(target=_blank)

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多