Search Documents for a Phrase - C# .NET 6

This tutorial shows how to search documents for a phrase in a C# .NET 6 application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to search for a phrase in a C# .NET 6 application.
Completion Time 10 minutes
Visual Studio Project Download tutorial project (1 KB)
Platform C# .NET 6 Console Application
IDE Visual Studio 2022
Runtime Target .NET 6 or Higher
Development License Download LEADTOOLS
Try it in another language
  • C#: .NET 6+ (Console)

  • Python: Python

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Search Documents for a Phrase - C# .NET 6 tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project.

This tutorial requires the following NuGet packages:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Add the Search for a Phrase Code

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Program.cs. Add the following statements to the using block at the top of Program.cs.

C#
using System.Text.RegularExpressions; 
 
using Leadtools; 
using Leadtools.Ocr; 
using Leadtools.Document; 

Add the following global variables to the Program class.

C#
static LEADDocument _document; 
static IOcrEngine _ocrEngine; 

In the Main() method add the following code:

C#
static void Main(string[] args) 
{ 
    try 
    { 
        var searchString = "LEAD Technologies"; //Phrase to Search For 
        var file = @"C:\LEADTOOLS22\LICENSE.pdf"; //@"File to Scan"; 
        InitLEAD(); 
 
        using var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD); 
        ocrEngine.Startup(null, null, null, null); 
 
        using var document = DocumentFactory.LoadFromFile(file, new LoadDocumentOptions { UseCache = true }); 
        FindPhrase(searchString, document, ocrEngine); 
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.Message); 
    } 
} 

Note

You can modify the variables _phrase and _fileLocation to use different files or phrases with this application.

Add a new function to the Program class named FindPhrase. This method will be called inside the Main method, as shown above. Add the code below to find the number of times the given phrase is in the document.

C#
static void FindPhrase(string searchString, LEADDocument document, IOcrEngine ocrEngine) 
{ 
    document.Text.OcrEngine = ocrEngine; 
 
    foreach (var page in document.Pages) 
    { 
        var text = page.GetText(); 
        text.BuildTextWithMap(); 
        text.BuildWords(); 
 
        var regex = new Regex($@"\b({searchString})\b", RegexOptions.IgnoreCase | RegexOptions.Multiline); 
        var matches = regex.Matches(text.Text); 
 
        foreach (Match match in matches) 
        { 
            var firstCapture = match.Captures[0]; 
            var words = new List<DocumentWord>(); 
 
            var firstCharIndex = firstCapture.Index; 
            var length = firstCapture.Length; 
 
            for (int index = firstCharIndex; index <= firstCharIndex + length; index++) 
            { 
                var charIndex = text.TextMap[index]; 
                if (charIndex > 0) //ensure it's not a special character 
                { 
                    var character = text.Characters[charIndex]; 
 
                    if (character.IsEndOfWord) 
                    { 
                        DocumentWord? word = text.Words.FirstOrDefault(w => w.LastCharacterIndex == charIndex); 
                        if (word != null) 
                            words.Add(word.Value); 
                    } 
                } 
            } 
 
            //combine the word bounds to get the phrase bounds 
            var phraseRect = words.Select(w => w.Bounds).First(); 
            for (int i = 1; i < words.Count; i++) 
                phraseRect.Union(words[i].Bounds); 
 
            var pixelBounds = document.RectToPixels(phraseRect); 
            Console.WriteLine($"{searchString} found on page {page.PageNumber} at {pixelBounds}"); 
        } 
    } 
} 

Note

The above code snippet will print to the console for every matched phrase detected in the LEADDocument. It returns the page number of the page and the location on the page where the phrase can be found. The location returned is in terms of pixels on the page. If you want the coordinates to be compatible to altering a document in a viewer, you must use the RectToContainerCoordinates method.

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the console appears and the application will search the chosen document for the chosen phrase.

Phrase Search Console Output

Wrap-up

This tutorial showed how to use the LEADTOOLS SDK to load a file, search for a phrase, and return the location of every instance of the phrase.

See Also

Help Version 22.0.2024.3.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.