Skip to content
DemoAPI ReferenceFAQ

PDF Generation Template Editor

Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.

View on GitHub
React Native Guides Text search text selection

Text Search and Selection ​

In the React Native 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:

tsx
const pdfReaderRef = useRef<CPDFReaderView>(null);

<CPDFReaderView
  ref={pdfReaderRef}
	document={samplePDF}
/>

const document = pdfReaderRef.current?._pdfDocument;
const textSearcher = document!.textSearcher;

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.

tsx
// Search for keywords in the PDF document
const results = await textSearcher!.searchText('keywords', CPDFSearchOptions.CaseInsensitive);

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:

tsx
// Select the first search result
if (results.length > 0) {
  await textSearcher.selection(results[0]);
}

Clear Search Results ​

To reset the search state and clear results:

dart
await textSearcher.clearSearch();

Retrieve Contextual Text ​

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

tsx
// Assume we already have a search result
const range = results[0];

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

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