目录
1. 引入依赖
<dependency>
<groupId>gui.ava</groupId>
<artifactId>html2image</artifactId>
<version>2.0.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.14</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-core</artifactId>
<version>9.1.22</version>
</dependency>
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>cssbox</artifactId>
<version>5.0.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>org.codelibs.xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.12.0-sp1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<optional>true</optional>
</dependency>
2. 创建实体类
@Data
public class TemplateDTO {
/**
* 时间
*/
private String date;
/**
* 公司名称
*/
private String companyName;
}
3. 编写模版文件
在resources-template牡目录下创建weekNewspaper.ftl文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
body {
font-family: "SimSun,宋体";
}
.borderCss {
border: 1px solid black;
padding: 5px;
}
</style>
</head>
<body>
<table style="border-bottom: 1px solid black;border-top: 1px solid black;border-left: 1px solid black;border-right: 2px solid black;text-align:center;border-collapse: collapse;width:1800px">
<tr style="background: #e2f8ff">
<th style="border:1px solid black;height:40px">时间</th>
<th style="border:1px solid black;height:40px">公司名称</th>
</tr>
<tbody>
<#list list as row>
<tr>
<td class="borderCss">${row.date}</td>
<td class="borderCss">${row.companyName}</td>
</tr>
</#list>
</tbody>
</table>
</body>
</html>
4. 模版填充数据,然后转为图片保存在本地
Map<String, Object> htmlMap = new HashMap<>();
htmlMap.put(Constants.LIST, templateDTOList);
boolean html = getHtml(htmlMap, fileName);
/**
* html填充数据,然后转为图片保存在本地
*
* @param map html需要填充的数据
*/
private boolean getHtml(Map<String, Object> map, String fileName) {
//1. 将数据填充到html中
StringWriter stringWriter = new StringWriter();
try {
Template template = freemarkerConfig.getTemplate("weekNewspaper.ftl");
template.process(map, stringWriter);
} catch (Exception e) {
log.error("数据填充到html中失败: {}", e.getMessage());
return false;
}
//2. 将填充后的html转为图片存在本地
HtmlParser htmlParser = new HtmlParserImpl();
htmlParser.loadHtml(stringWriter.toString());
ImageRenderer renderer = new ImageRendererImpl(htmlParser);
File file = new File("/mnt/test/picture/");
file.mkdir();
renderer.saveImage("/mnt/test/picture/" + fileName + ".png");
return true;
}