2015-07-20 56 views
1

我需要一個PDF文件中搜索來查找string.I知道iTextSharp的有這個功能,我可以使用此代碼搜索來查找字符串

public bool SearchPdfFile(string fileName, String searchText) 
{ 
    /* technically speaking this should not happen, since "you" are calling it 
     therefore this should be handled critically 
     if (!File.Exists(fileName)) return false; //original workflow 
    */ 
    if (!File.Exists(fileName)) 
     throw new FileNotFoundException("File not found", fileName); 

    using (PdfReader reader = new PdfReader(fileName)) 
    { 
     var strategy = new SimpleTextExtractionStrategy(); 

     for (int page = 1; page <= pdfReader.NumberOfPages; page++) 
     { 
      var currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy); 
      if (currentPageText.Contains(searchText)) 
       return true; 
     } 
    } 

    return false; 
} 

但使用下的IM的iText LGPL/MPL許可證(版本3.0/4.0),如果我根據AGPL免費製作我自己的軟件,則新版本5.0僅爲免費版本。 SimpleTextExtractionStrategy類在此版本的itext中未定義。是否有替代方法使用舊版本的itext來執行此操作?

回答

1

PDFClown。 一個愚蠢的名字,但它是一個相當詳細和靈活的PDF庫。我以前用過它。它在LGPL下是免費的。 http://pdfclown.org/about/#TheLicense

例如,從PDFClown網站修改(他們的榜樣是JAVA)

File file = new File(myFilePath); 

// Define the text pattern to look for! 
String textRegEx = "rabbit"; 
Pattern pattern = Pattern.compile(textRegEx, Pattern.CASE_INSENSITIVE); 

// Instantiate the extractor! 
TextExtractor textExtractor = new TextExtractor(true, true); 

for(final Page page : file.getDocument().getPages()) 
{ 
    // Extract the page text! 
    Map<Rectangle2D,List<ITextString>> textStrings = textExtractor.extract(page); 

    // Find the text pattern matches! 
    final Matcher matcher = pattern.matcher(TextExtractor.toString(textStrings)); 
} 
+0

感謝..我可以用它來搜索string.Can您提供一個例子 – techno

+0

是的,可以。我會用一個例子來更新它。這是從PDFClown網站和它的Java中提取/修改的,但是對於C#,該過程是相同的。 – Taekahn

+0

非常感謝。我已經看到你的例子,但我怎麼能從匹配對象獲得頁碼。 – techno