前些天接了個(gè)需求, 需要推送產(chǎn)品 日/月/季 度榜單到群給大佬們看, 方便大佬們決策
飛書可以推送圖片
所以技術(shù)方案定為根據(jù)數(shù)據(jù)生成圖片
用node + puppeteer.js做了一版, 但是要另外起個(gè)服務(wù), 且要跑在有顯卡的服務(wù)器上
于是就用java實(shí)現(xiàn)了一遍 ( 有兩個(gè)方式, 傾向于用cssbox )
思路如下
1: 樣式有前端些( 畢竟java程序員大多數(shù)都很頭疼css )
2: 把模板渲染成頁面, 然后生成一張圖
三個(gè)依賴 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);
// 轉(zhuǎn)文檔
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);
// 創(chuàng)建一個(gè)字節(jié)流
InputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
DocumentSource docSource = new StreamDocumentSource(is, null, "text/html; charset=utf-8");
// 設(shè)置樣式屬性
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();
// 轉(zhuǎn)圖片
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;
}
}
調(diào)用 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;
}
}
至此完成,
至此完成,
目前已知坑點(diǎn)是對css3支持很差, 但其實(shí)css2已經(jīng)可以滿足大部分樣式要求了
部署到Linux系統(tǒng)上發(fā)現(xiàn) 中文亂碼
解決方案如下
- cd /usr/share/fonts
- 把字體包解壓進(jìn)去 https://pan.baidu.com/s/110yjyPIOCyudejPz5ZM0xw 提取碼:6666
- 執(zhí)行 yum install mkfontscale
- 執(zhí)行 mkfontscale
- 執(zhí)行 mkfontscale
- 執(zhí)行 fc-cache
- 重啟服務(wù)
- 模板文件加上以下css樣式
html{
font-family: "Microsoft YaHei", "Microsoft YaHei UI", "FangSong", "SimSun", "微軟雅黑","sans-serif";
}