change for host

This commit is contained in:
2025-11-26 18:40:03 +01:00
parent baacb7cfac
commit abfe6c347a
6 changed files with 1835 additions and 26 deletions

View File

@@ -1,11 +1,27 @@
import * as pdfjsLib from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker?worker&url';
// pdf.js worker setup for Vite
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(pdfjsLib as any).GlobalWorkerOptions.workerSrc = pdfjsWorker;
type RotationsMap = Record<number, number>;
type RotationsMap = Record<number, number>; // key: 0-based page index, value: degrees
/**
* Helper: create a *copy* of the data for pdf.js to consume.
* pdf.js may transfer/detach the buffer it receives, so we NEVER
* pass the original ArrayBuffer directly.
*/
function makePdfJsDataCopy(arrayBuffer: ArrayBuffer): Uint8Array {
const src = new Uint8Array(arrayBuffer);
const copy = new Uint8Array(src.byteLength);
copy.set(src);
return copy;
}
/**
* Unrotated thumbnails used e.g. in the Split/Extract view.
*/
export async function generateThumbnails(
arrayBuffer: ArrayBuffer,
maxHeight = 150
@@ -13,6 +29,9 @@ export async function generateThumbnails(
return generateThumbnailsInternal(arrayBuffer, {}, maxHeight);
}
/**
* Thumbnails that respect per-page rotations (for the Reorder view).
*/
export async function generateThumbnailsWithRotations(
arrayBuffer: ArrayBuffer,
rotations: RotationsMap,
@@ -26,7 +45,10 @@ async function generateThumbnailsInternal(
rotations: RotationsMap,
maxHeight: number
): Promise<string[]> {
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
// IMPORTANT: use a COPY so pdf.js can detach it without breaking future calls
const dataCopy = makePdfJsDataCopy(arrayBuffer);
const loadingTask = pdfjsLib.getDocument({ data: dataCopy });
const pdf = await loadingTask.promise;
const thumbs: string[] = [];
@@ -37,6 +59,7 @@ async function generateThumbnailsInternal(
const scale = maxHeight / viewport.height;
const scaledViewport = page.getViewport({ scale });
// First render unrotated page into a canvas
const baseCanvas = document.createElement('canvas');
const baseCtx = baseCanvas.getContext('2d');
if (!baseCtx) {
@@ -55,13 +78,14 @@ async function generateThumbnailsInternal(
const originalIndex = pageNum - 1;
const rotationDegRaw = rotations[originalIndex] ?? 0;
const rotationDeg = ((rotationDegRaw % 360) + 360) % 360;
const rotationDeg = ((rotationDegRaw % 360) + 360) % 360; // normalize 0359
if (rotationDeg === 0) {
thumbs.push(baseCanvas.toDataURL('image/png'));
continue;
}
// Re-render onto a second canvas with rotation applied
const rotatedCanvas = document.createElement('canvas');
const rotatedCtx = rotatedCanvas.getContext('2d');
if (!rotatedCtx) {
@@ -95,6 +119,7 @@ async function generateThumbnailsInternal(
rotatedCtx.rotate(rad);
break;
default:
// fallback: no rotation
break;
}