Text Search and Selection
In the ReactNative 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
:
const pdfReaderRef = useRef<CPDFReaderView>(null);
<CPDFReaderView
ref={pdfReaderRef}
document={samplePDF}
/>
const document = pdfReaderRef.current?._pdfDocument;
const textSearcher = document!.textSearcher;
Text Search
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.
// 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 Value | Description |
---|---|
CPDFSearchOptions.CaseInsensitive | Case-insensitive search (default) |
CPDFSearchOptions.CaseSensitive | Case sensitive search |
CPDFSearchOptions.MatchWholeWord | Matches a whole word only |
Select a Search Result
You can highlight a specific result in the document using the selection
method:
// 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:
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.
// 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");