Search code examples
c#pdfitext

Search particular word in PDF using iTextSharp


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();
}

Solution

  • 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;
    }