分享一个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

好了,今天的分享到此结束,有问题欢迎留言

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值