所需jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<!--模板引擎相关依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<!--二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<!--pdf -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.18</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.0.7</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.0.7</version>
</dependency>
代码片段
/**
* 渲染html文件
* 将html转换为pdf,并设置目录,添加页眉,水印,背景
* @param response
* @param request
*/
public void generatePdf(HttpServletResponse response, HttpServletRequest request){
Map<String, Object> param = htmlParam();
log.info(“获取到模板内容,开始渲染html模板”);
WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale());
ctx.setVariables(param);
String htmlContent = templateEngine.process(HtmlTemplateEnum.REPORT_CREDIT_BASE.getLocalUrl(), ctx);
log.info(“模板内容渲染完成,开始转换为临时pdf文件”);
String basepath = this.getClass().getClassLoader().getResource("./").getPath();
String tempPath = basepath + “temp”;
File filedir = new File(tempPath);
if (!filedir.exists()) {// 文件夹不存在则创建
filedir.mkdirs();
}
String sourceFile = PdfUtil.createPDF(basepath, tempPath, htmlContent);
log.info(“临时pdf文件文件生成成功”);
// 新的pdf地址
String pdfNumber = “PDF” + System.currentTimeMillis();
// 二维码图片地址
String orImgPath = tempPath + File.separator + pdfNumber + “.png”;
// 新pdf地址
String targetFile = tempPath + File.separator + pdfNumber + “.pdf”;
String fontPath = basepath + “static” + File.separator + “simsun.ttc”;
// 二维码图片内容
String content = “www.baidu.com”;
try {
QRCodeUtils.encodeToPath(content, 100, 100, “png”, new File(orImgPath).getPath());
// 生成新的pdf
PdfUtil.createPdfWithCatalog(sourceFile, targetFile, fontPath, pdfNumber, this.catalogs(), orImgPath, basepath, “pdf生成工具”);
log.info(“pdf文件生成成功,文件地址为:”+targetFile);
}catch (Exception e){
log.info(“pdf生成出错,错误信息:”+e.getMessage());
}finally {
// 删除创建的临时文件
File file = new File(sourceFile);
if (file.exists()) {
file.delete();
}
/File file1 = new File(targetFile);
if (file1.exists()) {
file1.delete();
}/
File file2 = new File(orImgPath);
if (file2.exists()) {
file2.delete();
}
}
}