You add search to your PDF viewer. You type a word from the first page and it highlights correctly. Everything looks done.
Then a user searches a scanned contract and gets zero results. Another searches for “office” and misses every match, because the document stores the “ffi” as a single ligature character.
PDF search looks simple but depends on how the text was stored.
Why PDF text is awkward
A PDF does not store a paragraph. It stores positioned fragments of text. A single line may be split into several pieces, words can break across fragments, and the order in the file may not match the reading order.
Detect pages with no text at all
A scanned PDF is often just images. There is no text to search, so extraction returns nothing. Check whether a page returns any text, and tell the user when it doesn’t. Searching these documents needs OCR, which is a separate step.Normalise before you compare
Search quality often fails on small text differences:
- Ligatures: "fi" (U+FB01) will not match “fi” until you normalise it.
- Unicode normalisation (NFKC) handles this.
- Accents: decide whether “resume” should match “résumé”.
- Case and whitespace: fold case and collapse repeated spaces.
- Hyphenation: a word broken across two lines may need joining.
Map matches back to positions
Join the page’s text fragments into one string and keep an index that links each character back to its fragment. Search the joined string, then use the index to find where to draw the highlight.Keep search from blocking the interface
Extracting text from a large document is real work.
Extract page by page and cache the results.
Debounce typing, and cancel the previous search when a new one starts.
Show progress for large files, and consider running the work in a web worker.
Align the highlight layer
Highlights must use the same scale, rotation and offset as the text layer, or they drift after zooming. Recalculate whenever the viewport changes.
Try it in a real project
If you don’t want to build all of this yourself, we’ve been working on TeamSync PDF Viewer, an open-source PDF viewer SDK for React with rendering, search and annotations. You can read the code and try it here:
https://github.com/angelbot-ai/TeamSync-PDF-Viewer
Question for you: what breaks first in your PDF search: scanned documents, special characters, or highlight alignment?
If the project is useful, a star on the repo helps, and reproducible issues are very welcome.
