【Java】Word文件相关转换、关键字替换
Doc、Docx、Pdf各文件相互转换
基本介绍
一般都会使用Apache POI,这是一个开源的Java API,用于处理Microsoft Office格式的文件,包括Word文档。它提供了一组类和方法,可以读取、写入和修改Word文档内容。但是我发现Aspose.Words这个第三方的Java库更加好用,下面是相关操作:
相关依赖
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
授权文件
添加相关的授权文件license.xml
建议放在config目录下
<?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>
工具类中添加验证授权的公用方法
/**
* 验证授权文件
*/
private static void verifyLicense() {
try {
// 验证授权文件
InputStream inputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("config/license.xml");
License asposeLic = new License();
asposeLic.setLicense(inputStream);
assert inputStream != null;
inputStream.close();
AssertUtil.isTrue(!asposeLic.getIsLicensed(), "授权文件失效");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
具体方法
下面提供Doc转换为Docx,Doc转换为Pdf工具类
Doc转换为Docx
/**
* Doc文件转换为Docx
*
* @param docFilePath DOC文件
*/
public static void docToDocx(String docFilePath) {
try {
// 验证授权
verifyLicense();
InputStream docInputStream = Files.newInputStream(Paths.get(docFilePath));
Document document = new Document(docInputStream);
document.save(docxFilePath, SaveFormat.DOCX);
} catch (Exception e) {
e.printStackTrace();
}
}
Doc转换为Pdf
/**
* DOC或者DOCX文件转换为PDF文件
*
* @param wordFilePath WORD文件
* @param pdfFilePath PDF文件
*/
public static void docOrDocxToPdf(String wordFilePath, String pdfFilePath) {
log.info("【WORD转换PDF请求开始】");
log.info("【WORD文件地址】--{}", wordFilePath);
try {
// 验证授权
verifyLicense();
// 加载要转换的文档
Document document = new Document(wordFilePath);
// 将文档保存为PDF格式
document.save(pdfFilePath, SaveFormat.PDF);
// WORD文件用不到就可以删除
File f = new File(wordFilePath);
if (f.exists() && f.delete()) {
log.info("【WORD文件删除成功】");
}
log.info("【WORD转换PDF请求成功】");
log.info("【PDF文件地址】--{}", pdfFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
拓展方法
使用Apache POI JAR包进行关键字替换会出现RUNS对象分段的问题
目前使用Aspose.Words暂时未出现替换失败的问题,个人觉得比Apache POI更加稳定更加好。
/**
* WORD文件查找并替换
*
* @param sourceFile WORD源文件地址
* @param targetFile 目标文件地址
* @param map 替换MAP数据
*/
@TrackTime
public static void searchAndReplace(String sourceFile, String targetFile, Map<String, String> map) {
try {
// 验证授权
verifyLicense();
FileInputStream fis = new FileInputStream(sourceFile);
Document document = new Document(fis);
map.forEach(
(key, value) -> {
try {
document.getRange().replace(key, value, Boolean.FALSE, Boolean.FALSE);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
);
document.save(targetFile, SaveFormat.DOCX);
log.warn("【文书模板替换后的文件路径为】--{}", targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
注:如找不到上述相关依赖可私信小编领取