Java將Word轉(zhuǎn)換成PDF的常用用法
java中word轉(zhuǎn)換PDF的常用用法
1、POI
POI是Apache下的一個Java類庫,可以幫助我們實現(xiàn)Java與各種Office格式文件的互相轉(zhuǎn)換。(不推薦,只能用于文字的文檔,如果有圖片和表格則會排版錯誤)
2、Aspose.Words
Aspose.Words for Java是一個原生庫,為開發(fā)人員提供了豐富的功能來創(chuàng)建、編輯和轉(zhuǎn)換 Word、PDF、Web 文檔,而無需在系統(tǒng)上安裝 Microsoft Word 環(huán)境。這個工具非常好用,maven上有對應(yīng)的依賴和jar包,但是轉(zhuǎn)換后會有水印,因為他是(收費的)
3、spire.doc.free
Spire.Doc for Java是一個專業(yè)的 Word API,它使 Java 應(yīng)用程序能夠創(chuàng)建、轉(zhuǎn)換、操作和打印 Word文檔,而無需依賴 Microsoft Word。通過使用這個多功能庫,開發(fā)人員可以輕松處理大量任務(wù),例如插入圖像、超鏈接、 數(shù)字簽名、書簽和水印、設(shè)置頁眉和頁腳、創(chuàng)建表格、設(shè)置背景圖像以及添加腳注和尾注。這個跟aspose功能感覺有點差不多,也很好用,但是收費比對還是aspose更好用,而且這個也是收費的
4、documents4j
官網(wǎng):https://documents4j.com/#/
GitHub:https://github.com/documents4j/documents4j
documents4j 是一個跨平臺的文檔轉(zhuǎn)換庫,并且可以在 Linux 上進(jìn)行 Word 轉(zhuǎn) PDF 的操作。這個比較推薦,開源而且轉(zhuǎn)換后也不會有格式錯誤(推薦)
documents4j用法
注意Windows和linux系統(tǒng)的代碼不一樣
1.Windows系統(tǒng)用法
1.導(dǎo)入依賴,本地必須要有wps或者微軟的office
<!--word轉(zhuǎn)換為PDF文檔--> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-local</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-transformer-msoffice-word</artifactId> <version>1.0.3</version> </dependency>
2.編寫轉(zhuǎn)換代碼(這里我都是傳入input輸出output然后根據(jù)流自己操作)
package com.daysuns.dmas.module.testReportwd.util; import com.documents4j.api.DocumentType; import com.documents4j.api.IConverter; import com.documents4j.job.LocalConverter; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @Slf4j public class Documents4jUtil { /** * word轉(zhuǎn)pdf * */ public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) { String os = System.getProperty("os.name").toLowerCase(); log.info("convertWordToPdf 當(dāng)前操作系統(tǒng):{}", os); if (os.contains("win")) { // Windows操作系統(tǒng) windowsWordToPdf(stream,sourceOutput); } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { // Unix/Linux/Mac操作系統(tǒng) linuxWordToPdf(stream,sourceOutput); } else { // 未知操作系統(tǒng) throw new RuntimeException("不支持當(dāng)前操作系統(tǒng)轉(zhuǎn)換文檔。"); } } /** * 通過documents4j 實現(xiàn)word轉(zhuǎn)pdf -- Windows 環(huán)境 需要有 Microsoft Office 服務(wù) * */ public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) { try{ IConverter converter = LocalConverter.builder().build(); converter.convert(stream) .as(DocumentType.DOCX) .to(sourceOutput) .as(DocumentType.PDF).execute(); } catch (Exception e) { log.error("winWordToPdf windows環(huán)境word轉(zhuǎn)換為pdf時出現(xiàn)異常:", e); } } /** * 通過libreoffice 實現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù) * */ public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) { // 創(chuàng)建臨時文件 File tempFile = createTempFileFromInputStream(stream); // 構(gòu)建LibreOffice的命令行工具命令 String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent(); // 執(zhí)行轉(zhuǎn)換命令 try { if (!executeLinuxCmd(command)) { throw new IOException("轉(zhuǎn)換失敗"); } readPdfFileToByteArrayOutputStream(tempFile,sourceOutput); } catch (Exception e) { log.error("ConvertWordToPdf: Linux環(huán)境word轉(zhuǎn)換為pdf時出現(xiàn)異常:"+e +tempFile.getPath()); // 清理臨時文件 tempFile.delete(); } finally { File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf")); //清理轉(zhuǎn)換后的pdf文件 pdfFile.delete(); // 清理臨時文件,無論是否成功轉(zhuǎn)換 tempFile.delete(); } } /** * 執(zhí)行命令行 * * @param cmd 命令行 * @return * @throws IOException */ private static boolean executeLinuxCmd(String cmd) throws IOException { Process process = Runtime.getRuntime().exec(cmd); try { process.waitFor(); } catch (InterruptedException e) { log.error("executeLinuxCmd 執(zhí)行Linux命令異常:", e); Thread.currentThread().interrupt(); return false; } return true; } /** * * 創(chuàng)建臨時文件 */ private static File createTempFileFromInputStream(InputStream inputStream) { try { File tempFile = File.createTempFile("temp_word", ".docx"); Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); return tempFile; } catch (IOException e) { log.error("創(chuàng)建臨時文件失?。?, e); throw new RuntimeException("創(chuàng)建臨時文件失敗", e); } } /** * 讀取pdf文件 */ private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){ try { Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf")); Files.copy(outputFile, sourceOutput); } catch (Exception e) { throw new RuntimeException(e); } } }
2.linux系統(tǒng)用法
linux操作系統(tǒng)要安裝libreoffice6,原因是documents4j調(diào)用的是office的API
1.在線安裝
sudo yum install libreoffice (這里建議安裝低版本,高版本要求服務(wù)器的很多對應(yīng)API庫版本要求也比較高)
2.離線安裝(點擊后選擇版本下載rpm包,上傳至linux系統(tǒng))
3.解壓文件
4.進(jìn)入兩個文件夾安裝rpm包
使用安裝命令
cd LibreOffice_6.4.2_Linux_x86-64_rpm/RPMS yum localinstall *.rpm
安裝完成查看版本
which libreoffice6.4 --》顯示路徑說明安裝成功 ll /usr/bin/libreoffice6.4 --》得到 "/opt/libreoffice6.4/program/soffice",說明安裝到了 "/opt/libreoffice6.4"
5.腳本測試是否可以成功轉(zhuǎn)換
libreoffice --headless --convert-to pdf 1.doc --》去/temp 臨時目錄查看,也可以指定文件目錄導(dǎo)出
6.同樣適用上面代碼成功轉(zhuǎn)換文檔
package com.daysuns.dmas.module.testReportwd.util; import com.documents4j.api.DocumentType; import com.documents4j.api.IConverter; import com.documents4j.job.LocalConverter; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @Slf4j public class Documents4jUtil { /** * word轉(zhuǎn)pdf * */ public static void convertWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) { String os = System.getProperty("os.name").toLowerCase(); log.info("convertWordToPdf 當(dāng)前操作系統(tǒng):{}", os); if (os.contains("win")) { // Windows操作系統(tǒng) windowsWordToPdf(stream,sourceOutput); } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { // Unix/Linux/Mac操作系統(tǒng) linuxWordToPdf(stream,sourceOutput); } else { // 未知操作系統(tǒng) throw new RuntimeException("不支持當(dāng)前操作系統(tǒng)轉(zhuǎn)換文檔。"); } } /** * 通過documents4j 實現(xiàn)word轉(zhuǎn)pdf -- Windows 環(huán)境 需要有 Microsoft Office 服務(wù) * */ public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) { try{ IConverter converter = LocalConverter.builder().build(); converter.convert(stream) .as(DocumentType.DOCX) .to(sourceOutput) .as(DocumentType.PDF).execute(); } catch (Exception e) { log.error("winWordToPdf windows環(huán)境word轉(zhuǎn)換為pdf時出現(xiàn)異常:", e); } } /** * 通過libreoffice 實現(xiàn)word轉(zhuǎn)pdf -- linux 環(huán)境 需要有 libreoffice 服務(wù) * */ public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) { // 創(chuàng)建臨時文件 File tempFile = createTempFileFromInputStream(stream); // 構(gòu)建LibreOffice的命令行工具命令 String command = "libreoffice6.4 --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent(); // 執(zhí)行轉(zhuǎn)換命令 try { if (!executeLinuxCmd(command)) { throw new IOException("轉(zhuǎn)換失敗"); } readPdfFileToByteArrayOutputStream(tempFile,sourceOutput); } catch (Exception e) { log.error("ConvertWordToPdf: Linux環(huán)境word轉(zhuǎn)換為pdf時出現(xiàn)異常:"+e +tempFile.getPath()); // 清理臨時文件 tempFile.delete(); } finally { File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf")); //清理轉(zhuǎn)換后的pdf文件 pdfFile.delete(); // 清理臨時文件,無論是否成功轉(zhuǎn)換 tempFile.delete(); } } /** * 執(zhí)行命令行 * * @param cmd 命令行 * @return * @throws IOException */ private static boolean executeLinuxCmd(String cmd) throws IOException { Process process = Runtime.getRuntime().exec(cmd); try { process.waitFor(); } catch (InterruptedException e) { log.error("executeLinuxCmd 執(zhí)行Linux命令異常:", e); Thread.currentThread().interrupt(); return false; } return true; } /** * * 創(chuàng)建臨時文件 */ private static File createTempFileFromInputStream(InputStream inputStream) { try { File tempFile = File.createTempFile("temp_word", ".docx"); Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); return tempFile; } catch (IOException e) { log.error("創(chuàng)建臨時文件失?。?, e); throw new RuntimeException("創(chuàng)建臨時文件失敗", e); } } /** * 讀取pdf文件 */ private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){ try { Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf")); Files.copy(outputFile, sourceOutput); } catch (Exception e) { throw new RuntimeException(e); } } }
總結(jié)
到此這篇關(guān)于Java將Word轉(zhuǎn)換成PDF的常用用法的文章就介紹到這了,更多相關(guān)Java將Word轉(zhuǎn)換PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java實現(xiàn)Word轉(zhuǎn)PDF的全過程
- Java調(diào)用py或者exe文件實現(xiàn)Word轉(zhuǎn)PDF
- Java實現(xiàn)一鍵將Word文檔轉(zhuǎn)為PDF
- Java實現(xiàn)WORD和PDF互相轉(zhuǎn)換以及數(shù)據(jù)填充示例
- java將word轉(zhuǎn)pdf的方法示例詳解
- Java將Word文檔轉(zhuǎn)換為PDF文件的幾種常用方法總結(jié)
- Java中Word與PDF轉(zhuǎn)換為圖片的方法詳解
- 探討Java 將Markdown文件轉(zhuǎn)換為Word和PDF文檔
- Java將word文件轉(zhuǎn)成pdf文件的操作方法
- Java實現(xiàn)word/pdf轉(zhuǎn)html并在線預(yù)覽
- Java實現(xiàn)一鍵將Word文檔轉(zhuǎn)為PDF的兩種方法
相關(guān)文章
springboot之redis cache TTL選項的使用
這篇文章主要介紹了springboot之redis cache TTL選項的使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Java里得到00:00:00格式的時分秒的Timestamp
Java里如何得到00:00:00格式的時分秒的Timestamp ,下面是具體的實現(xiàn)代碼,需要的朋友可以參考下。2009-09-09Spring boot項目部署到云服務(wù)器小白教程詳解
這篇文章主要介紹了Spring boot項目部署到云服務(wù)器小白教程詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04說說@ModelAttribute在父類和子類中的執(zhí)行順序
這篇文章主要介紹了@ModelAttribute在父類和子類中的執(zhí)行順序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Spring boot測試找不到SpringRunner.class的問題
這篇文章主要介紹了Spring boot測試找不到SpringRunner.class的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01