271 lines
9.5 KiB
TypeScript
271 lines
9.5 KiB
TypeScript
// CanvasData → dual-layer PDF.
|
|
//
|
|
// Visual layer: pages in flatten order, imported PDF content, markdown as
|
|
// vector text, ink as Ink annotations (with appearance streams).
|
|
// Source-of-truth layer: embedded files (see format.ts).
|
|
|
|
import fontkit from '@pdf-lib/fontkit';
|
|
import {
|
|
PDFArray,
|
|
PDFDict,
|
|
PDFDocument,
|
|
PDFName,
|
|
PDFNumber,
|
|
PDFObjectCopier,
|
|
PDFString,
|
|
degrees,
|
|
type PDFEmbeddedPage,
|
|
type PDFPage
|
|
} from 'pdf-lib';
|
|
|
|
interface EmbeddedSource {
|
|
page: PDFEmbeddedPage;
|
|
rotation: number;
|
|
src: PDFPage;
|
|
crop: { x: number; y: number };
|
|
}
|
|
import { flatten } from '$lib/model/tree';
|
|
import type { CanvasData, PageData, Stroke } from '$lib/model/types';
|
|
import { HIGHLIGHTER_OPACITY, outline, samples } from '$lib/ink/stroke';
|
|
import { ATTACH, FORMAT } from './format';
|
|
import { loadFonts } from './fonts';
|
|
import { drawMarkdown, fontsNeeded, hex, type Fonts, type Metrics } from './text';
|
|
|
|
export interface WriteOptions {
|
|
title: string;
|
|
getSource: (id: string) => Promise<Uint8Array | undefined>;
|
|
}
|
|
|
|
export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise<Uint8Array> {
|
|
const doc = await PDFDocument.create();
|
|
doc.registerFontkit(fontkit);
|
|
doc.setTitle(opts.title);
|
|
doc.setProducer('Papure');
|
|
doc.setCreator('Papure');
|
|
doc.setModificationDate(new Date(data.updatedAt));
|
|
|
|
const order = flatten(data.tree);
|
|
const pages = order.map((id) => data.pages[id]).filter(Boolean);
|
|
|
|
const embedded = await embedSources(doc, pages, opts.getSource);
|
|
const hasText = pages.some((p) => p.markdown.trim());
|
|
const text = hasText ? await embedFonts(doc, pages) : null;
|
|
|
|
for (const p of pages) {
|
|
const page = doc.addPage([p.width, p.height]);
|
|
const src = p.origin && embedded.get(`${p.origin.sourceId}:${p.origin.pageIndex}`);
|
|
if (src) {
|
|
drawSourcePage(page, src.page, src.rotation);
|
|
copyMarkupAnnotations(doc, page, src);
|
|
}
|
|
if (text && p.markdown.trim()) drawMarkdown(page, p.markdown, text.fonts, text.metrics);
|
|
for (const s of p.strokes) addInkAnnotation(doc, page, s);
|
|
}
|
|
if (pages.length === 0) doc.addPage([595.28, 841.89]);
|
|
|
|
// Source-of-truth layer.
|
|
const when = new Date(data.updatedAt);
|
|
const attach = (bytes: Uint8Array | string, name: string, mimeType: string) =>
|
|
doc.attach(typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes, name, {
|
|
mimeType,
|
|
creationDate: when,
|
|
modificationDate: when
|
|
});
|
|
|
|
const manifest = {
|
|
format: FORMAT,
|
|
version: data.version,
|
|
updatedAt: data.updatedAt,
|
|
tree: data.tree,
|
|
order,
|
|
pages: Object.fromEntries(pages.map((p) => [p.id, { width: p.width, height: p.height, origin: p.origin }]))
|
|
};
|
|
await attach(JSON.stringify(manifest), ATTACH.manifest, 'application/json');
|
|
for (const p of pages) {
|
|
if (p.markdown) await attach(p.markdown, ATTACH.markdown(p.id), 'text/markdown');
|
|
if (p.strokes.length) await attach(JSON.stringify({ strokes: p.strokes }), ATTACH.ink(p.id), 'application/json');
|
|
}
|
|
const sourceIds = new Set(pages.flatMap((p) => (p.origin ? [p.origin.sourceId] : [])));
|
|
for (const id of sourceIds) {
|
|
const bytes = await opts.getSource(id);
|
|
if (bytes) await attach(bytes, ATTACH.source(id), 'application/pdf');
|
|
}
|
|
|
|
return doc.save({ useObjectStreams: true });
|
|
}
|
|
|
|
async function embedFonts(doc: PDFDocument, pages: PageData[]) {
|
|
const needed = new Set<keyof Fonts>(['regular']);
|
|
for (const p of pages) fontsNeeded(p.markdown, needed);
|
|
const bytes = await loadFonts();
|
|
const fonts = {} as Fonts;
|
|
const metrics: Metrics = new Map();
|
|
for (const key of needed) {
|
|
// Files are pre-subset (scripts/subset-fonts.sh); pdf-lib's subsetter drops glyphs.
|
|
const font = await doc.embedFont(bytes[key], { subset: false });
|
|
fonts[key] = font;
|
|
metrics.set(font, fontMetrics(bytes[key]));
|
|
}
|
|
return { fonts, metrics };
|
|
}
|
|
|
|
function fontMetrics(bytes: Uint8Array) {
|
|
const f = fontkit.create(bytes);
|
|
return { ascent: f.ascent / f.unitsPerEm, descent: Math.abs(f.descent) / f.unitsPerEm };
|
|
}
|
|
|
|
async function embedSources(
|
|
doc: PDFDocument,
|
|
pages: PageData[],
|
|
getSource: WriteOptions['getSource']
|
|
): Promise<Map<string, EmbeddedSource>> {
|
|
const bySource = new Map<string, Set<number>>();
|
|
for (const p of pages) {
|
|
if (!p.origin) continue;
|
|
let set = bySource.get(p.origin.sourceId);
|
|
if (!set) bySource.set(p.origin.sourceId, (set = new Set()));
|
|
set.add(p.origin.pageIndex);
|
|
}
|
|
const out = new Map<string, EmbeddedSource>();
|
|
for (const [sourceId, indices] of bySource) {
|
|
const bytes = await getSource(sourceId);
|
|
if (!bytes) continue;
|
|
try {
|
|
const src = await PDFDocument.load(bytes, { ignoreEncryption: true, updateMetadata: false });
|
|
const idx = [...indices].filter((i) => i < src.getPageCount());
|
|
const srcPages = idx.map((i) => src.getPage(i));
|
|
const boxes = srcPages.map((sp) => {
|
|
const c = sp.getCropBox();
|
|
return { left: c.x, bottom: c.y, right: c.x + c.width, top: c.y + c.height };
|
|
});
|
|
for (let k = 0; k < idx.length; k++) {
|
|
// A blank source page has no content stream; there is nothing to draw
|
|
// (and pdf-lib would fail later, at save time).
|
|
if (!srcPages[k].node.Contents()) continue;
|
|
const [emb] = await doc.embedPages([srcPages[k]], [boxes[k]]);
|
|
out.set(`${sourceId}:${idx[k]}`, {
|
|
page: emb,
|
|
rotation: normRotation(srcPages[k].getRotation().angle),
|
|
src: srcPages[k],
|
|
crop: { x: boxes[k].left, y: boxes[k].bottom }
|
|
});
|
|
}
|
|
} catch (err) {
|
|
console.warn('Could not embed source PDF', sourceId, err);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export const normRotation = (a: number) => (((Math.round(a / 90) * 90) % 360) + 360) % 360;
|
|
|
|
/** Draw an embedded source page honouring its /Rotate. */
|
|
function drawSourcePage(page: PDFPage, emb: PDFEmbeddedPage, rotation: number) {
|
|
const { width: W, height: H } = page.getSize();
|
|
const size = { width: emb.width, height: emb.height };
|
|
switch (rotation) {
|
|
case 90:
|
|
return page.drawPage(emb, { x: 0, y: H, rotate: degrees(-90), ...size });
|
|
case 180:
|
|
return page.drawPage(emb, { x: W, y: H, rotate: degrees(180), ...size });
|
|
case 270:
|
|
return page.drawPage(emb, { x: W, y: 0, rotate: degrees(90), ...size });
|
|
default:
|
|
return page.drawPage(emb, { x: 0, y: 0, ...size });
|
|
}
|
|
}
|
|
|
|
// Annotations that are part of what a reader sees (ink, highlights, notes…).
|
|
// Links, form widgets and popups are left behind: they point into the source.
|
|
const MARKUP = new Set([
|
|
'Ink', 'Highlight', 'Underline', 'StrikeOut', 'Squiggly', 'Square', 'Circle', 'Line',
|
|
'Polygon', 'PolyLine', 'FreeText', 'Text', 'Stamp', 'Caret'
|
|
]);
|
|
|
|
/**
|
|
* embedPage only carries the content stream, so annotations on an imported
|
|
* page (e.g. ink from another app, or an earlier export) are copied across.
|
|
*/
|
|
function copyMarkupAnnotations(doc: PDFDocument, page: PDFPage, s: EmbeddedSource) {
|
|
// Rotated sources would need every Rect transformed; not supported yet.
|
|
if (s.rotation !== 0) return;
|
|
const annots = s.src.node.Annots();
|
|
if (!annots) return;
|
|
const srcContext = s.src.doc.context;
|
|
const copier = PDFObjectCopier.for(srcContext, doc.context);
|
|
for (let i = 0; i < annots.size(); i++) {
|
|
const a = annots.lookup(i);
|
|
if (!(a instanceof PDFDict)) continue;
|
|
const subtype = a.lookup(PDFName.of('Subtype'));
|
|
if (!(subtype instanceof PDFName) || !MARKUP.has(subtype.decodeText())) continue;
|
|
const clone = a.clone(srcContext);
|
|
// Drop back-references into the source document.
|
|
for (const k of ['P', 'Popup', 'IRT', 'Parent', 'StructParent']) clone.delete(PDFName.of(k));
|
|
const copied = copier.copy(clone);
|
|
const rect = copied.lookup(PDFName.of('Rect'));
|
|
if (rect instanceof PDFArray && (s.crop.x || s.crop.y)) {
|
|
const v = rect.asArray().map((n) => (n instanceof PDFNumber ? n.asNumber() : 0));
|
|
copied.set(PDFName.of('Rect'), doc.context.obj([v[0] - s.crop.x, v[1] - s.crop.y, v[2] - s.crop.x, v[3] - s.crop.y]));
|
|
}
|
|
page.node.addAnnot(doc.context.register(copied));
|
|
}
|
|
}
|
|
|
|
function addInkAnnotation(doc: PDFDocument, page: PDFPage, s: Stroke) {
|
|
const H = page.getHeight();
|
|
const poly = outline(s);
|
|
if (poly.length < 3) return;
|
|
const flip = (x: number, y: number) => [x, H - y] as const;
|
|
|
|
let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;
|
|
for (const [px, py] of poly) {
|
|
const [x, y] = flip(px, py);
|
|
x1 = Math.min(x1, x);
|
|
y1 = Math.min(y1, y);
|
|
x2 = Math.max(x2, x);
|
|
y2 = Math.max(y2, y);
|
|
}
|
|
const rect = [x1 - 1, y1 - 1, x2 + 1, y2 + 1].map((v) => +v.toFixed(2));
|
|
|
|
const c = hex(s.color);
|
|
const color = [c.red, c.green, c.blue].map((v) => +v.toFixed(3));
|
|
const opacity = s.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1;
|
|
|
|
// Appearance: the same filled outline the app renders (variable width).
|
|
const ops: string[] = ['q'];
|
|
if (opacity < 1) ops.push('/GS0 gs');
|
|
ops.push(`${color.join(' ')} rg`);
|
|
poly.forEach(([px, py], i) => {
|
|
const [x, y] = flip(px, py);
|
|
ops.push(`${x.toFixed(2)} ${y.toFixed(2)} ${i === 0 ? 'm' : 'l'}`);
|
|
});
|
|
ops.push('h f Q');
|
|
|
|
const ctx = doc.context;
|
|
const resources =
|
|
opacity < 1
|
|
? { ExtGState: { GS0: { Type: 'ExtGState', CA: opacity, ca: opacity, BM: 'Multiply' } } }
|
|
: {};
|
|
const ap = ctx.register(
|
|
ctx.stream(ops.join('\n'), { Type: 'XObject', Subtype: 'Form', BBox: rect, Resources: resources })
|
|
);
|
|
|
|
// Centreline for viewers that rebuild the appearance from InkList.
|
|
const ink: number[] = [];
|
|
for (const { x, y } of samples(s)) ink.push(...flip(x, y).map((v) => +v.toFixed(2)));
|
|
|
|
const annot = ctx.obj({
|
|
Type: 'Annot',
|
|
Subtype: 'Ink',
|
|
Rect: rect,
|
|
InkList: [ink],
|
|
C: color,
|
|
CA: opacity,
|
|
F: 4,
|
|
BS: { W: s.width * (s.tool === 'highlighter' ? 1 : 0.6) },
|
|
AP: { N: ap },
|
|
NM: PDFString.of(s.id)
|
|
});
|
|
annot.set(PDFName.of('M'), PDFString.fromDate(new Date()));
|
|
page.node.addAnnot(ctx.register(annot));
|
|
}
|