From 2aa9292d1b125ea0692c97f4d608aaf243dd8c75 Mon Sep 17 00:00:00 2001 From: trbKnl Date: Tue, 20 Feb 2024 10:47:33 +0100 Subject: [PATCH] links clickable in pdfs from pdf.js --- core/assets/js/pdf_viewer.js | 39 +++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/core/assets/js/pdf_viewer.js b/core/assets/js/pdf_viewer.js index 5d398910a..85d5f5164 100644 --- a/core/assets/js/pdf_viewer.js +++ b/core/assets/js/pdf_viewer.js @@ -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); @@ -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");