用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径

这篇具有很好参考价值的文章主要介绍了用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

嘿嘿嘿、嘿嘿,俺又回来了!

github代码地址 https://github.com/Tom-shushu/work-study
接口文档有道云 https://note.youdao.com/s/GShGsYE8
接口文档离线版本 https://files.cnblogs.com/files/Tom-shushu/%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3.rar?t=1682958343&download=true

一、巴拉巴拉

为什么发布这篇文档转换的文章呢?因为上周我要将一个PDF转换为Word,结果百度谷歌了所有文章,最终的结果都是“能转换,但是只能转换一点点,多了就要收费”,于是乎我突发奇想、心血来潮在放假的那天打算开发一款小程序实现各种文档的转换,在百度了一下午后发现目前都是借助Aspose实现的,但是好像要收费,在我新建项目时偶然间发现原来Maven仓库里面居然有人将破解好的Jar包上传到Maven中央仓库了,于是我测试了一下,哈哈真香,于是就有了这篇文章。至于小程序做的怎么样了呢?暂时又搁置了,因为我调查了一下已经有现成的好多优秀的微信小程序可以实现各种文档转换了,还有就是个人小程序没法上线,可能暂时不会做小程序了,大家有想法的可以按照自己的想法使用我的源码,直接和前端对接做出优秀的小程序。

二、PDF相关文件操作

1.引入依赖

        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>23.1</version>
        </dependency>

2.代码实现(只贴关键代码,代码我会放到GitHub跟Gitee上面,大家自取、还有完整的接口文档我都会放出来)

① 上传OSS工具类  OssUpLoadTools

