通过 JSF 将 PDF 发送到浏览器

2023-12-08

我正在尝试将 JasperReports 生成的 PDF 文件发送到用户的浏览器,我找不到托管 bean 方法中的问题,以下是一个片段:

System.out.println("Making pdf...");

        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        String tplPath = ec.getRealPath("testTemplate.jrxml");
        JasperReport jasperReport = JasperCompileManager.compileReport(tplPath);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String,Object>(), ds );

        String pdfName = "/testReport.pdf";
        String pdfPath = ec.getRealPath(pdfName);
        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);

        System.out.println("PDF ready!");

        ec.responseReset(); 
        ec.setResponseContentType(ec.getMimeType(pdfPath)); 
        //ec.setResponseContentLength(contentLength); 
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\""); 

        InputStream input = new FileInputStream(pdfPath);
        OutputStream output = ec.getResponseOutputStream();
        IOUtils.copy(input, output);

        System.out.println("Sending to browser...");

        fc.responseComplete();  

只需用户单击即可调用它:

<p:menuitem value="TestPDF" action="#{menuController.getTestPdf()}" />

我感觉这件事很容易查出来。为什么我看不到? :)


The <p:menuitem>默认使用ajax。不能通过ajax下载文件。由于安全原因,JavaScript 无法以编程方式强制执行Save As与变量中的任意内容进行对话。

关掉ajax就可以了。

<p:menuitem ... ajax="false" />

也可以看看:

  • 如何从 JSF 支持 bean 提供文件下载?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 JSF 将 PDF 发送到浏览器 的相关文章

随机推荐