我使用的是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 response文件包含了附件;
额外:
当浏览器打开PDF
格式时,它也显示保存选项,您也可以在浏览器打开(加载)后保存它