SpringBoot整合Freemarker生成动态Html文件,并转成png图片

1.添加依赖
<!--  添加2个依赖 html2image 把html转换成图片格式 freemarker模板引擎-->
<dependency>  
	<groupId>gui.ava</groupId>   
	<artifactId>html2image</artifactId></dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.设置模板参数
// 在yml 文件中设置Freemarker模板参数
spring:
  profiles:
    active: dev
  ## 设定ftl文件路径
  freemarker:
    template-loader-path: classpath:/templates
    ##是否开启缓存
    cache: false
    ##设置编码格式
    charset: utf-8
    ##检查模板路径是否存在
    check-template-location: true
    ##请求头格式
    content-type: text/html
    expose-request-attributes: false
    expose-session-attributes: false
    request-context-attribute: request
    suffix: .html
    ##模板生成位置
    path: /data/image/skc/images/FreemarkerTemplates.html

####3.模板文件

//模板文件  index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div
      style="
        width: 333px;
        height: 585px;
        padding: 36px 0 0;
        box-sizing: border-box;
        background: #f8f3ea
          url(http://xxxx/miniapp/logo.png);
          no-repeat: center / cover;
        text-align: center;
        border-radius: 10px;
        text-align: center;
        line-height: 1;
      "
    >
      <img
        style="height: 20px"
        src="http://xxxx/miniapp/logo.png"
        alt
      />
      <p
        style="
          margin-block-start: 0;
          margin-block-end: 0;
          margin-inline-start: 0px;
          margin-inline-end: 0px;
          padding-top: 30px;
          font-size: 18px;
          font-weight: 400;
          color: #333333;
          line-height: 1;
          letter-spacing: 2px;
        "
      >
        您的专属qq顾问
      </p>
      <div
        style="
          margin: 20px auto 35px;
          width: 34px;
          height: 2px;
          background: #cb8831;
        "
      ></div>
      <img
        style="margin: 0 auto; width: 111px; height: 111px; border-radius: 50%"
        src=${FreemarkerFormVO.avatar}
        alt=""
      />
      <div
        style="
          padding-top: 10px;
          font-size: 21px;
          font-weight: 500;
          color: #333333;
          line-height: 30px;
          letter-spacing: 2px;
        "
      >
        ${FreemarkerFormVO.userName}
      </div>
      <div
        style="
          padding: 5px 0;
          font-size: 15px;
          font-weight: 400;
          color: #333333;
        "
      >
        ${FreemarkerFormVO.department}
      </div>

      <img
        style="margin: 40px auto 10px; width: 110px; height: 110px"
        src=${FreemarkerFormVO.qrCode}
        alt=""
      />
      <div
        style="
          font-size: 13px;
          font-weight: 400;
          color: #333333;
          line-height: 24px;
          letter-spacing: 2px;
        "
      >
        请加我的QQ
      </div>
    </div>
  </body>
</html>
4.接口生成pdf图片
 /**
  *  接口调用层
  * FreemarkerFormVO 入参实体类,对应index.html 中需要替换的参数
  */
   @ApiOperation(value="模板")
    @PostMapping("/freemarker")
    public  ResponseEntity<ResultBean<String>> freemarkerIndex(@Valid @RequestBody FreemarkerFormVO bean, Model model) {
        model.addAttribute("FreemarkerFormVO",bean);
        Map<String, FreemarkerFormVO> root = new HashMap(1);
        root.put("FreemarkerFormVO", bean);
        String filePath = freeMarkerContent(root);
        try {
            File file = ResourceUtils.getFile(filePath);
            String html = FileReader.create(file).readString();
            String s = switchToPic(html);
            s= s.replaceAll("\\r\\n", "");
            base64StringToImage(s);
            return ResultBeanUtil.success(s);
        } catch (Exception e) {
            log.error("", e);
        }
        return ResultBeanUtil.success(filePath);
    }


    //测试的时候  生成到D盘的AMD文件夹下
    private String freeMarkerContent(Map<String, FreemarkerFormVO> root) {
        try {
            Template temp = cfg.getTemplate("index.html");
            //以classpath下面的static目录作为静态页面的存储目录,同时命名生成的静态html文件名称
//            File pathFile = new File(path.substring(path.indexOf('/')));
            File pathFile = new File("D:\\AMD\\FreemarkerTemplates.html");
            if (!pathFile.getParentFile().exists()) {
                pathFile.getParentFile().mkdirs();
            }
            Writer file = new FileWriter(pathFile);
            temp.process(root, file);
            file.flush();
            file.close();
            return "D:\\AMD\\FreemarkerTemplates.html";
        } catch (IOException | TemplateException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    //变成base64格式
    private  String switchToPic(String html) {
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.getBufferedImage();
//        File path=new File(html);
//        String urlPath=path.toURL().toString();
//        imageGenerator.loadUrl(urlPath);
        imageGenerator.loadHtml(html);
        //这里如果指定了盘符,可以直接存在本地,自己本地写demo的话可以用
        String imageName = imagePath + "html1.png";
        imageGenerator.saveAsImage(imageName);
        BufferedImage buffimg = imageGenerator.getBufferedImage();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(buffimg, "png", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] bytes1 = os.toByteArray();
        return encoder.encodeBuffer(bytes1).trim();
    }

    //base64转图片,生成到指定目录
    private void base64StringToImage(String base64) {
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File f = new File("D:\\AMD\\html.png");
            ImageIO.write(bi1, "png", f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
5.html模板层级结构

在这里插入图片描述

Best Regards!
Make a little progress every day!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Freemarker是一种模板引擎,可以将数据和模板进行整合生成输出内容。SpringBoot提供了对Freemarker的支持,可以很方便地整合Freemarker。 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` 2. 配置文件 在application.properties文件中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.cache=false ``` - template-loader-path:模板文件的路径,这里设置为classpath:/templates/,表示在项目的classpath下的templates目录中查找模板文件。 - cache:是否开启模板缓存,这里设置为false,表示关闭缓存。 3. 创建模板文件 在classpath:/templates/目录下创建一个名为index.ftl的模板文件,内容如下: ```html <!DOCTYPE html> <html> <head> <title>SpringBoot整合Freemarker</title> </head> <body> <h1>${message}</h1> </body> </html> ``` 4. 创建控制器 创建一个名为IndexController的控制器,代码如下: ```java @Controller public class IndexController { @RequestMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, World!"); return "index"; } } ``` 该控制器中,使用@RequestMapping注解指定了请求路径为/,并将一个名为message的属性值设置为“Hello, World!”,然后返回了index作为视图名称。由于配置了spring.freemarker.template-loader-path=classpath:/templates/,所以SpringBoot会在classpath:/templates/目录下查找名为index的模板文件,并将模板文件中的${message}替换为“Hello, World!”。 5. 运行程序 启动应用程序,访问http://localhost:8080/,可以看到页面中显示了“Hello, World!”的字样。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值