#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
Fix how the PDF text editor embeds fonts when saving (#8908)
Anthony Stirling47b066a67880
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfRevision.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfRevision.test.tsindex 6e2e067fb6..5072f1f8a7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfRevision.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfRevision.test.ts@@ -5,9 +5,11 @@ import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";import {appendRevision,plainObject,+ replaceObjects,streamObject,} from "@editor/tools/pdfTextEditor/pdfdoc/revision";import {+ buildClassicPdf,buildXrefStreamPdf,singleContentPdf,streamBody,@@ -148,3 +150,67 @@ describe("appendRevision", () => {expect(appendRevision(pdf as RawPdf, [])).toBe(original);});});++describe("replaceObjects", () => {+ it("rewrites objects in place and shifts the offsets after them", async () => {+ const pdf = (await RawPdf.parse(singleContentPdf()))!;+ const longer = "BT /F1 12 Tf (a much longer line of text) Tj ET";+ const out = replaceObjects(pdf, [+ { num: 4, body: streamObject("<< >>", fromLatin1(longer)) },+ ])!;++ const reparsed = (await RawPdf.parse(out))!;+ expect(toLatin1((await reparsed.pageContent(3))!)).toContain(longer);+ expect(reparsed.objectBody(5)).toContain("/Helvetica");+ expect(toLatin1(out)).not.toContain("/Prev");+ expect(out.length).toBeGreaterThan(pdf.bytes.length);+ });++ it("replaces only the object whose dictionary holds a (stream) string", async () => {+ const pdf = (await RawPdf.parse(+ buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [] /Count 0 >>" },+ { num: 3, body: "<< /Title (stream) >>" },+ { num: 4, body: streamBody("", "data") },+ { num: 5, body: "<< /Kept true >>" },+ ],+ 1,+ ),+ ))!;++ const reparsed = (await RawPdf.parse(+ replaceObjects(pdf, [{ num: 3, body: plainObject("<< /Title (x) >>") }])!,+ ))!;++ expect(reparsed.objectBody(3)).toContain("(x)");+ expect(toLatin1((await reparsed.streamData(4))!)).toBe("data");+ expect(reparsed.objectBody(5)).toContain("/Kept true");+ });++ it("declines a file with more than one cross-reference section", async () => {+ const pdf = (await RawPdf.parse(singleContentPdf()))!;+ const updated = (await RawPdf.parse(+ appendRevision(pdf, [{ num: 6, body: plainObject("<< >>") }])!,+ ))!;+ expect(+ replaceObjects(updated, [{ num: 1, body: plainObject("<< >>") }]),+ ).toBeNull();+ });++ it("declines a cross-reference stream", async () => {+ const pdf = (await RawPdf.parse(+ buildXrefStreamPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [] /Count 0 >>" },+ ],+ 1,+ ),+ ))!;+ expect(+ replaceObjects(pdf, [{ num: 2, body: plainObject("<< >>") }]),+ ).toBeNull();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.tsindex 7c75872781..db85f71d17 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/subsetEmbeddedFonts.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { readFile } from "node:fs/promises";import path from "node:path";+import { deflateSync } from "node:zlib";import { describe, expect, test } from "vitest";import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";import { subsetEmbeddedFonts } from "@editor/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts";@@ -62,6 +63,7 @@ interface PdfOptions {/** The page's /Font entry, in place of the inline `<< /F1 5 0 R >>`. */fonts?: string;info?: string;+ descriptorEntries?: string;/** Body of an object 11 added after the others. */extra?: string;}@@ -84,7 +86,7 @@ function pdfWithFont(font: Uint8Array, options: PdfOptions): Uint8Array {`<< /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 >>",+ `<< /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${options.descriptorEntries ?? ""} >>`,),(() => {const headPart = latin1(@@ -171,6 +173,15 @@ describe("subsetTrueType", () => {expect(glyph(subset, base).length).toBeGreaterThan(0);});+ test("keeps a font whole when its licence forbids subsetting", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const os2 = table(font, "OS/2")!;+ const fsType = new DataView(os2.buffer, os2.byteOffset + 8, 2);+ fsType.setUint16(0, fsType.getUint16(0) | 0x0100);++ expect(subsetTrueType(font, gidsOf(font, "Hello"))).toBeNull();+ });+test("declines a file that is not a TrueType font", () => {expect(subsetTrueType(new Uint8Array([1, 2, 3, 4]), [1])).toBeNull();});@@ -210,6 +221,21 @@ describe("subsetEmbeddedFonts", () => {expect(reread.objectBody(10)!.trim()).toBe("null");});+ test("keeps the space's width when words are drawn without one", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const [space] = gidsOf(font, " ");+ const pdf = pdfWithFont(font, {+ content: `BT /F1 12 Tf <${hex(gidsOf(font, "we"))}> Tj 20 0 Td <${hex(gidsOf(font, "want"))}> Tj ET`,+ });++ const out = await subsetEmbeddedFonts(pdf, [font]);++ const reread = (await RawPdf.parse(out))!;+ const widths = reread.valueSpan(reread.objectBody(6)!, "W")!.text;+ expect(widths).toContain(`${space} [${500 + space}]`);+ expect(parseTrueTypeCmap(await fontFileIn(out))!.get(0x20)).toBe(space);+ });+test("counts only the text shown in the embedded font", async () => {const font = new Uint8Array(await readFile(FONT));const [h] = gidsOf(font, "H");@@ -325,6 +351,38 @@ describe("subsetEmbeddedFonts", () => {},);+ test("drops the CIDSet that still lists the emptied glyphs", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET",+ descriptorEntries: " /CIDSet 11 0 R",+ extra: "<< /Length 2 >>\nstream\n\u00ff\u00ff\nendstream",+ });++ const reread = (await RawPdf.parse(+ await subsetEmbeddedFonts(pdf, [font]),+ ))!;++ const descriptor = reread.objectBody(7)!;+ expect(reread.valueSpan(descriptor, "CIDSet")).toBeNull();+ expect(reread.dictName(descriptor, "FontName")).toMatch(+ /^[A-Z]{6}\+Carlito$/,+ );+ });++ test("still subsets when an object stream's predictor rows are too wide to allocate", async () => {+ const font = new Uint8Array(await readFile(FONT));+ const packed = String.fromCharCode(...deflateSync(Buffer.from("1 0 ")));+ const pdf = pdfWithFont(font, {+ content: "BT /F1 12 Tf <0001> Tj ET",+ extra: `<< /Type /ObjStm /N 1 /First 4 /Filter /FlateDecode /DecodeParms << /Predictor 12 /Columns 99999999999999999 >> /Length ${packed.length} >>\nstream\n${packed}\nendstream`,+ });++ 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, {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.tsindex e4f635fe55..65694f70bd 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts@@ -3,6 +3,10 @@ import type {CharcodeResolveResult,ResolverContext,} from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";+import {+ readTableDirectory,+ SFNT_HEADER_SIZE,+} from "@editor/tools/pdfTextEditor/util/sfnt";import { sha256Hex } from "@editor/tools/pdfTextEditor/util/sha256";import {SCRATCH,@@ -159,7 +163,7 @@ export function parseTrueTypeCmap(bytes: Uint8Array,): Map<number, number> | null {const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);- if (bytes.length < 12) return null;+ if (bytes.length < SFNT_HEADER_SIZE) return null;// sfnt header: first 4 bytes are the scaler type// (0x00010000 for TrueType, 'OTTO' for OpenType/CFF, 'true', 'typ1').@@ -171,19 +175,7 @@ export function parseTrueTypeCmap(scaler === 0x74797031; // 'typ1'if (!isOpenTypeCff && !isTrueType) return null;- const numTables = dv.getUint16(4);- const tableRecordStart = 12;- // Find the 'cmap' table record.- let cmapOffset = 0;- for (let i = 0; i < numTables; i++) {- const recordOffset = tableRecordStart + i * 16;- if (recordOffset + 16 > bytes.length) return null;- const tag = dv.getUint32(recordOffset);- if (tag === CMAP_TABLE_TAG) {- cmapOffset = dv.getUint32(recordOffset + 8);- break;- }- }+ const cmapOffset = readTableDirectory(dv)?.get("cmap")?.offset ?? 0;if (cmapOffset === 0 || cmapOffset + 4 > bytes.length) return null;const numSubtables = dv.getUint16(cmapOffset + 2);@@ -278,9 +270,6 @@ function parseFormat4(return out;}-/** Big-endian "cmap" as an sfnt table tag. */-const CMAP_TABLE_TAG = 0x636d6170;-// Hard cap on entries built from any one cmap.const MAX_CMAP_ENTRIES = 200_000;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.tsindex 05b1c0b6a4..037b985b08 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts@@ -42,7 +42,7 @@ export class DuplicateRunCommand implements Command {Math.max(4, src.fontSize),);if (!newPtr) return;- // Base-14 renders only WinAnsi: drop other code points rather than persist them as U+00FF tofu.+ // Base-14 can only render WinAnsi; drop other code points, not U+00FF tofu.const textPtr = writeUtf16(m,sanitizeForBase14(src.text.replace(/\r?\n/g, " ")),diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.tsindex 94ecc4e2f7..35fc60d1d7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts@@ -731,8 +731,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {// Emit ONE word at (x, y) and return its pointer (0 on failure).const emitWord = (text: string, x: number): number => {- // base-14 can only render WinAnsi; drop the rest so PDFium never emits- // U+00FF tofu.+ // base-14 can only render WinAnsi; drop the rest, not U+00FF tofu.const base14Text = sanitizeForBase14(text);const newBase14 = (): number => {const ptr = m.FPDFPageObj_NewTextObj(opts.doc.docPtr, family, size);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.tsindex 318d079613..c12390a77e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -93,7 +93,7 @@ export class EditorDocument {private readonly fileStructure: FileStructure | null;private marked: boolean;private readonly ownedFonts: Map<string, FontRef>;- private readonly embeddedFonts: Uint8Array[] = [];+ private readonly _embeddedFontFiles: 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@@ -763,17 +763,14 @@ 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.- */+ /** Record a font file PDFium embeds whole, so the save can subset it. */recordEmbeddedFontFile(bytes: Uint8Array): void {- this.embeddedFonts.push(bytes);+ this._embeddedFontFiles.push(bytes);}/** The exact font files embedded into this document during the session. */embeddedFontFiles(): readonly Uint8Array[] {- return this.embeddedFonts;+ return this._embeddedFontFiles;}registerOwnedFont(font: FontRef): void {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/bytes.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/bytes.tsindex 48d85bc87e..4b0e8b0804 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/bytes.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/bytes.ts@@ -61,6 +61,7 @@ export function undoPngPredictor(const bpp = Math.max(1, Math.ceil((colors * bpc) / 8));const rowLen = Math.ceil((colors * bpc * columns) / 8);const rows = Math.floor(data.length / (rowLen + 1));+ if (rows < 1) return new Uint8Array(0);const out = new Uint8Array(rows * rowLen);let prev = new Uint8Array(rowLen);for (let r = 0; r < rows; r += 1) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.tsindex da8ad17f40..4deb3086da 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts.ts@@ -1,22 +1,34 @@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 {+ arrayItems,+ RawPdf,+ referencedObject,+ removeDictEntry,+ setDictEntry,+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import {+ replaceObjects,+ streamObject,+ type RevisionObject,+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";+import { stringBytes } from "@editor/tools/pdfTextEditor/pdfdoc/textString";import { subsetTrueType } from "@editor/tools/pdfTextEditor/util/ttfSubset";+import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";// 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 {}+const TAG_LENGTH = 6;+const TAG_LETTERS = 26;+const TAG_SPREAD = 7919;+const FNV_OFFSET_BASIS = 2166136261;+const FNV_PRIME = 16777619;interface Dict {num: number;@@ -30,10 +42,7 @@ interface FontUsers {type0: number[];}-interface Replacement {- num: number;- body: Uint8Array;-}+const SPACE = 0x20;function sameBytes(a: Uint8Array, b: Uint8Array): boolean {if (a.length !== b.length) return false;@@ -41,45 +50,38 @@ function sameBytes(a: Uint8Array, b: Uint8Array): boolean {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) });+ const extent = pdf.objectExtent(num);+ if (extent)+ out.push({ num, text: pdf.src.slice(extent.start, extent.dictEnd) });}return out;}-async function findFontFiles(+// A stream that cannot be decoded counts as matching every same-length file when `matchUnreadable`.+async function matchFontStreams(pdf: RawPdf,dicts: Dict[],files: readonly Uint8Array[],-): Promise<Map<number, Uint8Array>> {- const found = new Map<number, Uint8Array>();+ matchUnreadable: boolean,+): Promise<Array<[number, Uint8Array]>> {+ const matches: Array<[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);+ const data = pdf.encrypted ? null : await pdf.streamData(num);+ for (const file of sameLength)+ if (data ? sameBytes(file, data) : matchUnreadable)+ matches.push([num, file]);}- return found;+ return matches;}-/**- * `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.- */+/** Drop files the opened document already embedded: that copy may serve text this pass never sees. */async function newToDocument(opened: Uint8Array,files: readonly Uint8Array[],@@ -87,22 +89,12 @@ async function newToDocument(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);- }+ const matches = await matchFontStreams(pdf, collectDicts(pdf), files, true);+ const had = new Set(matches.map(([, file]) => 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.+// Only an Identity-mapped CID TrueType font is addressed by glyph id; any other use keeps it whole.function fontUsers(pdf: RawPdf, dicts: Dict[], file: number): FontUsers | null {const descriptors = dicts.filter((d) => pdf.dictRef(d.text, "FontFile2") === file)@@ -118,12 +110,10 @@ function fontUsers(pdf: RawPdf, dicts: Dict[], file: number): FontUsers | null {}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 descendants = pdf.resolve(d.text, "DescendantFonts")?.trim();+ const items = descendants ? arrayItems(descendants) : null;+ const refs = items?.map((item) => referencedObject(item.text)) ?? [];+ if (!refs.some((ref) => ref !== null && cidFonts.includes(ref))) continue;const encoding = pdf.dictName(d.text, "Encoding");if (encoding !== "Identity-H" && encoding !== "Identity-V") return null;type0.push(d.num);@@ -134,8 +124,7 @@ function fontUsers(pdf: RawPdf, dicts: Dict[], file: number): FontUsers | 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.+ // Scan every dictionary: a font map can be indirect, 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]);@@ -144,65 +133,29 @@ function resourceNames(dicts: Dict[], fonts: number[]): Set<string> {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.+// Glyph ids by font resource name; UNKNOWN_FONT holds text shown before any Tf, counted for all.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 {+// `q`/`Q` save and restore the font; null on an inline image, whose raw bytes the tokeniser cannot pass.+function scanContent(content: Uint8Array | null): ScannedStream | null {+ if (!content) return null;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 === "BI") return null;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);+ if (!/^[(<]/.test(text) || text.startsWith("<<")) continue;+ const bytes = stringBytes(text);+ if (!bytes) return null;let glyphs = shown.get(font);if (!glyphs) shown.set(font, (glyphs = []));for (let k = 0; k < bytes.length; k += 2)@@ -214,54 +167,88 @@ function scanContent(content: Uint8Array): ScannedStream {async function scanAllContent(pdf: RawPdf,dicts: Dict[],-): Promise<ScannedStream[]> {+): Promise<ScannedStream[] | null> {const out: ScannedStream[] = [];for (const pageNum of pdf.pageNumbers()) {const body = pdf.objectBody(pageNum);- if (!body) throw new Unreadable();+ if (!body) return null;if (pdf.contentRefs(body).length === 0) continue;- const content = await pdf.pageContent(pageNum);- if (!content) throw new Unreadable();- out.push(scanContent(content));+ const scanned = scanContent(await pdf.pageContent(pageNum));+ if (!scanned) return null;+ out.push(scanned);}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));+ const scanned = scanContent(await pdf.streamData(num));+ if (!scanned) return null;+ out.push(scanned);}return out;}+function usedGlyphs(streams: ScannedStream[], names: Set<string>): Set<number> {+ 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);+ }+ }+ return used;+}+function subsetTag(glyphs: Set<number>): string {- let hash = 2166136261;+ let hash = FNV_OFFSET_BASIS;for (const gid of [...glyphs].sort((a, b) => a - b))- hash = Math.imul(hash ^ gid, 16777619) >>> 0;+ hash = Math.imul(hash ^ gid, FNV_PRIME) >>> 0;let tag = "";- for (let i = 0; i < 6; i++) {- tag += String.fromCharCode(65 + (hash % 26));- hash = Math.floor(hash / 26) + i * 7919;+ for (let i = 0; i < TAG_LENGTH; i++) {+ tag += String.fromCharCode("A".charCodeAt(0) + (hash % TAG_LETTERS));+ hash = Math.floor(hash / TAG_LETTERS) + i * TAG_SPREAD;}return tag;}// ISO 32000-1 9.6.4: a subset font's name carries a six-letter tag.+function withTag(+ pdf: RawPdf,+ body: string,+ key: string,+ tag: string,+): string | null {+ const name = pdf.dictName(body, key);+ if (!name || SUBSET_TAG.test(name)) return null;+ return setDictEntry(body, key, `/${tag}+${name}`);+}+function tagged(pdf: RawPdf,num: number,key: string,tag: string,-): Replacement | null {+): RevisionObject | 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}`);+ const renamed = body && withTag(pdf, body, key, tag);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.+// A CIDSet would still list every glyph the subset emptied.+function retitledDescriptor(+ pdf: RawPdf,+ num: number,+ tag: string,+): RevisionObject | null {+ const body = pdf.objectBody(num);+ if (!body) return null;+ const updated = removeDictEntry(+ withTag(pdf, body, "FontName", tag) ?? body,+ "CIDSet",+ );+ return updated === body ? null : { num, body: fromLatin1(updated.trim()) };+}++// PDFium writes every glyph's width; keep only the used ones, as the full list outweighs the subset.function usedWidths(widths: string, used: Set<number>): string | null {const tokens = widths.match(/\[|\]|-?\d*\.?\d+/g);if (!tokens || tokens[0] !== "[" || tokens[tokens.length - 1] !== "]")@@ -298,7 +285,7 @@ function retitledCidFont(num: number,tag: string,used: Set<number>,-): Replacement[] {+): RevisionObject[] {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;@@ -306,9 +293,8 @@ function retitledCidFont(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 out: RevisionObject[] = [{ num, body: fromLatin1(updated) }];+ // Inline the array, or the indirect one stays in the file at full size, unreferenced.const indirect = pdf.dictRef(body, "W");const shared = dicts.some((d) => d.num !== num && pdf.dictRef(d.text, "W") === indirect,@@ -318,137 +304,69 @@ function retitledCidFont(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(+function renamedFontObjects(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);+ dicts: Dict[],+ users: FontUsers,+ used: Set<number>,+): RevisionObject[] {+ 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) => retitledDescriptor(pdf, n, tag)),+ ];+ return renames.filter((rename) => rename !== null);+}- 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);+async function fontFileObject(+ num: number,+ subset: Uint8Array,+): Promise<RevisionObject> {+ const packed = await deflate(subset);+ return {+ num,+ body: packed+ ? streamObject(+ `<< /Length1 ${subset.length} /Filter /FlateDecode >>`,+ packed,+ )+ : streamObject(`<< /Length1 ${subset.length} >>`, subset),+ };}-/**- * 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.- */+/** Subset session-embedded fonts to their used glyphs; run before any appended revision, else returns `bytes`. */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 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 = new Map(await matchFontStreams(pdf, dicts, added, false));+ if (embedded.size === 0) return bytes;+ const streams = await scanAllContent(pdf, dicts);+ if (!streams) return bytes;- 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;+ const replacements: RevisionObject[] = [];+ for (const [fileNum, file] of embedded) {+ const users = fontUsers(pdf, dicts, fileNum);+ if (!users) continue;+ const used = usedGlyphs(streams, resourceNames(dicts, users.type0));+ // Words drawn one per object never show a space, but readers still need its width to tell the words apart.+ const space = parseTrueTypeCmap(file)?.get(SPACE);+ if (space) used.add(space);+ const subset = subsetTrueType(file, used);+ if (!subset || subset.length > file.length * WORTHWHILE_RATIO) continue;+ replacements.push(+ await fontFileObject(fileNum, subset),+ ...renamedFontObjects(pdf, dicts, users, used),+ );}+ if (replacements.length === 0) return bytes;+ return replaceObjects(pdf, replacements) ?? bytes;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.tsindex 7d9eca8018..2b08840706 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts@@ -36,6 +36,15 @@ export interface ValueSpan {text: string;}+export interface ObjectExtent {+ start: number;+ /** Offset of the `stream` keyword, or the object's end when it has no stream. */+ dictEnd: number;+ stream: { start: number; end: number } | null;+ /** Offset of `endobj`, -1 when none follows the stream. */+ end: number;+}+export interface NumberTreeEntry {/** The object whose body holds the value. */objNum: number;@@ -459,15 +468,19 @@ export class RawPdf {return null;}- /** Decoded stream payload for an object, or null when unsupported. */- async streamData(num: number): Promise<Uint8Array | null> {- const entry = this.objects.get(num);- if (!entry || entry.offset === undefined) return null;- const body = this.objectBody(num);+ /** Where a top-level object's dictionary, stream payload and `endobj` sit in `src`; null when it has no offset. */+ objectExtent(num: number): ObjectExtent | null {+ const start = this.bodyOffset(num);+ const body = start < 0 ? null : this.objectBody(num);if (body === null) return null;- const kw = body.indexOf("stream");- if (kw < 0) return null;- let dataStart = entry.offset + kw + "stream".length;+ const valueEnd = scanValueEnd(body, skipWhitespace(body, 0));+ const keyword = /^\s*stream\b/.exec(body.slice(valueEnd));+ const kw = keyword ? valueEnd + keyword[0].length - "stream".length : -1;+ if (kw < 0) {+ const end = start + body.length;+ return { start, dictEnd: end, stream: null, end };+ }+ let dataStart = start + kw + "stream".length;if (this.src[dataStart] === "\r") dataStart += 1;if (this.src[dataStart] === "\n") dataStart += 1;@@ -484,7 +497,10 @@ export class RawPdf {// A wrong /Length is common enough in the wild that trusting it blindly// truncates real content; verify against the endstream keyword.const marker = this.src.indexOf("endstream", dataStart);- if (dataEnd < 0 || marker < 0 || dataEnd > marker) {+ const confirmed =+ dataEnd >= 0 &&+ /^\s*endstream/.test(this.src.slice(dataEnd, dataEnd + 16));+ if (!confirmed && (dataEnd < 0 || marker < 0 || dataEnd > marker)) {dataEnd = marker < 0 ? this.bytes.length : marker;while (dataEnd > dataStart &&@@ -493,7 +509,20 @@ export class RawPdf {dataEnd -= 1;}}- let data = this.bytes.subarray(dataStart, dataEnd);+ return {+ start,+ dictEnd: start + kw,+ stream: { start: dataStart, end: dataEnd },+ end: this.src.indexOf("endobj", dataEnd),+ };+ }++ /** Decoded stream payload for an object, or null when unsupported. */+ async streamData(num: number): Promise<Uint8Array | null> {+ const extent = this.objectExtent(num);+ const body = this.objectBody(num);+ if (!extent?.stream || body === null) return null;+ let data = this.bytes.subarray(extent.stream.start, extent.stream.end);const filters = this.filterNames(body);if (filters === null) return null;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.tsindex 53fb8b18e4..41b00b47c5 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts@@ -157,6 +157,58 @@ export function appendRevision(return concatBytes(parts);}+/** Rewrite `objects` in place, for when a new revision would keep the old bytes; null unless the file has one classic xref table. */+export function replaceObjects(+ pdf: RawPdf,+ objects: RevisionObject[],+): Uint8Array | null {+ const xref = pdf.startXref;+ if (xref < 0 || 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 objects) {+ const extent = pdf.objectExtent(num);+ if (!extent || extent.end < 0 || extent.end > xref) return null;+ const { start, end } = extent;+ 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);+}+/** Group sorted object numbers into consecutive runs for xref subsections. */function* runsOf(nums: number[]): Generator<[number, number[]]> {let run: number[] = [];diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.tsindex d3ee228546..d2bcf608b9 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts@@ -38,7 +38,8 @@ export function decodeTextString(token: string): string | null {return String.fromCharCode(...bytes.map(fromPdfDocEncoding));}-function stringBytes(token: string): number[] | null {+/** The raw bytes of a `(literal)` or `<hex>` string token; null when it is neither or is malformed. */+export function stringBytes(token: string): number[] | null {if (token.startsWith("(")) return literalBytes(token);if (token.startsWith("<") && !token.startsWith("<<")) return hexBytes(token);return null;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.tsindex 11ac63b016..c5f3bdd2a3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts@@ -144,8 +144,7 @@ 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.+ // First, on PDFium's exact bytes; skipped for incremental saves, whose bytes a signature covers.if (!incremental) {bytes = await subsetEmbeddedFonts(bytes,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.tsindex 4f2c3387b4..739ba84100 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/ttfSubset.ts@@ -1,14 +1,14 @@import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";+import {+ assembleSfnt,+ pad4,+ readTableDirectory,+ type SfntTable,+} from "@editor/tools/pdfTextEditor/util/sfnt";-/**- * 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.- */+/** Subset a TrueType font without renumbering: PDF text addresses glyphs by id, so unused ones empty. */-// 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.+// Tables a PDF viewer reads to draw and identify the font; layout and bitmap tables are dropped.const KEPT_TABLES = new Set(["head","hhea",@@ -33,44 +33,45 @@ 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_MIN_LENGTH = 54;const HEAD_LOCA_FORMAT = 50;+const MAXP_MIN_LENGTH = 6;const MAXP_NUM_GLYPHS = 4;const HHEA_NUM_H_METRICS = 34;+const LONG_METRIC_SIZE = 4;+const BEARING_SIZE = 2;+const GLYPH_HEADER_SIZE = 10;const POST_HEADER = 32;const POST_NO_GLYPH_NAMES = 0x00030000;const SHORT_LOCA_LIMIT = 0x1fffe;+const CMAP_HEADER_SIZE = 4;+const CMAP_ENCODING_RECORD_SIZE = 8;+const CMAP_FORMAT_12 = 12;+const FORMAT_12_HEADER_SIZE = 16;+const FORMAT_12_GROUP_SIZE = 12;+const PLATFORM_UNICODE = 0;+const UNICODE_FULL_REPERTOIRE = 4;+const PLATFORM_WINDOWS = 3;+const WINDOWS_UCS4 = 10;+const OS2_FS_TYPE = 8;+const FS_TYPE_NO_SUBSETTING = 0x0100;-interface Table {- offset: number;- length: number;+interface GlyphTables {+ glyf: Uint8Array;+ loca: Uint8Array;}-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);+function readTables(dv: DataView): Map<string, SfntTable> | null {+ const tables = readTableDirectory(dv);+ if (!tables || dv.getUint32(0) === TTC_TAG) return null;+ for (const { offset, length } of tables.values())if (offset + length > dv.byteLength) return null;- tables.set(tag, { offset, length });- }return tables;}function readLoca(dv: DataView,- loca: Table,+ loca: SfntTable,long: boolean,numGlyphs: number,): number[] | null {@@ -86,9 +87,9 @@ function readLoca(// 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 [];+ if (end - start < GLYPH_HEADER_SIZE || dv.getInt16(start) >= 0) return [];const out: number[] = [];- let at = start + 10;+ let at = start + GLYPH_HEADER_SIZE;while (at + 4 <= end) {const flags = dv.getUint16(at);out.push(dv.getUint16(at + 2));@@ -103,7 +104,7 @@ function componentsOf(dv: DataView, start: number, end: number): number[] {function closeOverComponents(dv: DataView,- glyf: Table,+ glyf: SfntTable,loca: number[],wanted: Iterable<number>,): Set<number> | null {@@ -132,8 +133,7 @@ function closeOverComponents(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.+// Rebuild the cmap for kept glyphs only, or editors could type characters that draw nothing.function buildCmap(mapping: Map<number, number>,kept: Set<number>,@@ -150,22 +150,22 @@ function buildCmap(groups.push([cp, cp, gid]);}}- const header = 4 + 2 * 8;- const subtable = 16 + groups.length * 12;+ const header = CMAP_HEADER_SIZE + 2 * CMAP_ENCODING_RECORD_SIZE;+ const subtable = FORMAT_12_HEADER_SIZE + groups.length * FORMAT_12_GROUP_SIZE;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.setUint16(4, PLATFORM_UNICODE);+ dv.setUint16(6, UNICODE_FULL_REPERTOIRE);dv.setUint32(8, header);- dv.setUint16(12, 3); // Windows platform, UCS-4- dv.setUint16(14, 10);+ dv.setUint16(12, PLATFORM_WINDOWS);+ dv.setUint16(14, WINDOWS_UCS4);dv.setUint32(16, header);- dv.setUint16(header, 12);+ dv.setUint16(header, CMAP_FORMAT_12);dv.setUint32(header + 4, subtable);dv.setUint32(header + 12, groups.length);groups.forEach(([start, end, gid], i) => {- const at = header + 16 + i * 12;+ const at = header + FORMAT_12_HEADER_SIZE + i * FORMAT_12_GROUP_SIZE;dv.setUint32(at, start);dv.setUint32(at + 4, end);dv.setUint32(at + 8, gid);@@ -173,85 +173,86 @@ function buildCmap(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.+// hmtx has full metrics for numberOfHMetrics glyphs then bearings only; both are cut to the new count.function truncatedMetrics(hhea: Uint8Array,hmtx: Uint8Array,glyphCount: number,-): Uint8Array | null {+): { hmtx: Uint8Array; numberOfHMetrics: number } | 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 full = new DataView(+ hhea.buffer,+ hhea.byteOffset,+ hhea.byteLength,+ ).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;+ const fullSize = full * LONG_METRIC_SIZE;+ const keptSize = keptFull * LONG_METRIC_SIZE;+ if (full === 0 || hmtx.length < fullSize + bearings * BEARING_SIZE)+ return null;+ const out = new Uint8Array(keptSize + bearings * BEARING_SIZE);+ out.set(hmtx.subarray(0, keptSize));+ out.set(+ hmtx.subarray(fullSize, fullSize + bearings * BEARING_SIZE),+ keptSize,+ );+ return { hmtx: out, numberOfHMetrics: keptFull };}-function pad4(n: number): number {- return (n + 3) & ~3;+function rebuildGlyf(+ font: Uint8Array,+ glyf: SfntTable,+ loca: number[],+ kept: Set<number>,+ glyphCount: number,+ long: boolean,+): GlyphTables | null {+ 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);+ });+ return { glyf: newGlyf, loca: locaBytes };}-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 withoutGlyphNames(post: Uint8Array): Uint8Array | null {+ if (post.length < POST_HEADER) return null;+ const header = post.slice(0, POST_HEADER);+ new DataView(header.buffer).setUint32(0, POST_NO_GLYPH_NAMES);+ return header;}-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;+function forbidsSubsetting(dv: DataView, os2: SfntTable | undefined): boolean {+ if (!os2 || os2.length < OS2_FS_TYPE + 2) return false;+ return (dv.getUint16(os2.offset + OS2_FS_TYPE) & FS_TYPE_NO_SUBSETTING) !== 0;}-/**- * 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.- */+/** The font with only usedGlyphs drawn, at their ids; null when it is not one TrueType face or its OS/2 fsType forbids subsetting. */export function subsetTrueType(font: Uint8Array,usedGlyphs: Iterable<number>,@@ -260,82 +261,49 @@ export function subsetTrueType(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;+ if (forbidsSubsetting(dv, tables.get("OS/2"))) return null;const head = tables.get("head")!;+ const maxp = tables.get("maxp")!;const glyf = tables.get("glyf")!;- if (head.length < 54 || tables.get("maxp")!.length < 6) return null;+ if (head.length < HEAD_MIN_LENGTH || maxp.length < MAXP_MIN_LENGTH)+ return null;const long = dv.getInt16(head.offset + HEAD_LOCA_FORMAT) !== 0;- const numGlyphs = dv.getUint16(- tables.get("maxp")!.offset + MAXP_NUM_GLYPHS,- );+ const numGlyphs = dv.getUint16(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.+ // Per-glyph tables stop at the last kept glyph id.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 glyphs = rebuildGlyf(font, glyf, loca, kept, glyphCount, long);+ if (!glyphs) return null;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("glyf", glyphs.glyf);+ out.set("loca", glyphs.loca);out.set("cmap", buildCmap(mapping, kept));- const hmtx = truncatedMetrics(- out.get("hhea")!,- out.get("hmtx")!,- glyphCount,+ const hhea = out.get("hhea")!;+ const metrics = truncatedMetrics(hhea, out.get("hmtx")!, glyphCount);+ if (!metrics) return null;+ out.set("hmtx", metrics.hmtx);+ new DataView(hhea.buffer).setUint16(+ HHEA_NUM_H_METRICS,+ metrics.numberOfHMetrics,);- 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);+ const namelessPost = post && withoutGlyphNames(post);+ if (namelessPost) out.set("post", namelessPost);+ return assembleSfnt(dv.getUint32(0), out);} catch {return null;}