嘿嘿嘿、嘿嘿,俺又回來了!
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 |
一、巴拉巴拉
為什么發(fā)布這篇文檔轉換的文章呢?因為上周我要將一個PDF轉換為Word,結果百度谷歌了所有文章,最終的結果都是“能轉換,但是只能轉換一點點,多了就要收費”,于是乎我突發(fā)奇想、心血來潮在放假的那天打算開發(fā)一款小程序實現(xiàn)各種文檔的轉換,在百度了一下午后發(fā)現(xiàn)目前都是借助Aspose實現(xiàn)的,但是好像要收費,在我新建項目時偶然間發(fā)現(xiàn)原來Maven倉庫里面居然有人將破解好的Jar包上傳到Maven中央倉庫了,于是我測試了一下,哈哈真香,于是就有了這篇文章。至于小程序做的怎么樣了呢?暫時又擱置了,因為我調查了一下已經(jīng)有現(xiàn)成的好多優(yōu)秀的微信小程序可以實現(xiàn)各種文檔轉換了,還有就是個人小程序沒法上線,可能暫時不會做小程序了,大家有想法的可以按照自己的想法使用我的源碼,直接和前端對接做出優(yōu)秀的小程序。
二、PDF相關文件操作
1.引入依賴
<dependency> <groupId>com.luhuiguo</groupId> <artifactId>aspose-pdf</artifactId> <version>23.1</version> </dependency>
2.代碼實現(xiàn)(只貼關鍵代碼,代碼我會放到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()); // 保存目錄位置根據(jù)項目需求可隨意更改 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){ // 創(chuàng)建OSSClient實例。 OSS ossClient = ossConfig.getOssClient(); try { // 創(chuàng)建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); //加載源文件數(shù)據(jù) 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.引入相關依賴
<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); //加載源文件數(shù)據(jù) 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; }
六、同時我還找到了一個幾乎所有文件轉換圖片的工具類,被我稍作修改,就可以實現(xiàn)文件轉圖片,返回阿里云圖片的儲存地址集合啦
七、演示(演示有兩個意思一下,別的大家自行測試)
1.PDF轉Word
我有一個 cs.pdf 的PDF文件,通過調用PDF 轉其他文件的接口,將其轉換為 Wprd 形式?
?通過訪問返回的地址就可以發(fā)現(xiàn),文件已經(jīng)被轉換為Word格式的文件啦~
文章來源:http://www.zghlxwxcb.cn/news/detail-431172.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-431172.html
到了這里,關于用Aspose-Java免費實現(xiàn) PDF、Word、Excel、Word互相轉換并將轉換過得文件上傳OSS,返回轉換后的文件路徑的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!