C# 使用 Itextsharp 在 PDF 中搜索特定单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17485548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search Particular Word in PDF using Itextsharp
提问by user2553159
This is my first post in StackOverflow.
这是我在 StackOverflow 上的第一篇文章。
I have a PDF file in my System drive... I want to write a program in C# using Itextsharp.dll reference to search for a Particular word in that PDF ... say I want to search "StackOverFlow"... If the PDF contains the Word " StackOverFlow" , it should return true.
我的系统驱动器中有一个 PDF 文件...我想使用 Itextsharp.dll 引用在 C# 中编写一个程序来搜索该 PDF 中的特定单词...说我想搜索“StackOverFlow”...如果PDF 包含单词 "StackOverFlow" ,它应该返回 true。
Else it should return false.
否则它应该返回false。
I have looked into many articles but didn't get the solution till now ..:-(
我已经查看了很多文章,但直到现在还没有得到解决方案..:-(
What I have tried till now is :
到目前为止我尝试过的是:
public string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = "2154/MUM/2012 A";// PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
}
return text.ToString();
}
Thanks in advance, Sabya Dev
提前致谢,Sabya Dev
采纳答案by Lalitya
The following method works fine. It gives the list of pages in which the text is found.
以下方法工作正常。它给出了在其中找到文本的页面列表。
public List<int> ReadPdfFile(string fileName, String searthText)
{
List<int> pages = new List<int>();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
if (currentPageText.Contains(searthText))
{
pages.Add(page);
}
}
pdfReader.Close();
}
return pages;
}

