SelectPdf for .NET - Search for Text in PDF - C# / ASP.NET 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:


Sample Code C#



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SelectPdf.Samples
{
    public partial class search_pdf_text : System.Web.UI.Page
    {
        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            // the test file
            string filePdf = Server.MapPath("~/files/selectpdf.pdf");

            // settings
            bool caseSensitive = ChkCaseSensitive.Checked;
            bool wholeWordsOnly = ChkWholeWordsOnly.Checked;

            // 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(TxtSearchText.Text, 
                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
            doc.Save(Response, false, "Sample.pdf");

            // close pdf document
            doc.Close();

        }
    }
}