/**
      * @description:  获取文件保存地址
      * @return: java.lang.String
      * @author: zhouhong
      * @date: 2023/4/30 12:36
      */
    public String getSavePath() {
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\templates\\";
    }

    /**
      * @description:  上传文件到阿里云OSS
      * @return: java.lang.String
      * @author: zhouhong
      * @date: 2023/5/1 22:55
      */
    public String uploadOssFile(String fileName, File file){
        // 创建OSSClient实例。
        OSS ossClient = ossConfig.getOssClient();
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(),
                    fileName, file);
            putObjectRequest.setProcess("true");
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功,则返回200。
            if (result.getResponse().getStatusCode() == 200) {
                return result.getResponse().getUri();
            }
        } catch (OSSException oe) {
        } catch (ClientException ce) {
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

② PDF转其他文件

    /**
      * @description: PDF 转其他文件
      * @return: java.util.List<java.lang.String>
      * @author: zhouhong
      * @date: 2023/5/1 23:34
      */
    @Override
    public List<String> pdfToFile(MultipartFile file,String type) {
        List<String> res = new ArrayList<>();
        String checkType = FilenameUtils.getExtension(file.getOriginalFilename());
        if (!"pdf".equals(checkType)) {
            throw new ServiceException(1, "输入文件不是PDF文件!");
        }
        try {
            switch (type.toUpperCase()) {
                case "WORD" : {
                    return switchFile(file, com.aspose.pdf.SaveFormat.DocX, "docx");
                }
                case "XML" : {
                    return switchFile(file, SaveFormat.PdfXml, "xml");
                }
                case "EXCEL" : {
                    return switchFile(file, com.aspose.pdf.SaveFormat.Excel, "xlsx");
                }
                case "PPT" : {
                    return switchFile(file, com.aspose.pdf.SaveFormat.Pptx, "pptx");
                }
                case "PNG" : {
                    // 图片类型的需要获取每一页PDF,一张一张转换
                    Document pdfDocument = new Document(file.getInputStream());
                    //分辨率
                    Resolution resolution = new Resolution(130);
                    PngDevice pngDevice = new PngDevice(resolution);
                    //
                    if (pdfDocument.getPages().size() <= 10) {
                        for (int index = 0; index < pdfDocument.getPages().size(); index++) {
                            String fileName = UUID.randomUUID() + ".png";
                            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
                            File tmpFile = new File(filePath);
                            FileOutputStream fileOS = new FileOutputStream(tmpFile);
                            pngDevice.process(pdfDocument.getPages().get_Item(index), fileOS);
                            res.add(ossUpLoadTools.uploadOssFile(fileName, tmpFile));
                            fileOS.close();
                            tmpFile.delete();
                        }
                    } else {
                        throw new ServiceException(2, "抱歉超过10页暂时无法转图片");
                    }
                    return res;
                }
                case "HTML" : {
                    String fileName = UUID.randomUUID() + ".html";
                    String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
                    Document doc = new Document(file.getInputStream());

                    HtmlSaveOptions saveOptions = new HtmlSaveOptions();
                    saveOptions.setFixedLayout(true);
                    saveOptions.setSplitIntoPages(false);
                    saveOptions.setRasterImagesSavingMode(HtmlSaveOptions.RasterImagesSavingModes.AsExternalPngFilesReferencedViaSvg);
                    doc.save(filePath , saveOptions);
                    doc.close();
                    File outputfile  = new File(filePath);
                    res.add(ossUpLoadTools.uploadOssFile(fileName, outputfile));
                    outputfile.delete();
                    return res;
                }
                default:{}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<String> switchFile(MultipartFile file, SaveFormat saveFormat, String suffix) {
        List<String> resUrl = new ArrayList<>();
        try {
            long old = System.currentTimeMillis();
            // 输出路径
            String fileName = UUID.randomUUID() + "." + suffix;
            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
            FileOutputStream os = new FileOutputStream(filePath);
            Document doc = new Document(file.getInputStream());
            doc.save(os, saveFormat);
            os.close();
            doc.close();
            File outputfile  = new File(filePath);
            resUrl.add(ossUpLoadTools.uploadOssFile(fileName, outputfile));
            outputfile.delete();
            long now = System.currentTimeMillis();
            log.info("共耗时:" + ((now - old) / 1000.0) + "秒");

        }catch (IOException e) {
            e.printStackTrace();
        }
        return resUrl;
    }

 ③ 合并两个、多个PDF文件

    /**
      * @description: 合并两个PDF文件
      * @return: java.lang.String
      * @author: zhouhong
      * @date: 2023/5/1 23:40
      */
    @Override
    public String mergeTwoPdfFile(MultipartFile  file1, MultipartFile file2) {
        try {
            Document doc1 = new Document(file1.getInputStream());
            Document doc2 = new Document(file2.getInputStream());
            doc1.getPages().add(doc2.getPages());

            String fileName = UUID.randomUUID() + ".pdf";
            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
            doc1.save(filePath);
            doc1.close();
            File outputfile  = new File(filePath);
            String res = ossUpLoadTools.uploadOssFile(fileName, outputfile);
            outputfile.delete();
            return res;
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    /**
      * @description:  合并对个PDF文件
      * @return: java.lang.String
      * @author: zhouhong
      * @date: 2023/5/1 23:40
      */
    @Override
    public String mergeMorePdfFile(MultipartFile ... file) {
        try {
            String mergeFileName = UUID.randomUUID() + ".pdf";
            String mergePdfPath = ossUpLoadTools.getSavePath() + "/"  + mergeFileName;
            String[] chilPdfPath = new String[file.length];
            // 读取PDF并获取路径
            for (int i = 0; i < file.length; i++) {
                String fileName = UUID.randomUUID() + ".pdf";
                String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
                FileOutputStream os = new FileOutputStream(filePath);
                Document doc = new Document(file[i].getInputStream());
                doc.save(os);
                chilPdfPath[i] = filePath;
                os.close();
                doc.close();
            }
            // 合并多个PDF
            PdfFileEditor pdfFileEditor = new PdfFileEditor();
            pdfFileEditor.concatenate(chilPdfPath, mergePdfPath);

            // 读取文件上传OSS
            File outputfile  = new File(mergePdfPath);
            String resUrl = ossUpLoadTools.uploadOssFile(mergeFileName, outputfile);
            outputfile.delete();
            return resUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

三、Excel相关操作

1.引入相关依赖

        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>22.10</version>
        </dependency>

2.相关关键代码

    /**
      * @description: Excel转其他文件
      * @return: java.lang.String
      * @author: zhouhong
      * @date: 2023/5/1 23:44
      */
    @Override
    public String excelToFile(MultipartFile file, String type) {
        String checkType = FilenameUtils.getExtension(file.getOriginalFilename());
        if (!"xlsx".equals(checkType) && !"xls".equals(checkType)) {
            throw new ServiceException(1, "输入文件不是Excel文件!");
        }
        try {
            switch (type.toUpperCase()) {
                /******************** 文档类型 ***************/
                case "WORD" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.DOCX, "docx");
                }
                case "PDF" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.PDF, "pdf");
                }
                case "PPT" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.PPTX, "pptx");
                }
                case "HTML" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.HTML, "html");
                }
                case "JSON" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.JSON, ".json");
                }
                case "MARKDOWN" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.MARKDOWN, "md");
                }
                /***************** 图片类型 (注意图片格式的默认只转换第一个 Sheet1)*********************/
                case "PNG" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.PNG, "png");
                }
                case "JPG" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.JPG, "jpg");
                }
                case "BMP" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.BMP, "bmp");
                }
                case "CSV" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.CSV, "csv");
                }
                case "SVG" : {
                    return SwitchFile(file, com.aspose.cells.SaveFormat.SVG, "svg");
                }
                // 好像有问题,有需要大家自己调试一下
