起因:需要画合同评审表的模板,由于对HTML不够熟悉,所以找到了jasper reports,使用jasper reports来画合同评审表的模板,然后生成合同评审表pdf,然后输出到页面上。
关键代码:
try {
// 导入模板
File file = new File(sourcePath);
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(file);
// 将JAVABEAN转换为map数据
Map<String, Object> parameters = BeanMapTool.beanToMap(contractAudit);
// 填充数据
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(auditFlowVOList));
jasperPrintList.add(jasperPrint);
// 输出pdf
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
byte[] bytes = baos.toByteArray();
File exportPdf = new File(fileSavePath+"\\" + orderNum + "合同评审表.pdf");
try {
FileOutputStream fos = new FileOutputStream(exportPdf);
fos.write(bytes);
System.out.println("写入成功");
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JRException e) {
e.printStackTrace();
}
坑1:输出整个页面空白
// 如果当new JRBeanCollectionDataSource(auditFlowVOList)为空时,输出整个页面为空白
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(auditFlowVOList));
坑2:输出中文空白
输出中文空白是因为,idea没有pdf模板中的中文字体导致,所以需要引入你在jasper resport中所用的字体文件。
在jasper reports中,右键项目,点击properties,进入fonts。
然后就可以在jasper resport中使用你的文件了。
这样还不够。
需要在idea中导入你所用到的字体文件。
先,将字体文件导出为jar包
导出为jar。
然后,在idea的控制台中,使用以下指令。
mvn install:install-file -Dfile="E:\font.jar" -DgroupId=cjc -DartifactId=cjc -Dversion=cjc -Dpackaging=jar
然后在你的pom文件中引入。
完成!