react-native-pdf-text-search
v0.2.1
Published
Full-text search inside PDFs for React Native, returning normalized match rectangles you can draw as highlights. Native on iOS (PDFKit) and Android (PdfBox-Android).
Maintainers
Readme
react-native-pdf-text-search
Full-text search inside PDF files for React Native. Returns, for every match, the page, the matched text, and normalized rectangles you can draw as highlights.
| Platform | Engine | |----------|--------| | iOS | PDFKit | | Android | PdfBox-Android |
Status
Extracted from a production React Native app, where these modules have been shipping since 2024. The API is new, so it may still change before 1.0.
Install
npm install react-native-pdf-text-search
cd ios && pod installContains native code, so it needs a custom dev client — it does not run in Expo Go.
Usage
import { searchPDF } from 'react-native-pdf-text-search';
const { matches } = await searchPDF('/path/to/file.pdf', 'sustainability');
// matches[0] =
// {
// page: 3,
// text: 'sustainability',
// rects: [{ x: 0.12, y: 0.34, width: 0.21, height: 0.02 }]
// }Options
await searchPDF(path, 'term', {
caseSensitive: false, // default false
wholeWord: false, // default false
startPage: 1, // 1-based, inclusive
endPage: 10, // 1-based, inclusive
});Drawing the highlights
rects are normalized 0..1 against the page, origin top-left, one rect per line a
match spans. Multiply by the size of the rendered page:
<View style={{ width, height }}>
<Pdf source={{ uri }} style={{ flex: 1 }} page={page} />
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
{matches
.filter((m) => m.page === page)
.flatMap((m, i) =>
m.rects.map((r, j) => (
<View
key={`${i}-${j}`}
style={{
position: 'absolute',
left: r.x * width,
top: r.y * height,
width: r.width * width,
height: r.height * height,
backgroundColor: 'rgba(255,235,59,0.4)',
}}
/>
)),
)}
</View>
</View>Because the values are relative, they stay correct at any zoom level or screen size.
Errors
The promise rejects with:
| Code | Meaning |
|------|---------|
| E_FILE_NOT_FOUND | no file at the given path |
| E_OPEN_FAILED | the file is not a readable PDF |
| E_SEARCH_FAILED | any other native failure |
Limitations
- Only PDFs with a text layer. Scanned documents without OCR return no matches.
- Matches that wrap across lines yield several rects; there is no single bounding box.
wholeWorduses alphanumeric boundaries, which suits Latin scripts best.- Large documents are searched page by page on a background thread; a very large PDF still takes a few seconds.
heightdiffers slightly between platforms: iOS reports the selection line height (PDFKit includes leading), Android the glyph height — roughly half.x,yandwidthagree to four decimals. Pad the rect vertically if you need identical visuals.
License
MIT
