使用freemarker动态填充html并可转为图片
1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2. 模板html文件中将需要替换的地方使用占位符进行替换
- 使用占位符
${}
进行占位操作;
<div style="height: 17px;">
<span style="height: 100%;
line-height: 17px;">姓名:</span>
<span style="height: 100%;
line-height: 17px;">${name}</span>
</div>
3. 编写Util类
- 使用
try (FileWriter writer = new FileWriter(targetHtmlPath)) { }
来自动关闭流,避免手动释放; - 将模板
html
文件放到starter
目录下的resource
里的templates
包下即可;
public class GenHtmlUtil {
public static void genNewHtml(String template, Map<String, Object> map, String targetHtmlPath) {
try (FileWriter writer = new FileWriter(targetHtmlPath)) {
Configuration configuration = new Configuration(Configuration.getVersion());
String templatePath = GenHtmlUtil.class.getResource("/").getPath() + "templates";
configuration.setDirectoryForTemplateLoading(new File(templatePath));
Template t = configuration.getTemplate(template);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
writer.write(content);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 调用Util
- 对第2步中使用
${}
进行占位的地方使用Map
进行填充,并调用Util;
Map<String, Object> map = Maps.newHashMap();
map.put("name", name);
map.put("sex", sex);
map.put("age", age);
GenHtmlUtil.genNewHtml("template.html", map, "result.html");
然后就可在项目根目录下找到生成的名为"result.html"
的html
文件啦。
那么如何将生成的html文件转为图片文件呢?
请看我的另一篇博客:使用cssbox将html文件转为图片文件