项目中使用到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
好了,今天的分享到此结束,有问题欢迎留言