admin管理员组文章数量:1605330
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
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());
}
}
}
凭证也得需要这里直接写了
<?xml version="1.0" encoding="UTF-8"?> Aspose.Total for Java Aspose.Words for Java Enterprise 20991231 20991231 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7 sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=总结
以上就是今天要讲的内容,本文仅仅简单介绍了word转换pdf的使用,已经过本人测试,本地与linux环境下均可使用。
本次分享如有疑问,可私聊 看到了就回复!
版权声明:本文标题:用java程序word转换PDF(window、linux都可以使用) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728481416a1160138.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论