java springboot 将html页面转成图片

一、实现流程:通过freemarker模板引擎将数据动态添加到模板中,然后将已添加动态数据的模板代码通过xhtmlrenderer转换成图片。

二、依赖jar:

     
           org.springframework.boot
          spring-boot-starter-freemarker
      

       
            org.xhtmlrenderer
            core-renderer
            R8
        

注意xhtmlrenderer中央仓库为:

      
              mvnrepository
              mvnrepository
              https://mvnrepository.com
        

三、模板引擎配置:

    spring:
        freemarker:
        cache: false
        # 字符集
        charset: UTF-8
        # 检查模板位置
        check-template-location: true
        # 模板内容类型
        content-type: text/html
        expose-request-attributes: true
        expose-session-attributes: true
        request-context-attribute: request
        # 模板位置
        template-loader-path: classpath:/templates

模板地址对应的地址为:


java springboot 将html页面转成图片_第1张图片
图片.png

三 模板代码 index.ftl

  
  
          
              
              海报
        
        
              
              ${msg}
         
  
注意:这里全部采用行内样式,却不能有js否则图片会展示出代码

四、生成图片代码

  public class FreemarkerUtils {

      private static String getTemplate(String template, Map map) throws IOException,TemplateException {
          Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
          String templatePath = FreemarkerUtils.class.getResource("/").getPath()+"/templates";
          cfg.setDirectoryForTemplateLoading(new File(templatePath));
          cfg.setDefaultEncoding("UTF-8");
          cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
          cfg.setLogTemplateExceptions(false);
          Template temp = cfg.getTemplate(template);
          StringWriter stringWriter = new StringWriter();
          temp.process(map, stringWriter);
          stringWriter.flush();
          stringWriter.close();
          String resutl = stringWriter.getBuffer().toString();
          return resutl;
      }

      public static void turnImage(String template, Map map, HttpServletResponse response) throws Exception {
          String html = getTemplate(template, map);

          byte[] bytes=html.getBytes();
          ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
          DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
          DocumentBuilder builder=factory.newDocumentBuilder();
          Document  document=builder.parse(bin);
          Java2DRenderer renderer = new Java2DRenderer(document,600,800);
          BufferedImage img = renderer.getImage();
          response.setContentType("image/jpeg");
          response.setDateHeader("expries", -1);
          response.setHeader("Cache-Control", "no-cache");
          response.setHeader("Pragma", "no-cache");
          ImageIO.write(img, "jpg", response.getOutputStream());
      }
  }

五、测试类

@RequestMapping(value = "/test", method = {RequestMethod.GET})
public void test(HttpServletResponse response) {
    try {
        Map map=new HashMap<>();
        map.put("msg","html--生成图片测试");
        map.put("img","https://upload-images.jianshu.io/upload_images/912344-3054132dd6939004.png?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240");
        FreemarkerUtils.turnImage("index.ftl",map,response);
    } catch (Exception e) {
        _log.error("异常", e.getMessage());
    }
}

六、效果


java springboot 将html页面转成图片_第2张图片
图片.png

你可能感兴趣的:(java springboot 将html页面转成图片)