javascript
SpringBoot下实现PDF转word(Maven项目)
目錄
前言
一、簡易版本(只可以將PDF轉為文字)
二、完整版本
1.引入庫
2.編寫工具類
3.編寫controller類
4.vue前端實現下載
5.提示
三、注意事項
總結
前言
在日常工作學習中經常會遇到需要將PDF文件轉成Word文件的場景,但是現在網上絕大部分PDF轉Word的軟件都是打著免費的噱頭吸引你下載,但是使用時才發現,這些軟件只能免費轉幾頁,剩下的還是要購買會員。但是實際要轉的PDF頁數都遠遠超過了免費額度,這個時候,我們就可以通過這篇文章,自己寫一個工具接口,來達到我們PDF轉Word的目的
一、簡易版本(只可以將PDF轉為文字)
1、首先,進入Apache官網下載pdfbox最新版jar包,官網地址為:https://pdfbox.apache.org/download.cgi
2、將jar包導入到項目中,具體步驟如下:
(1)在項目resources目錄下新建lib文件夾。并將下載的pdfbox最新版jar包放入lib文件夾
?
?
?
(2)進入project structure中導入項目中jar包
?
(3)在Modules目錄下點擊右方+添加jar包
?
(4)選擇JARs and Directories
?
(5)選擇jar包所在目錄并點擊ok
3、編寫代碼進行文件轉換,代碼如下:
public static void main(String[] args) {try {String pdfFile = "E:/乙方鏈賬號.pdf";PDDocument doc = PDDocument.load(new File(pdfFile));int pagenumber = doc.getNumberOfPages();pdfFile = pdfFile.substring(0, pdfFile.lastIndexOf("."));String fileName = pdfFile + ".doc";File file = new File(fileName);if (!file.exists()){file.createNewFile();}FileOutputStream fos = new FileOutputStream(fileName);Writer writer = new OutputStreamWriter(fos, "UTF-8");PDFTextStripper stripper = new PDFTextStripper();stripper.setSortByPosition(true);// 排序stripper.setStartPage(1);// 設置轉換的開始頁stripper.setEndPage(pagenumber);// 設置轉換的結束頁stripper.writeText(doc, writer);writer.close();doc.close();System.out.println("pdf轉換word成功!");} catch (IOException e) {e.printStackTrace();}}?
?
二、完整版本
1.引入庫
完整版不僅可以轉換文字,還可以轉換圖片,并將樣式都轉換好,因此需要第三方工具包
我這邊使用的是Spire的PDFmaven庫
首先,需要使用Spire的maven私服,在pom文件中添加以下代碼:
<repositories><repository><id>com.e-iceblue</id><url>http://repo.e-iceblue.cn/repository/maven-public/</url></repository> </repositories>然后導入PDF相關工具包
<dependency><groupId> e-iceblue </groupId><artifactId>spire.pdf</artifactId><version>3.4.2</version> </dependency>2.編寫工具類
該工具類主要作用是將前端傳過來的MultipartFile轉成File類型,具體代碼如下
public class CommonUtil {/*** MultipartFile 轉換成File** @param multfile 原文件類型* @return File*/public static File multipartToFile(MultipartFile multfile) throws IOException {File file = null; // file = File.createTempFile("prefix","_" + multfile.getOriginalFilename());String projectPath = System.getProperty("user.dir");file = new File(projectPath + "/prefix_" + multfile.getOriginalFilename());multfile.transferTo(file);return file;}}3.編寫controller類
實現接收PDF文件,轉成Word文件并將轉好的文件返回以供前端下載。具體代碼如下:
@PostMapping("pdfToDoc")public void pdfToDoc(@RequestParam("pdfFile") MultipartFile pdfFile, HttpServletResponse response) throws Exception {// 將MultiparFile轉為FileFile file = CommonUtil.multipartToFile(pdfFile);// 創建Pdf工具類對象PdfDocument pdf = new PdfDocument();// 拼接Word文件名String projectPath = System.getProperty("user.dir");String name = file.getName();pdf.loadFromFile(projectPath + "/" + name);//保存為Word格式String fileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + ".docx";pdf.saveToFile(fileName, FileFormat.DOCX);// 將問文件轉為字節流返回供前端下載File wordFile = new File(fileName);response.setHeader("content-type", "application/octet-stream");response.setContentType("application/octet-stream");// 下載文件能正常顯示中文response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 實現文件下載byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;try {fis = new FileInputStream(wordFile);bis = new BufferedInputStream(fis);OutputStream os = response.getOutputStream();int i = bis.read(buffer);while (i != -1) {os.write(buffer, 0, i);i = bis.read(buffer);}log.info("word文件成功下載");} catch (Exception e) {log.info("word文件下載失敗");} finally {if (bis != null) {try {// 結束后關閉文件流bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {// 結束后關閉文件流fis.close();} catch (IOException e) {e.printStackTrace();}}// 最后刪除轉換過程中生成的文件wordFile.delete();file.delete();}}4.vue前端實現下載
個人原因,前端選擇了vue,在使用axios請求時想要把接口返回的json轉換成文件并下載需要額外處理,具體代碼如下:
handleAvatarSuccess(file) {// 將上傳的文件放入FormData對象中作為請求參數傳遞給后端var data = new FormData()data.append('pdfFile', file)console.log(file.name)this.fileName = file.name// 發送Post請求AdminApi.pdfToDoc(data).then(response => {console.log(response)// 將請求返回的數據封裝成文件并下載this.downloadFile(response.data)})},downloadFile(data) {// 文件導出if (!data) {return}const url = window.URL.createObjectURL(new Blob([data]))const link = document.createElement('a')link.style.display = 'none'link.href = urllink.setAttribute('download', this.fileName.substring(0, this.fileName.lastIndexOf('.')) + '.docx')document.body.appendChild(link)link.click()}5.提示
因為axios請求默認返回數據類型為json,無法直接下載,因此需要修改返回數據類型為blob,修改方法如下:
在axios設置中將responseType設置為 ‘blob’即可
三、注意事項
Spring框架默認上傳最大文件為10M,如果要轉換的PDF文件超過這個大小,則接口會報錯,這時候需要修改最大上傳文件大小具體代碼為:
@Configuration public class HttpConfiguration {/*** 文件上傳配置** @return*/@Beanpublic MultipartConfigElement multipartConfigElement() {MultipartConfigFactory factory = new MultipartConfigFactory();// 單個數據大小factory.setMaxFileSize(DataSize.ofMegabytes(50)); // KB,MB/// 總上傳數據大小factory.setMaxRequestSize(DataSize.ofMegabytes(200));return factory.createMultipartConfig();} }總結
如果只是將大部分內容為文字的pdf轉為Word文件那使用第一種方式即可,簡單而且效率高;
但是如果PDF內容比較復雜則需要第二種方法,第一種方法已經不再適用了,但是第二種方法效率較第一種稍微低一點,請根據情況選擇;
總結
以上是生活随笔為你收集整理的SpringBoot下实现PDF转word(Maven项目)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 秒懂MOS管选型技巧
- 下一篇: gradle idea java ssm