freemarker模板导出doc的之前有写过,这里就不再多说了,不清楚的可以看之前的文章Freemarker 模板导出(带图片)。

转换后的文件展示

FreemarkerUtils工具类(这里用的工具类导出和之前不一样,不仅仅是页面进行下载,还有本地的保存)

package com.sinosoft.common.utils.freemarker;import freemarker.template.Configuration;
import freemarker.template.Template;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;/*** @author 庭前云落* @description* @date 2022年07月25日 10:45*/
public class FreemarkerUtils {/*** 使用 freemarker 生成word文档** @param templateDir  模板所在目录路径* @param templateName 模板 例如:xxx.ftl* @param data         数据* @param fileSavePath 文档生成后,存放的路径* @param fileName     生成后的文件名称* @param response* @throws Exception*/public static void freemarkerExport(String templateDir, String templateName, Map<String, Object> data, String fileSavePath, String fileName, HttpServletResponse response) throws Exception {// 1.设置 freeMarker的版本和编码格式Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);configuration.setDefaultEncoding("UTF-8");// 2.设置 freeMarker生成Word文档,所需要的模板的路径configuration.setDirectoryForTemplateLoading(new File(templateDir));// 3.设置 freeMarker生成Word文档所需要的模板 ---> xxx.ftlTemplate t = null;try {// 模板文件名称t = configuration.getTemplate(templateName);} catch (IOException e) {throw new IOException("获取 ftl模板失败!" + e.getMessage());}File fileDir = new File(fileSavePath);if(!fileDir.exists()){fileDir.mkdirs();}// 4.生成 Word文档的全路径名称File outFile = new File(fileSavePath + fileName);System.out.println(outFile);// 5.创建一个 Word文档的输出流Writer writer = null;try {writer = new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8);} catch (Exception e) {throw new Exception(e.getMessage());}try {for (Map.Entry<String, Object> entry : data.entrySet()) {if (Objects.isNull(entry.getValue())) {data.put(entry.getKey(), "");System.out.println("您输入的" + entry.getKey() + "为空!");}else{// String value=entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n","<w:br/>");if (!Objects.isNull(entry.getValue()) && entry.getValue().getClass().isInstance(String.class)) {String value=entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n","<w:br/>");data.put(entry.getKey(),value );}if (!Objects.isNull(entry.getValue()) && entry.getValue().getClass().isInstance(List.class)) {data.put(entry.getKey(), new ArrayList<>().add(entry.getValue()));}else {String value = entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<w:br/>");data.put(entry.getKey(), value);}}}// 6.装载数据t.process(data, writer);response.setCharacterEncoding("utf-8");response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));response.setContentType("application/json");// 7.读取生成好的 Word文档File file = new File(fileSavePath + fileName);FileInputStream is = new FileInputStream(file);OutputStream os = response.getOutputStream();byte[] b = new byte[1024];int length;while ((length = is.read(b)) > 0) {os.write(b, 0, length);}os.flush();os.close();writer.flush();writer.close();} catch (IOException e) {throw new IOException(e.getMessage());} finally {deleteTempFile(fileSavePath + fileName);}}/*** 删除临时生成的文件*/public static void deleteTempFile(String filePath) {File f = new File(filePath);boolean delete = f.delete();}
}

数据的查询及填充,不同模板的选择判断这里就不进行展示了。

