2014-07-11 76 views
0

我一直试图在使用ServletOutputStream的Web浏览器中显示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")); 
    } 

如果我将content-diposition更改为附件。我可以下载文件。

回答

1

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

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

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

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

+0

我试过你的建议,它在firefox中完美工作,但在铬我得到这个错误:'资源解释为文档,但与MIME类型应用程序/ PDF传输' – unleashed

相关问题