When text is selected with the mouse, this demo shows a popup with the selection and draws a red rectangle around the selection (the current PDF is not changed).
window.onload = function () {
//DsPdfViewer.LicenseKey = "***key***";
// Note: this code uses jquery (see index.html),
// and additional styles (see styles.css).
var viewer = new DsPdfViewer('#viewer', { restoreViewStateOnLoad: false });
viewer.addDefaultPanels();
var pdf = "/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/wetlands.pdf";
viewer.open(pdf);
const hidePopupForTextSelection = () => {
// Hide popup:
$(".jquery-popup").remove();
// Hide highlighted-text-rectangle:
const textSelectionRect = document.querySelector(".highlighted-text-rectangle");
if (textSelectionRect) textSelectionRect.remove();
};
const showPopupForTextSelection = (selectedText, outerRect, lastPartRect) => {
// Show popup:
const [lp_x1, lp_y1, lp_x2, lp_y2] = lastPartRect;
const $div = $("<div>").addClass("jquery-popup")
.css({
left: `${lp_x2 + 4}px`,
top: `${lp_y1 + 4}px`,
width: '200px'
})
.html("Your popup content goes here. Selected text: <b>" + selectedText + "</b>")
.appendTo("body");
// Show highlighted-text-rectangle:
const [x1, y1, x2, y2] = outerRect;
const textSelectionRect = document.createElement('div');
textSelectionRect.className = "highlighted-text-rectangle";
textSelectionRect.style.cssText = `left: ${x1}px; top: ${y1}px; width: ${x2 - x1}px; height: ${y2 - y1}px;`;
document.body.appendChild(textSelectionRect);
}
const onPointerDown = () => {
hidePopupForTextSelection();
};
const onPointerUp = () => {
hidePopupForTextSelection();
const selectedText = viewer.getSelectedText();
const selectedTextCoordinates = viewer.getSelectedTextCoordinates();
if (selectedText && selectedTextCoordinates) {
// console.log(selectedText, selectedTextCoordinates);
const { pageIndex, outerRect, quadPoints } = selectedTextCoordinates;
const lastPartQuadPoints = quadPoints[quadPoints.length - 1];
const lastPartRect = [lastPartQuadPoints[0].x, lastPartQuadPoints[0].y, lastPartQuadPoints[3].x, lastPartQuadPoints[3].y];
showPopupForTextSelection(selectedText,
viewer.convertPdfRectToWindowCoordinates(pageIndex, outerRect),
viewer.convertPdfRectToWindowCoordinates(pageIndex, lastPartRect));
}
};
viewer.scrollView.addEventListener("pointerdown", onPointerDown);
viewer.scrollView.addEventListener("pointerup", () => setTimeout(onPointerUp));
viewer.scrollView.addEventListener("scroll", onPointerUp);
window.addEventListener("resize", () => setTimeout(onPointerUp));
}