Table of Contents
Installed via NuGet
PM> Install-Package Spire.PDF
Related Links
Searching for a specific text in a PDF document can sometimes be annoying, especially when the document contains hundreds of pages. Highlighting the text with a background color can help you find and locate it quickly. In this article, you will learn how to find and highlight specific text in PDF in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Find and Highlight Specific Text in PDF in C# and VB.NET
The following are the steps to find and highlight a specific text in a PDF document:
- Create a PdfDocument instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Create a PdfTextFindOptions instance.
- Specify the text finding parameter through PdfTextFindOptions.Parameter property.
- Loop through the pages in the PDF document.
- Within the loop, create a PdfTextFinder instance and set the text finding option through PdfTextFinder.Options property.
- Find a specific text in the document using PdfTextFinder.Find() method and save the results into a PdfTextFragment list.
- Loop through the list and call PdfTextFragment.Highlight() method to highlight all occurrences of the specific text with color.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Texts; using System.Collections.Generic; using System.Drawing; namespace HighlightTextInPdf { internal class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF file pdf.LoadFromFile("Sample.pdf"); //Creare a PdfTextFindOptions instance PdfTextFindOptions findOptions = new PdfTextFindOptions(); //Specify the text finding parameter findOptions.Parameter = TextFindParameter.WholeWord; //Loop through the pages in the PDF file foreach (PdfPageBase page in pdf.Pages) { //Create a PdfTextFinder instance PdfTextFinder finder = new PdfTextFinder(page); //Set the text finding option finder.Options = findOptions; //Find a specific text List<PdfTextFragment> results = finder.Find("Video"); //Highlight all occurrences of the specific text foreach (PdfTextFragment text in results) { text.HighLight(Color.Green); } } //Save the result file pdf.SaveToFile("HighlightText.pdf"); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.