Yes, you can highlight words while working with PDF.js
How the page contains
- canvas (for displayed content)
- HTMLDivElement (for text without text)
you can use the latter to select text elements.
Having access to the selection API in your browser, you can get a selection through document.getSelection()
.
The following code demonstrates how to do this if the selected text does not (inside) cover several HTMLElements:
var s = document.getSelection(); var oldstr = s.anchorNode.textContent; var textBeforeSelection = oldstr.substr(0, s.anchorOffset); var textInsideSelection = oldstr.substr(s.anchorOffset, s.focusOffset - s.anchorOffset); var textAfterSelection = oldstr.substr(s.focusOffset, oldstr.length - s.focusOffset); foo.anchorNode.parentElement.innerHTML = textBeforeSelection + "<span class='highlight'>" + textInsideSelection + "</span>" + textAfterSelection;
For a selection that spans multiple (internal) HTML elements, you can go through the DOM starting at s.anchorNode
, sequentially calling nextSibling
, until you reach the value of s.focusNode
.
I can say that elements can be placed in a document in a different order than the one that they have on the view.
Assuming s.anchorNode
not s.focusNode
,
s.anchorNode
will be allocated from 0 to s.anchorOffset
s.focusNode
from s.focusOffset
to the end of the node and- all nodes between them can be fully selected
This works (or at least it can work) for text nodes - the idea can be extended to non-text nodes, surrounding each non-text node with selection.
source share