Skip to content

Text Search and Selection

In the Flutter SDK, ComPDF provides the CPDFTextSearcher API to search for specific text in PDF documents, highlight results, and retrieve contextual text snippets.

Get a CPDFTextSearcher Instance

To perform a search, obtain a CPDFTextSearcher object from the CPDFDocument:

dart
late CPDFReaderWidgetController _controller;

Scaffold(
  resizeToAvoidBottomInset: false,
  body: CPDFReaderWidget(
    document: widget.documentPath,
    configuration: CPDFConfiguration(),
    onCreated: (controller) {
      setState(() {
        _controller = controller;
      });
    },
  ));


CPDFTextSearcher? textSearcher = _controller?.document.getTextSearcher();

Use the searchText method to search for keywords in the PDF document. You can specify search options such as case sensitivity or whole-word matching.

dart
// Search for keywords in the PDF document
List<CPDFTextRange> results = await searcher.searchText(
  'keywords',
  searchOptions: CPDFSearchOptions.caseInsensitive, // Search option
);

The search results are returned as a list of CPDFTextRange objects, each representing the position of the keyword in the document.

Explanation of Search Settings

Enum ValueDescription
CPDFSearchOptions.caseInsensitiveCase-insensitive search (default)
CPDFSearchOptions.caseSensitiveCase sensitive search
CPDFSearchOptions.matchWholeWordMatches a whole word only

Select a Search Result

You can highlight a specific result in the document using the selection method:

dart
// Select the first search result
if (results.isNotEmpty) {
  CPDFTextRange range = results[0];
  await searcher.selection(range);
}

Clear Search Results

To reset the search state and clear results:

dart
await searcher.clearSearch();

Retrieve Contextual Text

With CPDFPage.getText, you can extract a snippet of text for a given range and optionally expand the range to include surrounding context.

dart
// Assume we already have a search result
CPDFTextRange range = results[0];

// Expand the range to include 20 characters before and after
final expandedRange = range.expanded(before: 20, after: 20);

// Retrieve contextual text from the corresponding page
final contextText = await page.getText(expandedRange);
print("Text with context: $contextText");