前言
基于目前业务场景需要,自动化实现Word转换PDF。
一、Aspose-words是什么?
Aspose.Words是一款强大的Java库,用于处理和操作Microsoft Word文档。它提供了广泛的功能,使你能够创建、读取、修改和转换Word文档。
二、环境版本
JDK 1.8
aspose-words-15.8.0-jdk16
三、实现方案
1.引入依赖jar包
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
<classifier>jdk16</classifier> <!-- 加上这个刷新pom文件 -->
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
2.添加license.xml文件
验证License,若不验证则转化出的pdf文档会有水印产生
<?xml version="1.0" encoding="UTF-8"?>
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
</Data>
<Signature>
sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
</Signature>
</License>
3.FileAsposeUtil工具类
public static boolean getLicense(){
boolean result = false;
try {
InputStream is = FileAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
is.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String docTurnPdf(String sourceFileName,String newFileName) throws Exception {
if (!getLicense()) {// 验证License
return "";
}
File file = new File(newFileName); //新建一个pdf文档
if(file.exists()){
file.delete();
}
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(sourceFileName);//Address是将要被转化的word文档
doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
os.close();
return file.getPath();
4.验证测试
public static void main(String[] args) throws Exception {
docTurnPdf("D:\\temp\\202309141230001.doc","D:\\temp\\202309141230001.pdf");
}
运行结果如下,pdf已完成转换。
好了,以上就是要分享的内容,如果大家喜欢的话,记得点赞关注哦
总结
- 要在Java中实现Word到PDF的转换,可以使用Aspose.Words for Java这样的第三方库。
- 程序可以处理大量的文档,节省时间和人力成本。