Java高效實現(xiàn)Word轉PDF的完整指南
Java開發(fā)中如何高效穩(wěn)定地將Word文檔轉換為PDF格式? 這個看似簡單的需求,在企業(yè)合同電子歸檔、財務報表批量生成等場景中,開發(fā)者往往會遇到不同的問題,如樣式錯亂、字體丟失等。
今天我們將通過實測代碼,展示如何用 Spire.Doc for Java 庫實現(xiàn)Word到PDF文檔的快速轉換,并解析其轉換選項的靈活配置技巧。
方法一:三步實現(xiàn)核心功能
步驟1:添加Maven依賴
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>15.7.7</version>
</dependency>
</dependencies>
步驟2:核心代碼示例 (支持Doc和Docx格式)
// 創(chuàng)建文檔對象模型
Document doc = new Document();
// 加載Word
doc.loadFromFile("input.docx");
// 保存為PDF
doc.saveToFile("output.pdf", FileFormat.PDF);
doc.dispose();
步驟3:異常處理
try {
// 轉換代碼...
} catch (DocumentException e) {
System.err.println("轉換失敗: " + e.getMessage());
throw new RuntimeException(e);
}
最佳實踐
生產(chǎn)環(huán)境務必調用doc.close()釋放資源,避免服務器出現(xiàn)文件句柄泄露
方法二:高級選項配置
轉換過程中通過 ToPdfParameterList 對象可實現(xiàn)精細控制:
| 選項參數(shù) | 作用描述 | 典型應用場景 |
|---|---|---|
| isEmbeddedAllFonts | 強制嵌入所有字體 | 跨系統(tǒng)排版一致性 |
| setDisableLink | 禁用超鏈接 | 安全文檔轉換 |
| setPdfConformanceLevel | 設置PDF標準規(guī)范 | 歸檔級文檔(法律/醫(yī)療 |
| setCreateWordBookmarks | 保留書簽 | 技術手冊/論文等長文檔導航 |
加密PDF代碼示例:
// 高級轉換配置示例
ToPdfParameterList options = new ToPdfParameterList();
options.setPdfConformanceLevel(PdfConformanceLevel.Pdf_A_1_B); // 符合PDF/A-1b標準
String password1 = "E-iceblue"; // 打開密碼
String password2 = "123"; // 用戶密碼
options..getPdfSecurity().encrypt(password1, password2, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit); // 加密PDF
// 轉換Word為PDF
Document doc = new Document();
doc.loadFromFile("機密報告.docx");
doc.saveToFile("加密文檔.pdf", options);
最佳實踐
轉換時還可通過 setJPEGQuality 設置圖片壓縮質量 (0-100),以優(yōu)化PDF體積。
性能優(yōu)化建議
內存管理: 處理50頁以上文檔時,采用分段加載減少單次內存占用
批量處理:
File[] files = new File("docs/").listFiles((dir, name) -> name.endsWith(".docx"));
for (File file : files) {
// 循環(huán)調用轉換方法...
}
方法補充
Java 實現(xiàn) Word 轉PDF方案
轉換方案選擇
項目開發(fā)我主要使用過 Aspose 和 LibreOffice,兩者代碼實現(xiàn)都很簡單,轉換效果也不錯。其他生成 pdf 的方案,比如使用 html 轉換、xml、或者直接操作 pdf 模板,實際使用代碼邏輯繁瑣不易理解,且轉換生成效果一般。LibreOffice主要是后期做復雜的 pdf 模板導出,使用 word 難以動態(tài)填充內容,后來使用 excel,在 java中計算后填充 excel,設置好格式在轉換拼接 pdf 最后輸出。
- Aspose:商業(yè)收費軟件,免費版有水印。
- LibreOffice:開源免費, 需要部署環(huán)境安裝LibreOffice,實際使用需要控制并發(fā)與文件大小,避免對服務器整體造成影響。
Aspose 實現(xiàn)方案
a. 依賴注入
可以直接下載 jar 包,注入 maven 依賴后直接使用:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
b. 實際使用
基本用法:
// 先創(chuàng)建一個臨時文件用來存儲 PDF
String pdfPath = FileUtils.getTempDirectoryPath() + System.currentTimeMillis() + ".pdf";
/**
* 加載license 用于破解 不生成水印
*/
@SneakyThrows
private static void getLicense() {
try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("lib/License.xml")) {
License license = new License();
license.setLicense(is);
}
}
/**
* word轉pdf
*
* @param wordPath word文件保存的路徑
* @param pdfPath 轉換后pdf文件保存的路徑
*/
public static void wordToPdf(String wordPath, String pdfPath) throws Exception {
// 獲取許可證
getLicense();
// 加載 Word 文檔
Document doc = new Document(wordPath);
// 設置 PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
options.setSaveFormat(SaveFormat.PDF);
// 保存為 PDF
try (FileOutputStream os = new FileOutputStream(pdfPath)) {
doc.save(os, options);
}
}
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature> sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
</Signature>
</License>
c. 常見問題與解決思路
1. 字體文件缺失導致轉換亂碼
場景:在服務器或 Docker 環(huán)境下運行,可能會因缺少字體導致 PDF 亂碼。
解決方案一:將字體文件放在服務器的字體目錄,Docker 可在啟動時拷貝字體。
# 使用帶完整字體庫的基礎鏡像 FROM openjdk:17-jdk-slim # 拷貝字體 COPY fonts/ /usr/share/fonts/truetype/custom/ # 刷新字體緩存 RUN fc-cache -fv
解決方案二:將字體文件放在項目的 resources/fonts 目錄下,導出時拷貝到臨時目錄后再進行轉換(只需轉換一次)。
private final static String[] FONT_PATHS = {"fonts/Songti.ttc"};
fontPath = copyTempFileFont(FONT_PATHS);
/**
* 將項目中的字體文件拷貝到臨時目錄
* @return 字體目錄路徑
*/
private static String copyTempFileFont(String... fontPath) {
String tempDir = System.getProperty("java.io.tmpdir");
File fontDir = new File(tempDir, "fonts");
if (!fontDir.exists()) {
fontDir.mkdirs(); // 創(chuàng)建目錄
}
for (String path : fontPath) {
File tempFile = new File(fontDir, new File(path).getName());
if (!tempFile.exists()) {
try (InputStream inputStream = Object.class.getClassLoader().getResourceAsStream(path)) {
FileUtils.copyInputStreamToFile(inputStream, tempFile);
} catch (IOException e) {
throw new RuntimeException("字體文件轉換失敗,請稍候重試");
}
}
}
return fontDir.getPath() + "/";
}
帶字體目錄的轉換方法:
/**
* word轉pdf(指定字體目錄)
*
* @param wordPath word文件保存的路徑
* @param pdfPath 轉換后pdf文件保存的路徑
* @param fontPath 字體目錄
*/
public static void wordToPdf(String wordPath, String pdfPath, String fontPath) throws Exception {
// 獲取許可證
getLicense();
// 設置字體文件夾
FontSettings.setFontsFolder(fontPath, false);
// 加載 Word 文檔
Document doc = new Document(wordPath);
// 設置 PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
options.setSaveFormat(SaveFormat.PDF);
// 保存為 PDF
try (FileOutputStream os = new FileOutputStream(new File(pdfPath))) {
doc.save(os, options);
}
}LibreOffice 實現(xiàn)方案(對應 excel 也可以直接使用)
a. JODConverter(調用 LibreOffice 轉換)
引入依賴
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.4.4</version>
</dependency>
代碼實現(xiàn)
/**
* 轉換為PDF(同時適用于 word excel)
* @param file
* @return
* @throws OfficeException
* @throws IOException
*/
public File convertToPdf(File file) throws OfficeException, IOException {
File tempPdfFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".pdf");
LocalOfficeManager officeManager = null;
try {
officeManager = (LocalOfficeManager.builder().install()).build();
officeManager.start();
(LocalConverter.builder().officeManager(officeManager)).build().convert(file).to(tempPdfFile).execute();
} finally {
if (officeManager != null) {
officeManager.stop();
}
}
return tempPdfFile;
}拼接pdf
a. 依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.15</version>
</dependency>
b. 實現(xiàn)
/**
* 合并PDF文件
*/
private void mergePdfFiles(List<File> pdfFiles, String outputPath) throws IOException {
try (PdfWriter writer = new PdfWriter(outputPath);
PdfDocument mergedDoc = new PdfDocument(writer)) {
PdfMerger merger = new PdfMerger(mergedDoc);
for (File pdfFile : pdfFiles) {
try (PdfReader reader = new PdfReader(pdfFile);
PdfDocument sourceDoc = new PdfDocument(reader)) {
merger.merge(sourceDoc, 1, sourceDoc.getNumberOfPages());
}
}
}
}到此這篇關于Java高效實現(xiàn)Word轉PDF的完整指南的文章就介紹到這了,更多相關Java Word轉PDF內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android Home鍵監(jiān)聽的實現(xiàn)代碼
這篇文章主要介紹了Android Home 鍵監(jiān)聽的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
Java實現(xiàn)mysql數(shù)據(jù)庫的自動備份和自動還原
這篇文章主要為大家詳細介紹了如何通過Java實現(xiàn)mysql數(shù)據(jù)庫的自動備份和自動還原,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2024-11-11
Springboot重寫addInterceptors()方法配置攔截器實例
這篇文章主要介紹了Springboot重寫addInterceptors()方法配置攔截器實例,spring?boot拋棄了復雜的xml配置,我們可以自定義配置類(標注@Configuration注解的類)來實現(xiàn)WebMvcConfigurer接口,并重寫addInterceptors()方法來配置攔截器,需要的朋友可以參考下2023-09-09
Java實現(xiàn)一個敏感詞過濾有哪些方法以及怎么優(yōu)化詳解
我們在開發(fā)系統(tǒng)或者應用的過程中,經(jīng)常需要對用戶提交的評論或者文章進行審核,對其中的敏感詞進行校驗或者過濾,這篇文章主要介紹了Java實現(xiàn)一個敏感詞過濾有哪些方法以及怎么優(yōu)化的相關資料,需要的朋友可以參考下2025-07-07

