Text Search

This guide explains how to search a PDF for text, how to handle the results, and how the search can be controlled with various options.

First, create a TextSearcher object and register a result handler:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
private TextSearcher TextSearcher { get; set; }

public void MyPageConstructor()
{
    TextSearcher = new TextSearcher();

    pdfView.InitializationCompletedHandler += delegate
    {
        // We register the search result handler as soon as the PdfView is initialized.
        TextSearcher.SearchResultHandler += APIOnSearchResultHandler;
    };
}

The search result handler will be called on a non-UI thread, which allows you to do any long-running processing if needed. However, take care to dispatch any UI updates on the UI thread as demonstrated in this code, which was taken from the Catalog example provided with the SDK:

Copy
1
2
3
4
5
6
7
8
private async void APIOnSearchResultHandler(TextSearcher sender, IPageResults pageResults)
{
    // Dispatch on the UI thread. Otherwise, updating the `SearchResults` list will throw an exception.
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        foreach (var result in pageResults.Results) SearchResults.Add(new SearchResultFormatter(result));
    });
}

To initiate a search inside a document, create an instance of Query, passing in a search term via its constructor:

1
var searchQuery = new Query("pspdfkit");

Using the TextSearcher object, call the static method SearchDocument:

1
TextSearcher.SearchDocument(pdfView.Document, searchQuery);

The search result handler will be called once for each page searched. If no results are found, an empty results list will be passed to the handler.

Configuration

The Query object offers several properties to configure the search.

Property Description
CompareOptions Sets various compare options.
GenerateTextPreviews Set to generate a text preview. Default is true.
SearchAnnotations Set to search the content of annotations.
MaximumSearchResults Specifies the maximum search results returned.
SearchAllPages Set to specify whether all pages should be searched.
ReturnEmptyResults Set to true to return an empty result set for pages with no matches.
PriorityPages Search the pages in this list of IRanges first. Each IRange specifies a starting page index and a length.
PreviewRange Sets the range of the preview that should be generated.