//                case "XML" : {
//                    return SwitchFile(file, com.aspose.cells.SaveFormat.XML, "xml");
//                }
                default:{}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private String SwitchFile(MultipartFile file, int saveFormat, String suffix) {
        String url = "";
        try {
            long old = System.currentTimeMillis();
            String fileName = UUID.randomUUID() + "." + suffix;
            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
            FileOutputStream os = new FileOutputStream(filePath);
            //加载源文件数据
            Workbook excel = new Workbook(file.getInputStream());
            //设置转换文件类型并转换
            excel.save(os, saveFormat);
            os.close();
            File outputfile  = new File(filePath);
            url = ossUpLoadTools.uploadOssFile(fileName, outputfile);
            outputfile.delete();
            long now = System.currentTimeMillis();
            log.info("共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

四、Word相关操作

1.引入相关依赖

        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-words</artifactId>
            <version>23.1</version>
        </dependency>

2.关键代码

    @Override
    public String wordToFile(MultipartFile file, String type) {
        String checkType = FilenameUtils.getExtension(file.getOriginalFilename());
        if (!"doc".equals(checkType) && !"docx".equals(checkType)) {
            throw new ServiceException(1, "输入文件不是Word文件!");
        }
        try {
            switch (type.toUpperCase()) {
                case "TEXT" : {
                    return switchFile(file, SaveFormat.TEXT, "txt");
                }
                case "PDF" : {
                    return switchFile(file, com.aspose.words.SaveFormat.PDF, "pdf");
                }
                /*************** 需要操作每一页Word文件,一般Word类的直接电脑操作,应该用不上************/
//                case "PNG" : {
//                    return switchFile(file, com.aspose.words.SaveFormat.PNG, "png");
//                }
//                case "JPG" : {
//                    return switchFile(file, com.aspose.words.SaveFormat.JPEG, "jpg");
//                }
                default:{}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private String switchFile(MultipartFile file, int saveFormat, String suffix){
        String url = "";
        try {
            long old = System.currentTimeMillis();
            // 输出路径
            String fileName = UUID.randomUUID() + "." + suffix;
            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
            FileOutputStream os = new FileOutputStream(filePath);
            com.aspose.words.Document doc = new com.aspose.words.Document(file.getInputStream());
            doc.save(os, saveFormat);
            os.close();
            File outputfile  = new File(filePath);
            url = ossUpLoadTools.uploadOssFile(fileName, outputfile);
            outputfile.delete();
            long now = System.currentTimeMillis();
            log.info("共耗时:" + ((now - old) / 1000.0) + "秒");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

五、PPT相关操作

1.引入相关依赖

 <dependency>
    <groupId>com.luhuiguo</groupId>
<artifactId>aspose-slides</artifactId>
<version>23.1</version>
</dependency>

2.关键部分代码

    @Override
    public String PptToFile(MultipartFile file, String type) {
        // 获取文件后缀名
        String checkType = FilenameUtils.getExtension(file.getOriginalFilename());
        if (!"ppt".equals(checkType) && !"pptx".equals(checkType)) {
            throw new ServiceException(1, "输入文件不是PPT文件!");
        }
        try {
            switch (type.toUpperCase()) {
                case "HTML" : {
                    return SwitchFile(file, com.aspose.slides.SaveFormat.Html, "html");
                }
                case "HTML5" : {
                    return SwitchFile(file, com.aspose.slides.SaveFormat.Html5, "html");
                }
                case "PDF" : {
                    return SwitchFile(file, com.aspose.slides.SaveFormat.Pdf, "pdf");
                }
                default:{}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private String SwitchFile(MultipartFile file, int saveFormat, String suffix) {
        String url = "";
        try {
            long old = System.currentTimeMillis();
            String fileName = UUID.randomUUID() + "." + suffix;
            String filePath = ossUpLoadTools.getSavePath() + "/" + fileName;
            FileOutputStream os = new FileOutputStream(filePath);
            //加载源文件数据
            Presentation ppt = new Presentation(file.getInputStream());
            //设置转换文件类型并转换
            ppt.save(os, saveFormat);
            os.close();
            File outputfile  = new File(filePath);
            url = ossUpLoadTools.uploadOssFile(fileName, outputfile);
            // 删除临时文件
            outputfile.delete();
            long now = System.currentTimeMillis();
            log.info("共耗时:" + ((now - old) / 1000.0) + "秒");
            return url;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

六、同时我还找到了一个几乎所有文件转换图片的工具类,被我稍作修改,就可以实现文件转图片,返回阿里云图片的储存地址集合啦

七、演示(演示有两个意思一下,别的大家自行测试)

1.PDF转Word

我有一个 cs.pdf 的PDF文件,通过调用PDF 转其他文件的接口,将其转换为 Wprd 形式 

用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径

 通过访问返回的地址就可以发现,文件已经被转换为Word格式的文件啦~

用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径

 文章来源地址https://www.toymoban.com/news/detail-431172.html

到了这里,关于用Aspose-Java免费实现 PDF、Word、Excel、Word互相转换并将转换过得文件上传OSS,返回转换后的文件路径的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 【工具插件类教学】Unity通过Aspose读取并显示打开PDF,PPT,Excel,Word

    目录 一、获取Aspose支持.Net的DLL 二、导入Unity的Plugin文件夹 三、分别编写四种文件的读取显示

    2024年02月02日
    浏览(36)
  • Java将Word转换成PDF-aspose

    本文将演示用aspose-word.jar包来实现将Word转换成PDF,且可以保留图表和图片。 在公司OA项目开发中, 需要将word版本的合同模板上传,业务员只能下载pdf版本合同模板,需要实现将Word转换成PDF,并且动态填充项目编号以及甲乙方信息等。 Aspose.Words for Java是一个原生库,为开发

    2024年02月07日
    浏览(10)
  • Java实现Word文档转PDF,PDF转Word,PDF转Excel,PDF转换工具

    java实现word文档转PDF,PDF转word 解决只能转换4页问题 解决每页头部存在水印问题 引入依赖 破解的jar包 链接: https://pan.baidu.com/s/1MO8OBuf4FQ937R9KDtofPQ 提取码: 4tsn 源码路径:https://download.csdn.net/download/weixin_43992507/88215577 像流读取文件这些要关闭释放,不然异常报错文件的读取不会

    2024年02月13日
    浏览(10)
  • (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

    (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

    目录 1、引入jar包 2、pdf处理工具类 3、poi模板导出工具类 4、测试类 5、模板 6、最终效果  1、引入jar包   2、pdf处理工具类  3、poi模板导出工具类  4、测试类 5、模板 6、最终效果 

    2024年02月06日
    浏览(11)
  • aspose 使用ftl模板生成word和pdf

    aspose 使用ftl模板生成word和pdf

    1 先找到word模板,用${},替换变量,保存,然后另存为xml,最后把xml后缀改成ftl。 如下图: word 模板文件 ftl模板文件如下: 2 代码生成 下面函数将ftl填充数据,并生成word和pdf 3 测试主程序 4 结果: pdf文件 word文件 还可以生成图片:

    2024年02月13日
    浏览(5)
  • 使用Aspose.Words将word转PDF并且去水印。

    使用Aspose.Words将word转PDF并且去水印。

    😜 作           者 :是江迪呀 ✒️ 本文 : Java 、 工具类 、 转换 、 word转pdf 、 Aspose.Words 、 后端 ☀️ 每日   一言 : 只要思想不滑坡,办法总比困难多。 在我们日常开发中经常会有将 word文档 转为 PDF 的场景,有很多种方法我最倾向的的是使用 Aspose.Words ,原

    2024年02月11日
    浏览(8)
  • Java POI导出Word、Excel、Pdf文档(可在线预览PDF)

    Java POI导出Word、Excel、Pdf文档(可在线预览PDF)

    1、导入依赖Pom.xml        dependency             groupIdorg.apache.poi/groupId             artifactIdpoi/artifactId             version3.14/version         /dependency 2、Controller   3、Service a、pdfService b、wordService c、excelService  4、Utils 5、模板截图   6、前端

    2024年02月08日
    浏览(34)
  • java超简单实现文档在线预览功能,支持word\excel\text\pdf\图片等格式转pdf,aspost 转pdf部署linux中文乱码解决方案

    java超简单实现文档在线预览功能,支持word\excel\text\pdf\图片等格式转pdf,aspost 转pdf部署linux中文乱码解决方案

    一、背景         在工作中需要对上传到服务器的各种类型包括但不限于word、pdf、excel等文件进行在线预览,前端比较菜搞不定,只能本人亲自上。         网上的经验比较多也比较乱, 有的只有预览,没有文件格式转换,有的也不说linux存在字体问题, 本文会直白的给

    2024年04月10日
    浏览(209)
  • 前端实现文件预览(pdf、excel、word、图片)

    前端实现文件预览(pdf、excel、word、图片)

    需求:实现一个在线预览pdf、excel、word、图片等文件的功能。 介绍:支持pdf、xlsx、docx、jpg、png、jpeg。 以下使用Vue3代码实现所有功能,建议以下的预览文件标签可以在外层包裹一层弹窗。 sandbox 这个属性如果是单纯预览图片可以不使用,该属性对呈现在 iframe 框架中的内容

    2024年02月10日
    浏览(20)
  • PDF-Word-图片等的互相转换

    轻闪PDF客户端 - 功能强大的一站式PDF工具 | PDF编辑、转换、阅读 上面页面支持PDF转换成各类别:鼠标停留在PDF工具,点击转换类型即可在线转换 求职岗位的删除:PDF转word,将手机号码依次向前面删除替换掉求职岗位,手机号码后面就可以正确添加空格,到对应位置将联系地

    2024年02月07日
    浏览(4)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包