Skip to content

Instantly share code, notes, and snippets.

@clayadavis
Forked from yurydelendik/gist:f2b846dae7cb29c86d23
Last active January 22, 2016 17:15
Show Gist options
  • Save clayadavis/8a2b025b24fdd4b6016d to your computer and use it in GitHub Desktop.
Save clayadavis/8a2b025b24fdd4b6016d to your computer and use it in GitHub Desktop.
PDF.js get/show hightlight (for Chromium)
function getHightlightCoords() {
var pageIndex = PDFViewerApplication.pdfViewer.currentPageNumber - 1;
var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
var pageRect = page.canvas.getClientRects()[0];
var selectionRects = Array.apply(this, window.getSelection().getRangeAt(0).getClientRects());
var viewport = page.viewport;
var selected = selectionRects.map(function (r) {
return viewport.convertToPdfPoint(r.left - pageRect.left, r.top - pageRect.top).concat(
viewport.convertToPdfPoint(r.right - pageRect.left, r.bottom - pageRect.top));
});
return {page: pageIndex, coords: selected};
}
function showHighlight(selected) {
var pageIndex = selected.page;
var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
var pageElement = page.canvas.parentElement;
var viewport = page.viewport;
var nodes = [];
selected.coords.forEach(function (rect) {
var bounds = viewport.convertToViewportRectangle(rect);
var el = document.createElement('div');
// if (height > 0 && width > 0)
el.setAttribute('style', 'position: absolute; background-color: pink;' +
'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;');
pageElement.appendChild(el);
nodes.push(el);
});
return nodes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment