feat: PDF annotations for documents (#40) #54

Merged
marcel merged 10 commits from feat/40-pdf-annotations into main 2026-03-24 10:00:28 +01:00
Showing only changes of commit 1ad8fffd1b - Show all commits

View File

@@ -1,9 +1,6 @@
<script lang="ts">
import { getDocument, GlobalWorkerOptions, TextLayer } from 'pdfjs-dist';
import { onMount } from 'svelte';
import type { PDFDocumentProxy, PDFPageProxy, RenderTask } from 'pdfjs-dist';
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
GlobalWorkerOptions.workerSrc = workerUrl;
let { url }: { url: string } = $props();
@@ -22,7 +19,24 @@ let textLayerEl = $state<HTMLDivElement | null>(null);
let renderTask: RenderTask | null = null;
let textLayerInstance: { cancel: () => void } | null = null;
// Holds the dynamically-loaded pdfjs module (browser-only)
// Not $state — we use pdfjsReady as the reactive trigger instead
let pdfjsLib: typeof import('pdfjs-dist') | null = null;
let pdfjsReady = $state(false);
onMount(async () => {
// Dynamic import keeps pdfjs out of the SSR bundle entirely
const [lib, { default: workerUrl }] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url')
]);
lib.GlobalWorkerOptions.workerSrc = workerUrl;
pdfjsLib = lib;
pdfjsReady = true;
});
async function loadDocument(src: string) {
if (!pdfjsLib) return;
loading = true;
error = null;
pdfDoc = null;
@@ -30,7 +44,7 @@ async function loadDocument(src: string) {
totalPages = 0;
try {
const loadingTask = getDocument(src);
const loadingTask = pdfjsLib.getDocument(src);
const doc = await loadingTask.promise;
pdfDoc = doc;
totalPages = doc.numPages;
@@ -42,7 +56,7 @@ async function loadDocument(src: string) {
}
async function renderPage(doc: PDFDocumentProxy, pageNum: number) {
if (!canvasEl || !textLayerEl) return;
if (!pdfjsLib || !canvasEl || !textLayerEl) return;
// Cancel any in-flight render
if (renderTask) {
@@ -79,8 +93,6 @@ async function renderPage(doc: PDFDocumentProxy, pageNum: number) {
try {
await task.promise;
} catch (e: unknown) {
// Cancelled renders throw a specific error — ignore them
if (e instanceof Error && e.message === 'Rendering cancelled') return;
if (
typeof e === 'object' &&
e !== null &&
@@ -98,7 +110,7 @@ async function renderPage(doc: PDFDocumentProxy, pageNum: number) {
textDiv.style.width = `${viewport.width / dpr}px`;
textDiv.style.height = `${viewport.height / dpr}px`;
const tl = new TextLayer({
const tl = new pdfjsLib.TextLayer({
textContentSource: page.streamTextContent(),
container: textDiv,
viewport
@@ -123,7 +135,7 @@ async function prerender(doc: PDFDocumentProxy, pageNum: number) {
}
$effect(() => {
if (url) {
if (pdfjsReady && url) {
loadDocument(url);
}
});