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 2aa9292
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion core/assets/js/pdf_viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,13 @@ export const PDFViewer = {
renderPage(width, pageNum) {
console.log("[PDFViewer] Render page", pageNum);
this.pdf.getPage(pageNum).then(
(page) => {
async (page) => {
var canvas = this.createCanvas();
const context = canvas.getContext("2d");

const pdfWidth = page.getViewport({ scale: 1 }).width;
const viewport = page.getViewport({ scale: width / pdfWidth });
const scale = viewport.width / pdfWidth

console.log("[PDFViewer] width", width);
console.log("[PDFViewer] pdfWidth", pdfWidth);
Expand All @@ -61,9 +62,45 @@ export const PDFViewer = {
canvas.width = viewport.width;
canvas.height = viewport.height;

const annotations = await page.getAnnotations()

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.addEventListener("click", (event) => {
const {x, y} = translateEventCoordinatesToPdfViewport(canvas, event.clientX, event.clientY)
console.log(`${x} ${y}`)
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");
}
}
}
});

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"
}
}
})

page.render({ canvasContext: context, viewport: viewport });

this.renderPage(width, pageNum + 1);

},
() => {
console.log("[PDFViewer] end of document");
Expand Down

0 comments on commit 2aa9292

Please sign in to comment.