This commit is contained in:
Reudy 2026-09-26 19:13:02 +02:00
commit 0ad405c26e
78 changed files with 9127 additions and 0 deletions

162
src/lib/pdf/read.ts Normal file
View file

@ -0,0 +1,162 @@
// PDF → CanvasData. Reads the embedded source-of-truth layer first; a PDF
// without it (any ordinary PDF) is taken as an import: one trunk page per
// PDF page, with the file itself as the source.
import {
PDFArray,
PDFDict,
PDFDocument,
PDFHexString,
PDFName,
PDFRawStream,
PDFStream,
PDFString,
decodePDFRawStream
} from 'pdf-lib';
import { withTrunk, flatten, type Tree } from '$lib/model/tree';
import { newId, type CanvasData, type Origin, type PageData, type Stroke } from '$lib/model/types';
import { ATTACH, FORMAT, sha256Hex } from './format';
import { normRotation } from './write';
export interface ReadResult {
data: CanvasData;
/** Source PDFs referenced by pages, keyed by source id. */
sources: Map<string, Uint8Array>;
/** True when the file had no Papure layer and was imported as-is. */
imported: boolean;
}
export async function readCanvasPdf(bytes: Uint8Array, name: string): Promise<ReadResult> {
const doc = await PDFDocument.load(bytes, { ignoreEncryption: true, updateMetadata: false });
const files = readAttachments(doc);
const manifestBytes = files.get(ATTACH.manifest);
if (manifestBytes) {
try {
return { ...fromAttachments(files, JSON.parse(text(manifestBytes))), imported: false };
} catch (err) {
console.warn('Papure layer unreadable, importing visual content instead', err);
}
}
return importPdf(bytes, name, doc);
}
interface Manifest {
format: string;
version: 1;
updatedAt: number;
tree: Tree;
pages: Record<string, { width: number; height: number; origin?: Origin }>;
}
function fromAttachments(files: Map<string, Uint8Array>, m: Manifest) {
if (m.format !== FORMAT) throw new Error('not a papure manifest');
const pages: Record<string, PageData> = {};
for (const id of flatten(m.tree)) {
const meta = m.pages[id];
if (!meta) continue;
const md = files.get(ATTACH.markdown(id));
const ink = files.get(ATTACH.ink(id));
pages[id] = {
id,
width: meta.width,
height: meta.height,
origin: meta.origin,
markdown: md ? text(md) : '',
strokes: ink ? (JSON.parse(text(ink)).strokes as Stroke[]) : []
};
}
const sources = new Map<string, Uint8Array>();
for (const p of Object.values(pages)) {
if (!p.origin || sources.has(p.origin.sourceId)) continue;
const b = files.get(ATTACH.source(p.origin.sourceId));
if (b) sources.set(p.origin.sourceId, b);
}
const data: CanvasData = { version: 1, updatedAt: m.updatedAt, tree: m.tree, pages };
return { data, sources };
}
/** Pages of a PDF as they appear on screen (CropBox, /Rotate applied). */
export async function pdfPageSizes(bytes: Uint8Array, loaded?: PDFDocument) {
const doc = loaded ?? (await PDFDocument.load(bytes, { ignoreEncryption: true, updateMetadata: false }));
return doc.getPages().map((p) => {
const { width, height } = p.getCropBox();
const r = normRotation(p.getRotation().angle);
return r === 90 || r === 270 ? { width: height, height: width } : { width, height };
});
}
/** Build page records for every page of a source PDF, in order. */
export async function pagesFromPdf(bytes: Uint8Array, name: string, loaded?: PDFDocument) {
const sourceId = await sha256Hex(bytes);
const sizes = await pdfPageSizes(bytes, loaded);
const pages: PageData[] = sizes.map((s, pageIndex) => ({
id: newId(),
width: round(s.width),
height: round(s.height),
markdown: '',
strokes: [],
origin: { sourceId, pageIndex, name }
}));
return { sourceId, pages };
}
async function importPdf(bytes: Uint8Array, name: string, doc: PDFDocument): Promise<ReadResult> {
const { sourceId, pages } = await pagesFromPdf(bytes, name, doc);
const data: CanvasData = {
version: 1,
updatedAt: Date.now(),
tree: withTrunk(pages.map((p) => p.id)),
pages: Object.fromEntries(pages.map((p) => [p.id, p]))
};
return { data, sources: new Map([[sourceId, bytes]]), imported: true };
}
const round = (v: number) => Math.round(v * 100) / 100;
const text = (b: Uint8Array) => new TextDecoder().decode(b);
/** All embedded files (EmbeddedFiles name tree), by name. */
export function readAttachments(doc: PDFDocument): Map<string, Uint8Array> {
const out = new Map<string, Uint8Array>();
const names = doc.catalog.lookupMaybe(PDFName.of('Names'), PDFDict);
const root = names?.lookupMaybe(PDFName.of('EmbeddedFiles'), PDFDict);
if (!root) return out;
const visit = (node: PDFDict, depth: number) => {
if (depth > 32) return;
const arr = node.lookupMaybe(PDFName.of('Names'), PDFArray);
if (arr) {
for (let i = 0; i + 1 < arr.size(); i += 2) {
const key = arr.lookup(i);
const spec = arr.lookup(i + 1);
if (!(spec instanceof PDFDict)) continue;
const fileName =
decodeName(spec.lookup(PDFName.of('UF'))) ??
decodeName(spec.lookup(PDFName.of('F'))) ??
decodeName(key);
const ef = spec.lookupMaybe(PDFName.of('EF'), PDFDict);
const stream = ef?.lookup(PDFName.of('F'));
if (!fileName || !(stream instanceof PDFStream)) continue;
out.set(fileName, streamBytes(stream));
}
}
const kids = node.lookupMaybe(PDFName.of('Kids'), PDFArray);
if (kids) {
for (let i = 0; i < kids.size(); i++) {
const kid = kids.lookup(i);
if (kid instanceof PDFDict) visit(kid, depth + 1);
}
}
};
visit(root, 0);
return out;
}
function decodeName(v: unknown): string | undefined {
if (v instanceof PDFString || v instanceof PDFHexString) return v.decodeText();
return undefined;
}
function streamBytes(stream: PDFStream): Uint8Array {
if (stream instanceof PDFRawStream) return decodePDFRawStream(stream).decode();
return stream.getContents();
}