一、准备
1、准备好html文件,在需要填充数据的地方用#name#标识,如图:
二、代码示例
1、依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.0.3</version>
</dependency>
2、代码示例
//生成PDF报告,返回总页数
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public int reportPDFOut(PDFInfoVO params) throws Exception{
File directory = new File("");
//pdf输出路径
String filePath = directory.getCanonicalPath() + File.separator + "fileout";
if(!new File(filePath).exists()){
new File(filePath).mkdir();
}
//字体格式
String FONT = directory.getCanonicalPath() + File.separator + "file/simsun.ttc";
//html模版
String HtmlFilePath = directory.getCanonicalPath() + File.separator + "file/report.html";
try {
//读取html文件模版
FileInputStream fileInputStream = new FileInputStream(HtmlFilePath);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"utf8"));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String htmlInfo = stringBuilder.toString();
//替换参数、多个参数多次替换
htmlInfo = htmlInfo.replace("#customerList#",buffer.toString());
//生成临时文件
String htmlFileName = UUID.randomUUID().toString().replace("-","") + ".html";
String htmlFilePath = filePath + File.separator + htmlFileName;
File file = new File(htmlFilePath);
FileOutputStream fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = htmlInfo.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
//生成pdf
String fileName = UUID.randomUUID().toString().replace("-","") + ".pdf";
String pdfFilePath = filePath + File.separator + fileName;
String url = new File(htmlFilePath).toURI().toURL().toString();
OutputStream os = new FileOutputStream(pdfFilePath);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.close();
//获取总页数
PdfReader pdfReader = new PdfReader(new FileInputStream(pdfFilePath));
int pages = pdfReader.getNumberOfPages();
//上传阿里云,获取文件路径
//删除临时文件
File delFile = new File(pdfFilePath);
if(delFile.exists()){
delFile.delete();
}
File delHtmlFile = new File(htmlFilePath);
if(delHtmlFile.exists()){
delHtmlFile.delete();
}
return pages;
} catch (Exception ex) {
throw new Exception(ex);
}
}
三、总结
该方法适用于数据不确定性的pdf文件生成,比如pdf包含动态表格的情况。
如果模版数据pdf文件数据格式不变,可参考利用PDF模版生成PDF文件_奕安的博客-CSDN博客,使用pdf模版,当然也可以使用html的方式生成。