下载 Jasper 报告而不是在浏览器中打开

Download Jasper report instead of opening in browser

我正在使用 PrimeFaces 5.1 和 JSF 2.2

以下是我的代码:我正在从 TableModelDate 方法生成 PDF 文件,一切正常。但是我的浏览器打开了怎么不打开就下载呢

public void PDF() throws JRException, IOException {
    HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    simpleReport();
    httpServletResponse.addHeader("Content-disposition", "filename=report.pdf");
    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
    JasperExportManager.exportReportToPdfStream(jasperPrint,servletOutputStream);
    FacesContext.getCurrentInstance().responseComplete();
}

public void simpleReport() {
    TableModelData();
    try {
        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/");
        JasperCompileManager.compileReportToFile(reportPath+"/Report.jrxml");
        jasperPrint = JasperFillManager.fillReport(reportPath+"/Report.jasper", new HashMap(),new JRTableModelDataSource(tableModel));
    } catch (JRException ex) {
        ex.printStackTrace();
    }
}

你离它很近了。

只需添加 attachment; 语句和 filename=xx.pdf 喜欢:

httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");

它告诉 Http Servlet 响应该文件包含附件;

额外:

每当浏览器打开 PDF 格式时,它还会显示保存选项,您也可以在浏览器中打开(加载)后保存它