   /*** 文书转pdf保存** @return*/@ApiOperation(value = "文书转pdf保存")@RequestMapping(value = "/savePetitionTemplatePdf", method = RequestMethod.GET)@LogAnnotation("文书转pdf保存")public Result savePetitionTemplatePdf(String oid, HttpServletResponse response) {try {Map<String, String> nameMap = documentApproverInfoService.getName(oid);String templateName = nameMap.get("templateName");String exportFileName = nameMap.get("fileName");String pdfName = nameMap.get("pdfName");//给文书赋值Map<String, Object> map = documentInfoService.obtainTemplate(oid, templateName);//模板所在路径String templateFileName = this.getClass().getResource("/").getPath() + "templates" + File.separator;//生成word文档FreemarkerUtils.freemarkerExport(templateFileName, templateName, map, folder, exportFileName, response);// doc转换为pdfDocument document = new Document();document.loadFromFile(folder+exportFileName);document.saveToFile(folder+pdfName, FileFormat.PDF);return Result.ok().message("保存成功").data(folder+pdfName);} catch (Exception e) {log.error("保存异常", e);return Result.error().message("保存失败");}}

freemarker导出pdf相关推荐

  1. freemarker 导出pdf特殊字符处理

    在使用freemarker导出pdf时,有时候导出的内容里面有特殊字符,比如&符号,如果不处理,那么导出时将报错. 导出内容:他&和-#ta 报错信息如下: java.lang.Exc ...

  2. Java使用Freemarker通过模板文件导出PDF文件、横向显示

    前言: 尝试了不少通过模板文件导出pdf文件的方法,要么实现起来复杂,要么实现效果不理想,经过反复查找资料和尝试发现此方法是最理想的. 本博客又经大量网友实践及建议,经过几次完善修改,又日趋完善,在此 ...

  3. Java通过freemarker实现导出PDF

    制作模板 引入依赖 引入所需字体文件 工具类的编写 业务实现 一.模板制作 (1)编写html代码 ,需要替换的值与内容预留出来,用${name}代替,需循环处.表格前加上<#list list ...

  4. iText实现HTML页面导出PDF

    iText实现HTML页面导出PDF 引言 实现效果 前期准备 实现功能 1.需要的jar包 2.封装导出类 3.需要的jar包 4.前端调用 5.模板文件 引言 最近项目中,涉及到票据导出功能,ex ...

  5. 【原创】Java开发word模板转html导出pdf

    使用iText5来导出pdf,具体操作步骤如下: 1.首先创建一个doc格式的word文档,转换为html格式 word模板转html链接地址 2.替换要填充的内容,把html文件后缀改为ftl并放在 ...

  6. Docker 快速验证 HTML 导出 PDF 高效方案

    需求分析 项目中用到了 Echarts,想要把图文混排,当然包括 echarts 生成的 Canvas 图也导出 PDF. 设计和实现时,分析了 POI.iText.freemaker.world 的 ...

  7. freemarker转PDF,支持分页,增加页眉页脚

    参考 https://github.com/superad/pdf-kit.git 先看效果(不能上传PDF文档...) POM.XML <?xml version="1.0" ...

  8. Java 根据模板导出PDF

    文章目录 前言 思路一:直接导出pdf 使用itext模板导出pdf 思路二:先导出word再转成pdf 1)导出word 2)word转pdf 最终方案 ~~docx4j~~ spire.doc.f ...

  9. java按照模板导出pdf或者word

    一.java按照模板导出pdf (一)制作模板 1.在word里制作模板 因为PDF常用的软件不支持编辑,所以先用Word工具,如WPS或者Office新建一个空白Word文档,里面制作出自己想要的样 ...

最新文章

  1. linux系统用户属组,关于 Linux系统用户、组和权限管理
  2. 在html前面追加,在追加到DOM之前操纵html
  3. PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译)
  4. ajax response.write 执行失败_Day 42:一人分饰三角,初识AJAX
  5. 桑文锋:创业是场持久战,我希望能重构中国互联网的数据根基
  6. 最简单,最明了,看了就会的VScode和C++的配置!(Visual Studio Code)
  7. 注册界面的实现案例视频(前端开发)
  8. [html] 你有了解HTML5的地理定位吗?怎么使用?
  9. 为什么不能同时用const和static修饰成员函数?
  10. 使用node的pm2管理相关进程
  11. Go源码里的 //go: 指令集眼熟嘛?都是干嘛的?
  12. this 改变this的指向
  13. 计算机视觉的算法SIFT算法详细介绍
  14. 搭建百万级别邮件发送平台
  15. Sails基础之View层
  16. 【Tpshop商城使用】
  17. 【重点】Selenium + Nightwatch 自动化测试环境搭建
  18. RecyclerView嵌套实现购物车
  19. 那些年UNIX教我们的事
  20. ad设置塞孔_PCB设计中,如何设置跳线

热门文章

  1. Unity3d 控制物体transform移动的几种方法
  2. 神经网络系列之五 -- 线性二分类的方法与原理
  3. Python(9):利用selenium操作网页并抓取内容
  4. DRiV Incorporated 在今年晚些时候将从 Tenneco 脱离
  5. yml:java.lang.IllegalArgumentException: Could not resolve placeholder ‘jdbc.driverClassName‘
  6. flume-Kafka-Strom架构的搭建及使用
  7. 计算机开机显示花屏,导致电脑开机花屏出现的几种原因
  8. 程序人生 | 编程的上帝视角应该怎么去找
  9. 谁说做软件测试没有好的前途?反驳之
  10. 高通平台开发系列讲解(USB篇)linux下U盘识别问题