提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
java转换Word转换PDF(windows、linux通用)
前言
话不多说,我们直接上代码
提示:以下是本篇文章正文内容,下面案例可供参考
一、导入pom依赖

这里需要说明一下,因为mavan直接下载会下载不成功可以百度下载jar包
二、工具类
1.实例代码
代码如下(示例):
@Slf4j
public class PdfUtils {
//字体存放路径
/**
* 将office文件转pdf格式 <br>
* 使用aspose-words转pdf <br>
* 无损格式转换
* @param sourceFile 需要转换的word文件
* @return
*/
public static String officeToPdf(String sourceFile) {
if (sourceFile.endsWith(".pdf")) {
return sourceFile;
}
int suffixIndex = sourceFile.lastIndexOf(".");// 文件路径中最后一个“xx.xx”的位置
if (suffixIndex < 0) {
log.info("文件名无后缀,转换pdf失败。");
return sourceFile;
}
String targetFile = sourceFile.substring(0, suffixIndex) + ".pdf";// 生成新的pdf文件路径
File file = new File(sourceFile);
if (!file.exists()) {
log.info("目标文件不存在。");
return sourceFile;
}
File file2 = new File(targetFile);
/* if (file2.exists()) {
return targetFile;
}*/
getVoucher();// 获取生成pdf的凭证,要不然会有水印
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file2);
// 要转换的word文件
OsInfo osInfo = SystemUtil.getOsInfo();
if(osInfo.isLinux()){
FontSettings.setFontsFolder("/usr/share/fonts",true);
}
Document doc = new Document(sourceFile);
doc.save(fileOutputStream, SaveFormat.PDF);
log.info("word转pdf成功。{}", targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return targetFile;
}
/**
* 获取生成pdf的凭证,要不然会有水印
*/
private static void getVoucher() {
try {
InputStream is = new ClassPathResource("/license.xml").getInputStream();
License aposeLic = new License();
aposeLic.setLicense(is);
} catch (Exception e) {
log.info("获取生成pdf凭证异常。{}", e.getMessage());
}
}
}
凭证也得需要这里直接写了

总结
以上就是今天要讲的内容,本文仅仅简单介绍了word转换pdf的使用,已经过本人测试,本地与linux环境下均可使用。
本次分享如有疑问,可私聊 看到了就回复!
本文介绍如何使用Java和Aspose库在Windows和Linux系统中将Word文档转换为PDF格式,包括导入Maven依赖、工具类中的代码示例以及处理字体问题。
4468





