Skip to content

Commit

Permalink
links clickable in pdfs from pdf.js
Browse files Browse the repository at this point in the history
  • Loading branch information
trbKnl committed Feb 20, 2024
1 parent ef3566d commit f731222
Showing 1 changed file with 47 additions and 11 deletions.
58 changes: 47 additions & 11 deletions core/assets/js/pdf_viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,55 @@ export const PDFViewer = {
renderPage(width, pageNum) {
console.log("[PDFViewer] Render page", pageNum);
this.pdf.getPage(pageNum).then(
(page) => {
var canvas = this.createCanvas();
async (page) => {
var scale = window.devicePixelRatio;
var viewport = page.getViewport({ scale: scale });
if (width < viewport.width) {
scale = (width / viewport.width) * scale;
}

//This gives us the page's dimensions at full scale
viewport = page.getViewport({ scale: scale });

//We'll create a canvas for each page to draw it on
const canvas = this.createCanvas(viewport);
const context = canvas.getContext("2d");
page.render({ canvasContext: context, viewport: viewport });

const pdfWidth = page.getViewport({ scale: 1 }).width;
const viewport = page.getViewport({ scale: width / pdfWidth });
// Make annotations clickable
const annotations = await page.getAnnotations()

console.log("[PDFViewer] width", width);
console.log("[PDFViewer] pdfWidth", pdfWidth);
console.log("[PDFViewer] viewport.width", viewport.width);
function translateEventCoordinatesToPdfViewport(canvas, x ,y) {
const rect = canvas.getBoundingClientRect();
const newx = (x - rect.left) / scale;
const newy = (-1 * (y - rect.bottom)) / scale;
return {x: newx, y: newy}
}

canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.addEventListener("click", (event) => {
const {x, y} = translateEventCoordinatesToPdfViewport(canvas, event.clientX, event.clientY)
for (let annotation of annotations) {
const rect = annotation.rect
if (x > rect[0] && x < rect[2] && y > rect[1] && y < rect[3]) {
if (annotation.url) {
window.open(annotation.url, "_blank");
}
}
}
});

page.render({ canvasContext: context, viewport: viewport });
canvas.addEventListener("mousemove", (event) => {
const {x, y} = translateEventCoordinatesToPdfViewport(canvas, event.clientX, event.clientY)
for (let annotation of annotations) {
const rect = annotation.rect
if (x > rect[0] && x < rect[2] && y > rect[1] && y < rect[3]) {
canvas.style.cursor = "pointer"
break
} else {
canvas.style.cursor = "default"
}
}
})

this.renderPage(width, pageNum + 1);
},
Expand All @@ -79,9 +113,11 @@ export const PDFViewer = {
this.container.style.display = "block";
this.el.appendChild(this.container);
},
createCanvas() {
createCanvas(viewport) {
var canvas = document.createElement("canvas");
canvas.style.display = "block";
canvas.height = viewport.height;
canvas.width = viewport.width;
this.container.appendChild(canvas);
return canvas;
},
Expand Down

0 comments on commit f731222

Please sign in to comment.