java springboot 将html页面转成图片

原文地址: https://www.jianshu.com/p/bedacdc8841b

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

二、依赖jar:

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

<dependency>
  <groupId>org.xhtmlrenderer</groupId>
  <artifactId>core-renderer</artifactId>
  <version>R8</version>
</dependency>

注意xhtmlrenderer中央仓库为:

<repository>
  <id>mvnrepository</id>
  <name>mvnrepository</name>
  <url>https://mvnrepository.com</url>
</repository>

三、模板引擎配置:

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

模板地址对应的地址为:

模板代码 index.ftl

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <title>海报</title>
</head>
<body style=" 500px; height: 800px;margin: 0;padding: 0;">
  <img src="${img}" alt="" />
  <span>${msg}</span>
</body>
</html>

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

四、生成图片代码

public class FreemarkerUtils {

    private static String getTemplate(String template, Map<String,Object> 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<String,Object> 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<String,Object> 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());
  }
}

六、效果


补充使用感受:

图片不能引用本地图片,/images/a.png这种形式无法加载,必须是http://xxx/images/a.png形式才行

打成jar包,放在linux服务器上,获取不到jar包里面的模板. 线上部署的话,最好通过配置指定模板路径

如果需要导出到文件,可以使用下面代码

方式1:
ImageIO.write(img, "jpg", file);

方式2:
FSImageWriter imageWriter = new FSImageWriter();
imageWriter.setWriteCompressionQuality(1.0f);//设置压缩率
imageWriter.write(img, file);

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注