javaspringboot将html页⾯转成图⽚
⼀、实现流程:通过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>mvnrepository</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 >
<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 = Resource("/").getPath()+"/templates";
cfg.setDirectoryForTemplateLoading(new File(templatePath));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
Template temp = Template(template);
StringWriter stringWriter = new StringWriter();
temp.process(map, stringWriter);
stringWriter.flush();
stringWriter.close();
String resutl = Buffer().toString();
return resutl;
}
public static void turnImage(String template, Map<String,Object> map, HttpServletResponse response) throws Exception {
五、测试类
@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","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) {
<("异常", e.getMessage());
}
}
六、效果pdf转html
补充使⽤感受:
1.
2. 打成jar包,放在linux服务器上,获取不到jar包⾥⾯的模板. 线上部署的话,最好通过配置指定模板路径
3. 如果需要导出到⽂件,可以使⽤下⾯代码
⽅式1:
ImageIO.write(img, "jpg", file);
⽅式2:
FSImageWriter imageWriter = new FSImageWriter();
imageWriter.setWriteCompressionQuality(1.0f);//设置压缩率
imageWriter.write(img, file);