Search text in PDFs using JavaScript
Nutrient Web SDK provides full-text search for PDFs. It counts the occurrences of a search term, enables navigation through the results, and highlights all matches directly in the document. It operates much like your browser’s search feature. But what if you need a customized PDF search using JavaScript to behave differently or meet specific requirements?

Customizing PDF search with JavaScript
Nutrient Web SDK enables developers to customize search behavior by hooking into search queries via the search.termChange event. This event triggers on every text change in the search field:
let lastSearchTerm = "";
instance.addEventListener("search.termChange", async (event) => { // Opt out from the default implementation. event.preventDefault();
const { term } = event; // Update the search term in the search box. Without this line, // the search box would stay empty. instance.setSearchState((state) => state.set("term", term)); lastSearchTerm = term;
// Perform a custom search for the term. const results = await customSearch(term, instance);
// Our results could return in a different order than expected. // Let's make sure only results matching our current term are applied. if (term !== lastSearchTerm) { return; }
// Finally, we apply the results. Note that you can also modify // the search state first and then pass the new state // to `instance.setSearchState`. const newState = instance.searchState.set("results", results); instance.setSearchState(newState);});For instance, to match only whole words in your PDF search results, use the customSearch function. This function uses Nutrient Web SDK’s instance.search API and takes instance as an argument. After the default search runs, the function filters the results to whole-word matches only:
async function customSearch(term, instance) { // We would get an error if we called `instance.search` with a term of // 2 characters or less. if (term.length <= 2) { return NutrientViewer.Immutable.List([]); }
// Let's take the results from the default search as the foundation. const results = await instance.search(term);
// We only want to find whole words that match the term we entered. const filteredResults = results.filter((result) => { const searchWord = new RegExp(`\\b${term}\\b`, "i"); return searchWord.test(result.previewText); });
return filteredResults;}Whitespace-tolerant search
If your PDFs contain extracted text with inconsistent whitespace, such as multiline phrases split across line wraps, columns, or tables, use NutrientViewer.SearchType.WORD_BASED with instance.search():
const results = await instance.search("Smith, John", { searchType: NutrientViewer.SearchType.WORD_BASED});This mode normalizes whitespace differences between the query and the extracted document text while preserving punctuation. Matches then succeed even when PDF text extraction inserts unexpected spaces or line breaks.
Default instance.search() behavior is unchanged. In standalone mode, SearchType.WORD_BASED works immediately. In server-backed mode, it requires Document Engine 1.16.x.
Highlighting custom search results
You can highlight custom search results using one of the following:
Highlighting custom PDF search results with highlight annotations
To enhance your customized PDF search experience, you can visually emphasize search results with highlight annotations. Follow the steps below:
- Use the
searchAPI to perform a search across the entire PDF or a specific page range. - Use the
createAPI to generate highlight annotations around the search results so users can locate key information.
The code below highlights the word hello on all the pages of a PDF document:
try { const results = await instance.search("hello");
const annotations = results.map((result) => { return new NutrientViewer.Annotations.HighlightAnnotation({ pageIndex: result.pageIndex, rects: result.rectsOnPage, boundingBox: NutrientViewer.Geometry.Rect.union(result.rectsOnPage) }); }); await instance.create(annotations); console.log(`Created ${annotations.size} highlight annotations`);} catch (error) { console.error("Failed to search and highlight:", error.message);}Highlighting custom PDF search results with custom overlay items
For a more dynamic approach to emphasizing PDF search results, you can use custom overlay items. Follow the steps below:
- Perform a search across the PDF or specific pages using the
searchAPI. - Surround the search results with custom overlay items to add a layer of interactivity and style to the document.
The code below highlights the word hello on all the pages of a PDF document:
instance .search("hello") .then((results) => { results.toJS().forEach((result, i) => { const div = document.createElement("div"); div.style.backgroundColor = "#808000"; div.style.mixBlendMode = "multiply"; div.style.opacity = 0.5; div.style.width = result.rectsOnPage[0].width + "px"; div.style.height = result.rectsOnPage[0].height + "px"; const item = new NutrientViewer.CustomOverlayItem({ id: "overlay" + i, node: div, pageIndex: result.pageIndex, position: new NutrientViewer.Geometry.Point({ x: result.rectsOnPage[0].left, y: result.rectsOnPage[0].top }) }); instance.setCustomOverlayItem(item); }); }) .catch(console.log);Implementing a custom PDF search functionality
You can implement your own search logic. Your customSearch function could range from a simple local implementation, like the one above, to a query sent to a large search data center. The key is to return the search results in the correct format for the searchState.
Provide your results as a NutrientViewer.Immutable.List of NutrientViewer.SearchResult so they integrate with Nutrient Web SDK’s customized PDF search capabilities.
Additional information
For more information, see our detailed API documentation pages:
NutrientViewer.SearchTermChangeEventNutrientViewer.SearchStateNutrientViewer.Instance.setSearchStateNutrientViewer.SearchResultNutrientViewer.SearchType