New to Telerik UI for .NET MAUI? Start a free 30-day trial

.NET MAUI PDF Viewer Custom Search

You can extend the search functionality by implementing a custom TextSearchWorker. The TextSearchWorker object performs the actual search according to the search criteria.

The example below implements a custom search by multiple words-any word that is entered into the input is considered as a separate search text.

1. Create a custom class that derives from Telerik.Maui.Controls.PdfViewer.PdfViewerTextSearchWorker-you need to override the Search method that returns TextSearchResult object:

public class MultipleWordsSearchWorker : Telerik.Maui.Controls.PdfViewer.PdfViewerTextSearchWorker
{
    protected override PdfViewerTextSearchResult Search(PdfViewerSearchContext context)
    {
        string regex = GetMultiWordRegex(context.Text);
        TextSearchOptions regexOptions = new TextSearchOptions { UseRegularExpression = true };
        PdfViewerSearchContext newContext = new PdfViewerSearchContext(context.PdfViewer, context.Document, regex, regexOptions, context.SearchProgress, context.CancellationToken);

        return base.Search(newContext);
    }

    private static string GetMultiWordRegex(string text)
    {
        string[] words = text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < words.Length; i++)
        {
            if (i > 0)
            {
                sb.Append("|");
            }

            string expr = string.Format(@"({0})", words[i]);
            sb.Append(expr);
        }

        return sb.ToString();
    }
}

2. Apply the MultipleWordsSearchWorker object to the TextSearchWorker property of the SearchSettings of RadPdfViewer:

<telerik:RadPdfViewer x:Name="pdfViewer">
    <telerik:RadPdfViewer.SearchSettings>
        <telerik:PdfViewerSearchSettings MainSearchResultFill="#99FF7F7F"
                                            SearchResultsStringFormat="Result: {0}, Total: {2}"
                                            SearchResultsFill="#997FC9FF"
                                            TextSearchTrigger="TextChanged">
            <telerik:PdfViewerSearchSettings.TextSearchWorker>
                <local:MultipleWordsSearchWorker/>
            </telerik:PdfViewerSearchSettings.TextSearchWorker>
        </telerik:PdfViewerSearchSettings>
    </telerik:RadPdfViewer.SearchSettings>
</telerik:RadPdfViewer >

3. Set the Source to the PDF viewer:

Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
    Assembly assembly = typeof(SearchSettings).Assembly;
    string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n => n.Contains("pdf-processing.pdf"));
    Stream stream = assembly.GetManifestResourceStream(fileName);
    return stream;
});
this.pdfViewer.Source = streamFunc;

4. Add the telerik namespace:

xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"

See Also

In this article