highlight in pdf code example
Example: pdf highlighter
function getSelectionCoords() {
var pdfViewer = window.appPdfViewer;
var pageIndex = pdfViewer.currentPageNumber - 1;
var page = pdfViewer.getPageView(pageIndex);
var pageRect = page.canvas.getClientRects()[0];
var selectionRects = window.getSelection().getRangeAt(0).getClientRects();
var viewport = page.viewport;
var selectionRectsList = Object.values(selectionRects);
var selected = selectionRectsList.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() {
var selected = getSelectionCoords();
var pageIndex = selected.page;
var pdfViewer = window.appPdfViewer;
var page = pdfViewer.getPageView(pageIndex);
var pageElement = page.canvas.parentElement;
var viewport = page.viewport;
selected.coords.forEach(function (rect) {
// Individual Seletions...
var x1 = Math.min(bounds[0], bounds[2]);
var y1 = Math.min(bounds[1], bounds[3]);
var width = Math.abs(bounds[0] - bounds[2]);
var hight = Math.abs(bounds[1] - bounds[3]);
var el = createRectDiv([x1, y1, width, hight]);
pageElement.appendChild(el);
});
}
function createRectDiv(boundBox){
var randomColor = Math.floor(Math.random()*16777215).toString(16);
console.log(randomColor);
var el = document.createElement('div');
el.setAttribute('class', 'hiDiv')
el.setAttribute('style', 'position: absolute; background-color: #'+randomColor+'; opacity: 0.5;' +
'left:' + boundBox[0] + 'px; top:' + boundBox[1] + 'px;' +
'width:' + boundBox[2] + 'px; height:' + boundBox[3] + 'px;');
return el;
}
window.addEventListener('mouseup', function() {
var length = window.getSelection().toString().length;
if(length > 0){
showHighlight();
}else{
// Clear All ?!
}
console.log();
});