13

I have a PDF file in my System drive. I want to write a program in C# using iTextSharp 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, else it should return false.

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();
}
janw
  • 8,758
  • 11
  • 40
  • 62
user2553159
  • 133
  • 1
  • 1
  • 4
  • 2
    You have `PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy).` And you have the string you search. Have you checked whether your search string is in the result of the `GetTextFromPage` method yet? If it is not, have you checked what the return of that method looks like (it'S a string after all)? – mkl Jul 05 '13 at 09:35

1 Answers1

25

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;
}
janw
  • 8,758
  • 11
  • 40
  • 62
Lalitya
  • 719
  • 8
  • 11