springboot使用itext生成pdf并保存到本地

使用html渲染页面,将页面转换为pdf文件,设置pdf页眉,页码,水印,目录,二维码

  • 所需jar包
    • 代码片段
    • 代码连接地址

所需jar包

	
        org.projectlombok
        lombok
    

    
        org.apache.commons
        commons-lang3
        3.5
    
    
        com.google.guava
        guava
        21.0
    
    
    
        org.thymeleaf
        thymeleaf-spring5
    
    
        org.springframework
        spring-test
        5.1.3.RELEASE
        compile
    

    
    
        com.google.zxing
        javase
        3.3.3
    
    
        com.google.zxing
        core
        3.3.3
    

    
    
        org.xhtmlrenderer
        flying-saucer-pdf-itext5
        9.1.18
    

    
        com.itextpdf
        kernel
        7.0.7
    
    
        com.itextpdf
        layout
        7.0.7
    

代码片段

/**
* 渲染html文件
* 将html转换为pdf,并设置目录,添加页眉,水印,背景
* @param response
* @param request
*/
public void generatePdf(HttpServletResponse response, HttpServletRequest request){
Map 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();
}
}

}

代码连接地址

链接: https://download.csdn.net/download/whyUnhappy/15513597.

你可能感兴趣的:(使用itext生成pdf,html模板渲染,java,xpdf,spring,boot)