如何使用ServletOutputStream在Web浏览器中显示PDF

时间:2014-07-11 16:19:35

标签: jsf servlets pdf

我一直在尝试使用ServletOutputStream在Web浏览器中显示pdf报告。到目前为止,我可以下载该文件,但我无法在浏览器中显示它。这是我的代码

private void initReport()
{
    DBConnection connection = new DBConnection();

     try {
         jasperPrint = JasperFillManager.fillReport(getContext().getExternalContext().getRealPath("/WEB-INF/reports/testReport.jasper"), new HashMap(),connection.getConnection());

     } catch (JRException ex) {
         Logger.getLogger(ReportBacking.class.getName()).log(Level.SEVERE, null, ex);
     }

}

public void showPDF()
{
    initReport();
     try {
         HttpServletResponse httpServletResponse;httpServletResponse = (HttpServletResponse)  getContext().getExternalContext().getResponse();

         httpServletResponse.setContentType("application/pdf");
         httpServletResponse.addHeader("Content-disposition", "inline;filename=testReport.pdf");
         ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

         JasperExportManager.exportReportToPdfStream(jasperPrint,servletOutputStream);

         getContext().responseComplete();
         getContext().renderResponse();

     } catch (JRException | IOException ex) {
         Logger.getLogger(CertificateApplicationAddBacking.class.getName()).log(Level.SEVERE, null, ex);
       getContext().addMessage(null, new FacesMessage("Could not generate report")); 
     }

如果我将内容替换更改为附件。我可以下载该文件。

1 个答案:

答案 0 :(得分:1)

无论是在浏览器中下载还是显示,都无法控制。它是浏览器或Acrobat中的设置,或者只有用户可以更改的组合(如果他们知道如何)。

但是,您可以使用Flash / Silverlight应用程序,让您将PDF加载到其中,或者通过将PDF字节从服务器传递到PDF.js并让它呈现给您来找到使用PDF.js的方法PDF在浏览器中。查看示例页面。他们在哪里:

PDFJS.getDocument('helloworld.pdf').then(function(pdf) {
  // you can now use *pdf* here
});

您可以将'helloworld.pdf'更改为您的servlet的URL。

相关问题