html转成PDF,替换内容

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body class="b1 b2">
<p class="p1"> <span class="s1">个人信息授权书本人(姓名:${realName}</span> </p>
</body>
</html>

比如有如上所以一个html文件,需要转成同样格式的pdf文件,同时替换 realName成真实姓名。java项目resources根目录下有个templates文件夹,test.html在templates目录下。

Configuration起到缓存Template作用,不用每次生成Template时都需要重新生成,

import freemarker.template.Configuration
import freemarker.template.Template
import org.apache.commons.io.FileUtils
import org.apache.commons.io.IOUtils

public class CrdQueryProvider{
private static Configuration cfg
    static{
      //从jar templates目录加载html freemarker模版
        cfg = new Configuration()
        cfg.setClassForTemplateLoading(CrdQueryProvider.class, "/templates")
        cfg.setDefaultEncoding("UTF-8");
      }
public static void htmlToPdf(){
    Map instContractModel = new HashMap(){{put("realName":    "张三")}}
    //加载模版 cfg缓存
                    Template template = cfg.getTemplate("test.html")
     //模版格式化后的输出
                    String output = loadFtlHtml( template, instContractModel)
FileOutputStream outputStream = new FileOutputStream("/data/test.pdf", false)
savePdf(outputStream, output)
}
    
public static void savePdf(OutputStream out, String html) {
        Document document = new Document(PageSize.A4, 50, 50, 60, 0);//marginBottom : 60
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            Charset charset = Charset.forName("UTF-8");
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes("UTF-8")),charset, new PdfFont());
        } catch (Exception e) {
            logger.warn(String.format("savaPDF failure ex: %s",e.getMessage()), e);
            throw new RuntimeException(e);
        } finally {
            document.close();
        }
    }

public static String loadFtlHtml( Template template, InstContractModel model){
        if(template == null || model ==null) {
            logger.warn("loadFtlHtml异常,参数不对");
        }

        StringWriter stringWriter = null;
        try {
            stringWriter = new StringWriter();
            template.process(model, stringWriter);

            return stringWriter.toString();
        } catch (Exception e) {
            logger.error("process异常",e);
        } finally {
            if (null != stringWriter) {
                try {
                    stringWriter.close();
                } catch (IOException e) {
                    logger.error("close异常",e);
                }
            }
        }
        return null;
    }
}

StringWriter存放输出字符串。

欢迎关注Java流水账公众号
原文地址:https://www.cnblogs.com/guofu-angela/p/10067412.html