在java中的HTTP请求中生成PDF作为输出流

时间:2014-10-20 14:42:46

标签: java http pdf


     我正在使用以下片段代码将生成PDF作为输出流在java中的HTTP请求中     代码是: -

        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% 20 ob​​j<>streamx + r    26S 00SI 2P 5 1 BҸ4>>> / MediaBox [0 0 595 842] / Parent 3 0 R /目录   2 0 R /类型/页面>> endobj 1 0 obj<> endobj 3 0 obj<> endobj 5 0 obj   <> endobj 6 0 obj<> endobj xref 0 7 0000000000 65535 f 0000000331   00000 n 0000000015 00000 n 0000000419 00000 n 0000000174 00000 n   0000000470 00000 n 0000000515 00000 n预告片<] / Info 6 0 R>>   %iText-5.4.0 startxref 668 %% EOF


请帮我解决同样的问题

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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();

答案 2 :(得分:-1)

感谢上帝终于工作了!!!,我通过在新标签中打开.PDF文件来进行操作,从开发角度来看点击按钮或链接目标应该是balnk例如(target = _blank)