前些天接了个需求, 需要推送产品 日/月/季 度榜单到群给大佬们看, 方便大佬们决策
飞书可以推送图片
所以技术方案定为根据数据生成图片
用node + puppeteer.js做了一版, 但是要另外起个服务, 且要跑在有显卡的服务器上
于是就用java实现了一遍 ( 有两个方式, 倾向于用cssbox )
思路如下
1: 样式有前端些( 毕竟java程序员大多数都很头疼css )
2: 把模板渲染成页面, 然后生成一张图
三个依赖 pom.xml
<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>
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>cssbox</artifactId>
<version>4.12</version>
</dependency>
核心工具类 FreemarkerUtils.class
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.fit.cssbox.css.CSSNorm;
import org.fit.cssbox.css.DOMAnalyzer;
import org.fit.cssbox.io.DocumentSource;
import org.fit.cssbox.io.StreamDocumentSource;
import org.fit.cssbox.layout.BrowserCanvas;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Component
public class FreemarkerUtils {
private static String fileUrl = FreemarkerUtils.class.getResource("/").getPath();
public static String getTemplate(String template, Object object) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
String templatePath = fileUrl + "html/";
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(object, stringWriter);
stringWriter.flush();
stringWriter.close();
return stringWriter.getBuffer().toString();
}
public BufferedImage turnImage(String template, Object object, Integer width, Integer height) throws Exception {
String html = getTemplate(template, object);
// 转文档
byte[] bytes=html.getBytes();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(bin);
/*
画笔生成图
*/
DOMAnalyzer da = new DOMAnalyzer(document);
// 创建一个字节流
InputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
DocumentSource docSource = new StreamDocumentSource(is, null, "text/html; charset=utf-8");
// 设置样式属性
da.attributesToStyles();
da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT);
da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT);
da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT);
da.getStyleSheets();
// 转图片
BrowserCanvas contentCanvas = new BrowserCanvas(da.getRoot(), da, docSource.getURL());
contentCanvas.createLayout(new Dimension(width, height));
// contentCanvas.setSize(width, height);
// contentCanvas.setAutoSizeUpdate(false);
// 生成图片
BufferedImage img = contentCanvas.getImage();
/*
Rendere文档生成图
*/
// Java2DRenderer renderer = new Java2DRenderer(document, width, height);
// BufferedImage img = renderer.getImage();
// final FSImageWriter imageWriter = new FSImageWriter();
// imageWriter.setWriteCompressionQuality(1.0f);
// // 生成图片名字
// String uuid = UUID.randomUUID().toString();
// //输出路径
// imageWriter.write(img, "E:\\8080server\\img\\" + uuid + ".jpg");
return img;
}
}
调用 LaunchPlanTopToImgHandleJob.class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.image.BufferedImage;
@Service
public class LaunchPlanTopToImgHandleJob {
@Autowired
FreemarkerUtils freemarkerUtils;
public BufferedImage createByFtlToImg (Object object, String type, Integer width, Integer height) throws Exception {
String template = "";
BufferedImage img = null;
switch (type){
// 模板
default: template = "index.ftl";
img = freemarkerUtils.turnImage(template, object, width, height);
}
return img;
}
}
至此完成,
至此完成,
目前已知坑点是对css3支持很差, 但其实css2已经可以满足大部分样式要求了
部署到Linux系统上发现 中文乱码
解决方案如下
- cd /usr/share/fonts
- 把字体包解压进去 https://pan.baidu.com/s/110yjyPIOCyudejPz5ZM0xw 提取码:6666
- 执行 yum install mkfontscale
- 执行 mkfontscale
- 执行 mkfontscale
- 执行 fc-cache
- 重启服务
- 模板文件加上以下css样式
html{
font-family: "Microsoft YaHei", "Microsoft YaHei UI", "FangSong", "SimSun", "微软雅黑","sans-serif";
}