原理:Jacob (Java-COM Bridge) 調用 Word.Application COM 組件,將文檔另存為 HTML/XML,再解析文本。
jacob.jar + 平台相關 jacob.dll (放入 PATH)。ActiveXComponent word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false));
Dispatch docs = word.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
new Object[]{inFile, new Variant(false), new Variant(true)}, new int[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
new Object[]{htmlFile, new Variant(8)}, new int[1]); // 8 = wdFormatHTML
Dispatch.call(doc, "Close", new Variant(false));
word.invoke("Quit", new Variant[]{});
原理:POI 直接解析 OLE2 (doc) / OOXML (docx) 結構,提取文本。
poi.jar、poi-ooxml.jar、xmlbeans.jar 等。// .doc (HWPF)
FileInputStream fis = new FileInputStream("a.doc");
WordExtractor extractor = new WordExtractor(fis);
String text = extractor.getText();
// .docx (XWPF)
XWPFDocument doc = new XWPFDocument(new FileInputStream("a.docx"));
String text = doc.getText();
原理:PDFBox 解析 PDF 結構,PDFTextStripper 提取文本。
pdfbox.jar、fontbox.jar。PDDocument pdf = PDDocument.load(new File("a.pdf"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(pdf);
pdf.close();
原理:調用 Xpdf 開源項目的 pdftotext.exe 進程,輸出 UTF-8 文本。
xpdf 二進制包 + 中文補丁包 (含字體配置),按 README 部署。String cmd = "C:/Program Files/xpdf/pdftotext.exe -enc UTF-8 -q a.pdf -";
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append('\n');
br.close();
p.waitFor();
String text = sb.toString();
| 維度 | Jacob | POI | PDFBox | Xpdf |
|---|---|---|---|---|
| 平台 | 僅 Windows | 跨平台 | 跨平台 | 跨平台(需各平台二進制) |
| Office 依賴 | 需安裝 Word | 無 | 無 | 無 |
| .doc 支援 | 完美 | 良好 | 不支援 | 不支援 |
| .docx 支援 | 完美 | 良好 | 不支援 | 不支援 |
| PDF 支援 | 需 Word 開啟 | 不支援 | 良好(中文弱) | 優秀(中文強) |
| 併發適合度 | 極低 | 中 (大文件記憶體壓力) | 中 | 低 (進程開銷) |
| 部署複雜度 | 高 | 低 | 低 | 中 (補丁包配置) |