兩種方案比較
| 方案 | 原理 | 優點 | 缺點 |
| POI + iText | 讀取 Excel 內容重寫 PDF | 無需 Office | 格式複雜(圖表、圖片、樣式)極難完美還原 |
| Jacob (COM) | 自動化 Excel 應用程式另存為 PDF | 完美保留原始排版 | 需 Windows + Office 安裝;無法在 Linux 伺服器運行 |
Jacob 實作代碼
package com.bplead.module.sign.util;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class TransferTool {
public static void excelToPdf(String excelPath, String pdfPath) {
System.out.println("Starting Excel...");
long start = System.currentTimeMillis();
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
app.setProperty("Visible", false);
Dispatch workbooks = app.getProperty("Workbooks").toDispatch();
System.out.println("Opening: " + excelPath);
Dispatch workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method,
new Object[]{excelPath, new Variant(false), new Variant(false)}, new int[3]).toDispatch();
// 57 = xlTypePDF (Excel 2007+ 需安裝 SaveAsPDFandXPS.exe)
Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, new Object[]{
pdfPath, new Variant(57), new Variant(false), new Variant(57),
new Variant(57), new Variant(false), new Variant(true),
new Variant(57), new Variant(true), new Variant(true)
}, new int[1]);
Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f);
System.out.println("Completed in " + (System.currentTimeMillis() - start)/1000 + "s");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
if (app != null) app.invoke("Quit", new Variant[]{});
}
}
public static void main(String[] args) {
excelToPdf("F:/Project/Template.xlsx", "F:/pdf.pdf");
}
}
環境準備
- 安裝 Microsoft Office 2010+(含 Excel)。
- Office 2007 需額外安裝 SaveAsPDFandXPS.exe。
- 下載 Jacob,將 `jacob.jar` 加入 classpath。
- 將對應架構的 DLL (`jacob-1.17-x64.dll` 或 `jacob-1.17-x86.dll`) 放入 `JRE/bin` 或系統 `PATH` 目錄。
注意
- 伺服器端運行需啟用「互動式服務」或使用者登入會話,否則 Excel 自動化會失敗(DCOM 權限、桌面堆疊限制)。
- 併發轉換會啟動多個 Excel 進程,記憶體佔用高,建議序列化處理或使用無頭轉換庫(LibreOffice headless、Aspose.Cells 等)。