Skip to content

Instantly share code, notes, and snippets.

@yurydelendik
Last active October 1, 2024 08:02
Show Gist options
  • Save yurydelendik/f2b846dae7cb29c86d23 to your computer and use it in GitHub Desktop.
Save yurydelendik/f2b846dae7cb29c86d23 to your computer and use it in GitHub Desktop.
PDF.js get/show hightlight
function getHightlightCoords() {
var pageIndex = PDFViewerApplication.pdfViewer.currentPageNumber - 1;
var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
var pageRect = page.canvas.getClientRects()[0];
var selectionRects = window.getSelection().getRangeAt(0).getClientRects();
var viewport = page.viewport;
var selected = selectionRects.map(function (r) {
return viewport.convertToPdfPoint(r.left - pageRect.x, r.top - pageRect.y).concat(
viewport.convertToPdfPoint(r.right - pageRect.x, r.bottom - pageRect.y));
});
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;
selected.coords.forEach(function (rect) {
var bounds = viewport.convertToViewportRectangle(rect);
var el = document.createElement('div');
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);
});
}
@dieggop
Copy link

dieggop commented Apr 26, 2024

Is possible to get only position of click on document? in points?

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