我正在参与掘金创作者训练营第4期(带链接:juejin.cn/post/706419…
利用freemarker模板生成pdf (一)
需求
根据模板生成pdf,并且需要插入柱状图,雷达图等统计图表
实现思路
在网上查询了很多生成pdf的案例,但是实现起来都比较麻烦,所以决定曲线救国,先生成word文档,再将word文档转换成pdf
1 准备工作
将准备好的word模板,另存为xml形式 文件 ->另存为->其他格式->xml
2 动态替换模板内容
${变量} 替换你需要动态生成的内容 模板图片会转换成base64的字符串,需要把这一长串都替换掉
3 将模板放到指定目录
直接改名为 .ftl
4 配置pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
5 写配置文件
spring
freemarker:
template-loader-path: classpath:/templates
cache: false # 开发环境缓存关闭
suffix: xml
charset: UTF-8
6 生成word模板代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import java.io.*;
import java.util.Map;
/**
* Word文档工具类
*/
public class WordUtil {
public static Configuration getConfiguration(){
//创建配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
//设置编码
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(WordUtil.class, "/templates");
return configuration;
}
/**
* 生成doc文件
*
* @param params 动态传入的数据参数
* @param outFilePath 生成的最终doc文件的保存完整路径
*/
public static void ftlToDoc(Map<String,Object> params, String outFilePath) {
try {
//模板ftl文件的名称
String ftlFileName = "word模板.ftl";
/** 加载模板文件 **/
Template template = getConfiguration().getTemplate(ftlFileName);
/** 指定输出word文件的路径 **/
File docFile = new File(outFilePath);
FileOutputStream fos = new FileOutputStream(docFile);
Writer bufferedWriter = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
template.process(params, bufferedWriter);
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
直接调用工具类就可以根据模板生成想要的word啦! 注: 生成文件为.doc文件 例如: ./test.doc
下一篇写如何生成统计表图表