使用freemarker动态填充html并可转为图片

1. 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2. 模板html文件中将需要替换的地方使用占位符进行替换

  1. 使用占位符${}进行占位操作;
<div style="height: 17px;">
  <span style="height: 100%;
  line-height: 17px;">姓名:</span>
  <span style="height: 100%;
  line-height: 17px;">${name}</span>
</div>

3. 编写Util类

  1. 使用try (FileWriter writer = new FileWriter(targetHtmlPath)) { }来自动关闭流,避免手动释放;
  2. 将模板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

  1. 对第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文件转为图片文件

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kuo-Teng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值