首先准备word模版配置信息,如下图所示
pom.xml需要引入以下jar包
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> <dependency> <groupId>com.luhuiguo</groupId> <artifactId>aspose-words</artifactId> <version>23.1</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.7</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> <dependency> <groupId>com.luhuiguo</groupId> <artifactId>aspose-words</artifactId> <version>23.1</version> </dependency>
根据word模版内容填充数据代码内容如下
Map params = new HashMap<>();
params.put("today", TimeTransferUtil.todayTimeString());
params.put("year", TimeTransferUtil.yearTimeString());
params.put("number", String.format("%03d", code));
WordUtil.createWord("word模版文档路径", "内容填充后word生成路径","填充参数");
WordUtil代码内容
public class WordUtil {
public static boolean createWord(String templatePath, String filePath, Map<String, Object> paramMap) {
// 读取模板templatePath并将paramMap的内容填充进模板,即编辑模板+渲染数据
XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
try {
// 将填充之后的模板写入filePath
template.writeToFile(filePath);
template.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Word转pdf的代码
inPath:word文件路径
outPath:pdf文件输出路径
public static void doc2pdf(String inPath, String outPath) { FileOutputStream os = null; try { File file = new File(outPath); os = new FileOutputStream(file); Document doc = new Document(inPath); doc.save(os, SaveFormat.PDF); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }