html转图片
一、Pom依赖
<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>
二、freemarker模板
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>LogParse问题统计结果</title>
<style>
table.reference {
border-collapse: collapse;
width: 100%;
margin-bottom: 4px;
margin-top: 4px;
}
table.reference tr:nth-child(even) {
background-color: #fff;
}
table.reference tr:nth-child(odd) {
background-color: #f6f4f0;
}
table.reference th {
color: #fff;
background-color: #0dcde8;
border: 1px solid #555;
font-size: 14px;
padding: 4px;
vertical-align: center;
}
table.reference td {
line-height: 2em;
min-width: 24px;
border: 1px solid #d4d4d4;
padding: 7px 5px;
vertical-align: center;
text-align: center;
}
.article-body h3 {
font-size: 1.8em;
margin: 2px 0;
line-height: 1.8em;
}
</style>
</head>
<body>
<div>
<table class="reference">
<tbody>
<tr>
<th colspan="5" >问题统计结果</th>
</tr>
<tr>
<th>统计时间</th>
<th>日志类型</th>
<th>问题类型</th>
<th>问题出现次数</th>
<th>车机数</th>
</tr>
<#list problemList as element>
<tr>
<td> ${element.statisticsTime} </td>
<td> ${element.logSource} </td>
<td> ${element.problemType} </td>
<td> ${element.totalQuantity} </td>
<td> ${element.totalVin} </td>
</tr>
</#list>
</tbody>
</table>
</div>
</body>
</html>
三、代码实现
大致过程:组装Model数据,加载freemarker模板,生成Html文件,再将Html文件转成图片(可以设置图片的长和宽,字体等)
// 查询数据库生成Model
QueryWrapper<ProblemStatistics> queryWrapper = new QueryWrapper<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String statisticsTime = LocalDate.now().minusDays(2).format(formatter);
queryWrapper
.ge("statistics_time", statisticsTime)
.orderByDesc("statistics_time", "total_quantity");
List<ProblemStatistics> problemList = problemStatisticsMapper.selectList(queryWrapper);
// 通过数据model和模板生成html
Map<String, Object> model = new HashMap<String, Object>();
model.put("problemList", problemList);
Template template = configuration.getTemplate("logparse.ftlh");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
// 将html转成文件
String inputFileName = "logparse.xhtml";
FileWriter writer = new FileWriter(inputFileName);
writer.write(html);
writer.flush();
writer.close();
// 将html文件转成图片
String outFileName = "logparse.jpg";
File imageFile = new File(inputFileName);
int widthImage = 1600;
int heightImage = 1000;
Java2DRenderer renderer = new Java2DRenderer(imageFile, widthImage, heightImage);
BufferedImage img = renderer.getImage();
FSImageWriter imageWriter = new FSImageWriter();
imageWriter.setWriteCompressionQuality(0.9f);
imageWriter.write(img, outFileName);, outFileName);
四、效果