1.word模板填充内容
使用EasyPoi写入Word文档。
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class WriteWordtemplate {public static void main(String[] args) throws Exception {Map<String, Object> params = createDate();String sourceFile = "d:/temp/模版word3.docx";String targetFile = "d:/temp/输出结果3.docx";FileOutputStream fos = null;try {//获取模板文档File templateFile = new File(sourceFile);System.out.println(templateFile.getName());// 写入wordXWPFDocument doc = WordExportUtil.exportWord07(templateFile.getPath(), params);fos = FileUtils.openOutputStream(new File(targetFile));doc.write(fos);} catch (Exception e) {System.out.println(e);} finally {IOUtils.closeQuietly(fos);}}private static Map<String, Object> createDate() {//填充数据List<WordExportBatch> resultList = new ArrayList<>();WordExportBatch wordExport = new WordExportBatch();WordExportBatch wordExport1 = new WordExportBatch();wordExport.setCreateDate("2022/9/30");wordExport1.setCreateDate("2022/9/28");wordExport.setNumber("11");wordExport.setExMoneny("11");wordExport.setExFunc("支付宝");wordExport1.setNumber("15");wordExport.setAmount("1234.5");wordExport1.setAmount("2345.77");wordExport.setEndDate("2022/12/31");wordExport1.setEndDate("2022/11/30");wordExport.setType("支付宝");wordExport1.setType("微信");wordExport1.setExMoneny("22");wordExport1.setExFunc("微信");resultList.add(wordExport);resultList.add(wordExport1);//准备数据Map<String, Object> params = new HashMap<>();params.put("number", "112");params.put("amount", "1234.5");params.put("endDate", "2022/11/30");params.put("resultList", resultList);return params;}}
pom依赖可以参考https://blog.csdn.net/u011067966/article/details/134293480#comments_36351020
把word转换为pdf
word生成pdf的方法比较多,调研了常用的方式
- 一种方式是部署一台windowserver,对外提供接口来进行生成,能最大程度还原格式。
- 第二种方式就是利用jodconverter,会有少许的失真。
现在介绍的是基于jodconverter把word转换为PDF。首先引入jar包
<!--jodconverter--><dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-local</artifactId><version>4.2.2</version></dependency><!--springboot支持包,里面包括了自动配置类 --><dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-spring-boot-starter</artifactId><version>4.2.2</version></dependency>
在配置文件中加入如下配置
jodconverter:local:enabled: true # 启用本地模式office-home: /opt/libreoffice7.5 # LibreOffice 的安装路径max-tasks-per-process: 10 # 每个 Office 进程处理的最大任务数port-numbers: 8202 # LibreOffice 后台服务使用的端口号
在处理类中注入,之所以使用@Lazy是因为加载的使用会报错,让它延迟加载。
@Lazy@Autowiredprivate DocumentConverter converter;public void wordConvertToPdf(File wordFile, File pdfFile) {try {logger.info("word转换pdf开始");converter.convert(wordFile).to(pdfFile).execute();logger.info("word转换pdf结束");} catch (Exception e) {logger.error("word转pdf异常", e);}}
后续使用
之前写过word模板生成段落和生成表格的段落。
结合起来就能生成相对完整的word了。后续如果需要盖章什么的直接拿生成的pdf文件就可以了。