需要使用到core-renderer-R8這個工具,加入以下依賴:
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>R8</version>
</dependency>
工具類FtlUtil:
public class FtlUtil {
private static String getTemplate(String template, Map<String, Object> map) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
String templatePath = FtlUtil.class.getResource("/").getPath() + "/templates";
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(map, stringWriter);
String result = stringWriter.getBuffer().toString();
stringWriter.flush();
stringWriter.close();
return result;
}
/**
* 模板文件轉圖片
* @param template 模板文件地址
* @param map 數據map
* @param tagPath 保存圖片地址
* @param width 圖片寬度
* @param height 圖片高度
* @throws Exception
*/
public static void turnImage(String template, Map<String, Object> map, String tagPath, int width, int height) throws Exception {
String html = getTemplate(template, map);
byte[] bytes = html.getBytes();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(bin);
Java2DRenderer renderer = new Java2DRenderer(document, width, height);
BufferedImage img = renderer.getImage();
ImageIO.write(img, "jpg", new File(tagPath));
}
}
freemarker模板文件report.html:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"></meta>
<title>報表模板</title>
<style type="text/css">
header div {
font-size: 16px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1rem;
color: #212529;
border-color: rgba(77, 82, 89, 0.07)!important;
border: 1px solid #dee2e6;
}
table td, table th {
border: 1px solid #dee2e6;
}
</style>
</head>
<body>
<div>
<header><div>${title}</div></header>
<table>
<thead>
<tr>
<th>#</th>
<#list fieldNames as fieldNames>
<th>${fieldName}</th>
</#list>
</tr>
</thead>
<tbody>
<#list list as row>
<tr>
<th scope="row">${row_index + 1}</th>
<#list fields as field>
<td>${row[field]!''}</td>
</#list>
</tr>
</#list>
</tbody>
</table>
</div>
</body>
</html>
調用FtlUtil.turnImage生成圖片:
Map<String,Object> map = new HashMap<>();
map.put("title", "測試報表"); // 標題
map.put("fieldNames", fieldNames); // fieldNames是字段中文名
map.put("fields", fields); // fields是字段名
map.put("list", list); // list是數據列表
FtlUtil.turnImage("report.html", map, "result.jpg", 600, 700);
效果:
注意:
模板文件中的外部css和js是無法加載和起作用的,所以樣式要直接寫在模板文件中。