目录
aspose-words jar包:百度网盘 请输入提取码
1.引入aspose-words依赖
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>16.8.0</version>
</dependency>
2.在resource路径下配置license.xml文件
aspose-words需要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>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data> <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
3.转换工具类
package com.dhp.utils.pdf;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 获取license
*
* @return
*/
private static boolean getLicense() {
boolean result = false;
try {
InputStream license = WordPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
if (license == null) {
log.error("License file not found in classpath.");
return false;
}
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
log.error("error:", e);
}
return result;
}
/**
* word转pdf
* @param pdfFilePath pdf生成路径
* @param wordFilePath word文件路径
*/
public static void word2Pdf(String pdfFilePath,String wordFilePath) {
// 检查 License
if (!getLicense()) {
log.error("License 验证失败,转换可能带有水印!");
}
// 检查输入文件是否存在
File inputFile = new File(wordFilePath);
if (!inputFile.exists()) {
log.error("输入文件不存在: {}", wordFilePath);
return;
}
// 确保输出目录存在
File outputFile = new File(pdfFilePath);
File parentDir = outputFile.getParentFile();
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs(); // 创建所有缺失的目录
}
// 自动关闭资源(Java 7+)
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(pdfFilePath)) {
Document doc = new Document(fis);
doc.save(fos, SaveFormat.PDF);
log.info("PDF 转换成功: {}", pdfFilePath);
} catch (Exception e) {
log.error("转换失败:", e);
}
}
public static void main(String[] args) {
//本地调用
WordPdfUtil.word2Pdf("D:\\storage\\borrowFrom.pdf","E:\\ems_admin\\src\\main\\resources\\templates\\borrowFrom.docx");
}
}