This example shows how to find all instances of a string in a PDF and add text highlight markup annotations on each instance.
// Example: Highlight All Instances of a String in a PDF using Highlight Annotations
window.onload = function () {
const viewer = new DsPdfViewer("#viewer", {
workerSrc: "/document-solutions/javascript-pdf-viewer/demos/product-bundles/build/dspdfviewer.worker.js",
supportApi: getSupportApiSettings()
});
viewer.addDefaultPanels(); // Add default viewer panels
viewer.addAnnotationEditorPanel(); // Add annotation editor panel
viewer.addFormEditorPanel(); // Add form editor panel
var pdf = "/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/wetlands.pdf";
loadPdf(viewer, pdf, "wetlands"); // Load the PDF and search for the text "wetlands"
}
// Load the PDF, find occurrences of the search text, and add highlight annotations:
async function loadPdf(viewer, pdf, searchText) {
await viewer.open(pdf); // Open the PDF document
// Adjust search options as needed:
var findOptions = {
Text: searchText,
MatchCase: true, // Match case exactly
WholeWord: true, // Match whole words only
StartsWith: false, // Do not limit to words starting with the search text
EndsWith: false, // Do not limit to words ending with the search text
Wildcards: false, // Do not use wildcards in the search
Proximity: false, // Do not limit search based on word proximity
SearchBackward: false, // Search forward in the document
HighlightAll: false // Do not highlight all occurrences automatically
};
var searchIterator = await viewer.searcher.search(findOptions); // Start the search
var searchResult = await searchIterator.next(); // Get the first search result
var searchResults = [];
while (!searchResult.done) {
searchResults.push(searchResult); // Add the search result to the array
searchResult = await searchIterator.next(); // Get the next search result
}
// Add a highlight annotation for each search result:
createHighlights(viewer, searchResults);
}
// Create highlight annotations for search results:
async function createHighlights(viewer, searchResults) {
for (let i = 0; i < searchResults.length; i++) {
const searchResultValue = searchResults[i].value;
await viewer.addAnnotation(searchResultValue.PageIndex, {
annotationType: 9, // AnnotationTypeCode.HIGHLIGHT
subtype: "Highlight",
color: [255, 63, 127], // Highlight color (RGB)
rect: searchResultValue.coordinates.outerRect // Rectangle coordinates of the text
});
}
viewer.repaint(); // Repaint the viewer to display the annotations
}