#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Subset the fonts the text editor embeds when saving (#8883)
Anthony Stirling1d83803670c7
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.tsindex ba40dc74bf..d1b6c92ea8 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts@@ -158,6 +158,7 @@ function fakeHarness(options: FakeModuleOptions = {}): FakeHarness {.FPDFPageObj_CreateTextObj;}const ownedFonts = new Map<string, FontRef>();+ const embeddedFontFiles: Uint8Array[] = [];const doc = {module,docPtr: 7,@@ -165,6 +166,9 @@ function fakeHarness(options: FakeModuleOptions = {}): FakeHarness {ownedFonts.set(font.id, font);},ownedFont: (id: string) => ownedFonts.get(id),+ recordEmbeddedFontFile: (bytes: Uint8Array) =>+ embeddedFontFiles.push(bytes),+ embeddedFontFiles: () => embeddedFontFiles,} as unknown as EditorDocument;const page = new Page({ index: 0, pagePtr: 3, width: 200, height: 200 });return { doc, page, calls, ownedFonts };@@ -346,6 +350,7 @@ describe("loadDeviceFontInto", () => {expect(loadDeviceFontInto(harness.doc, "Segoe UI")).toBe(900);expect(harness.calls.loadFont).toBe(1);expect(isDeviceFontEmbedded(harness.doc, "Segoe UI")).toBe(true);+ expect(harness.doc.embeddedFontFiles()).toHaveLength(1);});it("embeds separately per document", async () => {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.tsnew file mode 100644index 0000000000..7c75872781--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.ts@@ -0,0 +1,335 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import path from "node:path";+import { describe, expect, test } from "vitest";+import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";+import { subsetEmbeddedFonts } from "@editor/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import { subsetTrueType } from "@editor/tools/pdfTextEditor/util/ttfSubset";++const FONT = path.join(+ import.meta.dirname,+ "../../../../../../../app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf",+);++const TAG = (s: string) =>+ ((s.charCodeAt(0) << 24) |+ (s.charCodeAt(1) << 16) |+ (s.charCodeAt(2) << 8) |+ s.charCodeAt(3)) >>>+ 0;++function table(font: Uint8Array, tag: string): Uint8Array | null {+ const dv = new DataView(font.buffer, font.byteOffset, font.byteLength);+ for (let i = 0; i < dv.getUint16(4); i++) {+ const rec = 12 + i * 16;+ if (dv.getUint32(rec) !== TAG(tag)) continue;+ const offset = dv.getUint32(rec + 8);+ return font.subarray(offset, offset + dv.getUint32(rec + 12));+ }+ return null;+}++function glyph(font: Uint8Array, gid: number): Uint8Array {+ const head = table(font, "head")!;+ const loca = table(font, "loca")!;+ const glyf = table(font, "glyf")!;+ const long = new DataView(head.buffer, head.byteOffset).getInt16(50) !== 0;+ const dv = new DataView(loca.buffer, loca.byteOffset, loca.byteLength);+ const at = (i: number) =>+ long ? dv.getUint32(i * 4) : dv.getUint16(i * 2) * 2;+ return glyf.subarray(at(gid), at(gid + 1));+}++function trimmed(bytes: Uint8Array): number[] {+ let end = bytes.length;+ while (end > 0 && bytes[end - 1] === 0) end -= 1;+ return [...bytes.subarray(0, end)];+}++function gidsOf(font: Uint8Array, text: string): number[] {+ const cmap = parseTrueTypeCmap(font)!;+ return [...text].map((ch) => cmap.get(ch.codePointAt(0)!)!);+}++const hex = (gids: number[]) =>+ gids.map((g) => g.toString(16).padStart(4, "0")).join("");++interface PdfOptions {+ content: string;+ encoding?: string;+ cidSubtype?: string;+ /** The page's /Font entry, in place of the inline `<< /F1 5 0 R >>`. */+ fonts?: string;+ info?: string;+ /** Body of an object 11 added after the others. */+ extra?: string;+}++function pdfWithFont(font: Uint8Array, options: PdfOptions): Uint8Array {+ const latin1 = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0));+ const objects: Uint8Array[] = [+ latin1("<< /Type /Catalog /Pages 2 0 R >>"),+ latin1("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),+ latin1(+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font ${options.fonts ?? "<< /F1 5 0 R >>"} >> >>`,+ ),+ latin1(+ `<< /Length ${options.content.length} >>\nstream\n${options.content}\nendstream`,+ ),+ latin1(+ `<< /Type /Font /Subtype /Type0 /BaseFont /Carlito /Encoding /${options.encoding ?? "Identity-H"} /DescendantFonts [6 0 R] >>`,+ ),+ latin1(+ `<< /Type /Font /Subtype /${options.cidSubtype ?? "CIDFontType2"} /BaseFont /Carlito /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor 7 0 R /CIDToGIDMap /Identity /W 10 0 R >>`,+ ),+ latin1(+ "<< /Type /FontDescriptor /FontName /Carlito /Flags 4 /FontBBox [0 0 1000 1000] /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 8 0 R >>",+ ),+ (() => {+ const headPart = latin1(+ `<< /Length ${font.length} /Length1 ${font.length} >>\nstream\n`,+ );+ const tailPart = latin1("\nendstream");+ const out = new Uint8Array(+ headPart.length + font.length + tailPart.length,+ );+ out.set(headPart);+ out.set(font, headPart.length);+ out.set(tailPart, headPart.length + font.length);+ return out;+ })(),+ latin1(options.info ?? "<< /Producer (after the font) >>"),+ latin1(`[0 [${Array.from({ length: 400 }, (_, i) => 500 + i).join(" ")}]]`),+ ];+ if (options.extra) objects.push(latin1(options.extra));+ const parts: Uint8Array[] = [latin1("%PDF-1.4\n")];+ const offsets: number[] = [];+ let size = parts[0].length;+ objects.forEach((body, i) => {+ offsets.push(size);+ const chunk = [latin1(`${i + 1} 0 obj\n`), body, latin1("\nendobj\n")];+ for (const c of chunk) {+ parts.push(c);+ size += c.length;+ }+ });+ const xref =+ `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n` ++ offsets.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`).join("") ++ `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R /Info 9 0 R >>\nstartxref\n${size}\n%%EOF\n`;+ parts.push(latin1(xref));+ const out = new Uint8Array(size + xref.length);+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+}++describe("subsetTrueType", () => {+ test("keeps the used glyphs at their ids and empties the rest", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const used = gidsOf(font, "Hello");+ const subset = subsetTrueType(font, used)!;++ expect(subset.length).toBeLessThan(font.length / 5);+ for (const gid of used)+ expect(trimmed(glyph(subset, gid))).toEqual(trimmed(glyph(font, gid)));+ const unused = gidsOf(font, "Z")[0];+ expect(glyph(font, unused).length).toBeGreaterThan(0);+ expect(glyph(subset, unused).length).toBe(0);+ const glyphCount = Math.max(...used) + 1;+ const maxp = table(subset, "maxp")!;+ expect(new DataView(maxp.buffer, maxp.byteOffset).getUint16(4)).toBe(+ glyphCount,+ );+ const metrics = (f: Uint8Array) => [...table(f, "hmtx")!.subarray(0, 8)];+ expect(metrics(subset)).toEqual(metrics(font));+ expect(table(subset, "GSUB")).toBeNull();+ });++ test("maps only the characters whose glyphs survive", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const subset = subsetTrueType(font, gidsOf(font, "Hello"))!;+ const cmap = parseTrueTypeCmap(subset)!;++ expect(cmap.get("H".codePointAt(0)!)).toBe(gidsOf(font, "H")[0]);+ expect(cmap.has("Z".codePointAt(0)!)).toBe(false);+ });++ test("keeps the parts a composite glyph is built from", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [accented, base] = gidsOf(font, "ée");+ const composite = glyph(font, accented);+ const isComposite =+ new DataView(composite.buffer, composite.byteOffset).getInt16(0) < 0;+ expect(isComposite).toBe(true);++ const subset = subsetTrueType(font, [accented])!;+ expect(glyph(subset, base).length).toBeGreaterThan(0);+ });++ test("declines a file that is not a TrueType font", () => {+ expect(subsetTrueType(new Uint8Array([1, 2, 3, 4]), [1])).toBeNull();+ });+});++describe("subsetEmbeddedFonts", () => {+ async function fontFileIn(pdfBytes: Uint8Array): Promise<Uint8Array> {+ const pdf = (await RawPdf.parse(pdfBytes))!;+ return (await pdf.streamData(8))!;+ }++ test("shrinks the embedded font to the glyphs the page draws", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const used = gidsOf(font, "Hello");+ const pdf = pdfWithFont(font, {+ content: `BT /F1 12 Tf <${hex(used)}> Tj ET`,+ });++ const out = await subsetEmbeddedFonts(pdf, [font]);++ expect(out.length).toBeLessThan(pdf.length / 5);+ const embedded = await fontFileIn(out);+ for (const gid of used)+ expect(trimmed(glyph(embedded, gid))).toEqual(trimmed(glyph(font, gid)));+ const reread = (await RawPdf.parse(out))!;+ expect(reread.objectBody(9)).toContain("after the font");+ expect(reread.dictName(reread.objectBody(5)!, "BaseFont")).toMatch(+ /^[A-Z]{6}\+Carlito$/,+ );+ expect(reread.dictName(reread.objectBody(7)!, "FontName")).toMatch(+ /^[A-Z]{6}\+Carlito$/,+ );+ expect(reread.pageNumbers()).toHaveLength(1);+ const widths = reread.valueSpan(reread.objectBody(6)!, "W")!.text;+ for (const gid of used) expect(widths).toContain(`${gid} [${500 + gid}]`);+ expect(widths.length).toBeLessThan(200);+ expect(reread.objectBody(10)!.trim()).toBe("null");+ });++ test("counts only the text shown in the embedded font", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [h] = gidsOf(font, "H");+ const other = 0x7a7a;+ const pdf = pdfWithFont(font, {+ content: `BT /F1 12 Tf q /Other 9 Tf (zz) Tj Q <${hex([h])}> Tj ET`,+ });++ const embedded = await fontFileIn(await subsetEmbeddedFonts(pdf, [font]));++ const maxp = table(embedded, "maxp")!;+ const glyphCount = new DataView(maxp.buffer, maxp.byteOffset).getUint16(4);+ expect(glyphCount).toBe(h + 1);+ expect(glyphCount).toBeLessThan(other);+ expect(glyph(embedded, h).length).toBeGreaterThan(0);+ });++ test("reads glyph ids from literal strings and arrays too", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [h, i] = gidsOf(font, "Hi");+ const escaped = (gid: number) =>+ `\\${(gid >> 8).toString(8).padStart(3, "0")}\\${(gid & 0xff).toString(8).padStart(3, "0")}`;+ const pdf = pdfWithFont(font, {+ content: `BT /F1 12 Tf [(${escaped(h)}) -20 <${hex([i])}>] TJ ET`,+ });++ const embedded = await fontFileIn(await subsetEmbeddedFonts(pdf, [font]));++ expect(glyph(embedded, h).length).toBeGreaterThan(0);+ expect(glyph(embedded, i).length).toBeGreaterThan(0);+ });++ test.each([+ ["a font the session did not embed", {}, false],+ ["codes that are not glyph ids", { encoding: "UniJIS-UCS2-H" }, true],+ ["a font that is not CID TrueType", { cidSubtype: "CIDFontType0" }, true],+ ])("leaves the file alone for %s", async (_label, options, known) => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET",+ ...options,+ });+ expect(await subsetEmbeddedFonts(pdf, known ? [font] : [])).toBe(pdf);+ });++ test("leaves a font the opened document already embedded", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, { content: "BT /F1 12 Tf <0001> Tj ET" });+ const without = pdfWithFont(font.subarray(0, 64), { content: "" });++ expect(await subsetEmbeddedFonts(pdf, [font], pdf)).toBe(pdf);+ expect(+ (await subsetEmbeddedFonts(pdf, [font], without)).length,+ ).toBeLessThan(pdf.length / 5);+ });++ test("keeps glyphs shown in a font bound through an indirect /Font", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [h] = gidsOf(font, "H");+ const pdf = pdfWithFont(font, {+ content: `BT /F1 12 Tf <${hex([h])}> Tj ET`,+ fonts: "11 0 R",+ extra: "<< /F1 5 0 R >>",+ });++ const embedded = await fontFileIn(await subsetEmbeddedFonts(pdf, [font]));++ expect(glyph(embedded, h).length).toBeGreaterThan(0);+ });++ test("keeps glyphs shown after a graphics state may have set the font", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [h] = gidsOf(font, "H");+ const pdf = pdfWithFont(font, {+ content: `BT /Other 12 Tf /GS1 gs <${hex([h])}> Tj ET`,+ });++ const embedded = await fontFileIn(await subsetEmbeddedFonts(pdf, [font]));++ expect(glyph(embedded, h).length).toBeGreaterThan(0);+ });++ test("keeps a widths array another font still points at", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET",+ extra: "<< /Type /Font /Subtype /CIDFontType2 /W 10 0 R >>",+ });++ const reread = (await RawPdf.parse(+ await subsetEmbeddedFonts(pdf, [font]),+ ))!;++ expect(reread.objectBody(10)!.trim()).not.toBe("null");+ expect(+ reread.valueSpan(reread.objectBody(6)!, "W")!.text.length,+ ).toBeLessThan(200);+ });++ test(+ "is not slowed by a /Size inside a string",+ { timeout: 5000 },+ async () => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET",+ info: "<< /Title (/Size 1000000000) >>",+ });++ expect((await subsetEmbeddedFonts(pdf, [font])).length).toBeLessThan(+ pdf.length / 5,+ );+ },+ );++ test("leaves the file alone when a page holds an inline image", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET BI /W 1 /H 1 ID \u0000 EI",+ });+ expect(await subsetEmbeddedFonts(pdf, [font])).toBe(pdf);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.tsindex 37d7fb0bb5..305df8c332 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -93,6 +93,7 @@ export class EditorDocument {private readonly fileStructure: FileStructure | null;private marked: boolean;private readonly ownedFonts: Map<string, FontRef>;+ private readonly embeddedFonts: Uint8Array[] = [];private _disposed: boolean;// Form-fill environment. Widgets with no appearance stream are drawn ONLY by// this layer, so without it such fields are invisible in the editor while@@ -761,6 +762,19 @@ export class EditorDocument {});}+ /**+ * Note a font file handed to PDFium for embedding in this document. PDFium+ * writes such a font whole; the save uses these to find and subset them.+ */+ recordEmbeddedFontFile(bytes: Uint8Array): void {+ this.embeddedFonts.push(bytes);+ }++ /** The exact font files embedded into this document during the session. */+ embeddedFontFiles(): readonly Uint8Array[] {+ return this.embeddedFonts;+ }+registerOwnedFont(font: FontRef): void {this.ownedFonts.set(font.id, font);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.tsnew file mode 100644index 0000000000..da8ad17f40--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.ts@@ -0,0 +1,454 @@+import {+ concatBytes,+ deflate,+ fromLatin1,+ toLatin1,+} from "@editor/tools/pdfTextEditor/pdfdoc/bytes";+import { tokenize } from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";+import { RawPdf, setDictEntry } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import { streamObject } from "@editor/tools/pdfTextEditor/pdfdoc/revision";+import { subsetTrueType } from "@editor/tools/pdfTextEditor/util/ttfSubset";++// A subset this close to the original is not worth rewriting the file for.+const WORTHWHILE_RATIO = 0.9;+const SUBSET_TAG = /^[A-Z]{6}\+/;+const ESCAPES: Record<string, number> = { n: 10, r: 13, t: 9, b: 8, f: 12 };+const RESOURCE_REF = /\/([^\s/<>[\]()%{}]+)\s+(\d+)\s+0\s+R/g;++/** Raised when a file holds something this cannot read with certainty. */+class Unreadable extends Error {}++interface Dict {+ num: number;+ /** The object's dictionary, without any stream payload. */+ text: string;+}++interface FontUsers {+ descriptors: number[];+ cidFonts: number[];+ type0: number[];+}++interface Replacement {+ num: number;+ body: Uint8Array;+}++function sameBytes(a: Uint8Array, b: Uint8Array): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++function dictPart(body: string): string {+ const stream = body.search(/stream\r?\n/);+ return stream < 0 ? body : body.slice(0, stream);+}++function collectDicts(pdf: RawPdf): Dict[] {+ const out: Dict[] = [];+ for (const num of pdf.objectNumbers()) {+ if (pdf.bodyOffset(num) < 0) continue;+ const body = pdf.objectBody(num);+ if (body) out.push({ num, text: dictPart(body) });+ }+ return out;+}++async function findFontFiles(+ pdf: RawPdf,+ dicts: Dict[],+ files: readonly Uint8Array[],+): Promise<Map<number, Uint8Array>> {+ const found = new Map<number, Uint8Array>();+ for (const { num, text } of dicts) {+ const length1 = pdf.dictInt(text, "Length1");+ if (length1 === null) continue;+ const sameLength = files.filter((file) => file.length === length1);+ if (sameLength.length === 0) continue;+ const data = await pdf.streamData(num);+ const file = data && sameLength.find((f) => sameBytes(f, data));+ if (file) found.set(num, file);+ }+ return found;+}++/**+ * `files` without any the opened document already embedded whole: that copy+ * may serve text this pass never sees, such as a form field filled in later.+ * A stream that cannot be read counts as a match, and an unreadable file as+ * matching everything.+ */+async function newToDocument(+ opened: Uint8Array,+ files: readonly Uint8Array[],+): Promise<Uint8Array[]> {+ if (opened.length === 0) return [...files];+ const pdf = await RawPdf.parse(opened);+ if (!pdf) return [];+ const had = new Set<Uint8Array>();+ for (const { num, text } of collectDicts(pdf)) {+ const length1 = pdf.dictInt(text, "Length1");+ if (length1 === null) continue;+ const sameLength = files.filter((file) => file.length === length1);+ if (sameLength.length === 0) continue;+ const data = pdf.encrypted ? null : await pdf.streamData(num);+ for (const file of sameLength)+ if (!data || sameBytes(file, data)) had.add(file);+ }+ return files.filter((file) => !had.has(file));+}++// Text addresses a font by glyph id only when it is a CID TrueType font with an+// identity mapping. Any other use of the file means the codes in the content+// are not glyph ids, so the font is left whole.+function fontUsers(pdf: RawPdf, dicts: Dict[], file: number): FontUsers | null {+ const descriptors = dicts+ .filter((d) => pdf.dictRef(d.text, "FontFile2") === file)+ .map((d) => d.num);+ const cidFonts: number[] = [];+ for (const d of dicts) {+ const descriptor = pdf.dictRef(d.text, "FontDescriptor");+ if (descriptor === null || !descriptors.includes(descriptor)) continue;+ if (pdf.dictName(d.text, "Subtype") !== "CIDFontType2") return null;+ const map = pdf.valueSpan(d.text, "CIDToGIDMap");+ if (map && pdf.dictName(d.text, "CIDToGIDMap") !== "Identity") return null;+ cidFonts.push(d.num);+ }+ const type0: number[] = [];+ for (const d of dicts) {+ const descendants = pdf.valueSpan(d.text, "DescendantFonts");+ if (!descendants) continue;+ const refs = [...descendants.text.matchAll(/(\d+)\s+\d+\s+R/g)].map((m) =>+ parseInt(m[1], 10),+ );+ if (!refs.some((ref) => cidFonts.includes(ref))) continue;+ const encoding = pdf.dictName(d.text, "Encoding");+ if (encoding !== "Identity-H" && encoding !== "Identity-V") return null;+ type0.push(d.num);+ }+ return type0.length > 0 ? { descriptors, cidFonts, type0 } : null;+}++/** Every resource name any dictionary binds to one of `fonts`. */+function resourceNames(dicts: Dict[], fonts: number[]): Set<string> {+ const names = new Set<string>();+ // Every dictionary, not only those holding /Font: a resource dictionary may+ // point at its font map indirectly, and a stray name only keeps more glyphs.+ for (const { text } of dicts) {+ for (const m of text.matchAll(RESOURCE_REF)) {+ if (fonts.includes(parseInt(m[2], 10))) names.add(m[1]);+ }+ }+ return names;+}++function literalBytes(token: string): number[] {+ const out: number[] = [];+ const text = token.slice(1, -1);+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (ch !== "\\") {+ out.push(text.charCodeAt(i) & 0xff);+ continue;+ }+ i += 1;+ const next = text[i];+ if (next === undefined) break;+ const octal = /^[0-7]{1,3}/.exec(text.slice(i, i + 3));+ if (octal) {+ out.push(parseInt(octal[0], 8) & 0xff);+ i += octal[0].length - 1;+ } else if (next === "\r") {+ if (text[i + 1] === "\n") i += 1;+ } else if (next !== "\n") {+ out.push(ESCAPES[next] ?? next.charCodeAt(0) & 0xff);+ }+ }+ return out;+}++function hexBytes(token: string): number[] {+ const digits = token.slice(1, -1).replace(/[^0-9a-fA-F]/g, "");+ const padded = digits.length % 2 ? `${digits}0` : digits;+ const out: number[] = [];+ for (let i = 0; i < padded.length; i += 2)+ out.push(parseInt(padded.slice(i, i + 2), 16));+ return out;+}++// Glyph ids a stream shows, by the resource name of the font in force.+// UNKNOWN_FONT holds text shown before the stream selects any font, which a+// form XObject may inherit from its caller: every font has to count those.+type ScannedStream = Map<string, number[]>;+const UNKNOWN_FONT = "";++// The font is part of the graphics state, so `q`/`Q` save and restore it.+function scanContent(content: Uint8Array): ScannedStream {+ const tokens = tokenize(toLatin1(content));+ const shown: ScannedStream = new Map();+ const saved: string[] = [];+ let font = UNKNOWN_FONT;+ for (let i = 0; i < tokens.length; i++) {+ const text = tokens[i].text;+ // An inline image carries raw bytes the tokeniser cannot be trusted past.+ if (text === "BI") throw new Unreadable();+ if (text === "q") saved.push(font);+ else if (text === "Q") font = saved.pop() ?? UNKNOWN_FONT;+ else if (text === "Tf" && i >= 2 && tokens[i - 2].text.startsWith("/"))+ font = tokens[i - 2].text.slice(1);+ // An ExtGState may set the font too, and which one is not read here.+ else if (text === "gs") font = UNKNOWN_FONT;+ const literal = text.startsWith("(");+ if (!literal && !(text.startsWith("<") && !text.startsWith("<<"))) continue;+ const bytes = literal ? literalBytes(text) : hexBytes(text);+ let glyphs = shown.get(font);+ if (!glyphs) shown.set(font, (glyphs = []));+ for (let k = 0; k < bytes.length; k += 2)+ glyphs.push((bytes[k] << 8) | (bytes[k + 1] ?? 0));+ }+ return shown;+}++async function scanAllContent(+ pdf: RawPdf,+ dicts: Dict[],+): Promise<ScannedStream[]> {+ const out: ScannedStream[] = [];+ for (const pageNum of pdf.pageNumbers()) {+ const body = pdf.objectBody(pageNum);+ if (!body) throw new Unreadable();+ if (pdf.contentRefs(body).length === 0) continue;+ const content = await pdf.pageContent(pageNum);+ if (!content) throw new Unreadable();+ out.push(scanContent(content));+ }+ for (const { num, text } of dicts) {+ if (!/\/Subtype\s*\/Form\b/.test(text) && !text.includes("/PatternType"))+ continue;+ const content = await pdf.streamData(num);+ if (!content) throw new Unreadable();+ out.push(scanContent(content));+ }+ return out;+}++function subsetTag(glyphs: Set<number>): string {+ let hash = 2166136261;+ for (const gid of [...glyphs].sort((a, b) => a - b))+ hash = Math.imul(hash ^ gid, 16777619) >>> 0;+ let tag = "";+ for (let i = 0; i < 6; i++) {+ tag += String.fromCharCode(65 + (hash % 26));+ hash = Math.floor(hash / 26) + i * 7919;+ }+ return tag;+}++// ISO 32000-1 9.6.4: a subset font's name carries a six-letter tag.+function tagged(+ pdf: RawPdf,+ num: number,+ key: string,+ tag: string,+): Replacement | null {+ const body = pdf.objectBody(num);+ const name = body && pdf.dictName(body, key);+ if (!body || !name || SUBSET_TAG.test(name)) return null;+ const renamed = setDictEntry(body, key, `/${tag}+${name}`);+ return renamed ? { num, body: fromLatin1(renamed.trim()) } : null;+}++// PDFium writes a width for every glyph the font has; only the used ones are+// ever read, and the full list outweighs a subset font several times over.+function usedWidths(widths: string, used: Set<number>): string | null {+ const tokens = widths.match(/\[|\]|-?\d*\.?\d+/g);+ if (!tokens || tokens[0] !== "[" || tokens[tokens.length - 1] !== "]")+ return null;+ const kept = new Map<number, string>();+ let i = 1;+ while (i < tokens.length - 1) {+ const first = Number(tokens[i]);+ if (!Number.isInteger(first)) return null;+ if (tokens[i + 1] === "[") {+ let gid = first;+ for (i += 2; tokens[i] !== "]"; i++, gid++) {+ if (tokens[i] === undefined || tokens[i] === "[") return null;+ if (used.has(gid)) kept.set(gid, tokens[i]);+ }+ i += 1;+ } else {+ const last = Number(tokens[i + 1]);+ const width = tokens[i + 2];+ if (!Number.isInteger(last) || width === undefined || width === "]")+ return null;+ for (const gid of used)+ if (gid >= first && gid <= last) kept.set(gid, width);+ i += 3;+ }+ }+ const sorted = [...kept].sort((a, b) => a[0] - b[0]);+ return `[${sorted.map(([gid, width]) => `${gid} [${width}]`).join(" ")}]`;+}++function retitledCidFont(+ pdf: RawPdf,+ dicts: Dict[],+ num: number,+ tag: string,+ used: Set<number>,+): Replacement[] {+ const renamed = tagged(pdf, num, "BaseFont", tag);+ const body = renamed ? toLatin1(renamed.body) : pdf.objectBody(num)?.trim();+ const widths = body ? pdf.resolve(body, "W") : null;+ const trimmed = widths === null ? null : usedWidths(widths, used);+ const updated =+ body && trimmed !== null ? setDictEntry(body, "W", trimmed) : null;+ if (!body || !updated) return renamed ? [renamed] : [];+ const out: Replacement[] = [{ num, body: fromLatin1(updated) }];+ // The array moves inline; an indirect one would otherwise stay in the file+ // at full size with nothing pointing at it.+ const indirect = pdf.dictRef(body, "W");+ const shared = dicts.some(+ (d) => d.num !== num && pdf.dictRef(d.text, "W") === indirect,+ );+ if (indirect !== null && !shared)+ out.push({ num: indirect, body: fromLatin1("null") });+ return out;+}++function objectEnd(pdf: RawPdf, num: number, start: number): number {+ const body = pdf.objectBody(num);+ if (!body) return -1;+ const stream = /stream\r?\n/.exec(body);+ if (!stream) return pdf.src.indexOf("endobj", start);+ const length = pdf.dictInt(body.slice(0, stream.index), "Length");+ if (length === null) return -1;+ return pdf.src.indexOf(+ "endobj",+ start + stream.index + stream[0].length + length,+ );+}++// Rewrites the file in place instead of appending a revision: an appended+// revision keeps the old object, and the old object is the megabytes this pass+// exists to drop. Only a single classic cross-reference table is rewritten.+function replaceObjects(+ pdf: RawPdf,+ replacements: Replacement[],+): Uint8Array | null {+ const xref = pdf.startXref;+ if (pdf.src.slice(xref, xref + 4) !== "xref") return null;+ const tail = pdf.src.slice(xref);+ const trailerAt = tail.indexOf("trailer");+ const startxrefAt = tail.lastIndexOf("startxref");+ if (trailerAt < 0 || startxrefAt < trailerAt) return null;+ const trailer = tail.slice(trailerAt, startxrefAt);+ if (/\/(Prev|XRefStm)\b/.test(trailer)) return null;++ const spans: Array<{+ start: number;+ end: number;+ bytes: Uint8Array;+ delta: number;+ }> = [];+ for (const { num, body } of replacements) {+ const start = pdf.bodyOffset(num);+ const end = start < 0 ? -1 : objectEnd(pdf, num, start);+ if (end < 0 || end > xref) return null;+ const bytes = concatBytes([fromLatin1("\n"), body, fromLatin1("\n")]);+ spans.push({ start, end, bytes, delta: bytes.length - (end - start) });+ }+ spans.sort((a, b) => a.start - b.start);+ const shifted = (offset: number): number =>+ spans.reduce((at, s) => (s.start < offset ? at + s.delta : at), offset);++ const parts: Uint8Array[] = [];+ let cursor = 0;+ for (const span of spans) {+ if (span.start < cursor) return null;+ parts.push(pdf.bytes.subarray(cursor, span.start), span.bytes);+ cursor = span.end;+ }+ parts.push(pdf.bytes.subarray(cursor, xref));+ const table = tail+ .slice(0, trailerAt)+ .replace(+ /(\d{10}) (\d{5}) n/g,+ (_entry, offset: string, generation: string) =>+ `${String(shifted(parseInt(offset, 10))).padStart(10, "0")} ${generation} n`,+ );+ parts.push(+ fromLatin1(`${table}${trailer}startxref\n${shifted(xref)}\n%%EOF\n`),+ );+ return concatBytes(parts);+}++/**+ * Replace each of `fontFiles` that the saved file embeds whole with a copy+ * holding only the glyphs the file's content draws. `fontFiles` are the exact+ * font programs embedded during this session; fonts `opened`, the file as it+ * was opened, already had are never touched.+ *+ * Must run on the bytes PDFium wrote, before any pass appends a revision: it+ * rewrites the cross-reference table in place. Never throws and never guesses:+ * whenever a font's use or a content stream cannot be read with certainty, that+ * font (or the whole file) is returned unchanged, which only costs size.+ */+export async function subsetEmbeddedFonts(+ bytes: Uint8Array,+ fontFiles: readonly Uint8Array[],+ opened: Uint8Array = new Uint8Array(0),+): Promise<Uint8Array> {+ if (fontFiles.length === 0) return bytes;+ try {+ const added = await newToDocument(opened, fontFiles);+ if (added.length === 0) return bytes;+ const pdf = await RawPdf.parse(bytes);+ if (!pdf || pdf.encrypted || pdf.usesXrefStream) return bytes;+ const dicts = collectDicts(pdf);+ const embedded = await findFontFiles(pdf, dicts, added);+ if (embedded.size === 0) return bytes;+ const streams = await scanAllContent(pdf, dicts);++ const replacements: Replacement[] = [];+ for (const [fileNum, file] of embedded) {+ const users = fontUsers(pdf, dicts, fileNum);+ if (!users) continue;+ const names = resourceNames(dicts, users.type0);+ const used = new Set<number>([0]);+ for (const stream of streams) {+ for (const [font, glyphs] of stream) {+ if (font !== UNKNOWN_FONT && !names.has(font)) continue;+ for (const gid of glyphs) used.add(gid);+ }+ }+ const subset = subsetTrueType(file, used);+ if (!subset || subset.length > file.length * WORTHWHILE_RATIO) continue;+ const packed = await deflate(subset);+ replacements.push({+ num: fileNum,+ body: packed+ ? streamObject(+ `<< /Length1 ${subset.length} /Filter /FlateDecode >>`,+ packed,+ )+ : streamObject(`<< /Length1 ${subset.length} >>`, subset),+ });+ const tag = subsetTag(used);+ const renames = [+ ...users.type0.map((n) => tagged(pdf, n, "BaseFont", tag)),+ ...users.cidFonts.flatMap((n) =>+ retitledCidFont(pdf, dicts, n, tag, used),+ ),+ ...users.descriptors.map((n) => tagged(pdf, n, "FontName", tag)),+ ];+ for (const rename of renames) if (rename) replacements.push(rename);+ }+ if (replacements.length === 0) return bytes;+ return replaceObjects(pdf, replacements) ?? bytes;+ } catch {+ return bytes;+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.tsindex d1f78f15ff..7d9eca8018 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts@@ -317,6 +317,11 @@ export class RawPdf {return this.objects.get(num)?.offset ?? -1;}+ /** The numbers of every object the file's index holds, ascending. */+ objectNumbers(): number[] {+ return [...this.objects.keys()].filter((n) => n > 0).sort((x, y) => x - y);+ }+/** `/Key 12 0 R` -> 12. */dictRef(body: string, key: string): number | null {const span = this.valueSpan(body, key);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.tsindex c351413357..8e3d5c6e08 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts@@ -184,6 +184,7 @@ export function loadDeviceFontInto(m.pdfium.wasmExports.free(ptr);return 0;}+ doc.recordEmbeddedFontFile(bytes);doc.registerOwnedFont(new FontRef({id,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.tsindex 6c47dde1ee..11ac63b016 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts@@ -16,6 +16,7 @@ import { nameArtifactKinds } from "@editor/tools/pdfTextEditor/pdfdoc/passes/namimport { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";import { setDocumentLanguage } from "@editor/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage";import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";+import { subsetEmbeddedFonts } from "@editor/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts";import { PdfiumSave } from "@editor/tools/pdfTextEditor/pdfium/PdfiumSave";import { writesArtifactKinds } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {@@ -143,6 +144,15 @@ async function serializeEdits(// so reading first always yielded an empty list and silently skipped the// shading repair on the first save after an edit.let bytes = PdfiumSave.serialize(doc, { incremental });+ // First, while the file is still exactly what PDFium wrote. Skipped for an+ // incremental save, whose earlier bytes a signature covers.+ if (!incremental) {+ bytes = await subsetEmbeddedFonts(+ bytes,+ doc.embeddedFontFiles(),+ doc.openedBytes,+ );+ }const regenerated = doc.regeneratedPages();if (regenerated.length > 0 && doc.openedBytes.length > 0) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.tsindex c8f513750c..1c15170767 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts@@ -100,6 +100,7 @@ export function loadFallbackFontInto(doc: EditorDocument): number {m.pdfium.wasmExports.free(ptr);return 0;}+ doc.recordEmbeddedFontFile(bytes);doc.registerOwnedFont(new FontRef({id: FALLBACK_FONT_ID,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.tsnew file mode 100644index 0000000000..4f2c3387b4--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.ts@@ -0,0 +1,342 @@+import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";++/**+ * Cut a TrueType font down to the glyphs a document uses, WITHOUT renumbering+ * them. Text in a PDF addresses these fonts by glyph id, so every kept glyph+ * must stay at its id: unused glyphs become empty outlines rather than being+ * removed.+ */++// What a PDF viewer needs to draw the font, plus the tables that identify it.+// Layout, bitmap and signature tables are dropped: a PDF never consults them.+const KEPT_TABLES = new Set([+ "head",+ "hhea",+ "maxp",+ "loca",+ "glyf",+ "hmtx",+ "cvt ",+ "fpgm",+ "prep",+ "cmap",+ "OS/2",+ "name",+ "post",+ "gasp",+]);+const REQUIRED_TABLES = ["head", "hhea", "maxp", "loca", "glyf", "hmtx"];++const TTC_TAG = 0x74746366;+const MORE_COMPONENTS = 0x0020;+const ARGS_ARE_WORDS = 0x0001;+const HAS_SCALE = 0x0008;+const HAS_XY_SCALE = 0x0040;+const HAS_TWO_BY_TWO = 0x0080;+const CHECKSUM_MAGIC = 0xb1b0afba;+const HEAD_CHECKSUM_ADJUSTMENT = 8;+const HEAD_LOCA_FORMAT = 50;+const MAXP_NUM_GLYPHS = 4;+const HHEA_NUM_H_METRICS = 34;+const POST_HEADER = 32;+const POST_NO_GLYPH_NAMES = 0x00030000;+const SHORT_LOCA_LIMIT = 0x1fffe;++interface Table {+ offset: number;+ length: number;+}++function readTables(dv: DataView): Map<string, Table> | null {+ if (dv.byteLength < 12 || dv.getUint32(0) === TTC_TAG) return null;+ const count = dv.getUint16(4);+ const tables = new Map<string, Table>();+ for (let i = 0; i < count; i++) {+ const rec = 12 + i * 16;+ if (rec + 16 > dv.byteLength) return null;+ const tag = String.fromCharCode(+ dv.getUint8(rec),+ dv.getUint8(rec + 1),+ dv.getUint8(rec + 2),+ dv.getUint8(rec + 3),+ );+ const offset = dv.getUint32(rec + 8);+ const length = dv.getUint32(rec + 12);+ if (offset + length > dv.byteLength) return null;+ tables.set(tag, { offset, length });+ }+ return tables;+}++function readLoca(+ dv: DataView,+ loca: Table,+ long: boolean,+ numGlyphs: number,+): number[] | null {+ const width = long ? 4 : 2;+ if (loca.length < (numGlyphs + 1) * width) return null;+ const offsets: number[] = [];+ for (let i = 0; i <= numGlyphs; i++) {+ const at = loca.offset + i * width;+ offsets.push(long ? dv.getUint32(at) : dv.getUint16(at) * 2);+ }+ return offsets;+}++// A composite glyph draws other glyphs by id, so they must be kept with it.+function componentsOf(dv: DataView, start: number, end: number): number[] {+ if (end - start < 10 || dv.getInt16(start) >= 0) return [];+ const out: number[] = [];+ let at = start + 10;+ while (at + 4 <= end) {+ const flags = dv.getUint16(at);+ out.push(dv.getUint16(at + 2));+ at += 4 + (flags & ARGS_ARE_WORDS ? 4 : 2);+ if (flags & HAS_SCALE) at += 2;+ else if (flags & HAS_XY_SCALE) at += 4;+ else if (flags & HAS_TWO_BY_TWO) at += 8;+ if (!(flags & MORE_COMPONENTS)) break;+ }+ return out;+}++function closeOverComponents(+ dv: DataView,+ glyf: Table,+ loca: number[],+ wanted: Iterable<number>,+): Set<number> | null {+ const numGlyphs = loca.length - 1;+ const kept = new Set<number>([0]);+ const queue: number[] = [];+ for (const gid of wanted) {+ if (gid > 0 && gid < numGlyphs && !kept.has(gid)) {+ kept.add(gid);+ queue.push(gid);+ }+ }+ queue.push(0);+ while (queue.length > 0) {+ const gid = queue.pop()!;+ const start = glyf.offset + loca[gid];+ const end = glyf.offset + loca[gid + 1];+ if (end < start || end > glyf.offset + glyf.length) return null;+ for (const part of componentsOf(dv, start, end)) {+ if (part < numGlyphs && !kept.has(part)) {+ kept.add(part);+ queue.push(part);+ }+ }+ }+ return kept;+}++// A cmap left pointing at emptied glyphs would let an editor type characters+// that then draw as nothing, so it is rebuilt to cover only the kept glyphs.+function buildCmap(+ mapping: Map<number, number>,+ kept: Set<number>,+): Uint8Array {+ const pairs = [...mapping]+ .filter(([, gid]) => gid > 0 && kept.has(gid))+ .sort((a, b) => a[0] - b[0]);+ const groups: Array<[number, number, number]> = [];+ for (const [cp, gid] of pairs) {+ const last = groups[groups.length - 1];+ if (last && cp === last[1] + 1 && gid === last[2] + (cp - last[0])) {+ last[1] = cp;+ } else {+ groups.push([cp, cp, gid]);+ }+ }+ const header = 4 + 2 * 8;+ const subtable = 16 + groups.length * 12;+ const out = new Uint8Array(header + subtable);+ const dv = new DataView(out.buffer);+ dv.setUint16(2, 2);+ dv.setUint16(4, 0); // Unicode platform, full repertoire+ dv.setUint16(6, 4);+ dv.setUint32(8, header);+ dv.setUint16(12, 3); // Windows platform, UCS-4+ dv.setUint16(14, 10);+ dv.setUint32(16, header);+ dv.setUint16(header, 12);+ dv.setUint32(header + 4, subtable);+ dv.setUint32(header + 12, groups.length);+ groups.forEach(([start, end, gid], i) => {+ const at = header + 16 + i * 12;+ dv.setUint32(at, start);+ dv.setUint32(at + 4, end);+ dv.setUint32(at + 8, gid);+ });+ return out;+}++// hmtx holds a full metric for the first `numberOfHMetrics` glyphs and only a+// side bearing for the rest; both runs are cut to the new glyph count.+function truncatedMetrics(+ hhea: Uint8Array,+ hmtx: Uint8Array,+ glyphCount: number,+): Uint8Array | null {+ if (hhea.length < HHEA_NUM_H_METRICS + 2) return null;+ const view = new DataView(hhea.buffer, hhea.byteOffset, hhea.byteLength);+ const full = view.getUint16(HHEA_NUM_H_METRICS);+ const keptFull = Math.min(full, glyphCount);+ const bearings = glyphCount - keptFull;+ if (full === 0 || hmtx.length < full * 4 + bearings * 2) return null;+ const out = new Uint8Array(keptFull * 4 + bearings * 2);+ out.set(hmtx.subarray(0, keptFull * 4));+ out.set(hmtx.subarray(full * 4, full * 4 + bearings * 2), keptFull * 4);+ view.setUint16(HHEA_NUM_H_METRICS, keptFull);+ return out;+}++function pad4(n: number): number {+ return (n + 3) & ~3;+}++function checksum(bytes: Uint8Array): number {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let sum = 0;+ const whole = bytes.length & ~3;+ for (let i = 0; i < whole; i += 4) sum = (sum + dv.getUint32(i)) >>> 0;+ let tail = 0;+ for (let i = whole; i < bytes.length; i++)+ tail |= bytes[i] << (24 - (i - whole) * 8);+ return (sum + (tail >>> 0)) >>> 0;+}++function assemble(+ sfntVersion: number,+ tables: Map<string, Uint8Array>,+): Uint8Array {+ const tags = [...tables.keys()].sort();+ const count = tags.length;+ const entrySelector = Math.floor(Math.log2(count));+ const searchRange = 2 ** entrySelector * 16;+ const directory = 12 + count * 16;+ let size = directory;+ for (const tag of tags) size += pad4(tables.get(tag)!.length);+ const out = new Uint8Array(size);+ const dv = new DataView(out.buffer);+ dv.setUint32(0, sfntVersion);+ dv.setUint16(4, count);+ dv.setUint16(6, searchRange);+ dv.setUint16(8, entrySelector);+ dv.setUint16(10, count * 16 - searchRange);+ let at = directory;+ let headAt = -1;+ tags.forEach((tag, i) => {+ const data = tables.get(tag)!;+ const rec = 12 + i * 16;+ for (let k = 0; k < 4; k++) out[rec + k] = tag.charCodeAt(k);+ dv.setUint32(rec + 4, checksum(data));+ dv.setUint32(rec + 8, at);+ dv.setUint32(rec + 12, data.length);+ out.set(data, at);+ if (tag === "head") headAt = at;+ at += pad4(data.length);+ });+ dv.setUint32(+ headAt + HEAD_CHECKSUM_ADJUSTMENT,+ (CHECKSUM_MAGIC - checksum(out)) >>> 0,+ );+ return out;+}++/**+ * The font with only `usedGlyphs` (and the glyphs they are built from) still+ * drawn, each at its original glyph id. Null when the font is not a single+ * TrueType-outline face this can rewrite safely; the caller then keeps the+ * font whole.+ */+export function subsetTrueType(+ font: Uint8Array,+ usedGlyphs: Iterable<number>,+): Uint8Array | null {+ try {+ const dv = new DataView(font.buffer, font.byteOffset, font.byteLength);+ const tables = readTables(dv);+ if (!tables || REQUIRED_TABLES.some((tag) => !tables.has(tag))) return null;+ const head = tables.get("head")!;+ const glyf = tables.get("glyf")!;+ if (head.length < 54 || tables.get("maxp")!.length < 6) return null;+ const long = dv.getInt16(head.offset + HEAD_LOCA_FORMAT) !== 0;+ const numGlyphs = dv.getUint16(+ tables.get("maxp")!.offset + MAXP_NUM_GLYPHS,+ );+ const loca = readLoca(dv, tables.get("loca")!, long, numGlyphs);+ const mapping = parseTrueTypeCmap(font);+ if (!loca || !mapping) return null;+ const kept = closeOverComponents(dv, glyf, loca, usedGlyphs);+ if (!kept) return null;++ // Glyph ids past the last kept one address nothing, so the per-glyph tables+ // stop there instead of carrying an entry for every glyph the font had.+ const glyphCount = Math.max(...kept) + 1;+ const newLoca: number[] = [0];+ const pieces: Uint8Array[] = [];+ let size = 0;+ for (let gid = 0; gid < glyphCount; gid++) {+ if (kept.has(gid) && loca[gid + 1] > loca[gid]) {+ const data = font.subarray(+ glyf.offset + loca[gid],+ glyf.offset + loca[gid + 1],+ );+ const padded = new Uint8Array(pad4(data.length));+ padded.set(data);+ pieces.push(padded);+ size += padded.length;+ }+ newLoca.push(size);+ }+ if (!long && size > SHORT_LOCA_LIMIT) return null;+ const newGlyf = new Uint8Array(size);+ let at = 0;+ for (const piece of pieces) {+ newGlyf.set(piece, at);+ at += piece.length;+ }+ const locaBytes = new Uint8Array(newLoca.length * (long ? 4 : 2));+ const locaView = new DataView(locaBytes.buffer);+ newLoca.forEach((offset, i) => {+ if (long) locaView.setUint32(i * 4, offset);+ else locaView.setUint16(i * 2, offset / 2);+ });++ const out = new Map<string, Uint8Array>();+ for (const [tag, table] of tables) {+ if (!KEPT_TABLES.has(tag)) continue;+ out.set(tag, font.slice(table.offset, table.offset + table.length));+ }+ out.set("glyf", newGlyf);+ out.set("loca", locaBytes);+ out.set("cmap", buildCmap(mapping, kept));+ const hmtx = truncatedMetrics(+ out.get("hhea")!,+ out.get("hmtx")!,+ glyphCount,+ );+ if (!hmtx) return null;+ out.set("hmtx", hmtx);+ new DataView(out.get("maxp")!.buffer).setUint16(+ MAXP_NUM_GLYPHS,+ glyphCount,+ );+ const post = out.get("post");+ if (post && post.length >= POST_HEADER) {+ const header = post.slice(0, POST_HEADER);+ new DataView(header.buffer).setUint32(0, POST_NO_GLYPH_NAMES);+ out.set("post", header);+ }+ new DataView(out.get("head")!.buffer).setUint32(+ HEAD_CHECKSUM_ADJUSTMENT,+ 0,+ );+ return assemble(dv.getUint32(0), out);+ } catch {+ return null;+ }+}