Find Text Using Code

This example shows how to programmatically find and highlight all occurrences of a text in a PDF.

window.onload = function () { //DsPdfViewer.LicenseKey = "***key***"; var viewer = new DsPdfViewer('#viewer', { restoreViewStateOnLoad: false }); viewer.addDefaultPanels(); var pdf = "/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/wetlands.pdf"; loadPdf(viewer, pdf, "wetlands") } // Open the specified PDF and find/highlight all occurrences of the search text: async function loadPdf(viewer, pdf, searchText) { var afterOpenPromise = new Promise((resolve) => { viewer.onAfterOpen.register(() => { resolve(); }); }); await viewer.open(pdf); await afterOpenPromise; // Adjust search options as needed: var findOptions = { Text: searchText, MatchCase: true, WholeWord: true, StartsWith: false, EndsWith: false, Wildcards: false, Proximity: false, SearchBackward: false, HighlightAll: true }; var searchIterator = await viewer.searcher.search(findOptions); var searchResult = await searchIterator.next(); viewer.searcher.cancel(); viewer.searcher.highlight(searchResult.value); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>View PDF</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./src/styles.css"> <script src="/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.js"></script> <script src="/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/wasmSupportApi.js"></script> <script src="/document-solutions/javascript-pdf-viewer/demos/resource/js/init.js"></script> <script src="./src/app.js"></script> </head> <body> <div id="viewer"></div> </body> </html>
#viewer { height: 100%; }