用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 形式 

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

 

posted @ 2023-05-02 00:34  Tom-shushu  阅读(5434)  评论(2编辑  收藏  举报