Find and Highlight Selected Text in PDF in C#/VB.NET

Sometimes, we may want to use Find feature to locate specific text, but there must be numerous results returned. In order to confirm the location more conveniently, we can highlight the selected text with background color while searching. In this article, we're delivering a solution on how to find and highlight selected text in PDF programmatically using C#, VB.NET.

Within Spire.PDF for .NET, developers can use page.FindText(string) method and foreach sentence to find specified text in entire PDF pages , save the search reasults in a PdfTextFind array, then highlight selected text by invoking find.ApplyHighLight() method. More details:

Step 1: Create a new PDF document and load the sample file.

PdfDocument pdf = new PdfDocument("youth.pdf");

Step 2: Find and highlight all "Youth" in PDF document.

            PdfTextFind[] result = null;
            foreach (PdfPageBase page in pdf.Pages)
            {
                result = page.FindText("Youth").Finds;
                foreach (PdfTextFind find in result)
                {
                    find.ApplyHighLight();
                }
            }

Step 3: Save and launch the file.

pdf.SaveToFile("result.pdf");
System.Diagnostics.Process.Start("result.pdf");

Result:

Find and Highlight Selected Text in PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.General.Find;

namespace FindAndHighlightText
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument("youth.pdf");
            PdfTextFind[] result = null;
            foreach (PdfPageBase page in pdf.Pages)
            {
                result = page.FindText("Youth").Finds;
                foreach (PdfTextFind find in result)
                {
                    find.ApplyHighLight();
                }
            }
            pdf.SaveToFile("result.pdf");
            System.Diagnostics.Process.Start("result.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.General.Find

Namespace FindAndHighlightText
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument("youth.pdf")
			Dim result As PdfTextFind() = Nothing
			For Each page As PdfPageBase In pdf.Pages
				result = page.FindText("Youth").Finds
				For Each find As PdfTextFind In result
					find.ApplyHighLight()
				Next
			Next
			pdf.SaveToFile("result.pdf")
			System.Diagnostics.Process.Start("result.pdf")
		End Sub
	End Class
End Namespace