Search Particular Word in PDF using Itextsharp

家住魔仙堡 提交于 2019-11-30 11:53:07

问题


This is my first post in 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.

Else it should return 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


回答1:


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


来源:https://stackoverflow.com/questions/17485548/search-particular-word-in-pdf-using-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!