How to highlight different searched texts with different colors in WPF

Nowadays, many files are saved as PDF format. PDF has many advantages and its Find and Highlight feature makes it easier for us to find important information inside a lengthy PDF document.

In the following sections, I will demonstrate how to highlight different searched texts with different colors in WPF.

The code snippets are as followed:

Step 1: Initialize a new instance of PdfDocument class and load the PDF document from the file.

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

Step 2: Call FindText() method to search the string "thy" in the first page of the file, then return to Result1. Traverse result1 and call ApplyHighLight() method to highlight all elements in result1. Set the highlight color as yellow.

PdfTextFind[] result1 = null;
result1 = pdf.Pages[0].FindText("thy").Finds;
foreach (PdfTextFind find in result1)
{
    find.ApplyHighLight(System.Drawing.Color.Yellow);
}

Step 3: Repeat step 2 to highlight all the texts "to" on Page 1 with the color of DeepSkyBlue.

PdfTextFind[] result2 = null;
result2 = pdf.Pages[0].FindText("to").Finds;
foreach (PdfTextFind find in result2)
{
    find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue);
}

Step 4: Save the PDF document and launch the file.

pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF);
System.Diagnostics.Process.Start("HighlightedToHelen.pdf");

Effective screenshot:

How to highlight different searched texts with different colors in WPF

Full Codes:

[C#]
//load the PDF document from the file
PdfDocument pdf = new PdfDocument("ToHelen.pdf");

//highlight searched text "thy" with Yellow
PdfTextFind[] result1 = null;
result1 = pdf.Pages[0].FindText("thy").Finds;
foreach (PdfTextFind find in result1)
{
    find.ApplyHighLight(System.Drawing.Color.Yellow);
}

//highlight searched text “to” with DeepSkyBlue
PdfTextFind[] result2 = null;
result2 = pdf.Pages[0].FindText("to").Finds;
foreach (PdfTextFind find in result2)
{
    find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue);
}

//save and launch the file
pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF);
System.Diagnostics.Process.Start("HighlightedToHelen.pdf");
[VB.NET]
'load the PDF document from the file
Dim pdf As New PdfDocument("ToHelen.pdf")

'highlight searched text "thy" with Yellow
Dim result1 As PdfTextFind() = Nothing
result1 = pdf.Pages(0).FindText("thy").Finds
For Each find As PdfTextFind In result1
	 find.ApplyHighLight(System.Drawing.Color.Yellow)
Next

'highlight searched text "to" with DeepSkyBlue
Dim result2 As PdfTextFind() = Nothing
result2 = pdf.Pages(0).FindText("to").Finds
For Each find As PdfTextFind In result2
	 find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue)
Next

'save and launch the file
pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF)
System.Diagnostics.Process.Start("HighlightedToHelen.pdf")