一、实现流程:通过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 getTemplateString template, Map<String,Object> map) throws IOException,TemplateException {
Configuration cfg = new ConfigurationConfiguration.VERSION_2_3_25);
String templatePath = FreemarkerUtils.class.getResource"/").getPath)+"/templates";
cfg.setDirectoryForTemplateLoadingnew FiletemplatePath));
cfg.setDefaultEncoding"UTF-8");
cfg.setTemplateExceptionHandlerTemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptionsfalse);
Template temp = cfg.getTemplatetemplate);
StringWriter stringWriter = new StringWriter);
temp.processmap, stringWriter);
stringWriter.flush);
stringWriter.close);
String resutl = stringWriter.getBuffer).toString);
return resutl;
}
public static void turnImageString template, Map<String,Object> map, HttpServletResponse response) throws Exception {
String html = getTemplatetemplate, map);
byte[] bytes=html.getBytes);
ByteArrayInputStream bin=new ByteArrayInputStreambytes);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance);
DocumentBuilder builder=factory.newDocumentBuilder);
Document document=builder.parsebin);
Java2DRenderer renderer = new Java2DRendererdocument,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.writeimg, "jpg", response.getOutputStream));
}
}
五、测试类
@RequestMappingvalue = "/test", method = {RequestMethod.GET})
public void testHttpServletResponse 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.writeimg, "jpg", file);
方式2:
FSImageWriter imageWriter = new FSImageWriter);
imageWriter.setWriteCompressionQuality1.0f);//设置压缩率
imageWriter.writeimg, file);