Hey there,
In that case I would combine getTextByPageAndRect()
together with our search API documentViewer.textSearchInit. We can put our highlighting logic inside the onResult
callback .Here is the code that worked for me:
const { documentViewer, Annotations, Search } = instance.Core;
const getMouseLocation = e => {
const scrollElement = documentViewer.getScrollViewElement();
const scrollLeft = scrollElement.scrollLeft || 0;
const scrollTop = scrollElement.scrollTop || 0;
return {
x: e.pageX + scrollLeft,
y: e.pageY + scrollTop
};
};
const pageNumber = 1;
let quadCache = {};
documentViewer.setSearchHighlightColors({
searchResult: new Annotations.Color(0, 0, 255, 0.5),
});
documentViewer.addEventListener('mouseMove', e => {
const doc = documentViewer.getDocument();
const windowCoordinates = getMouseLocation(e);
const displayMode = documentViewer.getDisplayModeManager().getDisplayMode();
const pageCoordinates = displayMode.windowToPage(windowCoordinates, pageNumber);
// No need to run the search logic again if the cursor is still within the previous quads
if (
pageCoordinates.x > quadCache.x1 &&
pageCoordinates.y < quadCache.y1 &&
pageCoordinates.x < quadCache.x2 &&
pageCoordinates.y > quadCache.y4) {
return;
}
doc.getTextByPageAndRect(pageNumber,instance.Core.Math.Rect.createFromDimensions(pageCoordinates.x,pageCoordinates.y,2,2)).then(searchText => {
if (!searchText) {
return;
}
const mode = Search.Mode.CASE_SENSITIVE | Search.Mode.HIGHLIGHT | Search.Mode.PAGE_STOP;
const searchOptions = {
startPage: pageNumber,
endPage: pageNumber,
fullSearch: true,
onResult: result => {
if (result.resultCode === Search.ResultCode.FOUND) {
const textQuad = result.quads[0].getPoints();
// there could be several matching results, and we need the one that contains our cursor position
if (
pageCoordinates.x > textQuad.x1 &&
pageCoordinates.y < textQuad.y1 &&
pageCoordinates.x < textQuad.x2 &&
pageCoordinates.y > textQuad.y4) {
quadCache = textQuad;
documentViewer.displayAdditionalSearchResult(result)
// if you need to keep the highlights on the page after moving cursor to other words
// you will need to create highlight annotation here
// instead of calling documentViewer.displayAdditionalSearchResult();
}
}
}
}
documentViewer.textSearchInit(searchText, mode, searchOptions);
})
})