springboot整合freemarker根据模板导出word,pdf,以及word转pdf,读取工程resources下的模板文件
1、maven依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
2、创建模板
一种快捷创建模板的方式,将word样本打开,另存为xml文件

3、将生成好的xml模板文件放入resources下,新建一个templates文件夹将文件放入下面

4、导出world
public ByteArrayOutputStream createWord(Map<String, Object> dataMap, String templateName,String fileName) {
log.info("{}:产品要素表导出word开始生成...",fileName);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
Writer out = new BufferedWriter(oWriter);
try {
InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName));
createWordTemplate(new String(IOUtils.toByteArray(inputStream))).process(dataMap, out);
} catch (IOException | TemplateException e) {
log.error("{}:产品要素表导出word失败:",fileName, e);
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
log.error("{}:产品要素表导出word关闭流失败", fileName,e);
}
}
log.info("{}:产品要素表导出word生成完成...",fileName);
return outputStream;
}
5.word转pdf
public static ByteArrayOutputStream wordToPdf(ByteArrayOutputStream outputStream,String fileName) {
log.info("{

该博客介绍了如何在SpringBoot项目中结合Freemarker模板引擎和Aspose库,实现从XML模板生成Word文档,并进一步将Word转换为PDF。整个流程包括设置Maven依赖、创建XML模板、读取模板并填充数据、以及使用Aspose进行文件转换。同时,还提供了压缩多个Word和PDF文件到ZIP供下载的功能。
最低0.47元/天 解锁文章
1565

被折叠的 条评论
为什么被折叠?



