首页前端开发HTML使用freemarker动态填充html并可转为图片

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

时间2023-07-29 01:56:03发布访客分类HTML浏览330
导读:1. 引入依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-...

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, MapString, 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;
MapString, 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文件转为图片文件呢?

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 使用freemarker动态填充html并可转为图片
本文地址: https://pptw.com/jishu/340465.html
性价比高的香港云服务器怎么购买 免费服务器安全防护软件有哪些

游客 回复需填写必要信息