如何将freemarker文件转化为html文件?

最近在做静态的页面报表服务,将前端生成的ftl文件转化为html格式的文件,供后面合成pdf使用。

freemarker基础可以参见:freemarker官方文档

前期准备:需要一个基础的ftl格式的文件。

一个freemarker中注入的对象

这里面单独命名了一个类:

/**
 * 实体类
 * @author Xia
 */
public class Person {
    private String name;
    private String tele;
    private String email;

    public Person(String name, String tele, String email) {
        this.name = name;
        this.tele = tele;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTele() {
        return tele;
    }

    public void setTele(String tele) {
        this.tele = tele;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

具体的实现代码

static String templatePath = "/pdf0020ftlToHtml";
    static String templateName = "part2.ftl";
    static String targetHtmlPath = "src/main/resources/pdf0020ftlToHtml/part2.html";

    public static void crateHTML(String templatePath, String templateName, String targetHtmlPath) {
        FileWriter out = null;

        Person p = new Person("zhangsan", "13767682365", "qust@163.com");

        try {
            // 通过Configuration读取模版的配置文件
            Configuration freemarkerCfg = new Configuration(Configuration.VERSION_2_3_23);
            // 加载模版
            // 设置要解析的模板所在的目录  这里面有三种设置的方式
            // freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath));
            // freemarkerCfg.setServletContextForTemplateLoading(servletContext, path);

            freemarkerCfg.setClassForTemplateLoading(Pdf0020ftlToHtml.class, templatePath);
            // 设置默认的编码格式
            freemarkerCfg.setDefaultEncoding("utf-8");

            // 指定模版路径,并且获取模版
            Template template = freemarkerCfg.getTemplate(templateName, "utf-8");

            // 设置html静态页面输出路径
            File f = new File(targetHtmlPath);
            if (!f.exists()) {
                f.createNewFile();
            }
            out = new FileWriter(f);

            template.process(p, out);
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        crateHTML(templatePath, templateName, targetHtmlPath);
    }

注意,在web项目中可能会有乱码的情况。注意设置好响应的编码格式。