You can build a custom search interface by using the useSearch hook to access search results and the search function. To implement a complete search experience, follow these steps:
- Wrap your application in the
<Root> component and provide a PDF source. - Use the
<Search> component as a provider for your search UI. - Access search state via
useSearch(), which provides searchResults (containing exactMatches and fuzzyMatches) and the search method. - Handle results by mapping over
results.exactMatches and using calculateHighlightRects combined with usePdfJump to navigate to the found text. - Implement pagination by checking
results.hasMoreResults and calling search with an increased limit.
Note: It is recommended to use debouncing on your search input to prevent excessive search calls.
import {
Root,
Pages,
Page,
CanvasLayer,
TextLayer,
HighlightLayer,
Search,
calculateHighlightRects,
usePdf,
usePdfJump,
useSearch,
} from "@anaralabs/lector";
// ... inside your component
const { searchResults: results, search } = useSearch();
// To search with a limit:
await search(debouncedSearchText, { limit: 5 });
// To jump to a result:
const { jumpToHighlightRects } = usePdfJump();
const pageProxy = getPdfPageProxy(result.pageNumber);
const rects = await calculateHighlightRects(pageProxy, {
pageNumber: result.pageNumber,
text: result.text,
matchIndex: result.matchIndex,
searchText: originalSearchText,
});
jumpToHighlightRects(rects, "pixels");