嘿嘿嘿、嘿嘿,俺又回來了! github代碼地址 https://github.com/Tom-shushu/work-study 介面文檔有道雲 https://note.youdao.com/s/GShGsYE8 介面文檔離線版本 https://files.cnblogs.com/files/ ...
嘿嘿嘿、嘿嘿,俺又回來了!
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格式的文件啦~
本文來自博客園,作者:Tom-shushu,轉載請註明原文鏈接:https://www.cnblogs.com/Tom-shushu/p/17367203.html