Poi-tl参考文档地址:http://deepoove.com/poi-tl/1.8.x/#hack-loop-table
word模板替换,转pdf
- 1. 依赖引入:
- 2. word模板配置:
- 3. 示例demo:
- 4 . 效果图
1. 依赖引入:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.2</version>
<classifier>jdk16</classifier>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.8.2</version>
</dependency>
<!-- 通过Maven库拿不到,就加下面的配置 -->
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>AsposeJavaAPI</id>
<url>https://repository.aspose.com/repo/</url>
</pluginRepository>
</pluginRepositories>
2. word模板配置:
绿色部分是直接渲染的,对应map中的key-value,蓝色部分是绑定collections对象,进行遍历循环集合数据
3. 示例demo:
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream docOutput = new ByteArrayOutputStream();
Map<String, Object> map = new HashMap<>(3);
map.put("zfkp", "AAAA");
map.put("kpjg", "123");
map.put("kpr", "李四");
List<Map> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>(3);
map1.put("number", 1);
map1.put("kprlist", "xxxa");
map1.put("fs", 17);
Map<String, Object> map2 = new HashMap<>(3);
map2.put("number", 2);
map2.put("kprlist", "xxxa3aa");
map2.put("fs", 10);
list.add(map1);
list.add(map2);
//列表集合数据
map.put("collections", list);
HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
Configure config = Configure.newBuilder()
//绑定集合数据
.bind("collections", policy).build();
System.out.println(map);
//加载配置的word模板
XWPFTemplate template = XWPFTemplate.compile("C:\\Users\\DELL\\Desktop\\kpwtlb.docx", config);
template.render(map);
//写入word,swapStream可输出word文档
template.write(docOutput);
ByteArrayInputStream swapStream = new ByteArrayInputStream(docOutput.toByteArray());
//word转PDF
Document doc = new Document(swapStream);
ByteArrayOutputStream pdfOutput = new ByteArrayOutputStream();
doc.save(pdfOutput, SaveFormat.PDF);
ByteArrayInputStream pdfinput = new ByteArrayInputStream(pdfOutput.toByteArray());
FileUtil.inputStreamToFile(pdfinput, "C:\\Users\\DELL\\Desktop\\", "123.pdf");
}
4 . 效果图
转换的pdf有水印,去水印很方便, 加载License(要买)即可 封装一个工具类
https://blog.csdn.net/weixin_42827159/article/details/105031663