这是我第一次使用Jasper Report,我需要使用Java Server Face JSF生成PDF,所以,PDF生成后,它应该由浏览器下载
我使用netbeans代码生成Web应用程序,使用java服务器面框架和primefaces
public void createPDF() throws IOException {
List<Pelanggan> asdf = pelangganFacade.findAll();
try {
ServletContext ctx = (ServletContext)FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String ReportTemplate = ctx.getRealPath("/WEB-INF/Blank_A4.jasper");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("nama", asdf.get(1));
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance()
.getExternalContext().getContext();
response.addHeader("Content-disposition", "attachment; filename=testing.pdf");
ServletOutputStream outputStream = response.getOutputStream();
JasperPrint jasperPrint = JasperFillManager.fillReport(ReportTemplate, parameters);
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
} catch (JRException ex) {
Logger.getLogger(TestReport.class.getName()).log(Level.SEVERE, null, ex);
}
}
但它没有工作,给我一个错误
java.lang.ClassCastException: org.apache.catalina.core.ApplicationContextFacade cannot be cast to javax.servlet.http.HttpServletResponse
Caused by: java.lang.ClassCastException: org.apache.catalina.core.ApplicationContextFacade cannot be cast to javax.servlet.http.HttpServletResponse
at com.joandilee.TestReport.createPDF(TestReport.java:55)
是否有任何简单的方法来使用Jasper报告生成PDF报告,然后将其下载到浏览器?
这不是Jasper的错误
代替HttpServletResponse response = (HttpServletResponse)FacesContext
.getCurrentInstance().getExternalContext().getContext();
HttpServletResponse response = (HttpServletResponse) FacesContext
.getCurrentInstance().getExternalContext().getResponse();