摘要:Lucene.Net 取出PDF 內文
若要索引 PDF 的內容 , 首先必須先把 PDF 裡面的內容抽取出來 ,
在這裡會介紹兩個元件來實現這個目的 , ITextSharp 和 PDFBox
在選擇元件時皆須考慮幾點 :
1. 取得的內文品質 , 有些結構在擷取上較差
2. 是否對中文有良好的支援
3. 擷取內文的速度
ITextSharp Code :
Step 1 : 引入NameSpace
using iTextSharp.text.pdf.parser;
using iTextSharp.text.pdf;
Step 2 : 抽取文字
public void GetTextFromAllPages(String pdfPath)
{
PdfReader reader = new PdfReader(pdfPath);
string text = "";
for (int page = 1; page <= reader.NumberOfPages; page++)
{
text = PdfTextExtractor.GetTextFromPage(reader, page);
Response.Write(text.ToString());
}
}
也可以針對特定頁數抽取內文 :
text = PdfTextExtractor.GetTextFromPage(reader, 1);
PDFBox :
Step 1 : 引入空間
using org.pdfbox.pdmodel;
using org.pdfbox.util;
Step 2 : 抽取文字
PDDocument objDocument = PDDocument.load("C:\\test3.pdf");
PDFTextStripper objTextStripper = new PDFTextStripper();
Response.Write(objTextStripper.getText(objDocument));
另外 , PDFBox 有提供 LucenePDFDocument 這個類別提供與 Lucene 做整合之用 ,
可以直接使用 IndexWriter 把它加入 Lucene 的 Index 中 , LucenePDFDocument 會
自動把 PDF 檔案的各種 Field 抓出並把他們加入 Document 中 .