在c#中找到pdf文件中字符串的页码

时间:2012-04-22 07:04:04

标签: c# .net itextsharp

我正在开发一个pdf阅读器。我想在pdf中找到任何字符串并知道相应的页码。我正在使用iTextSharp。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

// add any string you want to match on
Regex regex = new Regex("the", 
  RegexOptions.IgnoreCase | RegexOptions.Compiled 
);
PdfReader reader = new PdfReader(pdfPath);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int i = 1; i <= reader.NumberOfPages; i++) {
  ITextExtractionStrategy strategy = parser.ProcessContent(
    i, new SimpleTextExtractionStrategy()
  );
  if ( regex.IsMatch(strategy.GetResultantText()) ) {
    // do whatever with corresponding page number i...
  }
}

答案 1 :(得分:1)

要使用Itextsharp,您可以使用Acrobat.dll查找当前页码。首先打开pdf文件并使用L

搜索字符串
Acroavdoc.open("Filepath","Temperory title") 

Acroavdoc.FindText("String").

如果在此pdf文件中找到该字符串,则光标移动到特定页面,并且将突出显示搜索到的字符串。现在我们使用Acroavpageview.GetPageNum()来获取当前页码。

Dim AcroXAVDoc As CAcroAVDoc
Dim Acroavpage As AcroAVPageView
Dim AcroXApp As CAcroApp

AcroXAVDoc = CType(CreateObject("AcroExch.AVDoc"), Acrobat.CAcroAVDoc)
AcroXApp = CType(CreateObject("AcroExch.App"), Acrobat.CAcroApp)
AcroXAVDoc.Open(TextBox1.Text, "Original document")
AcroXAVDoc.FindText("String is to searched", True, True, False)
Acroavpage = AcroXAVDoc.GetAVPageView()

Dim x As Integer = Acroavpage.GetPageNum
MsgBox("the string found in page number" & x)