2014-10-20 88 views
0


我使用下面的代码片段代码生成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%2 0 OBJ <>流X + R 26S00SI2P51BҸ4>>> /多媒体[0 0 595 842] /家长3 0 R /内容 2 0 R /类型/页>> endobj 1 0 OBJ <> endobj 3 0 OBJ <> endobj 5 0 OBJ <> endobj 6 0 OBJ <> endobj外部参照0 7 0000000000 65535˚F0000000331 00000Ñ0000000015 00000Ñ0000000419 00000ñ0000000174 00000ñ 0000000470 00000ñ0000000515 00000ñ拖车<] /信息6 0 R >> %的iText-5.4.0 startxref 668 %% EOF


请帮我出了相同的

+1

您需要设置内容类型标题。您收回的数据是PDF,但浏览器不知道它是PDF。 – HocusPocus 2014-10-20 14:46:47

+0

我应该为此添加哪段代码?能否请你给我.. – eagle 2014-10-20 14:53:05

回答

0
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(); 
+0

非常感谢你,但它不工作仍然是相同的错误 – eagle 2014-10-20 15:30:25

+0

你确定该文件正常工作,当你不试图通过HTTP服务它?即您是否尝试将文件写入磁盘并验证它是否从hd打开? – zmf 2014-10-20 15:32:15

+0

是的,它保存在磁盘(D :)但我的问题是相同的http://stackoverflow.com/questions/16407156/why-does-generated-pdf-display-properly-in-internet-explorer-but-not -in-firefox – eagle 2014-10-20 15:45:04

2

你可能要添加一个标题,你提的响应是一个附件 - >

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

嗨Amit,pdfFileName变量的值是什么? – eagle 2014-10-21 06:33:29

+0

文件的名称。 – Amit 2017-10-12 06:22:34

-1

感谢上帝,终于它的工作!我sucessed通过在新标签中打开.pdf文件,从点击更新发育的角度按钮或链接目标应该是balnk,例如(target = _blank)