分享一个word转pdf的工具类Aspose[java]
项目中使用到office文件的格式转换pdf阅读,但是没有一款好用的转换工具。由于本人是mac系统,openoffice也没法使用,前期使用itext转换一直中文乱码,也没有解决这个问题,后来发现aspose,虽说是付费的,但是确实是好用,更重要的是中国程序员的无私奉献精神,下面就来展示一下怎么转换的吧,其实关键就是几行代码
代码中file即要转换的文件,path即转换的pdf输出路径
使用aspose首先的肯定是验证下面就是验证
private static boolean getLicense() {
boolean result = false;
try {
// 凭证
String licenseStr = "此处放入凭证,可自行百度,aspose验证";
InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
log.error("error:", e);
}
return result;
}
word转pdf
public static void word2Pdf(MultipartFile multipartFile, String pdfFilePath) {
FileOutputStream fileOS = null;
// 验证License
if (!getLicense()) {
log.error("验证License失败!");
return;
}
try {
Document doc = new Document(multipartFile.getInputStream());
fileOS = new FileOutputStream(new File(pdfFilePath));
// 保存转换的pdf文件
doc.save(fileOS, SaveFormat.PDF);
} catch (Exception e) {
log.error("error:", e);
} finally {
try {
if(fileOS != null){
fileOS.close();
}
} catch (IOException e) {
log.error("error:", e);
}
}
}
excel转pdf
public static void excel2pdf(MultipartFile file, String path) {
if (!getLicense()) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
File pdfFile = new File(path)
Workbook wb = new Workbook(file.getInputStream());
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
FileOutputStream fileOS = new FileOutputStream(pdfFile);
wb.save(fileOS, SaveFormat.PDF);
fileOS.close();
}catch (Exception e) {
e.printStackTrace();
}
}
ppt转pdf
public static void ppt2pdf(MultipartFile file, String path){
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
Presentation pres = new Presentation(file.getInputStream());
FileOutputStream fileOS = new FileOutputStream(path);
pres.save(fileOS, SaveFormat.PDF);
fileOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
下面是附上jar包的地址
链接:https://pan.baidu.com/s/11js-Vi_HqYwAlid14xDmZg 密码:wxg8
好了,今天的分享到此结束,有问题欢迎留言
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了