制作pdf
使用iReport-5.6.0(需要jdk1.7环境)软件制作pdf模板,一般会生成jrxml格式文件
生成pdf
项目中引入依赖包,如下:
<!-- jasperreports Start -->
<!-- 该包的作用完成ireport中Preview按扭功能。通过该包可以通过java来ireport生成模板(.jrxml或.jasper)填充数据源并导出pdf,excel,html等格式文件 -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.0.0</version>
</dependency>
<!-- 生成pdf所依赖的包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-pdfa</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!--将.jrxml编译成.jasper.如果你不使用java编译,而使用ireport工具编译则无须导入该 包 -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.13</version>
</dependency>
<!-- jasperreports End -->
//jrxmlSourcePath 输入的jrxml文件路径,jasperFilePath 输出的jasper文件路径
JasperCompileManager.compileReportToFile(jrxmlSourcePath, jasperFilePath);
//jasperFilePath 输入的jasper文件路径,pdfOutPutPath 生成的pdf文件路径
JasperReportUtil.printPdfWithJasper(jasperFilePath, pdfOutPutPath, list, parameterMap);
JasperReporUtil代码如下:
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.*;
import net.sf.jasperreports.export.type.PdfaConformanceEnum;
import java.io.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class JasperReportUtil {
public static JasperPrint fill(String jasperTemplatePath, Map<String, Object> parameters, Connection connection) {
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperTemplatePath, parameters, connection);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public static JasperPrint printPdfWithJasper(String jasperTemplatePath, String filePath, List list, Map<String, Object> parameters) throws Exception {
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperTemplatePath, parameters, dataSource);
File destFile = new File(filePath);
JRPdfExporter exporter = new JRPdfExporter();
SimpleExporterInput simpleExporterInput = new SimpleE