@[TOC]
1.需要的maven依赖
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- htmlString生成图片 -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>R8</version>
</dependency>
2.需要的模板文件(例子)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8"></meta>
<title>测试</title>
<style>
</style>
</head>
<body>
<div >
<div style="font-size: 100px;margin: 0;text-align: center">
${name!''}
</div>
<div style="text-align: center">
<img src="${picture}" alt=""></img>
</div>
</div>
</body>
</html>
存放位置:
3.新建FreeMarkerUtils
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xml.sax.SAXException;
import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class FreeMarkerUtils {
public static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtils.class);
/**
* FreemarkerUtils加载index.ftl模板,渲染数据
* @param template
* @param map
* @return
* @throws IOException
* @throws TemplateException
*/
public static String getTemplate(String template, Map<String, Object> map) {
//创建freeMarker配置对象
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//设置读取模板的基础路径
cfg.setTemplateLoader(new ClassTemplateLoader(
FreeMarkerUtils.class.getClass().getClassLoader(), "/templates"));
//设置编码格式
cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
//设置模板异常处理
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
//选择日志处理
cfg.setLogTemplateExceptions(true);
Template temp = null;
String result = "";
try {
//获取模板问价
temp = cfg.getTemplate(template, StandardCharsets.UTF_8.toString());
StringWriter stringWriter = new StringWriter();
//替换占位符
temp.process(map, stringWriter);
stringWriter.flush();
stringWriter.close();
//获取ftl内容字符串
result = stringWriter.getBuffer().toString();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
logger.info("模板读取异常" + e.getBlamedExpressionString());
e.printStackTrace();
}
return result;
}
/**
* 生成Image
* @param template 模板地址
* @param map 替换对象
* @param width 图片宽度
* @param height 图片高度
* @throws Exception
*/
public static void turnImage(String template, Map<String, Object> map,Integer width,Integer height,String format,String outImagePath) {
//获取freeMarker替换占位符后的字符串
String html = FreeMarkerUtils.getTemplate(template, map);
//将字符串转为bytes
byte[] bytes = html.getBytes(StandardCharsets.UTF_8);
//将byte[]转换为流
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
//实例化文档工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
//利用文档工厂实例化文档
DocumentBuilder builder = factory.newDocumentBuilder();
//解析流
Document document = builder.parse(bin);
//设置渲染图片的像素(宽和高)
Java2DRenderer renderer = new Java2DRenderer(document, width, height);
//获取渲染后的BufferedImage
BufferedImage img = renderer.getImage();
//在生成图片
ImageIO.write(img,format,new File(outImagePath));
//关闭流
bin.close();
} catch (ParserConfigurationException e) {
logger.info("解析流出现异常!" + e.getStackTrace());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "迪迦");
map.put("picture", "file:///E://picture//23.jpg");
turnImage("index.ftl", map,1000,1600,"jpg","E:\\picture\\迪迦.jpg");
}
}