需求描述:
需要将数据转存为图片在前端展示。
查阅资料后使用ftl模板,
1. 填充数据后使用freemaker进行html转png,
2. 将png转base64字符串传给前端进行渲染。
依赖
<!-- freemarker模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
数据准备
// 1.获取需要展示的数据
List<HjtzxTemplate> templateData = null;
String templateFileName = "";
String generateFileName = "";
if ("10".equals(calType)){
templateFileName = "qd.ftl";
templateData = mainBussinessMapper.getTemplateDataOfQd(userId,prdId,calType);
generateFileName = userId+"-QD.png";
} else if ("20".equals(calType)) {
templateFileName = "zy.ftl";
templateData = mainBussinessMapper.getTemplateDataOfZy(userId,prdId,calType);
generateFileName = userId+"-ZY.png";
} else {
logger.error("生成立项表传入计算类型有误,请检查后重新输入:"+calType);
throw new Exception("当前传入产品ID有误,请检查后重新输入");
}
if (templateData.size() == 0) {
res.put("message","当前用户不存在产品数据,生成立项表失败!");
res.put("code","40002");
res.put("data",null);
return res;
}
ModelMap modelMap = new ModelMap();
*.ftl
<html>
<head>
<style>
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<div align="center">
<h4>和办公产品立项表(渠道)</h4>
</div>
<div style="text-align:center;">
<table border="1" style="margin: auto;" width='80%' >
<tr>
<th>客户全称</th>
<th>移动分公司</th>
<th>客户经理</th>
<th>业务支撑</th>
<th>提报日期</th>
<th>档位</th>
<th>功能费</th>
<th>合约期(月)</th>
<th>颜色</th>
<th>数量</th>
<th>单台采购价</th>
<th>采购价小计</th>
<th>是否符合利润标准(是/否)</th>
</tr>
<#list templateData as item>
<tr><td>${item.customerFullName}</td>
<td></td>
<td>${item.customerManager}</td>
<td>${item.customerManager}</td>
<td>${item.insertTime}</td>
<td>${item.gearSecName}</td>
<td></td>
<td>${item.gearName}</td>
<td></td>
<td>${item.gearAmount}</td>
<td>${item.singleQdPrice}</td>
<td>${item.totalQqdPrice}</td>
<td></td>
</tr>
</#list>
</table>
</div>
</body>
</html>
工具类
package com.zhengqi.png;
import com.zhengqi.util.FileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
/**
* @author zhuling
* @Description
* @create 2021-07-14 15:40
*/
public class FreemarkeTools {
private static final Logger logger = LoggerFactory.getLogger(FreemarkeTools.class);
private static final String encoding = "UTF-8";
/**
* 获取模板转为html
*/
public static String ftlToString(Map<String,Object> map, String templateName) throws IOException, TemplateException {
String value = "";
Configuration configuration = new Configuration();
// linux环境用不了
// Resource resource = new ClassPathResource("templates");
// File sourceFile = resource.getFile();
// String ftlPath = sourceFile.getAbsolutePath();
StringWriter out = new StringWriter();
configuration.setDirectoryForTemplateLoading(new File("/opt/calculator/file/template"));
configuration.unsetCacheStorage();
Template template = configuration.getTemplate(templateName,encoding);
template.setEncoding(encoding);
template.process(map, out);
out.flush();
out.close();
value = out.getBuffer().toString();
// logger.info("模板文件html内容为:======="+value);
return value;
}
/**
* html转为图片
* @param html
* @param inputFileName
* @param outputFileName
* @param widthImage
* @param heightImage
* @return
* @throws IOException
*/
public static String turnImage(String html, String inputFileName, String outputFileName
,int widthImage, int heightImage) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputFileName),encoding));
bufferedWriter.write(html);
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
File f = new File(inputFileName);
Java2DRenderer renderer = new Java2DRenderer(f, widthImage, heightImage);
BufferedImage image = renderer.getImage();
FSImageWriter imageWriter = new FSImageWriter();
imageWriter.setWriteCompressionQuality(0.9f);
File imgFile = new File(outputFileName);
FileOutputStream fout = new FileOutputStream(imgFile);
imageWriter.write(image, fout);
fout.close();
return outputFileName;
}
}
问题记录
(1)首先模板文件转html出现乱码
解决:
在ftl文件中添加代码:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
(2)其次在html转图片之后,出现中文乱码:
将下载好的ttc和ttf文件上传到服务器的路径:
/usr/share/fonts/chinese路径下(chinese文件夹要新建)
http://www.pc6.com/softview/SoftView_100415.html(下载地址)
1. 修改权限:
chmod -R 755 /usr/share/fonts/Chinese
2. 安装yum -y install ttmkfdir
3. 执行:ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir
4. vi /etc/fonts/fonts.conf
5. fc-cache 刷新缓存
6. Fc -list检查列表
7. 如果还没有好就重启下服务器