如何将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项目中可能会有乱码的情况。注意设置好响应的编码格式。
分类:
itext
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话