SelectPdf for .NET - Search for Text in PDF - C# / ASP.NET MVC Sample

This sample shows how to use SelectPdf PDF Library for .NET to search for text in a PDF document.
A new PDF will be created highlighting the text that has been found.

The sample uses the following (existing) test PDF:
Test PDF document

Text to Search:


Search Settings:
Case Sensitive
Whole Words Only


Sample Code C#



using System.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class SearchPdfTextController : Controller
    {
        // GET: SearchPdfText
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // the test file
            string filePdf = Server.MapPath("~/files/selectpdf.pdf");

            // settings
            bool caseSensitive = collection["ChkCaseSensitive"] == "on";
            bool wholeWordsOnly = collection["ChkWholeWordsOnly"] == "on";

            // instantiate a pdf to text converter object
            PdfToText pdfToText = new PdfToText();

            // load PDF file
            pdfToText.Load(filePdf);

            // search for text and retrieve all found text positions
            TextPosition[] positions = pdfToText.Search(collection["TxtSearchText"],
                caseSensitive, wholeWordsOnly);

            // open the existing PDF document in editing mode
            PdfDocument doc = new PdfDocument(filePdf);

            // highlight the found text in the existing PDF document
            for (int i = 0; i < positions.Length; i++)
            {
                TextPosition position = (TextPosition)positions[i];

                PdfPage page = doc.Pages[position.PageNumber - 1];

                PdfRectangleElement rect = new PdfRectangleElement(
                    position.X, position.Y, position.Width, position.Height);
                rect.BackColor = new PdfColor(240, 240, 0);
                rect.Transparency = 30;
                page.Add(rect);
            }

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }
    }
}