用JasperResport生成模板文件,放在WEB-INF目录下
maven引入依赖
<!-- groovy --> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.2.0</version> </dependency> <!-- jasperreport --> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>5.2.0</version> <exclusions> <exclusion> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> </exclusion> </exclusions> </dependency>
根据jasperReport模板生成PDF的模板代码
// 根据 jasperReport模板 生成pdf // 读取模板文件 String jrxml = ServletActionContext.getServletContext().getRealPath( "/WEB-INF/jasper/xxx.jrxml"); JasperReport report = JasperCompileManager.compileReport(jrxml); // 设置模板数据 // Parameter变量 Map<String, Object> paramerters = new HashMap<String, Object>(); paramerters.put("company", "xxx"); // Field变量 JasperPrint jasperPrint = JasperFillManager.fillReport(report, paramerters, new JRBeanCollectionDataSource(你的数据)); // 生成PDF客户端 JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ServletActionContext.getResponse().getOutputStream()); exporter.exportReport();// 导出 ServletActionContext.getResponse().getOutputStream().close();