javascript
SpringBoot下实现PDF转word(Maven项目)
目錄
前言
一、簡(jiǎn)易版本(只可以將PDF轉(zhuǎn)為文字)
二、完整版本
1.引入庫(kù)
2.編寫(xiě)工具類(lèi)
3.編寫(xiě)controller類(lèi)
4.vue前端實(shí)現(xiàn)下載
5.提示
三、注意事項(xiàng)
總結(jié)
前言
在日常工作學(xué)習(xí)中經(jīng)常會(huì)遇到需要將PDF文件轉(zhuǎn)成Word文件的場(chǎng)景,但是現(xiàn)在網(wǎng)上絕大部分PDF轉(zhuǎn)Word的軟件都是打著免費(fèi)的噱頭吸引你下載,但是使用時(shí)才發(fā)現(xiàn),這些軟件只能免費(fèi)轉(zhuǎn)幾頁(yè),剩下的還是要購(gòu)買(mǎi)會(huì)員。但是實(shí)際要轉(zhuǎn)的PDF頁(yè)數(shù)都遠(yuǎn)遠(yuǎn)超過(guò)了免費(fèi)額度,這個(gè)時(shí)候,我們就可以通過(guò)這篇文章,自己寫(xiě)一個(gè)工具接口,來(lái)達(dá)到我們PDF轉(zhuǎn)Word的目的
一、簡(jiǎn)易版本(只可以將PDF轉(zhuǎn)為文字)
1、首先,進(jìn)入Apache官網(wǎng)下載pdfbox最新版jar包,官網(wǎng)地址為:https://pdfbox.apache.org/download.cgi
2、將jar包導(dǎo)入到項(xiàng)目中,具體步驟如下:
(1)在項(xiàng)目resources目錄下新建lib文件夾。并將下載的pdfbox最新版jar包放入lib文件夾
?
?
?
(2)進(jìn)入project structure中導(dǎo)入項(xiàng)目中jar包
?
(3)在Modules目錄下點(diǎn)擊右方+添加jar包
?
(4)選擇JARs and Directories
?
(5)選擇jar包所在目錄并點(diǎn)擊ok
3、編寫(xiě)代碼進(jìn)行文件轉(zhuǎn)換,代碼如下:
public static void main(String[] args) {try {String pdfFile = "E:/乙方鏈賬號(hào).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);// 設(shè)置轉(zhuǎn)換的開(kāi)始頁(yè)stripper.setEndPage(pagenumber);// 設(shè)置轉(zhuǎn)換的結(jié)束頁(yè)stripper.writeText(doc, writer);writer.close();doc.close();System.out.println("pdf轉(zhuǎn)換word成功!");} catch (IOException e) {e.printStackTrace();}}?
?
二、完整版本
1.引入庫(kù)
完整版不僅可以轉(zhuǎn)換文字,還可以轉(zhuǎn)換圖片,并將樣式都轉(zhuǎn)換好,因此需要第三方工具包
我這邊使用的是Spire的PDFmaven庫(kù)
首先,需要使用Spire的maven私服,在pom文件中添加以下代碼:
<repositories><repository><id>com.e-iceblue</id><url>http://repo.e-iceblue.cn/repository/maven-public/</url></repository> </repositories>然后導(dǎo)入PDF相關(guān)工具包
<dependency><groupId> e-iceblue </groupId><artifactId>spire.pdf</artifactId><version>3.4.2</version> </dependency>2.編寫(xiě)工具類(lèi)
該工具類(lèi)主要作用是將前端傳過(guò)來(lái)的MultipartFile轉(zhuǎn)成File類(lèi)型,具體代碼如下
public class CommonUtil {/*** MultipartFile 轉(zhuǎn)換成File** @param multfile 原文件類(lèi)型* @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.編寫(xiě)controller類(lèi)
實(shí)現(xiàn)接收PDF文件,轉(zhuǎn)成Word文件并將轉(zhuǎn)好的文件返回以供前端下載。具體代碼如下:
@PostMapping("pdfToDoc")public void pdfToDoc(@RequestParam("pdfFile") MultipartFile pdfFile, HttpServletResponse response) throws Exception {// 將MultiparFile轉(zhuǎn)為FileFile file = CommonUtil.multipartToFile(pdfFile);// 創(chuàng)建Pdf工具類(lèi)對(duì)象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);// 將問(wèn)文件轉(zhuǎn)為字節(jié)流返回供前端下載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"));// 實(shí)現(xiàn)文件下載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 {// 結(jié)束后關(guān)閉文件流bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {// 結(jié)束后關(guān)閉文件流fis.close();} catch (IOException e) {e.printStackTrace();}}// 最后刪除轉(zhuǎn)換過(guò)程中生成的文件wordFile.delete();file.delete();}}4.vue前端實(shí)現(xiàn)下載
個(gè)人原因,前端選擇了vue,在使用axios請(qǐng)求時(shí)想要把接口返回的json轉(zhuǎn)換成文件并下載需要額外處理,具體代碼如下:
handleAvatarSuccess(file) {// 將上傳的文件放入FormData對(duì)象中作為請(qǐng)求參數(shù)傳遞給后端var data = new FormData()data.append('pdfFile', file)console.log(file.name)this.fileName = file.name// 發(fā)送Post請(qǐng)求AdminApi.pdfToDoc(data).then(response => {console.log(response)// 將請(qǐng)求返回的數(shù)據(jù)封裝成文件并下載this.downloadFile(response.data)})},downloadFile(data) {// 文件導(dǎo)出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.提示
因?yàn)閍xios請(qǐng)求默認(rèn)返回?cái)?shù)據(jù)類(lèi)型為json,無(wú)法直接下載,因此需要修改返回?cái)?shù)據(jù)類(lèi)型為blob,修改方法如下:
在axios設(shè)置中將responseType設(shè)置為 ‘blob’即可
三、注意事項(xiàng)
Spring框架默認(rèn)上傳最大文件為10M,如果要轉(zhuǎn)換的PDF文件超過(guò)這個(gè)大小,則接口會(huì)報(bào)錯(cuò),這時(shí)候需要修改最大上傳文件大小具體代碼為:
@Configuration public class HttpConfiguration {/*** 文件上傳配置** @return*/@Beanpublic MultipartConfigElement multipartConfigElement() {MultipartConfigFactory factory = new MultipartConfigFactory();// 單個(gè)數(shù)據(jù)大小factory.setMaxFileSize(DataSize.ofMegabytes(50)); // KB,MB/// 總上傳數(shù)據(jù)大小factory.setMaxRequestSize(DataSize.ofMegabytes(200));return factory.createMultipartConfig();} }總結(jié)
如果只是將大部分內(nèi)容為文字的pdf轉(zhuǎn)為Word文件那使用第一種方式即可,簡(jiǎn)單而且效率高;
但是如果PDF內(nèi)容比較復(fù)雜則需要第二種方法,第一種方法已經(jīng)不再適用了,但是第二種方法效率較第一種稍微低一點(diǎn),請(qǐng)根據(jù)情況選擇;
總結(jié)
以上是生活随笔為你收集整理的SpringBoot下实现PDF转word(Maven项目)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 秒懂MOS管选型技巧
- 下一篇: 怎么复制PDF文件页面?用什么方法操作