Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lotharthesavior/0f9c33175caad0052d79 to your computer and use it in GitHub Desktop.
Save lotharthesavior/0f9c33175caad0052d79 to your computer and use it in GitHub Desktop.
Hightlight Selected Text in PDFJS
function HighlightSelectedText()
{
var pageIndex = window.PDFViewerApplication.pdfViewer.currentPageNumber - 1;
var page = window.PDFViewerApplication.pdfViewer.pages[pageIndex];
var pageElement = page.canvas.parentElement;
var pageRect = page.canvas.getClientRects()[0];
var selectionRects = window.getSelection().getRangeAt(0).getClientRects();
var viewport = page.viewport;
var i = 0;
var selected = $.map(selectionRects, function (r) {
var rect = viewport.convertToPdfPoint(r.left - pageRect.left, r.top - pageRect.top).concat(viewport.convertToPdfPoint(r.right - pageRect.left, r.bottom - pageRect.top));
var bounds = viewport.convertToViewportRectangle(rect);
if( i % 2 == 0 ){ // verify if not odd (must be pair)
var el = document.createElement('div');
el.setAttribute('style', 'position: absolute; background-color: rgba(255, 255, 51, 0.3);' +
'left:' + Math.min(bounds[0], bounds[2]) + 'px; top:' + Math.min(bounds[1], bounds[3]) + 'px;' +
'width:' + Math.abs(bounds[0] - bounds[2]) + 'px; height:' + Math.abs(bounds[1] - bounds[3]) + 'px;');
el.setAttribute('id','newElement'+i);
pageElement.appendChild(el);
}
i++;
});
}
@setienne24
Copy link

hi lotharthesavior, i m interested in show highlight function. It is possible to send me by mail "s.etienne.24@gmail.com" an example which open a pdf file and allow me to select some words in pdf. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment