一丶引用相关jar包
<!-- word转图工具 -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-words</artifactId>
<version>23.1</version>
</dependency>
word操作包: aspose-words-21.1.jar, 如下链接自行下载:
aspose-words-21.1.jar, 提取码为: zwcs
二丶编辑一张word文档, 如下图:
三丶将文档关键字替换并转换为图片,代码由下:
主类代码:
package com.demo.ceshi;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.deepoove.poi.XWPFTemplate;
import com.demo.ceshi.util.OfficeUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CeshiApplicationTests {
@Test
public void test4() {
try {
// 获取word文档
File file = new File("E:\\横屏.docx");
// 读取文件
InputStream ins = Files.newInputStream(file.toPath());
// 使用模板引擎将模板渲染,并传入一个数据映射表 initWordMap()。
XWPFTemplate template = XWPFTemplate.compile(ins).render(OfficeUtils.initWordMap());
// 将模板渲染后保存为新的 Word 文件
template.writeToFile("E:\\test.docx");
// 填充数据完毕的test.docx,在转换成图片
File file1 = new File("E:\\test.docx");
// 打开生成的 Word 文件
Document doc = new Document(Files.newInputStream(file1.toPath()));
String filePath = "E:\\";
String pathPre = new Date().getTime() + ".png";
// 逐页将 Word 文件保存为图片(PNG格式)
for (int i = 0; i < doc.getPageCount(); i++) {
Document extractedPage = doc.extractPages(i,1);
// 拼接上文件名
String path = filePath + pathPre;
// 将 Word 文件保存为图片PNG格式
extractedPage.save(path, SaveFormat.PNG);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
工具类代码:
public class OfficeUtils {
/**
* word文档需要填充的数据
* @return
*/
public static Map<String, Object> initWordMap() {
Map<String, Object> wordData = new HashMap<>();
wordData.put("XM", "陈XX");
wordData.put("ZSMC", "上班摸鱼许可证");
wordData.put("KCMC", "野外生存摸鱼达人");
wordData.put("JGMC", "Super摸鱼有限责任公司");
wordData.put("BFRQ", "2024年3月23日");
return wordData;
}
}
四丶执行效果图, 如下: