Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Text editor accessibility improvements (#8460)

James Bruntone895c68996b8
diff --git a/frontend/editor/src/core/constants/featureFlags.ts b/frontend/editor/src/core/constants/featureFlags.ts
index f8a72b752f..9c55a4da97 100644
--- a/frontend/editor/src/core/constants/featureFlags.ts
+++ b/frontend/editor/src/core/constants/featureFlags.ts
@@ -5,3 +5,6 @@
// Refill an empty workbench from the tab's last session (survives a provider remount or a reload).
export const WORKBENCH_SESSION_RESTORE: boolean = true;
+
+// Edit image descriptions and decorative markers in the PDF text editor.
+export const ACCESSIBILITY_EDITING: boolean = false;
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
index d228d9cd27..7bdbea03a9 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
@@ -103,7 +103,7 @@ async function typeInto(
},
{ id: runId, text, mode },
);
- await page.waitForTimeout(450);
+ await expect.poll(() => page.evaluate(RUN_ID, text)).not.toBeNull();
}
async function saveAndReopen(page: import("@playwright/test").Page) {
@@ -111,7 +111,7 @@ async function saveAndReopen(page: import("@playwright/test").Page) {
await page.getByTestId("pdf-editor-download").click();
const confirm = page.getByTestId("pdf-editor-save-risk-confirm");
if (await confirm.isVisible().catch(() => false)) await confirm.click();
- const saved = "test-results/tagged-structure.pdf";
+ const saved = test.info().outputPath("tagged-structure.pdf");
await (await downloaded).saveAs(saved);
await page.evaluate(() => {
const w = window as unknown as {
@@ -139,7 +139,6 @@ async function saveAndReopen(page: import("@playwright/test").Page) {
undefined,
{ timeout: 30_000 },
);
- await page.waitForTimeout(1200);
}
test.describe("PDF text editor - tagged documents", () => {
@@ -155,7 +154,9 @@ test.describe("PDF text editor - tagged documents", () => {
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
- await page.waitForTimeout(1800);
+ await expect
+ .poll(() => page.evaluate(RUN_ID, "product line"), { timeout: 30_000 })
+ .not.toBeNull();
expect(await page.evaluate(AUDIT)).toEqual({
untaggedText: 0,
@@ -173,12 +174,16 @@ test.describe("PDF text editor - tagged documents", () => {
await typeInto(page, paragraph!, " Up 4%.", "append");
await saveAndReopen(page);
- expect(await page.evaluate(RUN_ID, "Annual summary")).not.toBeNull();
- expect(await page.evaluate(RUN_ID, "Up 4%.")).not.toBeNull();
- expect(await page.evaluate(AUDIT)).toEqual({
- untaggedText: 0,
- contentMcids: [0, 1, 2],
- treeMcids: [0, 1, 2],
- });
+ await expect
+ .poll(() => page.evaluate(RUN_ID, "Annual summary"))
+ .not.toBeNull();
+ await expect.poll(() => page.evaluate(RUN_ID, "Up 4%.")).not.toBeNull();
+ // The save gives each repeated sequence of an edited run its own MCID, so
+ // the count depends on how many objects the edit emitted. What must hold
+ // is that the originals survive and content and tree still agree.
+ const saved = await page.evaluate(AUDIT);
+ expect(saved.untaggedText).toBe(0);
+ expect(saved.contentMcids).toEqual(saved.treeMcids);
+ expect(saved.contentMcids).toEqual(expect.arrayContaining([0, 1, 2]));
});
});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
new file mode 100644
index 0000000000..e437d4b493
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
@@ -0,0 +1,243 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so the real fixture's object stream would not inflate.
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
+import { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { toLatin1 } from "@app/tools/pdfTextEditor/pdfdoc/bytes";
+import {
+ StructureEditError,
+ applyStructureEdits,
+} from "@app/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import { RawPdf } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ buildClassicPdf,
+ buildXrefStreamPdf,
+ streamBody,
+ type FixtureObject,
+} from "@app/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const TAGGED_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+
+// Two pages. Page 1: a paragraph (MCID 0) and a figure (MCID 1). Page 2: a
+// figure (MCID 0). Element numbers: 10 = P, 11 = figure on page 1, 12 =
+// figure on page 2.
+function objects(parentTree = "<< /Nums [0 [10 0 R 11 0 R] 1 [12 0 R]] >>") {
+ const page = (num: number, content: number, key: number) => ({
+ num,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents ${content} 0 R /StructParents ${key} >>`,
+ });
+ return [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>" },
+ page(3, 5, 0),
+ page(4, 6, 1),
+ {
+ num: 5,
+ body: streamBody(
+ "",
+ "/P <</MCID 0>> BDC EMC /Figure <</MCID 1>> BDC 0 0 10 10 re f EMC",
+ ),
+ },
+ {
+ num: 6,
+ body: streamBody("", "/Figure <</MCID 0>> BDC 0 0 10 10 re f EMC"),
+ },
+ {
+ num: 7,
+ body: `<< /Type /StructTreeRoot /K 9 0 R /ParentTree ${parentTree} /ParentTreeNextKey 2 >>`,
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R 11 0 R 12 0 R] >>",
+ },
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 9 0 R /Pg 3 0 R /K 0 >>",
+ },
+ {
+ num: 11,
+ body: "<< /Type /StructElem /S /Figure /P 9 0 R /Pg 3 0 R /K 1 /Alt (Old one) >>",
+ },
+ {
+ num: 12,
+ body: "<< /Type /StructElem /S /Figure /P 9 0 R /Pg 4 0 R /K 0 >>",
+ },
+ ] satisfies FixtureObject[];
+}
+
+async function elementBody(bytes: Uint8Array, num: number): Promise<string> {
+ const pdf = await RawPdf.parse(bytes);
+ return pdf!.objectBody(num)!;
+}
+
+async function failuresOf(
+ bytes: Uint8Array,
+ edits: Parameters<typeof applyStructureEdits>[1],
+): Promise<string[]> {
+ const error = await applyStructureEdits(bytes, edits).catch((e) => e);
+ expect(error).toBeInstanceOf(StructureEditError);
+ return (error as StructureEditError).failures.map((f) => f.reason);
+}
+
+describe("applyStructureEdits", () => {
+ test("hands back the bytes untouched when there is nothing to write", async () => {
+ const bytes = buildClassicPdf(objects(), 1);
+ expect(await applyStructureEdits(bytes, [])).toBe(bytes);
+ });
+
+ test("sets, replaces and removes /Alt on the elements the MCIDs resolve to", async () => {
+ const bytes = buildClassicPdf(objects(), 1);
+ const out = await applyStructureEdits(bytes, [
+ { pageIndex: 0, mcid: 0, alt: "Intro" },
+ { pageIndex: 0, mcid: 1, alt: null },
+ { pageIndex: 1, mcid: 0, alt: "Second figure" },
+ ]);
+ expect(await elementBody(out, 10)).toContain("/Alt (Intro)");
+ expect(await elementBody(out, 11)).not.toContain("/Alt");
+ expect(await elementBody(out, 12)).toContain("/Alt (Second figure)");
+ });
+
+ test("appends a revision and leaves the original bytes in place", async () => {
+ const bytes = buildClassicPdf(objects(), 1);
+ const out = await applyStructureEdits(bytes, [
+ { pageIndex: 1, mcid: 0, alt: "x" },
+ ]);
+ expect(out.subarray(0, bytes.length)).toEqual(bytes);
+ // Only the one element changed, so only it is appended.
+ const appended = toLatin1(out.subarray(bytes.length));
+ expect(appended.match(/\d+ \d+ obj/g)).toEqual(["12 0 obj"]);
+ });
+
+ test("lets the later of two edits to one element win", async () => {
+ const out = await applyStructureEdits(buildClassicPdf(objects(), 1), [
+ { pageIndex: 0, mcid: 1, alt: "first" },
+ { pageIndex: 0, mcid: 1, alt: "second" },
+ ]);
+ const body = await elementBody(out, 11);
+ expect(body).toContain("/Alt (second)");
+ expect(body).not.toContain("first");
+ });
+
+ test("resolves a ParentTree held by reference, with the page's array by reference", async () => {
+ const tree = [
+ ...objects("20 0 R"),
+ { num: 20, body: "<< /Kids [21 0 R] >>" },
+ { num: 21, body: "<< /Limits [0 1] /Nums [0 22 0 R 1 [12 0 R]] >>" },
+ { num: 22, body: "[10 0 R 11 0 R]" },
+ ];
+ const out = await applyStructureEdits(buildClassicPdf(tree, 1), [
+ { pageIndex: 0, mcid: 1, alt: "Found" },
+ ]);
+ expect(await elementBody(out, 11)).toContain("/Alt (Found)");
+ });
+
+ test("extends a cross-reference-stream file", async () => {
+ const bytes = buildXrefStreamPdf(objects(), 1);
+ const out = await applyStructureEdits(bytes, [
+ { pageIndex: 0, mcid: 1, alt: "Streamed" },
+ ]);
+ expect(await elementBody(out, 11)).toContain("/Alt (Streamed)");
+ expect((await RawPdf.parse(out))?.usesXrefStream).toBe(true);
+ });
+
+ test("names every edit it cannot write, and writes none of them", async () => {
+ const reasons = await failuresOf(buildClassicPdf(objects(), 1), [
+ { pageIndex: 0, mcid: 1, alt: "fine on its own" },
+ { pageIndex: 5, mcid: 0, alt: "x" },
+ { pageIndex: 0, mcid: 7, alt: "x" },
+ ]);
+ expect(reasons).toEqual([
+ "no such page",
+ "no structure element owns this MCID",
+ ]);
+ });
+
+ test("fails for a page with no /StructParents", async () => {
+ const untaggedPage = objects().map((o) =>
+ o.num === 4 ? { ...o, body: o.body.replace(" /StructParents 1", "") } : o,
+ );
+ expect(
+ await failuresOf(buildClassicPdf(untaggedPage, 1), [
+ { pageIndex: 1, mcid: 0, alt: "x" },
+ ]),
+ ).toEqual(["the page has no /StructParents"]);
+ });
+
+ test("fails for a file with no structure tree", async () => {
+ const untagged = objects().map((o) =>
+ o.num === 1 ? { ...o, body: "<< /Type /Catalog /Pages 2 0 R >>" } : o,
+ );
+ expect(
+ await failuresOf(buildClassicPdf(untagged, 1), [
+ { pageIndex: 0, mcid: 0, alt: "x" },
+ ]),
+ ).toEqual(["the file has no structure tree"]);
+ });
+
+ test("fails for an encrypted file rather than writing plaintext into it", async () => {
+ const encrypted = toLatin1(buildClassicPdf(objects(), 1)).replace(
+ "/Root 1 0 R",
+ "/Root 1 0 R /Encrypt 30 0 R",
+ );
+ const bytes = Uint8Array.from(encrypted, (c) => c.charCodeAt(0));
+ expect(
+ await failuresOf(bytes, [{ pageIndex: 0, mcid: 0, alt: "x" }]),
+ ).toEqual(["the file is encrypted"]);
+ });
+});
+
+describe("applyStructureEdits on a real producer's output", () => {
+ beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+ });
+
+ afterAll(() => {
+ vi.unstubAllGlobals();
+ });
+
+ test("PDFium reads the new description from the saved file", async () => {
+ const bytes = new Uint8Array(await readFile(TAGGED_SAMPLE));
+ const out = await applyStructureEdits(bytes, [
+ { pageIndex: 0, mcid: 2, alt: "Revenue by region, \u00e9t\u00e9 2026" },
+ ]);
+
+ const doc = await EditorDocument.open(out);
+ try {
+ const m = doc.module;
+ const tree = m.FPDF_StructTree_GetForPage(doc.page(0).pagePtr);
+ const document = m.FPDF_StructTree_GetChildAtIndex(tree, 0);
+ const figure = m.FPDF_StructElement_GetChildAtIndex(document, 2);
+ const len = m.FPDF_StructElement_GetAltText(figure, 0, 0);
+ const buf = m.pdfium.wasmExports.malloc(len);
+ m.FPDF_StructElement_GetAltText(figure, buf, len);
+ expect(m.pdfium.UTF16ToString(buf)).toBe(
+ "Revenue by region, \u00e9t\u00e9 2026",
+ );
+ m.pdfium.wasmExports.free(buf);
+ m.FPDF_StructTree_Close(tree);
+ } finally {
+ doc.dispose();
+ }
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
index 4d1db9b122..62fd4aec54 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
@@ -4,7 +4,13 @@ import {
toLatin1,
undoPngPredictor,
} from "@app/tools/pdfTextEditor/pdfdoc/bytes";
-import { RawPdf } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ RawPdf,
+ arrayItems,
+ removeDictEntry,
+ setDictEntry,
+ spliceValue,
+} from "@app/tools/pdfTextEditor/pdfdoc/raw";
import {
buildClassicPdf,
buildXrefStreamPdf,
@@ -68,6 +74,20 @@ describe("RawPdf.parse", () => {
});
});
+describe("RawPdf.encrypted", () => {
+ it.each([
+ ["by reference", "/Encrypt 9 0 R"],
+ ["written directly", "/Encrypt << /Filter /Standard /V 1 /R 2 >>"],
+ ])("sees an /Encrypt dictionary %s", async (_, entry) => {
+ const plain = toLatin1(singleContentPdf());
+ const bytes = fromLatin1(
+ plain.replace("trailer\n<<", `trailer\n<< ${entry}`),
+ );
+ expect((await RawPdf.parse(bytes))?.encrypted).toBe(true);
+ expect((await RawPdf.parse(singleContentPdf()))?.encrypted).toBe(false);
+ });
+});
+
describe("RawPdf.valueSpan", () => {
it("reads a value from the outermost dictionary only", async () => {
const pdf = await RawPdf.parse(singleContentPdf());
@@ -222,6 +242,200 @@ describe("RawPdf streams and pages", () => {
});
});
+const CATALOG = { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" };
+const PAGES = { num: 2, body: "<< /Type /Pages /Kids [] /Count 0 >>" };
+
+async function treePdf(...objects: { num: number; body: string }[]) {
+ const pdf = await RawPdf.parse(
+ buildClassicPdf([CATALOG, PAGES, ...objects], 1),
+ );
+ if (!pdf) throw new Error("fixture did not parse");
+ return pdf;
+}
+
+describe("RawPdf.numberTreeEntry", () => {
+ it("finds a value in a tree written directly in its holder", async () => {
+ const pdf = await treePdf({
+ num: 5,
+ body: "<< /Type /StructTreeRoot /ParentTree << /Nums [0 [8 0 R] 1 9 0 R] >> >>",
+ });
+ const entry = pdf.numberTreeEntry(5, "ParentTree", 1);
+ expect(entry?.objNum).toBe(5);
+ expect(entry?.span.text).toBe("9 0 R");
+ const body = pdf.objectBody(5)!;
+ expect(body.slice(entry!.span.start, entry!.span.end)).toBe("9 0 R");
+ });
+
+ it("follows a referenced tree through /Kids, skipping kids whose /Limits exclude the key", async () => {
+ const pdf = await treePdf(
+ { num: 5, body: "<< /Type /StructTreeRoot /ParentTree 6 0 R >>" },
+ { num: 6, body: "<< /Kids [7 0 R 8 0 R] >>" },
+ // Holds a decoy for key 3 outside its own limits, so a search that
+ // ignored /Limits would stop here.
+ { num: 7, body: "<< /Limits [0 1] /Nums [0 [10 0 R] 3 (decoy)] >>" },
+ {
+ num: 8,
+ body: "<< /Limits [2 4] /Nums [2 [11 0 R] 3 [12 0 R 13 0 R]] >>",
+ },
+ );
+ const entry = pdf.numberTreeEntry(5, "ParentTree", 3);
+ expect(entry?.objNum).toBe(8);
+ expect(entry?.span.text).toBe("[12 0 R 13 0 R]");
+ });
+
+ it("searches kids that have no /Limits", async () => {
+ const pdf = await treePdf(
+ { num: 5, body: "<< /ParentTree << /Kids [6 0 R] >> >>" },
+ { num: 6, body: "<< /Nums [4 [9 0 R]] >>" },
+ );
+ expect(pdf.numberTreeEntry(5, "ParentTree", 4)?.objNum).toBe(6);
+ });
+
+ it("does not read a key out of a value's position", async () => {
+ // 9 appears in the array, but only as part of a value.
+ const pdf = await treePdf({
+ num: 5,
+ body: "<< /ParentTree << /Nums [0 [9 0 R] 1 9] >> >>",
+ });
+ expect(pdf.numberTreeEntry(5, "ParentTree", 9)).toBeNull();
+ });
+
+ it("returns null rather than hanging on a cyclic tree", async () => {
+ const pdf = await treePdf(
+ { num: 5, body: "<< /ParentTree 6 0 R >>" },
+ { num: 6, body: "<< /Kids [7 0 R] >>" },
+ { num: 7, body: "<< /Kids [6 0 R] >>" },
+ );
+ expect(pdf.numberTreeEntry(5, "ParentTree", 0)).toBeNull();
+ });
+
+ it("honours /Limits and /Kids written as references", async () => {
+ const pdf = await treePdf(
+ { num: 5, body: "<< /ParentTree 6 0 R >>" },
+ { num: 6, body: "<< /Kids 20 0 R >>" },
+ { num: 20, body: "[7 0 R 8 0 R]" },
+ { num: 7, body: "<< /Limits 21 0 R /Nums [0 [10 0 R] 3 (decoy)] >>" },
+ { num: 21, body: "[0 1]" },
+ { num: 8, body: "<< /Limits 22 0 R /Nums [3 [12 0 R]] >>" },
+ { num: 22, body: "[2 4]" },
+ );
+ expect(pdf.numberTreeEntry(5, "ParentTree", 3)?.span.text).toBe("[12 0 R]");
+ });
+
+ it("searches a tree wider than a few dozen nodes", async () => {
+ const leaves = Array.from({ length: 100 }, (_, i) => ({
+ num: 100 + i,
+ body: `<< /Nums [${i} [${i + 1000} 0 R]] >>`,
+ }));
+ const kids = leaves.map((l) => `${l.num} 0 R`).join(" ");
+ const pdf = await treePdf(
+ { num: 5, body: "<< /ParentTree 6 0 R >>" },
+ { num: 6, body: `<< /Kids [${kids}] >>` },
+ ...leaves,
+ );
+ expect(pdf.numberTreeEntry(5, "ParentTree", 99)?.span.text).toBe(
+ "[1099 0 R]",
+ );
+ });
+
+ it("returns null when the holder has no such tree", async () => {
+ const pdf = await treePdf({ num: 5, body: "<< /Type /StructTreeRoot >>" });
+ expect(pdf.numberTreeEntry(5, "ParentTree", 0)).toBeNull();
+ });
+
+ it("gives a span a replacement can be spliced into", async () => {
+ const pdf = await treePdf(
+ { num: 5, body: "<< /ParentTree 6 0 R >>" },
+ { num: 6, body: "<< /Nums [0 [8 0 R] 1 [9 0 R]] >>" },
+ );
+ const entry = pdf.numberTreeEntry(5, "ParentTree", 1)!;
+ const body = pdf.objectBody(entry.objNum)!;
+ expect(spliceValue(body, entry.span, "[9 0 R 14 0 R]")).toContain(
+ "/Nums [0 [8 0 R] 1 [9 0 R 14 0 R]]",
+ );
+ });
+});
+
+describe("setDictEntry", () => {
+ it("replaces an existing value", () => {
+ expect(setDictEntry("<< /S /Figure /Alt (old) >>", "Alt", "(new)")).toBe(
+ "<< /S /Figure /Alt (new) >>",
+ );
+ });
+
+ it("adds a missing entry to the outermost dictionary, not a nested one", () => {
+ const out = setDictEntry("<< /A << /B 1 >> >>", "Alt", "(x)");
+ expect(out).toBe("<< /A << /B 1 >> /Alt (x) >>");
+ });
+
+ it("is not fooled by a matching key inside a nested dictionary", () => {
+ const out = setDictEntry("<< /A << /Alt (inner) >> >>", "Alt", "(outer)");
+ expect(out).toContain("/A << /Alt (inner) >>");
+ expect(out).toContain("/Alt (outer) >>");
+ });
+
+ it("keeps the result lexable when the value abuts its key", () => {
+ expect(setDictEntry("<< /K[1 2] >>", "K", "3")).toBe("<< /K 3 >>");
+ });
+
+ it("returns null for a body with no dictionary", () => {
+ expect(setDictEntry("[1 2 3]", "K", "4")).toBeNull();
+ expect(setDictEntry("<< /K 1", "Alt", "(x)")).toBeNull();
+ });
+});
+
+describe("removeDictEntry", () => {
+ it("removes the key and its value from the outermost dictionary only", () => {
+ const out = removeDictEntry(
+ "<< /A << /Alt (inner) >> /Alt (outer) /S /Figure >>",
+ "Alt",
+ );
+ expect(out).toBe("<< /A << /Alt (inner) >> /S /Figure >>");
+ });
+
+ it("leaves a body without the key unchanged", () => {
+ expect(removeDictEntry("<< /S /P >>", "Alt")).toBe("<< /S /P >>");
+ });
+});
+
+describe("arrayItems", () => {
+ it("reads an indirect reference as one element", () => {
+ expect(arrayItems("[8 0 R 9 0 R 3]")?.map((i) => i.text)).toEqual([
+ "8 0 R",
+ "9 0 R",
+ "3",
+ ]);
+ });
+
+ it("keeps nested arrays, dictionaries and strings whole", () => {
+ expect(
+ arrayItems("[[1 2] << /Type /MCR /MCID 0 >> (a ] b) <FEFF> /N]")?.map(
+ (i) => i.text,
+ ),
+ ).toEqual(["[1 2]", "<< /Type /MCR /MCID 0 >>", "(a ] b)", "<FEFF>", "/N"]);
+ });
+
+ it("skips comments", () => {
+ expect(arrayItems("[1 % one ]\n2]")?.map((i) => i.text)).toEqual([
+ "1",
+ "2",
+ ]);
+ });
+
+ it("gives spans into the text it was handed", () => {
+ const text = "[ 8 0 R (x) ]";
+ for (const item of arrayItems(text)!) {
+ expect(text.slice(item.start, item.end)).toBe(item.text);
+ }
+ });
+
+ it("returns null for anything it cannot read", () => {
+ expect(arrayItems("<< /K 1 >>")).toBeNull();
+ expect(arrayItems("[1 2")).toBeNull();
+ expect(arrayItems("[1 ) 2]")).toBeNull();
+ });
+});
+
describe("undoPngPredictor", () => {
it("reverses an Up-filtered image back to its original rows", () => {
const rowLen = 3;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/repairStructure.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/repairStructure.test.ts
new file mode 100644
index 0000000000..919c0b58ee
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/repairStructure.test.ts
@@ -0,0 +1,479 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so the repaired streams would not deflate or inflate.
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { toLatin1 } from "@app/tools/pdfTextEditor/pdfdoc/bytes";
+import { parseOps } from "@app/tools/pdfTextEditor/pdfdoc/contentOps";
+import { repairStructure } from "@app/tools/pdfTextEditor/pdfdoc/passes/repairStructure";
+import { RawPdf, arrayItems } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import { copyTagMarks } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";
+import {
+ buildClassicPdf,
+ streamBody,
+ type FixtureObject,
+} from "@app/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const TAGGED_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+
+const PAGE = 3;
+const P = 8;
+const FIGURE = 9;
+
+/**
+ * One tagged page: P (element 8) owns MCID 0, Figure (element 9) owns MCID 1.
+ * `content` is the page's content; `extra` adds or replaces objects.
+ */
+function taggedPdf(content: string | string[], extra: FixtureObject[] = []) {
+ const streams = Array.isArray(content) ? content : [content];
+ const contentRefs = streams.map((_, i) => `${20 + i} 0 R`).join(" ");
+ const base: FixtureObject[] = [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: `<< /Type /Pages /Kids [${PAGE} 0 R] /Count 1 >>` },
+ {
+ num: PAGE,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents [${contentRefs}] /StructParents 0 >>`,
+ },
+ {
+ num: 5,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 6 0 R /ParentTreeNextKey 1 >>",
+ },
+ { num: 6, body: `<< /Nums [0 [${P} 0 R ${FIGURE} 0 R]] >>` },
+ {
+ num: 7,
+ body: `<< /Type /StructElem /S /Document /P 5 0 R /K [${P} 0 R ${FIGURE} 0 R] >>`,
+ },
+ {
+ num: P,
+ body: `<< /Type /StructElem /S /P /P 7 0 R /Pg ${PAGE} 0 R /K 0 >>`,
+ },
+ {
+ num: FIGURE,
+ body: `<< /Type /StructElem /S /Figure /P 7 0 R /Pg ${PAGE} 0 R /K 1 /Alt (A square) >>`,
+ },
+ ...streams.map((s, i) => ({ num: 20 + i, body: streamBody("", s) })),
+ ];
+ const replaced = new Set(extra.map((o) => o.num));
+ return buildClassicPdf(
+ [...base.filter((o) => !replaced.has(o.num)), ...extra],
+ 1,
+ );
+}
+
+const WORD = (mcid: number, text: string) =>
+ `/P <</MCID ${mcid}>> BDC BT /F1 12 Tf 10 10 Td (${text}) Tj ET EMC\n`;
+const FIGURE_CONTENT = "/Figure <</MCID 1>> BDC 0 0 10 10 re f EMC\n";
+
+/** `original` defaults to `bytes`: the same page before the edit, so nothing reads as deleted. */
+async function repaired(
+ bytes: Uint8Array,
+ original: Uint8Array = bytes,
+): Promise<RawPdf> {
+ const out = await repairStructure(bytes, { pages: [0], original });
+ expect(out).not.toBeNull();
+ return (await RawPdf.parse(out!))!;
+}
+
+async function contentText(pdf: RawPdf): Promise<string> {
+ return toLatin1((await pdf.pageContent(pdf.pageNumberAt(0)!))!);
+}
+
+/** MCIDs in content order, one per BDC. */
+async function contentMcids(pdf: RawPdf): Promise<number[]> {
+ return parseOps(await contentText(pdf))
+ .filter((op) => op.op === "BDC")
+ .flatMap((op) => {
+ const m = op.operands.join(" ").match(/\/MCID (\d+)/);
+ return m ? [Number(m[1])] : [];
+ });
+}
+
+function kids(pdf: RawPdf, num: number): string {
+ return pdf.valueSpan(pdf.objectBody(num)!, "K")!.text;
+}
+
+/** The /S of the element the page's ParentTree maps `mcid` to. */
+function ownerType(pdf: RawPdf, mcid: number): string | null {
+ const root = pdf.dictRef(pdf.objectBody(pdf.rootNum)!, "StructTreeRoot")!;
+ const entry = pdf.numberTreeEntry(root, "ParentTree", 0)!.span.text;
+ const ref = entry.match(/^(\d+) \d+ R$/);
+ const list = ref ? pdf.objectBody(Number(ref[1]))!.trim() : entry;
+ const owner = arrayItems(list)![mcid]?.text.match(/^(\d+) \d+ R$/);
+ return owner ? pdf.dictName(pdf.objectBody(Number(owner[1]))!, "S") : null;
+}
+
+function parentArray(pdf: RawPdf): string {
+ return pdf.numberTreeEntry(5, "ParentTree", 0)!.span.text;
+}
+
+describe("repairStructure: repeated MCIDs", () => {
+ test("gives each repeat its own MCID, owned by the same element", async () => {
+ const pdf = await repaired(
+ taggedPdf(WORD(0, "Hello") + FIGURE_CONTENT + WORD(0, "world")),
+ );
+ expect(await contentMcids(pdf)).toEqual([0, 1, 2]);
+ expect(kids(pdf, P)).toBe("[0 2]");
+ expect(parentArray(pdf)).toBe(`[${P} 0 R ${FIGURE} 0 R ${P} 0 R]`);
+ });
+
+ test("keeps reading order by placing new MCIDs right after the original", async () => {
+ const pdf = await repaired(
+ taggedPdf(WORD(0, "a") + WORD(0, "b") + WORD(3, "c") + WORD(3, "d"), [
+ {
+ num: P,
+ body: `<< /Type /StructElem /S /P /P 7 0 R /Pg ${PAGE} 0 R /K [0 3] >>`,
+ },
+ {
+ num: 6,
+ body: `<< /Nums [0 [${P} 0 R ${FIGURE} 0 R null ${P} 0 R]] >>`,
+ },
+ ]),
+ );
+ expect(await contentMcids(pdf)).toEqual([0, 4, 3, 5]);
+ expect(kids(pdf, P)).toBe("[0 4 3 5]");
+ });
+
+ test("renumbers across the parts of a multi-stream page", async () => {
+ const pdf = await repaired(
+ taggedPdf([WORD(0, "first") + FIGURE_CONTENT, WORD(0, "appended")]),
+ );
+ expect(await contentMcids(pdf)).toEqual([0, 1, 2]);
+ });
+
+ test("writes an MCR for an element whose /Pg is another page", async () => {
+ const pdf = await repaired(
+ taggedPdf(WORD(0, "a") + WORD(0, "b"), [
+ {
+ num: P,
+ body: `<< /Type /StructElem /S /P /P 7 0 R /Pg 99 0 R /K [<< /Type /MCR /Pg ${PAGE} 0 R /MCID 0 >>] >>`,
+ },
+ ]),
+ );
+ expect(kids(pdf, P)).toBe(
+ `[<< /Type /MCR /Pg ${PAGE} 0 R /MCID 0 >> << /Type /MCR /Pg ${PAGE} 0 R /MCID 2 >>]`,
+ );
+ });
+
+ test("changes nothing in the content but the MCID numbers", async () => {
+ const before = WORD(0, "Hello (world)") + FIGURE_CONTENT + WORD(0, "again");
+ const pdf = await repaired(taggedPdf(before));
+ const mask = (s: string) => s.replace(/\/MCID \d+/g, "/MCID n");
+ expect(mask(await contentText(pdf))).toBe(mask(`${before}\n`));
+ });
+
+ test("leaves repeats of an MCID no element owns alone", async () => {
+ const bytes = taggedPdf(
+ WORD(0, "a") + FIGURE_CONTENT + WORD(7, "b") + WORD(7, "c"),
+ );
+ expect(
+ await repairStructure(bytes, { pages: [0], original: bytes }),
+ ).toBeNull();
+ });
+});
+
+/** Moves the page's MCIDs into named property lists, on the page or inherited from /Pages. */
+function namedProperties(where: "page" | "inherited"): FixtureObject[] {
+ const resources =
+ "/Resources << /Properties << /MC0 << /MCID 0 >> /MC1 12 0 R >> >>";
+ return [
+ where === "page"
+ ? {
+ num: PAGE,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents [20 0 R] /StructParents 0 ${resources} >>`,
+ }
+ : {
+ num: 2,
+ body: `<< /Type /Pages /Kids [${PAGE} 0 R] /Count 1 ${resources} >>`,
+ },
+ { num: 12, body: "<< /MCID 1 >>" },
+ ];
+}
+
+const NAMED_WORD = "/P /MC0 BDC BT /F1 12 Tf 10 10 Td (kept) Tj ET EMC\n";
+const NAMED_FIGURE = "/Figure /MC1 BDC 0 0 10 10 re f EMC\n";
+
+describe("repairStructure: named property lists", () => {
+ test.each(["page", "inherited"] as const)(
+ "reads MCIDs named in the %s /Properties",
+ async (where) => {
+ const original = taggedPdf(
+ NAMED_WORD + NAMED_FIGURE,
+ namedProperties(where),
+ );
+ const pdf = await repaired(
+ taggedPdf(
+ NAMED_WORD + NAMED_FIGURE + WORD(0, "copy"),
+ namedProperties(where),
+ ),
+ original,
+ );
+ expect(kids(pdf, FIGURE)).toBe("1");
+ // The named occurrence keeps MCID 0; the inline repeat moves.
+ expect(kids(pdf, P)).toBe("[0 2]");
+ expect(parentArray(pdf)).toBe(`[${P} 0 R ${FIGURE} 0 R ${P} 0 R]`);
+ expect(await contentMcids(pdf)).toEqual([2]);
+ },
+ );
+});
+
+describe("repairStructure: deleted content", () => {
+ test("removes an MCID the page no longer has from its element and the ParentTree", async () => {
+ const pdf = await repaired(
+ taggedPdf(WORD(0, "only the text is left")),
+ taggedPdf(WORD(0, "a") + FIGURE_CONTENT),
+ );
+ expect(kids(pdf, FIGURE)).toBe("[]");
+ expect(parentArray(pdf)).toBe(`[${P} 0 R null]`);
+ // The description belongs to the element, which survives.
+ expect(pdf.objectBody(FIGURE)).toContain("/Alt (A square)");
+ });
+
+ test("never removes an MCID it could not read before the edit", async () => {
+ // A name missing from /Properties is unreadable in both versions.
+ const bytes = taggedPdf(
+ WORD(0, "a") + "/Figure /Missing BDC 0 0 10 10 re f EMC\n",
+ );
+ expect(
+ await repairStructure(bytes, { pages: [0], original: bytes }),
+ ).toBeNull();
+ });
+
+ test("removes nothing without the original to compare against", async () => {
+ expect(
+ await repairStructure(taggedPdf(WORD(0, "only the text is left")), {
+ pages: [0],
+ original: new Uint8Array(0),
+ }),
+ ).toBeNull();
+ });
+});
+
+describe("repairStructure: what it leaves alone", () => {
+ test("returns null for a page whose tags are already sound", async () => {
+ const bytes = taggedPdf(WORD(0, "a") + FIGURE_CONTENT);
+ expect(
+ await repairStructure(bytes, { pages: [0], original: bytes }),
+ ).toBeNull();
+ });
+
+ test("returns null for an untagged file", async () => {
+ const bytes = buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Contents 4 0 R >>",
+ },
+ { num: 4, body: streamBody("", WORD(0, "a") + WORD(0, "b")) },
+ ],
+ 1,
+ );
+ const parse = vi.spyOn(RawPdf, "parse");
+ expect(
+ await repairStructure(bytes, { pages: [0], original: bytes }),
+ ).toBeNull();
+ // The original is only needed for a tagged file.
+ expect(parse).toHaveBeenCalledTimes(1);
+ parse.mockRestore();
+ });
+
+ test("only looks at the pages it is given", async () => {
+ const bytes = taggedPdf(WORD(0, "a") + WORD(0, "b"));
+ expect(
+ await repairStructure(bytes, { pages: [], original: bytes }),
+ ).toBeNull();
+ });
+});
+
+describe("repairStructure on the editor's own output", () => {
+ const opened: EditorDocument[] = [];
+
+ beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+ });
+
+ afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+ });
+
+ afterAll(() => {
+ vi.unstubAllGlobals();
+ });
+
+ function newText(doc: EditorDocument, text: string, x: number): number {
+ const m = doc.module;
+ const ptr = m.FPDFPageObj_NewTextObj(doc.docPtr, "Helvetica", 14);
+ const wide = m.pdfium.wasmExports.malloc((text.length + 1) * 2);
+ m.pdfium.stringToUTF16(text, wide, (text.length + 1) * 2);
+ m.FPDFText_SetText(ptr, wide);
+ m.pdfium.wasmExports.free(wide);
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, x, 600);
+ return ptr;
+ }
+
+ function objectsWithMcid(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ id: number,
+ ) {
+ const out: number[] = [];
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetMarkedContentID(obj) === id) out.push(obj);
+ }
+ return out;
+ }
+
+ test("a paragraph re-emitted word by word saves as one MCID per sequence", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(TAGGED_SAMPLE)),
+ );
+ opened.push(doc);
+ const m = doc.module;
+ const page = doc.page(0);
+ // The way emitTextLine re-emits an edited run: one object per word, each
+ // given the original's tags, so PDFium writes each as its own sequence.
+ const [first, ...rest] = objectsWithMcid(m, page.pagePtr, 1);
+ for (const [i, word] of ["Revenue", "grew", "fast"].entries()) {
+ const ptr = newText(doc, word, 72 + i * 80);
+ copyTagMarks(m, doc.docPtr, first, ptr);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ }
+ for (const old of [first, ...rest]) {
+ m.FPDFPage_RemoveObject(page.pagePtr, old);
+ m.FPDFPageObj_Destroy(old);
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+
+ const { blob } = await exportToBlob(doc, "sample.pdf");
+ const pdf = (await RawPdf.parse(new Uint8Array(await blob.arrayBuffer())))!;
+ const mcids = await contentMcids(pdf);
+ expect(new Set(mcids).size).toBe(mcids.length);
+
+ const reopened = await EditorDocument.open(
+ new Uint8Array(await blob.arrayBuffer()),
+ );
+ opened.push(reopened);
+ const paragraph = reopened
+ .structure(0)
+ .elements.find((e) => e.type === "P")!;
+ expect(paragraph.mcids).toHaveLength(3);
+ expect(paragraph.mcids[0]).toBe(1);
+ // A reader finds the element for content through the ParentTree.
+ for (const mcid of paragraph.mcids) {
+ expect(ownerType(pdf, mcid)).toBe("P");
+ }
+ });
+
+ test("editing one paragraph leaves the page's named-form tags alone", async () => {
+ // Elements 8 (edited P, MCID 0), 10 (untouched P, MCID 1) and 9 (Figure, MCID 2),
+ // every MCID held in a named property list.
+ const bytes = buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 20 0 R /StructParents 0 " +
+ "/Resources << /Font << /F1 4 0 R >> /Properties << /MC0 << /MCID 0 >> /MC1 << /MCID 1 >> /MC2 << /MCID 2 >> >> >> >>",
+ },
+ {
+ num: 4,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 5,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 6 0 R /ParentTreeNextKey 1 >>",
+ },
+ { num: 6, body: "<< /Nums [0 [8 0 R 10 0 R 9 0 R]] >>" },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 5 0 R /K [8 0 R 10 0 R 9 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>",
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 2 /Alt (A square) >>",
+ },
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 1 >>",
+ },
+ {
+ num: 20,
+ body: streamBody(
+ "",
+ "/P /MC0 BDC BT /F1 14 Tf 72 700 Td (Edited paragraph) Tj ET EMC\n" +
+ "/P /MC1 BDC BT /F1 14 Tf 72 650 Td (Untouched paragraph) Tj ET EMC\n" +
+ "/Figure /MC2 BDC 72 500 50 50 re f EMC\n",
+ ),
+ },
+ ],
+ 1,
+ );
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ const m = doc.module;
+ const page = doc.page(0);
+ const [old] = objectsWithMcid(m, page.pagePtr, 0);
+ for (const [i, word] of ["Edited", "again"].entries()) {
+ const ptr = newText(doc, word, 72 + i * 80);
+ copyTagMarks(m, doc.docPtr, old, ptr);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ }
+ m.FPDFPage_RemoveObject(page.pagePtr, old);
+ m.FPDFPageObj_Destroy(old);
+ page.markDirty();
+ page.markNeedsGenerate();
+
+ const { blob } = await exportToBlob(doc, "named.pdf");
+ const pdf = (await RawPdf.parse(new Uint8Array(await blob.arrayBuffer())))!;
+ // PDFium writes the untouched sequences back in named form.
+ expect(await contentText(pdf)).toContain("/MC1 BDC");
+ expect(kids(pdf, 10)).toBe("1");
+ expect(kids(pdf, 9)).toBe("2");
+ expect(ownerType(pdf, 1)).toBe("P");
+ expect(ownerType(pdf, 2)).toBe("Figure");
+ expect(kids(pdf, 8)).toMatch(/^\[0 \d+\]$/);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
new file mode 100644
index 0000000000..67ca106d95
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
@@ -0,0 +1,419 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so the real fixture's object stream would not inflate.
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { SetAltTextCommand } from "@app/tools/pdfTextEditor/commands/SetAltTextCommand";
+import { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { PageStructure } from "@app/tools/pdfTextEditor/model/PageStructure";
+import { StructureEditError } from "@app/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import { readPageStructure } from "@app/tools/pdfTextEditor/pdfium/PdfiumStructureReader";
+import { readFileStructure } from "@app/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { RawPdf } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import { PdfiumSave } from "@app/tools/pdfTextEditor/pdfium/PdfiumSave";
+import { PdfiumTextReader } from "@app/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ HistoryStack,
+ HistoryStepError,
+} from "@app/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@app/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const TAGGED_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+const FIGURE_MCID = 2;
+const FIGURE_ALT = "Bar chart of revenue by region";
+
+// A described figure (MCID 0) and a decorative rule drawn as an artifact image.
+function imagesPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /XObject << /Im1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "/Figure <</MCID 0>> BDC q 50 0 0 50 10 100 cm /Im1 Do Q EMC\n" +
+ "/Artifact BMC q 180 0 0 2 10 20 cm /Im1 Do Q EMC\n",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",
+ "\x80",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 0 /Alt (A grey square) >>",
+ },
+ { num: 9, body: "<< /Nums [0 [8 0 R]] >>" },
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ return doc;
+}
+
+async function openSample(): Promise<EditorDocument> {
+ return open(new Uint8Array(await readFile(TAGGED_SAMPLE)));
+}
+
+async function savedBytes(doc: EditorDocument): Promise<Uint8Array> {
+ const { blob } = await exportToBlob(doc, "sample.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("reading the structure tree", () => {
+ test("lists each element with its type, description and MCIDs", async () => {
+ const doc = await openSample();
+ const elements = readPageStructure(doc.module, doc.page(0).pagePtr);
+ expect(elements).toEqual([
+ { type: "Document", alt: null, actualText: null, mcids: [] },
+ { type: "H1", alt: null, actualText: null, mcids: [0] },
+ { type: "P", alt: null, actualText: null, mcids: [1] },
+ { type: "Figure", alt: FIGURE_ALT, actualText: null, mcids: [2] },
+ ]);
+ });
+
+ test("reads an untagged page as having no structure", async () => {
+ const doc = await open(
+ buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>",
+ },
+ ],
+ 1,
+ ),
+ );
+ expect(doc.structure(0).tagged).toBe(false);
+ });
+
+ test("gives each image its MCID or its artifact marking", async () => {
+ const doc = await open(imagesPdf());
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ expect(page.images.map((i) => i.snapshot())).toMatchObject([
+ { mcid: 0 },
+ { artifact: true },
+ ]);
+ expect(page.images[1].mcid).toBeNull();
+ expect(doc.structure(0).alt(0)).toBe("A grey square");
+ });
+});
+
+/**
+ * Page 0: Figure (element 8, MCID 0) and the start of a paragraph (element 9,
+ * MCID 5) that continues on page 1 as MCID 0, so PDFium lists the paragraph
+ * as [5, 0] on both pages. `slot0` is what page 0's ParentTree has at MCID 0.
+ */
+function spanningPdf(slot0 = "8 0 R"): Uint8Array {
+ const page0 =
+ "/Figure <</MCID 0>> BDC 0 0 10 10 re f EMC /P <</MCID 5>> BDC 0 0 5 5 re f EMC\n";
+ const page1 = "/P <</MCID 0>> BDC 0 0 5 5 re f EMC\n";
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 20 0 R /StructParents 0 >>",
+ },
+ {
+ num: 4,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 21 0 R /StructParents 1 >>",
+ },
+ {
+ num: 5,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 6 0 R /RoleMap << /Chart /Figure >> >>",
+ },
+ {
+ num: 6,
+ body: `<< /Nums [0 [${slot0} null null null null 9 0 R] 1 [9 0 R]] >>`,
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 5 0 R /K [8 0 R 9 0 R] >>",
+ },
+ {
+ num: 8,
+ // UTF-16BE for "Chart", under a custom role the RoleMap makes a Figure.
+ body: "<< /Type /StructElem /S /Chart /P 7 0 R /Pg 3 0 R /K 0 /Alt <FEFF00430068006100720074> >>",
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K [5 << /Type /MCR /Pg 4 0 R /MCID 0 >>] >>",
+ },
+ { num: 20, body: streamBody("", page0) },
+ { num: 21, body: streamBody("", page1) },
+ ],
+ 1,
+ );
+}
+
+describe("reading tags from the file's ParentTree", () => {
+ test("gives each page's MCIDs to the element its ParentTree names", async () => {
+ const structure = (await readFileStructure(spanningPdf()))!;
+ expect(structure.get(0)).toEqual([
+ { type: "Figure", alt: "Chart", actualText: null, mcids: [0] },
+ { type: "P", alt: null, actualText: null, mcids: [5] },
+ ]);
+ expect(structure.get(1)).toEqual([
+ { type: "P", alt: null, actualText: null, mcids: [0] },
+ ]);
+ });
+
+ test("describes the figure, not the paragraph that spans the page break", async () => {
+ const doc = await open(spanningPdf());
+ expect(doc.structure(0).alt(0)).toBe("Chart");
+ new HistoryStack().execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: 0, alt: "Revenue chart" }),
+ doc,
+ );
+ const pdf = (await RawPdf.parse(await savedBytes(doc)))!;
+ expect(pdf.objectBody(8)).toContain("/Alt (Revenue chart)");
+ expect(pdf.objectBody(9)).not.toContain("/Alt");
+ });
+
+ test("refuses an MCID only another page's content carries", async () => {
+ const doc = await open(spanningPdf("null"));
+ expect(doc.structure(0).cannotDescribe(0)).toMatch(/no structure element/);
+ });
+});
+
+describe("PageStructure", () => {
+ const figure = {
+ type: "Figure",
+ alt: "old",
+ actualText: null,
+ mcids: [3, 4],
+ };
+
+ test("holds one edit per element, whichever of its MCIDs addressed it", () => {
+ const s = new PageStructure([figure]);
+ s.setEdit(3, { mcid: 3, alt: "new" });
+ expect(s.alt(4)).toBe("new");
+ s.setEdit(4, { mcid: 4, alt: "newer" });
+ expect(s.pendingEdits()).toEqual([{ mcid: 4, alt: "newer" }]);
+ });
+
+ test("reads back the file's description once an edit is dropped", () => {
+ const s = new PageStructure([figure]);
+ s.setEdit(3, { mcid: 3, alt: null });
+ expect(s.alt(3)).toBeNull();
+ s.setEdit(3, null);
+ expect(s.alt(3)).toBe("old");
+ expect(s.pendingEdits()).toEqual([]);
+ });
+
+ test("refuses an edit no element can carry", () => {
+ expect(() =>
+ new PageStructure([figure]).setEdit(9, { mcid: 9, alt: "x" }),
+ ).toThrow();
+ });
+
+ test("describes figures and formulas but not elements that hold text", () => {
+ const s = new PageStructure([
+ figure,
+ { type: "Formula", alt: null, actualText: null, mcids: [5] },
+ { type: "P", alt: null, actualText: null, mcids: [6] },
+ ]);
+ expect(s.cannotDescribe(3)).toBeNull();
+ expect(s.cannotDescribe(5)).toBeNull();
+ expect(s.cannotDescribe(6)).toMatch(/P element/);
+ expect(s.cannotDescribe(9)).toMatch(/no structure element/);
+ });
+
+ test("refuses every description when the save cannot write them", () => {
+ expect(
+ new PageStructure([figure], "the file is encrypted").cannotDescribe(3),
+ ).toBe("the file is encrypted");
+ });
+});
+
+describe("SetAltTextCommand", () => {
+ test("undoes and redoes a description", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ history.execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: FIGURE_MCID, alt: "New" }),
+ doc,
+ );
+ expect(doc.structure(0).alt(FIGURE_MCID)).toBe("New");
+ history.undo(doc);
+ expect(doc.structure(0).alt(FIGURE_MCID)).toBe(FIGURE_ALT);
+ expect(doc.structureEdits()).toEqual([]);
+ history.redo(doc);
+ expect(doc.structureEdits()).toEqual([
+ { pageIndex: 0, mcid: FIGURE_MCID, alt: "New" },
+ ]);
+ });
+
+ test("collapses typing into one undo step that restores the original", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ for (const alt of ["B", "Ba", "Bar"]) {
+ history.execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: FIGURE_MCID, alt }),
+ doc,
+ );
+ }
+ expect(history.size().undo).toBe(1);
+ history.undo(doc);
+ expect(doc.structure(0).alt(FIGURE_MCID)).toBe(FIGURE_ALT);
+ });
+
+ test.each([
+ ["content no element owns", 42],
+ // The sample's paragraph: an /Alt there would replace its text.
+ ["a paragraph", 1],
+ ])("rolls back cleanly for %s", async (_, mcid) => {
+ const doc = await openSample();
+ const error = (() => {
+ try {
+ new HistoryStack().execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid, alt: "x" }),
+ doc,
+ );
+ } catch (e) {
+ return e;
+ }
+ })();
+ expect(error).toBeInstanceOf(HistoryStepError);
+ expect((error as HistoryStepError).documentIntact).toBe(true);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("refuses a description in an encrypted file, which the save could not write", async () => {
+ const plain = await openSample();
+ expect(plain.module.EPDF_SetEncryption(plain.docPtr, "", "owner", -4)).toBe(
+ true,
+ );
+ const doc = await open(PdfiumSave.serialize(plain));
+ expect(() =>
+ new HistoryStack().execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: FIGURE_MCID, alt: "x" }),
+ doc,
+ ),
+ ).toThrow(HistoryStepError);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+});
+
+describe("saving a description", () => {
+ test("appends it to the opened file when nothing else changed", async () => {
+ const doc = await openSample();
+ new SetAltTextCommand({
+ pageIndex: 0,
+ mcid: FIGURE_MCID,
+ alt: "Revenue, by region",
+ }).apply(doc);
+
+ const saved = await savedBytes(doc);
+ // An appended revision, not a PDFium rewrite of the whole file.
+ expect(saved.subarray(0, doc.openedBytes.length)).toEqual(doc.openedBytes);
+ const reopened = await open(saved);
+ expect(reopened.structure(0).alt(FIGURE_MCID)).toBe("Revenue, by region");
+ });
+
+ test("keeps it alongside regenerated page content", async () => {
+ const doc = await openSample();
+ new SetAltTextCommand({
+ pageIndex: 0,
+ mcid: FIGURE_MCID,
+ alt: null,
+ }).apply(doc);
+ doc.page(0).markNeedsGenerate();
+
+ const reopened = await open(await savedBytes(doc));
+ expect(reopened.structure(0).alt(FIGURE_MCID)).toBeNull();
+ expect(reopened.structure(0).element(FIGURE_MCID)?.type).toBe("Figure");
+ });
+
+ test("leaves a save with no edits byte-identical", async () => {
+ const doc = await openSample();
+ doc.structure(0);
+ expect(await savedBytes(doc)).toEqual(doc.openedBytes);
+ });
+
+ test("fails the save rather than dropping an edit it cannot write", async () => {
+ const doc = await openSample();
+ vi.spyOn(doc, "structureEdits").mockReturnValue([
+ { pageIndex: 0, mcid: 42, alt: "x" },
+ ]);
+ await expect(exportToBlob(doc, "sample.pdf")).rejects.toBeInstanceOf(
+ StructureEditError,
+ );
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/textString.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/textString.test.ts
new file mode 100644
index 0000000000..e3f8ba0998
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/textString.test.ts
@@ -0,0 +1,166 @@
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
+import { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { RawPdf, setDictEntry } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+} from "@app/tools/pdfTextEditor/pdfdoc/revision";
+import {
+ decodeTextString,
+ encodeTextString,
+} from "@app/tools/pdfTextEditor/pdfdoc/textString";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@app/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const FIGURE = 8;
+
+function figurePdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", "/Figure <</MCID 0>> BDC 0 0 10 10 re f EMC"),
+ },
+ {
+ num: 5,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 6 0 R /ParentTreeNextKey 1 >>",
+ },
+ { num: 6, body: "<< /Nums [0 [8 0 R]] >>" },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 5 0 R /K [8 0 R] >>",
+ },
+ {
+ num: FIGURE,
+ body: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 0 /Alt (old) >>",
+ },
+ ],
+ 1,
+ );
+}
+
+async function withAlt(alt: string): Promise<Uint8Array> {
+ const pdf = await RawPdf.parse(figurePdf());
+ const body = setDictEntry(
+ pdf!.objectBody(FIGURE)!,
+ "Alt",
+ encodeTextString(alt),
+ );
+ return appendRevision(pdf!, [{ num: FIGURE, body: plainObject(body!) }])!;
+}
+
+/** The figure's /Alt as PDFium decodes it. */
+async function readAlt(bytes: Uint8Array): Promise<string> {
+ const doc = await EditorDocument.open(bytes);
+ try {
+ const m = doc.module;
+ const tree = m.FPDF_StructTree_GetForPage(doc.page(0).pagePtr);
+ const document = m.FPDF_StructTree_GetChildAtIndex(tree, 0);
+ const figure = m.FPDF_StructElement_GetChildAtIndex(document, 0);
+ const len = m.FPDF_StructElement_GetAltText(figure, 0, 0);
+ const buf = m.pdfium.wasmExports.malloc(Math.max(len, 2));
+ m.FPDF_StructElement_GetAltText(figure, buf, len);
+ const alt = len > 2 ? m.pdfium.UTF16ToString(buf) : "";
+ m.pdfium.wasmExports.free(buf);
+ m.FPDF_StructTree_Close(tree);
+ return alt;
+ } finally {
+ doc.dispose();
+ }
+}
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("encodeTextString", () => {
+ test("writes printable ASCII as a literal, escaping its delimiters", () => {
+ expect(encodeTextString("a (b) \\ c")).toBe("(a \\(b\\) \\\\ c)");
+ });
+
+ test("writes anything else as UTF-16BE behind a byte order mark", () => {
+ expect(encodeTextString("caf\u00e9")).toBe("<FEFF00630061006600E9>");
+ expect(encodeTextString("\u{1F600}")).toBe("<FEFFD83DDE00>");
+ expect(encodeTextString("a\nb")).toBe("<FEFF0061000A0062>");
+ });
+
+ test.each([
+ ["plain ASCII", "Bar chart of revenue by region"],
+ ["delimiters", "Ratio (a) \\ (b)"],
+ ["accented Latin", "Caf\u00e9 cr\u00e8me br\u00fbl\u00e9e"],
+ ["non-Latin script", "\u53ce\u76ca\u306e\u30b0\u30e9\u30d5"],
+ ["astral emoji", "Chart \u{1F4C8}"],
+ ["empty", ""],
+ ])("PDFium reads back %s exactly", async (_label, alt) => {
+ expect(await readAlt(await withAlt(alt))).toBe(alt);
+ });
+});
+
+describe("decodeTextString", () => {
+ test.each([
+ ["plain ASCII", "Bar chart (Q3)"],
+ ["Latin-1 beyond ASCII", "Caf\u00e9"],
+ ["CJK", "\u6536\u5165"],
+ ["astral", "\u{1F4C8} up"],
+ ])("reads back what encodeTextString writes: %s", (_, text) => {
+ expect(decodeTextString(encodeTextString(text))).toBe(text);
+ });
+
+ test("reads literal escapes, balanced parentheses and octal codes", () => {
+ expect(decodeTextString("(a\\(b\\) (c) \\101\\\\ \\n)")).toBe(
+ "a(b) (c) A\\ \n",
+ );
+ });
+
+ test("joins a line continued with a backslash", () => {
+ expect(decodeTextString("(one \\\ntwo)")).toBe("one two");
+ });
+
+ test("reads hex, padding a missing final digit", () => {
+ expect(decodeTextString("<48 69 2>")).toBe("Hi ");
+ });
+
+ test("maps PDFDocEncoding where it differs from Latin-1", () => {
+ expect(decodeTextString("<80A0>")).toBe("\u2022\u20ac");
+ });
+
+ test("reads UTF-8 behind its byte order mark", () => {
+ expect(decodeTextString("<EFBBBFC3A9>")).toBe("\u00e9");
+ });
+
+ test("returns null for anything that is not a string", () => {
+ expect(decodeTextString("/Name")).toBeNull();
+ expect(decodeTextString("<< /A 1 >>")).toBeNull();
+ expect(decodeTextString("(unterminated")).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts
new file mode 100644
index 0000000000..fe82fa08d8
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts
@@ -0,0 +1,53 @@
+import {
+ RolledBackError,
+ type Command,
+} from "@app/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { StructureElementEdit } from "@app/tools/pdfTextEditor/model/PageStructure";
+
+/**
+ * Set or remove the description of the structure element owning `mcid`.
+ * Touches no page content: the edit is held on the document's structure index
+ * and written by the save pass, so the page is never regenerated for it.
+ */
+export class SetAltTextCommand implements Command {
+ readonly type = "set-alt-text";
+ private readonly pageIndex: number;
+ private readonly mcid: number;
+ private readonly alt: string | null;
+ private previous: StructureElementEdit | null | undefined;
+
+ constructor(opts: { pageIndex: number; mcid: number; alt: string | null }) {
+ this.pageIndex = opts.pageIndex;
+ this.mcid = opts.mcid;
+ this.alt = opts.alt;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ // Refused here, not at save: a description the save cannot write would
+ // fail every later save, the user's other edits included.
+ const refusal = structure.cannotDescribe(this.mcid);
+ if (refusal) {
+ throw new RolledBackError(
+ new Error(`MCID ${this.mcid} cannot take a description: ${refusal}`),
+ );
+ }
+ if (this.previous === undefined) {
+ this.previous = structure.editFor(this.mcid);
+ }
+ structure.setEdit(this.mcid, { mcid: this.mcid, alt: this.alt });
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ doc.structure(this.pageIndex).setEdit(this.mcid, this.previous);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ /** Keystrokes in one description field collapse into one undo step. */
+ coalesceKey(): string {
+ return `${this.type}:${this.pageIndex}:${this.mcid}`;
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
index d3fa6e5e94..c5496b9ded 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -5,6 +5,13 @@ import {
openRawDocument,
} from "@app/services/pdfiumService";
import { Page } from "@app/tools/pdfTextEditor/model/Page";
+import {
+ PageStructure,
+ type StructureElement,
+} from "@app/tools/pdfTextEditor/model/PageStructure";
+import type { StructureEdit } from "@app/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import { readPageStructure } from "@app/tools/pdfTextEditor/pdfium/PdfiumStructureReader";
+import { readFileStructure } from "@app/tools/pdfTextEditor/pdfdoc/readFileStructure";
import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
import { FontRef } from "@app/tools/pdfTextEditor/model/FontRef";
import { prepareForEditing } from "@app/tools/pdfTextEditor/pdfdoc/prepareForEditing";
@@ -24,6 +31,9 @@ export class EditorDocument {
/** Empty when the file was too large to keep a second copy of. */
readonly openedBytes: Uint8Array;
private readonly pageCache: Map<number, Page>;
+ private readonly structureCache = new Map<number, PageStructure>();
+ /** Each page's elements from the file's own ParentTree; null when only PDFium's view is available. */
+ private readonly fileStructure: Map<number, StructureElement[]> | null;
private readonly ownedFonts: Map<string, FontRef>;
private _disposed: boolean;
// Form-fill environment. Widgets with no appearance stream are drawn ONLY by
@@ -38,10 +48,12 @@ export class EditorDocument {
module: WrappedPdfiumModule,
docPtr: number,
openedBytes: Uint8Array,
+ fileStructure: Map<number, StructureElement[]> | null,
) {
this.module = module;
this.docPtr = docPtr;
this.openedBytes = openedBytes;
+ this.fileStructure = fileStructure;
this.pageCache = new Map();
this.ownedFonts = new Map();
this._disposed = false;
@@ -58,7 +70,11 @@ export class EditorDocument {
// PDFium already holds its own heap copy, so retaining these doubles the
// footprint; past a point the gradient repair is not worth that.
const keep = prepared.length <= MAX_RETAINED_BYTES ? prepared : EMPTY;
- return new EditorDocument(module, docPtr, keep);
+ const fileStructure =
+ keep.length > 0 && module.FPDFCatalog_IsTagged(docPtr)
+ ? await readFileStructure(keep).catch(() => null)
+ : null;
+ return new EditorDocument(module, docPtr, keep, fileStructure);
}
/** Page indices whose content stream has been regenerated this session. */
@@ -136,6 +152,42 @@ export class EditorDocument {
return page;
}
+ /**
+ * The page's structure elements and their unsaved edits.
+ */
+ structure(pageIndex: number): PageStructure {
+ const cached = this.structureCache.get(pageIndex);
+ if (cached) return cached;
+ // PDFium's tree is the fallback, read-only: its MCIDs carry no page, so
+ // an edit made through it could land on the wrong element.
+ const structure = this.fileStructure
+ ? new PageStructure(this.fileStructure.get(pageIndex) ?? [])
+ : new PageStructure(
+ readPageStructure(this.module, this.page(pageIndex).pagePtr),
+ this.encrypted()
+ ? "the file is encrypted"
+ : "the file's tags could not be read for editing",
+ );
+ this.structureCache.set(pageIndex, structure);
+ return structure;
+ }
+
+ private encrypted(): boolean {
+ try {
+ // -1 when the file has no security handler.
+ return this.module.FPDF_GetSecurityHandlerRevision(this.docPtr) >= 0;
+ } catch {
+ return false;
+ }
+ }
+
+ /** Every unsaved structure edit, in the form the save pass takes. */
+ structureEdits(): StructureEdit[] {
+ return [...this.structureCache].flatMap(([pageIndex, structure]) =>
+ structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),
+ );
+ }
+
registerOwnedFont(font: FontRef): void {
this.ownedFonts.set(font.id, font);
}
@@ -180,6 +232,7 @@ export class EditorDocument {
}
}
this.pageCache.clear();
+ this.structureCache.clear();
for (const font of this.ownedFonts.values()) {
font.dispose();
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/ImageObject.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/ImageObject.ts
index 57e70c55f1..0c83fcc601 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/ImageObject.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/ImageObject.ts
@@ -15,6 +15,8 @@ export class ImageObject {
dirty: boolean;
/** Session-only lock; see TextRun.locked. */
locked: boolean;
+ readonly mcid: number | null;
+ readonly artifact: boolean;
constructor(
init: ImageObjectSnapshot & {
@@ -30,6 +32,8 @@ export class ImageObject {
this.matrix = init.matrix;
this.dirty = false;
this.locked = init.locked ?? false;
+ this.mcid = init.mcid ?? null;
+ this.artifact = init.artifact ?? false;
}
snapshot(): ImageObjectSnapshot {
@@ -39,6 +43,8 @@ export class ImageObject {
bounds: { ...this.bounds },
matrix: { ...this.matrix },
locked: this.locked || undefined,
+ mcid: this.mcid ?? undefined,
+ artifact: this.artifact || undefined,
};
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/PageStructure.ts
new file mode 100644
index 0000000000..f3b7037fc3
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -0,0 +1,95 @@
+/** One structure element as the page sees it, read once when the page is first asked about. */
+export interface StructureElement {
+ /** The element's /S after the /RoleMap: "Figure", "P", or an unmapped custom role. */
+ type: string;
+ alt: string | null;
+ actualText: string | null;
+ /**
+ * The MCIDs the element owns on this page. The PDFium fallback cannot tell
+ * pages apart, so there it can also list other pages' MCIDs.
+ */
+ mcids: number[];
+}
+
+/** An unsaved change to an element, and the MCID the save addresses it by. */
+export interface StructureElementEdit {
+ mcid: number;
+ /** The new /Alt; null removes it. */
+ alt: string | null;
+}
+
+/**
+ * Types whose /Alt stands in for the content. On any other element it would
+ * replace text a reader speaks, so a description there is refused.
+ */
+const DESCRIBABLE_TYPES = new Set(["Figure", "Formula"]);
+
+/**
+ * The structure elements of one page plus the session's unsaved edits to
+ * them. Edits are keyed by element rather than MCID, so an element that owns
+ * several MCIDs has one description however it was addressed.
+ */
+export class PageStructure {
+ readonly elements: readonly StructureElement[];
+ private readonly byMcid = new Map<number, StructureElement>();
+ private readonly edits = new Map<StructureElement, StructureElementEdit>();
+
+ /** Why the save cannot write descriptions for this page, or null when it can. */
+ readonly readOnly: string | null;
+
+ constructor(
+ elements: readonly StructureElement[],
+ readOnly: string | null = null,
+ ) {
+ this.elements = elements;
+ this.readOnly = readOnly;
+ for (const el of elements) {
+ for (const mcid of el.mcids) this.byMcid.set(mcid, el);
+ }
+ }
+
+ get tagged(): boolean {
+ return this.elements.length > 0;
+ }
+
+ element(mcid: number): StructureElement | null {
+ return this.byMcid.get(mcid) ?? null;
+ }
+
+ /** Why the content `mcid` marks cannot take a description, or null when it can. */
+ cannotDescribe(mcid: number): string | null {
+ const el = this.element(mcid);
+ if (!el) return "no structure element owns it";
+ if (this.readOnly) return this.readOnly;
+ if (!DESCRIBABLE_TYPES.has(el.type)) {
+ return `it belongs to a ${el.type || "untyped"} element, whose description would replace its text`;
+ }
+ return null;
+ }
+
+ /** The description as it will be saved: the session's edit, else the file's. */
+ alt(mcid: number): string | null {
+ const el = this.element(mcid);
+ if (!el) return null;
+ const edit = this.edits.get(el);
+ return edit ? edit.alt : el.alt;
+ }
+
+ /** The unsaved edit to the element owning `mcid`, for a command to restore on undo. */
+ editFor(mcid: number): StructureElementEdit | null {
+ const el = this.element(mcid);
+ return el ? (this.edits.get(el) ?? null) : null;
+ }
+
+ /** Throws when no element owns `mcid`: a command must not record an edit the save cannot address. */
+ setEdit(mcid: number, edit: StructureElementEdit | null): void {
+ const el = this.element(mcid);
+ if (!el) throw new Error(`No structure element owns MCID ${mcid}`);
+ if (edit) this.edits.set(el, edit);
+ else this.edits.delete(el);
+ }
+
+ pendingEdits(): StructureElementEdit[] {
+ return [...this.edits.values()];
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
new file mode 100644
index 0000000000..b1decdff42
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
@@ -0,0 +1,122 @@
+/**
+ * Write tag edits into the structure tree, as an appended revision.
+ */
+import {
+ RawPdf,
+ referencedObject,
+ removeDictEntry,
+ setDictEntry,
+} from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+} from "@app/tools/pdfTextEditor/pdfdoc/revision";
+import { encodeTextString } from "@app/tools/pdfTextEditor/pdfdoc/textString";
+
+/** A change to the structure element that owns marked content `mcid` on a page. */
+export interface StructureEdit {
+ pageIndex: number;
+ mcid: number;
+ /** The new /Alt; null removes it. */
+ alt: string | null;
+}
+
+export interface StructureEditFailure {
+ edit: StructureEdit;
+ reason: string;
+}
+
+/** Thrown with every edit that could not be written; none of them were. */
+export class StructureEditError extends Error {
+ constructor(readonly failures: StructureEditFailure[]) {
+ super(
+ `Could not write ${failures.length} tag edit(s): ` +
+ failures
+ .map(
+ (f) =>
+ `page ${f.edit.pageIndex + 1} MCID ${f.edit.mcid}: ${f.reason}`,
+ )
+ .join("; "),
+ );
+ this.name = "StructureEditError";
+ }
+}
+
+/**
+ * Apply `edits` to `bytes`, all or none. Later edits to the same element win.
+ * Throws StructureEditError when any edit cannot be written, including when
+ * the file cannot be extended at all.
+ */
+export async function applyStructureEdits(
+ bytes: Uint8Array,
+ edits: readonly StructureEdit[],
+): Promise<Uint8Array> {
+ if (edits.length === 0) return bytes;
+ const fail = (reason: string) =>
+ new StructureEditError(edits.map((edit) => ({ edit, reason })));
+
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf) throw fail("the file could not be read");
+ // Strings in an encrypted file must be encrypted too, which this cannot do.
+ if (pdf.encrypted) throw fail("the file is encrypted");
+ const catalog = pdf.objectBody(pdf.rootNum);
+ const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
+ if (treeRoot === null) throw fail("the file has no structure tree");
+
+ const bodies = new Map<number, string>();
+ const failures: StructureEditFailure[] = [];
+ for (const edit of edits) {
+ const owner = elementFor(pdf, treeRoot, edit);
+ if (typeof owner === "string") {
+ failures.push({ edit, reason: owner });
+ continue;
+ }
+ const body = bodies.get(owner) ?? pdf.objectBody(owner)!;
+ const updated =
+ edit.alt === null
+ ? removeDictEntry(body, "Alt")
+ : setDictEntry(body, "Alt", encodeTextString(edit.alt));
+ if (updated === null) {
+ failures.push({
+ edit,
+ reason: "its structure element is not a dictionary",
+ });
+ continue;
+ }
+ bodies.set(owner, updated);
+ }
+ if (failures.length > 0) throw new StructureEditError(failures);
+
+ const out = appendRevision(
+ pdf,
+ [...bodies].map(([num, body]) => ({ num, body: plainObject(body) })),
+ );
+ if (!out)
+ throw fail("the file's cross-reference structure cannot be extended");
+ return out;
+}
+
+/** The structure element's object number, or why it cannot be found. */
+function elementFor(
+ pdf: RawPdf,
+ treeRoot: number,
+ edit: StructureEdit,
+): number | string {
+ const pageNum = pdf.pageNumberAt(edit.pageIndex);
+ const page = pageNum === null ? null : pdf.objectBody(pageNum);
+ if (!page) return "no such page";
+ const key = pdf.dictInt(page, "StructParents");
+ if (key === null) return "the page has no /StructParents";
+
+ const tree = pdf.parentTreeArray(treeRoot, key);
+ if (!tree) return "the ParentTree has no entry for the page";
+ if (!tree.items) return "the page's ParentTree entry is not an array";
+
+ const num = referencedObject(tree.items[edit.mcid]?.text ?? "");
+ if (num === null) return "no structure element owns this MCID";
+ const body = pdf.objectBody(num);
+ if (!body || pdf.dictName(body, "S") === null) {
+ return "the ParentTree points at something that is not a structure element";
+ }
+ return num;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
new file mode 100644
index 0000000000..034219e673
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
@@ -0,0 +1,365 @@
+/**
+ * Repair the structure tree after PDFium regenerates a tagged page.
+ */
+import {
+ deflate,
+ fromLatin1,
+ toLatin1,
+} from "@app/tools/pdfTextEditor/pdfdoc/bytes";
+import { parseOps, tokenize } from "@app/tools/pdfTextEditor/pdfdoc/contentOps";
+import {
+ RawPdf,
+ arrayItems,
+ referencedObject,
+ setDictEntry,
+ spliceValue,
+ type NumberTreeEntry,
+ type ValueSpan,
+} from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+ streamObject,
+ type RevisionObject,
+} from "@app/tools/pdfTextEditor/pdfdoc/revision";
+
+const REF = /^(\d+)\s+\d+\s+R$/;
+
+interface McidSite {
+ stream: number;
+ mcid: number;
+ /** Where the MCID's number is in the stream's text; null when a named property list holds it. */
+ number: { start: number; end: number } | null;
+}
+
+interface PageSites {
+ refs: number[];
+ texts: string[];
+ sites: McidSite[];
+}
+
+/** Changes to one element's /K for one page. */
+interface KidChanges {
+ pageNum: number;
+ removed: Set<number>;
+ /** New MCIDs to place after an existing one, in content order. */
+ added: Map<number, number[]>;
+}
+
+interface PageRepair {
+ streams: Map<number, string>;
+ /** Where the page's ParentTree array lives, and its replacement. */
+ parentEntry: NumberTreeEntry;
+ parentArray: string;
+ elements: Map<number, KidChanges>;
+}
+
+/**
+ * Repair the tags on `pages` (page indices) of `bytes`. Null when nothing
+ * needed repair or the file is not one this can extend.
+ */
+export async function repairStructure(
+ bytes: Uint8Array,
+ opts: { pages: number[]; original: Uint8Array },
+): Promise<Uint8Array | null> {
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf || pdf.encrypted) return null;
+ const catalog = pdf.objectBody(pdf.rootNum);
+ const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
+ if (treeRoot === null) return null;
+ const before =
+ opts.original.length > 0 ? await RawPdf.parse(opts.original) : null;
+
+ const sharedStreams = streamsUsedByMoreThanOnePage(pdf);
+ const objects: RevisionObject[] = [];
+ const elementBodies = new Map<number, string>();
+ const nodeSplices = new Map<number, { span: ValueSpan; text: string }[]>();
+
+ for (const pageIndex of new Set(opts.pages)) {
+ const pageNum = pdf.pageNumberAt(pageIndex);
+ if (pageNum === null) continue;
+ const beforeNum = before?.pageNumberAt(pageIndex) ?? null;
+ const beforeSites =
+ before && beforeNum !== null ? await pageSites(before, beforeNum) : null;
+ const repair = await planPage(
+ pdf,
+ treeRoot,
+ pageNum,
+ sharedStreams,
+ new Set(beforeSites?.sites.map((s) => s.mcid)),
+ );
+ if (!repair) continue;
+
+ for (const [num, text] of repair.streams) {
+ const raw = fromLatin1(text);
+ const packed = await deflate(raw);
+ objects.push({
+ num,
+ body: packed
+ ? streamObject("<< /Filter /FlateDecode >>", packed)
+ : streamObject("<< >>", raw),
+ });
+ }
+
+ const entry = repair.parentEntry;
+ const arrayRef = entry.span.text.match(REF);
+ if (arrayRef) {
+ objects.push({
+ num: parseInt(arrayRef[1], 10),
+ body: plainObject(repair.parentArray),
+ });
+ } else {
+ const splices = nodeSplices.get(entry.objNum) ?? [];
+ splices.push({ span: entry.span, text: repair.parentArray });
+ nodeSplices.set(entry.objNum, splices);
+ }
+
+ for (const [num, changes] of repair.elements) {
+ const body = elementBodies.get(num) ?? pdf.objectBody(num);
+ const updated = body ? rewriteKids(pdf, body, changes) : null;
+ if (updated) elementBodies.set(num, updated);
+ }
+ }
+
+ for (const [num, splices] of nodeSplices) {
+ // Spans index the original body, so splice back to front.
+ let body = pdf.objectBody(num)!;
+ for (const s of splices.sort((a, b) => b.span.start - a.span.start)) {
+ body = spliceValue(body, s.span, s.text);
+ }
+ objects.push({ num, body: plainObject(body) });
+ }
+ for (const [num, body] of elementBodies) {
+ objects.push({ num, body: plainObject(body) });
+ }
+
+ if (objects.length === 0) return null;
+ return appendRevision(pdf, objects);
+}
+
+async function planPage(
+ pdf: RawPdf,
+ treeRoot: number,
+ pageNum: number,
+ sharedStreams: Set<number>,
+ mcidsBefore: ReadonlySet<number>,
+): Promise<PageRepair | null> {
+ const page = pdf.objectBody(pageNum);
+ const key = page ? pdf.dictInt(page, "StructParents") : null;
+ if (!page || key === null) return null;
+ const read = await pageSites(pdf, pageNum);
+ // Renumbering a stream another page also draws would corrupt that page.
+ if (!read || read.refs.some((r) => sharedStreams.has(r))) return null;
+ const { refs, texts, sites } = read;
+
+ const tree = pdf.parentTreeArray(treeRoot, key);
+ if (!tree?.items) return null;
+ const entry = tree.entry;
+ const slots = tree.items.map((item) => item.text);
+ const owner = (mcid: number): number | null =>
+ referencedObject(slots[mcid] ?? "");
+
+ const elements = new Map<number, KidChanges>();
+ const changesFor = (num: number): KidChanges => {
+ const found = elements.get(num);
+ if (found) return found;
+ const created = { pageNum, removed: new Set<number>(), added: new Map() };
+ elements.set(num, created);
+ return created;
+ };
+
+ const present = new Set(sites.map((s) => s.mcid));
+ let next = Math.max(slots.length - 1, ...present) + 1;
+ // A named occurrence keeps its MCID: renumbering it means editing a property
+ // list that other BDCs may name too, so the inline repeats move instead.
+ const seen = new Set(sites.filter((s) => !s.number).map((s) => s.mcid));
+ const renumbered: { site: McidSite; mcid: number }[] = [];
+ for (const site of sites) {
+ if (!site.number) continue;
+ if (!seen.has(site.mcid)) {
+ seen.add(site.mcid);
+ continue;
+ }
+ const num = owner(site.mcid);
+ // An orphan's repeats have no element to join, so renumbering them
+ // would only make more orphans.
+ if (num === null) continue;
+ const mcid = next++;
+ renumbered.push({ site, mcid });
+ present.add(mcid);
+ while (slots.length < mcid) slots.push("null");
+ slots[mcid] = `${num} 0 R`;
+ const added = changesFor(num).added;
+ added.set(site.mcid, [...(added.get(site.mcid) ?? []), mcid]);
+ }
+
+ for (let mcid = 0; mcid < slots.length; mcid++) {
+ const num = owner(mcid);
+ if (num === null || present.has(mcid) || !mcidsBefore.has(mcid)) continue;
+ slots[mcid] = "null";
+ changesFor(num).removed.add(mcid);
+ }
+
+ if (elements.size === 0) return null;
+
+ const streams = new Map<number, string>();
+ texts.forEach((text, stream) => {
+ const here = renumbered
+ .filter((r) => r.site.stream === stream)
+ .map((r) => ({ at: r.site.number!, mcid: r.mcid }))
+ .sort((a, b) => b.at.start - a.at.start);
+ if (here.length === 0) return;
+ let out = text;
+ for (const { at, mcid } of here) {
+ out = out.slice(0, at.start) + String(mcid) + out.slice(at.end);
+ }
+ streams.set(refs[stream], out);
+ });
+
+ return {
+ streams,
+ parentEntry: entry,
+ parentArray: `[${slots.join(" ")}]`,
+ elements,
+ };
+}
+
+/** The page's content streams and every MCID they carry, or null when a stream cannot be read. */
+async function pageSites(
+ pdf: RawPdf,
+ pageNum: number,
+): Promise<PageSites | null> {
+ const page = pdf.objectBody(pageNum);
+ const refs = page ? pdf.contentRefs(page) : [];
+ if (refs.length === 0) return null;
+ const texts: string[] = [];
+ for (const ref of refs) {
+ const data = await pdf.streamData(ref);
+ if (!data) return null;
+ texts.push(toLatin1(data));
+ }
+ const resources = pdf.pageInherited(pageNum, "Resources");
+ const properties = resources ? pdf.resolve(resources, "Properties") : null;
+ const namedMcid = (name: string): number | null => {
+ const list = properties ? pdf.resolve(properties, name) : null;
+ return list ? pdf.dictInt(list, "MCID") : null;
+ };
+ return {
+ refs,
+ texts,
+ sites: texts.flatMap((text, stream) => mcidSites(text, stream, namedMcid)),
+ };
+}
+
+/**
+ * Every `BDC` carrying an MCID, in content order: inline (`/P <</MCID 0>> BDC`)
+ * or through a named property list (`/P /MC0 BDC`), which PDFium keeps in that
+ * form when it regenerates a page.
+ */
+function mcidSites(
+ text: string,
+ stream: number,
+ namedMcid: (name: string) => number | null,
+): McidSite[] {
+ const sites: McidSite[] = [];
+ for (const op of parseOps(text)) {
+ if (op.op !== "BDC") continue;
+ const properties = op.operands[1];
+ if (properties?.startsWith("/")) {
+ const mcid = namedMcid(properties.slice(1));
+ if (mcid !== null) sites.push({ stream, mcid, number: null });
+ continue;
+ }
+ const tokens = tokenize(text.slice(op.start, op.end));
+ let depth = 0;
+ for (let i = 0; i < tokens.length; i++) {
+ const t = tokens[i].text;
+ if (t === "<<") depth += 1;
+ else if (t === ">>") depth -= 1;
+ else if (
+ depth === 1 &&
+ t === "/MCID" &&
+ /^\d+$/.test(tokens[i + 1]?.text ?? "")
+ ) {
+ const number = tokens[i + 1];
+ sites.push({
+ stream,
+ mcid: parseInt(number.text, 10),
+ number: {
+ start: op.start + number.start,
+ end: op.start + number.end,
+ },
+ });
+ break;
+ }
+ }
+ }
+ return sites;
+}
+
+/**
+ * Apply `changes` to an element's /K. An integer kid names an MCID on the
+ * element's own /Pg, so a new MCID on another page is written as an MCR.
+ */
+function rewriteKids(
+ pdf: RawPdf,
+ body: string,
+ changes: KidChanges,
+): string | null {
+ const span = pdf.valueSpan(body, "K");
+ const kids = !span
+ ? []
+ : span.text.startsWith("[")
+ ? (arrayItems(span.text)?.map((k) => k.text) ?? null)
+ : [span.text];
+ if (!kids) return null;
+ const elementPage = pdf.dictRef(body, "Pg");
+
+ const mcidOnPage = (kid: string): number | null => {
+ if (/^\d+$/.test(kid)) {
+ return elementPage === changes.pageNum ? parseInt(kid, 10) : null;
+ }
+ const ref = kid.match(REF);
+ const dict = ref ? pdf.objectBody(parseInt(ref[1], 10)) : kid;
+ if (!dict?.trimStart().startsWith("<<")) return null;
+ if (pdf.dictName(dict, "Type") !== "MCR" || pdf.valueSpan(dict, "Stm")) {
+ return null;
+ }
+ const page = pdf.dictRef(dict, "Pg") ?? elementPage;
+ return page === changes.pageNum ? pdf.dictInt(dict, "MCID") : null;
+ };
+ const newKid = (mcid: number): string =>
+ elementPage === changes.pageNum
+ ? String(mcid)
+ : `<< /Type /MCR /Pg ${changes.pageNum} 0 R /MCID ${mcid} >>`;
+
+ const out: string[] = [];
+ const placed = new Set<number>();
+ for (const kid of kids) {
+ const mcid = mcidOnPage(kid);
+ if (mcid !== null && changes.removed.has(mcid)) continue;
+ out.push(kid);
+ const added = mcid === null ? undefined : changes.added.get(mcid);
+ if (added && !placed.has(mcid!)) {
+ out.push(...added.map(newKid));
+ placed.add(mcid!);
+ }
+ }
+ for (const [after, mcids] of changes.added) {
+ if (!placed.has(after)) out.push(...mcids.map(newKid));
+ }
+ return setDictEntry(body, "K", `[${out.join(" ")}]`);
+}
+
+function streamsUsedByMoreThanOnePage(pdf: RawPdf): Set<number> {
+ const seen = new Set<number>();
+ const shared = new Set<number>();
+ for (const pageNum of pdf.pageNumbers()) {
+ const body = pdf.objectBody(pageNum);
+ for (const ref of body ? new Set(pdf.contentRefs(body)) : []) {
+ if (seen.has(ref)) shared.add(ref);
+ seen.add(ref);
+ }
+ }
+ return shared;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/raw.ts
index 8703775d35..9a1f37e603 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/raw.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/raw.ts
@@ -1,5 +1,6 @@
/**
- * A deliberately small read-only view over raw PDF bytes.
+ * A deliberately small view over raw PDF bytes, plus the splicing helpers
+ * the passes build their revision objects with.
*
* PDFium's public API cannot express some of the repairs the editor needs
* (see `pdfdoc/passes/*`), so those passes work on the file itself. This is
@@ -23,7 +24,10 @@ const MAX_OBJECT_BYTES = 32 * 1024 * 1024;
const WHITESPACE = new Set([" ", "\t", "\r", "\n", "\f", "\0"]);
const DELIMITER = new Set(["(", ")", "<", ">", "[", "]", "{", "}", "/", "%"]);
-/** Span of a dictionary entry's value inside an object body. */
+/** Span of a value inside an object body. */
+/** Deeper than any real number tree; bounds a malformed one without a cycle. */
+const MAX_NUMBER_TREE_DEPTH = 32;
+
export interface ValueSpan {
/** Index of the first character of the value. */
start: number;
@@ -32,6 +36,23 @@ export interface ValueSpan {
text: string;
}
+export interface NumberTreeEntry {
+ /** The object whose body holds the value. */
+ objNum: number;
+ span: ValueSpan;
+}
+
+/**
+ * A page's ParentTree value (ISO 32000-1 14.7.4.4). Slot n of `items` names
+ * the element that owns MCID n on the page; `items` is null when the value is
+ * not an array.
+ */
+export interface ParentTreeArray {
+ /** Where the page's value sits: the array itself, or a reference to it. */
+ entry: NumberTreeEntry;
+ items: ValueSpan[] | null;
+}
+
interface ObjectSource {
/** Generation the file declares for this object; almost always 0. */
gen: number;
@@ -161,7 +182,7 @@ export class RawPdf {
usesXrefStream,
startXref,
trailerId,
- encrypted: /\/Encrypt\s+\d+\s+\d+\s+R/.test(src),
+ encrypted: /\/Encrypt\s*(?:\d+\s+\d+\s+R|<<)/.test(src),
objects,
});
await pdf.indexObjectStreams();
@@ -338,46 +359,97 @@ export class RawPdf {
* the page's own entry produces a file that opens but renders nothing.
*/
valueSpan(body: string, key: string): ValueSpan | null {
- const open = body.indexOf("<<");
- if (open < 0) return null;
- let i = open + 2;
- let depth = 1;
- while (i < body.length) {
- const ch = body[i];
- if (ch === "%") {
- while (i < body.length && body[i] !== "\n" && body[i] !== "\r") i += 1;
- continue;
- }
- if (ch === "(") {
- i = skipLiteralString(body, i);
- continue;
- }
- if (ch === "<" && body[i + 1] === "<") {
- depth += 1;
- i += 2;
- continue;
- }
- if (ch === ">" && body[i + 1] === ">") {
- depth -= 1;
- i += 2;
- if (depth === 0) return null;
- continue;
- }
- if (ch === "[" || ch === "]") {
- i += 1;
- continue;
- }
- if (ch === "/" && depth === 1) {
- const nameEnd = scanNameEnd(body, i + 1);
- if (body.slice(i + 1, nameEnd) === key) {
- const start = skipWhitespace(body, nameEnd);
- const end = scanValueEnd(body, start);
- return { start, end, text: body.slice(start, end) };
+ const entry = findEntry(body, key);
+ return entry
+ ? {
+ start: entry.start,
+ end: entry.end,
+ text: body.slice(entry.start, entry.end),
}
- i = nameEnd;
- continue;
+ : null;
+ }
+
+ /**
+ * Find the value a number tree (ISO 32000-1 7.9.7) holds for `key`. The
+ * tree is `/treeKey` in the body of object `holderNum`, written directly or
+ * by reference. The span is into the body of the returned object, so a
+ * caller can splice a replacement into it and append that object.
+ */
+ numberTreeEntry(
+ holderNum: number,
+ treeKey: string,
+ key: number,
+ ): NumberTreeEntry | null {
+ const holder = this.objectBody(holderNum);
+ const span = holder ? this.valueSpan(holder, treeKey) : null;
+ if (!holder || !span) return null;
+ const ref = span.text.match(/^(\d+)\s+\d+\s+R\b/);
+ if (!ref)
+ return this.searchNumberTree(holderNum, span.start, key, new Set(), 0);
+ return this.searchNumberTree(parseInt(ref[1], 10), 0, key, new Set(), 0);
+ }
+
+ /** The ParentTree value for `/StructParents key`, or null when the tree has none. */
+ parentTreeArray(treeRoot: number, key: number): ParentTreeArray | null {
+ const entry = this.numberTreeEntry(treeRoot, "ParentTree", key);
+ if (!entry) return null;
+ const ref = referencedObject(entry.span.text);
+ const list = ref === null ? entry.span.text : this.objectBody(ref)?.trim();
+ return { entry, items: list ? arrayItems(list) : null };
+ }
+
+ private searchNumberTree(
+ objNum: number,
+ nodeStart: number,
+ key: number,
+ seen: Set<number>,
+ depth: number,
+ ): NumberTreeEntry | null {
+ if (depth > MAX_NUMBER_TREE_DEPTH) return null;
+ // A direct node shares its holder's number, so only indirect ones can cycle.
+ if (nodeStart === 0) {
+ if (seen.has(objNum)) return null;
+ seen.add(objNum);
+ }
+ const body = this.objectBody(objNum);
+ if (!body) return null;
+ const node = body.slice(nodeStart);
+
+ const nums = this.valueSpan(node, "Nums");
+ const pairs = nums ? arrayItems(nums.text) : null;
+ if (nums && pairs) {
+ for (let i = 0; i + 1 < pairs.length; i += 2) {
+ if (pairs[i].text !== String(key)) continue;
+ const value = pairs[i + 1];
+ const at = nodeStart + nums.start;
+ return {
+ objNum,
+ span: {
+ start: at + value.start,
+ end: at + value.end,
+ text: value.text,
+ },
+ };
}
- i += 1;
+ }
+
+ const kids = this.resolve(node, "Kids");
+ for (const m of kids?.matchAll(/(\d+)\s+\d+\s+R/g) ?? []) {
+ const kidNum = parseInt(m[1], 10);
+ const kid = this.objectBody(kidNum);
+ const limits = kid ? this.resolve(kid, "Limits") : null;
+ const [lo, hi] = (limits ? arrayItems(limits.trim()) : null)?.map((b) =>
+ Number(b.text),
+ ) ?? [NaN, NaN];
+ // /Limits is only an index; without both bounds, search the kid anyway.
+ if (
+ Number.isInteger(lo) &&
+ Number.isInteger(hi) &&
+ (key < lo || key > hi)
+ )
+ continue;
+ const found = this.searchNumberTree(kidNum, 0, key, seen, depth + 1);
+ if (found) return found;
}
return null;
}
@@ -590,6 +662,122 @@ export function spliceValue(
);
}
+/**
+ * Set `/Key` in the body's outermost dictionary to `value`, a serialised PDF
+ * object, adding the entry when absent. Null when the body has no complete
+ * dictionary to put it in.
+ */
+export function setDictEntry(
+ body: string,
+ key: string,
+ value: string,
+): string | null {
+ const entry = findEntry(body, key);
+ if (entry) {
+ return spliceValue(
+ body,
+ {
+ start: entry.start,
+ end: entry.end,
+ text: body.slice(entry.start, entry.end),
+ },
+ value,
+ );
+ }
+ const open = body.indexOf("<<");
+ if (open < 0) return null;
+ const close = scanValueEnd(body, open);
+ if (body.slice(close - 2, close) !== ">>") return null;
+ return `${body.slice(0, close - 2)} /${key} ${value} ${body.slice(close - 2)}`;
+}
+
+/** Drop `/Key` and its value from the body's outermost dictionary. */
+export function removeDictEntry(body: string, key: string): string {
+ const entry = findEntry(body, key);
+ return entry ? body.slice(0, entry.keyStart) + body.slice(entry.end) : body;
+}
+
+/**
+ * The elements of a serialised array, each as one complete object: an
+ * indirect reference is one element, not three. Spans are into `text`. Null
+ * when `text` is not an array this can read.
+ */
+/** `12 0 R` -> 12; null for anything that is not a single reference. */
+export function referencedObject(text: string): number | null {
+ const m = text.match(/^(\d+)\s+\d+\s+R$/);
+ return m ? parseInt(m[1], 10) : null;
+}
+
+export function arrayItems(text: string): ValueSpan[] | null {
+ if (text[0] !== "[") return null;
+ const items: ValueSpan[] = [];
+ let i = 1;
+ for (;;) {
+ i = skipWhitespace(text, i);
+ if (text[i] === "%") {
+ while (i < text.length && text[i] !== "\n" && text[i] !== "\r") i += 1;
+ continue;
+ }
+ if (i >= text.length) return null;
+ if (text[i] === "]") return items;
+ const end = scanValueEnd(text, i);
+ // A token the scanner cannot consume, such as a stray `)`, would loop forever.
+ if (end <= i) return null;
+ items.push({ start: i, end, text: text.slice(i, end) });
+ i = end;
+ }
+}
+
+interface Entry {
+ keyStart: number;
+ start: number;
+ end: number;
+}
+
+function findEntry(body: string, key: string): Entry | null {
+ const open = body.indexOf("<<");
+ if (open < 0) return null;
+ let i = open + 2;
+ let depth = 1;
+ while (i < body.length) {
+ const ch = body[i];
+ if (ch === "%") {
+ while (i < body.length && body[i] !== "\n" && body[i] !== "\r") i += 1;
+ continue;
+ }
+ if (ch === "(") {
+ i = skipLiteralString(body, i);
+ continue;
+ }
+ if (ch === "<" && body[i + 1] === "<") {
+ depth += 1;
+ i += 2;
+ continue;
+ }
+ if (ch === ">" && body[i + 1] === ">") {
+ depth -= 1;
+ i += 2;
+ if (depth === 0) return null;
+ continue;
+ }
+ if (ch === "[" || ch === "]") {
+ i += 1;
+ continue;
+ }
+ if (ch === "/" && depth === 1) {
+ const nameEnd = scanNameEnd(body, i + 1);
+ if (body.slice(i + 1, nameEnd) === key) {
+ const start = skipWhitespace(body, nameEnd);
+ return { keyStart: i, start, end: scanValueEnd(body, start) };
+ }
+ i = nameEnd;
+ continue;
+ }
+ i += 1;
+ }
+ return null;
+}
+
function skipWhitespace(text: string, at: number): number {
let i = at;
while (i < text.length && WHITESPACE.has(text[i])) i += 1;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
new file mode 100644
index 0000000000..45a601556f
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -0,0 +1,87 @@
+import type { StructureElement } from "@app/tools/pdfTextEditor/model/PageStructure";
+import { RawPdf, referencedObject } from "@app/tools/pdfTextEditor/pdfdoc/raw";
+import { decodeTextString } from "@app/tools/pdfTextEditor/pdfdoc/textString";
+
+type ElementInfo = Omit<StructureElement, "mcids">;
+
+/**
+ * Every page's structure elements, keyed by page index, each listing only the
+ * MCIDs the page's ParentTree slots give it: the lookup the save addresses
+ * edits by. PDFium lists an element's MCIDs from every page with no page
+ * attached, so an element spanning a page break would claim another element's
+ * MCID there. Null when the file is untagged, cannot be parsed, or is
+ * encrypted, whose strings would read as ciphertext.
+ */
+export async function readFileStructure(
+ bytes: Uint8Array,
+): Promise<Map<number, StructureElement[]> | null> {
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf || pdf.encrypted) return null;
+ const catalog = pdf.objectBody(pdf.rootNum);
+ const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
+ const rootBody = treeRoot === null ? null : pdf.objectBody(treeRoot);
+ if (treeRoot === null || !rootBody) return null;
+ const roleMap = pdf.resolve(rootBody, "RoleMap");
+
+ const infos = new Map<number, ElementInfo | null>();
+ const infoFor = (num: number): ElementInfo | null => {
+ if (!infos.has(num)) infos.set(num, readElement(pdf, num, roleMap));
+ return infos.get(num)!;
+ };
+
+ const byPage = new Map<number, StructureElement[]>();
+ pdf.pageNumbers().forEach((pageNum, pageIndex) => {
+ const page = pdf.objectBody(pageNum);
+ const key = page ? pdf.dictInt(page, "StructParents") : null;
+ const items =
+ key === null ? null : pdf.parentTreeArray(treeRoot, key)?.items;
+ if (!items) return;
+ const owned = new Map<number, StructureElement>();
+ items.forEach((item, mcid) => {
+ const num = referencedObject(item.text);
+ const info = num === null ? null : infoFor(num);
+ if (num === null || !info) return;
+ const element = owned.get(num) ?? { ...info, mcids: [] };
+ element.mcids.push(mcid);
+ owned.set(num, element);
+ });
+ byPage.set(pageIndex, [...owned.values()]);
+ });
+ return byPage;
+}
+
+function readElement(
+ pdf: RawPdf,
+ num: number,
+ roleMap: string | null,
+): ElementInfo | null {
+ const body = pdf.objectBody(num);
+ const type = body ? pdf.dictName(body, "S") : null;
+ if (!body || type === null) return null;
+ const text = (key: string): string | null => {
+ const value = pdf.resolve(body, key);
+ return value === null ? null : decodeTextString(value.trim());
+ };
+ return {
+ type: applyRoleMap(pdf, roleMap, type),
+ alt: text("Alt"),
+ actualText: text("ActualText"),
+ };
+}
+
+/** Follow /RoleMap (ISO 32000-1 14.8.4) until a type it does not remap. */
+function applyRoleMap(
+ pdf: RawPdf,
+ roleMap: string | null,
+ type: string,
+): string {
+ let current = type;
+ const seen = new Set<string>();
+ while (roleMap && !seen.has(current)) {
+ seen.add(current);
+ const mapped = pdf.dictName(roleMap, current);
+ if (mapped === null) break;
+ current = mapped;
+ }
+ return current;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/textString.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/textString.ts
new file mode 100644
index 0000000000..8285e0e8ca
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfdoc/textString.ts
@@ -0,0 +1,130 @@
+/**
+ * Serialise `text` as a PDF text string (ISO 32000-1 7.9.2.2). Printable
+ * ASCII stays a readable literal, since it means the same in PDFDocEncoding;
+ * anything else is UTF-16BE behind a byte order mark, which every reader
+ * decodes, where PDFDocEncoding cannot hold most scripts at all.
+ */
+export function encodeTextString(text: string): string {
+ if (/^[\x20-\x7e]*$/.test(text)) {
+ return `(${text.replace(/[\\()]/g, (ch) => `\\${ch}`)})`;
+ }
+ let hex = "<FEFF";
+ // JS strings are UTF-16 code units, so astral characters arrive as their
+ // surrogate pair, which is exactly what UTF-16BE wants.
+ for (let i = 0; i < text.length; i += 1) {
+ hex += text.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0");
+ }
+ return `${hex}>`;
+}
+
+/**
+ * Read a PDF string token, `(literal)` or `<hex>`, as a text string (ISO
+ * 32000-1 7.9.2.2): UTF-16BE or UTF-8 behind a byte order mark, else
+ * PDFDocEncoding. Null when the token is not a string.
+ */
+export function decodeTextString(token: string): string | null {
+ const bytes = token.startsWith("(")
+ ? literalBytes(token)
+ : token.startsWith("<") && !token.startsWith("<<")
+ ? hexBytes(token)
+ : null;
+ if (!bytes) return null;
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) {
+ let text = "";
+ for (let i = 2; i + 1 < bytes.length; i += 2) {
+ text += String.fromCharCode((bytes[i] << 8) | bytes[i + 1]);
+ }
+ return text;
+ }
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
+ return new TextDecoder("utf-8").decode(Uint8Array.from(bytes.slice(3)));
+ }
+ return String.fromCharCode(...bytes.map(fromPdfDocEncoding));
+}
+
+const LITERAL_ESCAPES: Record<string, number> = {
+ n: 0x0a,
+ r: 0x0d,
+ t: 0x09,
+ b: 0x08,
+ f: 0x0c,
+ "(": 0x28,
+ ")": 0x29,
+ "\\": 0x5c,
+};
+
+/** The bytes of a literal string token (ISO 32000-1 7.3.4.2), or null when it is unterminated. */
+function literalBytes(token: string): number[] | null {
+ const out: number[] = [];
+ let depth = 0;
+ for (let i = 1; i < token.length; i += 1) {
+ const c = token[i];
+ if (c === "\\") {
+ i += 1;
+ const next = token[i];
+ if (next === undefined) return null;
+ if (next in LITERAL_ESCAPES) {
+ out.push(LITERAL_ESCAPES[next]);
+ } else if (next >= "0" && next <= "7") {
+ let digits = next;
+ while (digits.length < 3 && /[0-7]/.test(token[i + 1] ?? "")) {
+ i += 1;
+ digits += token[i];
+ }
+ out.push(parseInt(digits, 8) & 0xff);
+ } else if (next === "\r") {
+ // A backslash before an end-of-line continues the string on the next line.
+ if (token[i + 1] === "\n") i += 1;
+ } else if (next !== "\n") {
+ // An unknown escape keeps the character and drops the backslash.
+ out.push(next.charCodeAt(0) & 0xff);
+ }
+ continue;
+ }
+ if (c === "(") depth += 1;
+ if (c === ")") {
+ if (depth === 0) return out;
+ depth -= 1;
+ }
+ if (c === "\r") {
+ // Every end-of-line in a literal reads as a single LF.
+ out.push(0x0a);
+ if (token[i + 1] === "\n") i += 1;
+ continue;
+ }
+ out.push(c.charCodeAt(0) & 0xff);
+ }
+ return null;
+}
+
+function hexBytes(token: string): number[] | null {
+ const end = token.indexOf(">");
+ if (end < 0) return null;
+ let hex = token.slice(1, end).replace(/\s+/g, "");
+ if (!/^[0-9a-fA-F]*$/.test(hex)) return null;
+ // A missing final digit is taken as 0.
+ if (hex.length % 2 === 1) hex += "0";
+ const out: number[] = [];
+ for (let i = 0; i < hex.length; i += 2) {
+ out.push(parseInt(hex.slice(i, i + 2), 16));
+ }
+ return out;
+}
+
+// PDFDocEncoding (ISO 32000-1 Annex D.2) where it differs from Latin-1.
+const PDF_DOC_LOW = [
+ 0x02d8, 0x02c7, 0x02c6, 0x02d9, 0x02dd, 0x02db, 0x02da, 0x02dc,
+];
+const PDF_DOC_HIGH = [
+ 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x0192, 0x2044, 0x2039,
+ 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a,
+ 0x2122, 0xfb01, 0xfb02, 0x0141, 0x0152, 0x0160, 0x0178, 0x017d, 0x0131,
+ 0x0142, 0x0153, 0x0161, 0x017e,
+];
+
+function fromPdfDocEncoding(byte: number): number {
+ if (byte >= 0x18 && byte <= 0x1f) return PDF_DOC_LOW[byte - 0x18];
+ if (byte >= 0x80 && byte <= 0x9e) return PDF_DOC_HIGH[byte - 0x80];
+ if (byte === 0xa0) return 0x20ac;
+ return byte;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
new file mode 100644
index 0000000000..ba3914963b
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
@@ -0,0 +1,70 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { readUtf16 } from "@app/services/pdfiumService";
+import type { StructureElement } from "@app/tools/pdfTextEditor/model/PageStructure";
+
+type StringGetter = (el: number, buf: number, len: number) => number;
+
+/** Bound on tree depth: a cyclic /K would otherwise recurse forever. */
+const MAX_DEPTH = 64;
+
+/**
+ * Every structure element PDFium attributes to the page, in tree order. Empty
+ * for an untagged document. Never throws: a tree this cannot read reads as
+ * untagged, which is what the rest of the editor already handles.
+ */
+export function readPageStructure(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+): StructureElement[] {
+ const out: StructureElement[] = [];
+ let tree = 0;
+ try {
+ tree = m.FPDF_StructTree_GetForPage(pagePtr);
+ if (!tree) return out;
+ const visit = (el: number, depth: number): void => {
+ if (!el || depth > MAX_DEPTH) return;
+ const mcids: number[] = [];
+ const count = m.FPDF_StructElement_GetMarkedContentIdCount(el);
+ for (let i = 0; i < count; i++) {
+ const id = m.FPDF_StructElement_GetMarkedContentIdAtIndex(el, i);
+ if (id >= 0) mcids.push(id);
+ }
+ out.push({
+ type: readString(m, el, m.FPDF_StructElement_GetType) ?? "",
+ alt: readString(m, el, m.FPDF_StructElement_GetAltText),
+ actualText: readString(m, el, m.FPDF_StructElement_GetActualText),
+ mcids,
+ });
+ const kids = m.FPDF_StructElement_CountChildren(el);
+ for (let i = 0; i < kids; i++) {
+ visit(m.FPDF_StructElement_GetChildAtIndex(el, i), depth + 1);
+ }
+ };
+ const roots = m.FPDF_StructTree_CountChildren(tree);
+ for (let i = 0; i < roots; i++) {
+ visit(m.FPDF_StructTree_GetChildAtIndex(tree, i), 0);
+ }
+ } catch {
+ return [];
+ } finally {
+ if (tree) m.FPDF_StructTree_Close(tree);
+ }
+ return out;
+}
+
+/** Null when the entry is absent, which PDFium reports as length 0. */
+function readString(
+ m: WrappedPdfiumModule,
+ el: number,
+ get: StringGetter,
+): string | null {
+ const len = get(el, 0, 0);
+ if (len <= 0) return null;
+ const buf = m.pdfium.wasmExports.malloc(len);
+ try {
+ get(el, buf, len);
+ return readUtf16(m, buf, len);
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
index d51e150e17..a1c5dce99c 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
@@ -2,7 +2,7 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
const MCID = "MCID";
-const ARTIFACT = "Artifact";
+export const ARTIFACT_TAG = "Artifact";
/**
* A marked-content tag that links a page object to the structure tree, or
@@ -32,7 +32,7 @@ export function readTagMarks(
if (!mark) continue;
const name = markName(m, mark);
const mcid = markMcid(m, mark);
- if (mcid !== null || name === ARTIFACT) tags.push({ name, mcid });
+ if (mcid !== null || name === ARTIFACT_TAG) tags.push({ name, mcid });
}
} catch {
return [];
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index 6cb67d29eb..9f45543f9b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -18,7 +18,10 @@ import type {
import { readUtf16 } from "@app/services/pdfiumService";
import { registerEmbeddedFace } from "@app/tools/pdfTextEditor/util/embeddedFace";
import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
-import { readTagMarks } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import {
+ ARTIFACT_TAG,
+ readTagMarks,
+} from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
/** PDFium page-object type constants - mirrors `public/fpdf_edit.h`. */
const FPDF_PAGEOBJ_TEXT = 1;
@@ -1058,6 +1061,8 @@ function readImage(
if (!localBounds) return null;
const localMatrix = readMatrix(m, objPtr);
const ident = isIdentity(transform);
+ // A form XObject's MCIDs are not the page's, so only page-level images are tagged.
+ const tags = containerPtr === 0 ? readTagMarks(m, objPtr) : [];
return new ImageObject({
id: `p${page.index}-i${index}`,
pageIndex: page.index,
@@ -1065,5 +1070,7 @@ function readImage(
bounds: ident ? localBounds : transformRect(transform, localBounds),
matrix: ident ? localMatrix : composeAffine(transform, localMatrix),
containerPtr,
+ mcid: [...tags].reverse().find((t) => t.mcid !== null)?.mcid ?? undefined,
+ artifact: tags.some((t) => t.name === ARTIFACT_TAG) || undefined,
});
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/types.ts b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
index 63bca5595a..bb546b4e6b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/types.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
@@ -92,6 +92,10 @@ export interface ImageObjectSnapshot {
matrix: Affine;
/** Editor-only: see TextRunSnapshot.locked. */
locked?: boolean;
+ /** The marked-content ID that ties the image into the structure tree. */
+ mcid?: number;
+ /** Marked as an artifact: decoration that assistive technology skips. */
+ artifact?: boolean;
}
// One ruling line the page draws, with the ink needed to reproduce it: a table
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
index 2f5917bf59..543e5c5f1f 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -1,4 +1,6 @@
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { applyStructureEdits } from "@app/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import { repairStructure } from "@app/tools/pdfTextEditor/pdfdoc/passes/repairStructure";
import { preserveShadings } from "@app/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";
import { PdfiumSave } from "@app/tools/pdfTextEditor/pdfium/PdfiumSave";
import {
@@ -14,19 +16,62 @@ export async function exportToBlob(
blob: Blob;
filename: string;
}> {
- // Nothing was ever written to a page, so PDFium has nothing to contribute:
- // handing back what we opened keeps the file byte-identical. Rewriting it
- // changed the bytes of 8 of this suite's 10 fixtures and inflated the small
- // ones by up to 35% - for no edit at all.
+ const structureEdits = doc.structureEdits();
+ // A signed document is appended to rather than rewritten, so the bytes the
+ // signature covers are still there and still verify for their revision.
+ const incremental = documentIsSigned(doc);
+ let bytes: Uint8Array;
if (documentIsPristine(doc)) {
- return { blob: pdfBlob(doc.openedBytes), filename: exportName(sourceName) };
+ // Nothing was ever written to a page, so PDFium has nothing to contribute:
+ // starting from what we opened keeps the file byte-identical. Rewriting it
+ // changed the bytes of 8 of this suite's 10 fixtures and inflated the small
+ // ones by up to 35% - for no edit at all.
+ if (structureEdits.length === 0) {
+ return {
+ blob: pdfBlob(doc.openedBytes),
+ filename: exportName(sourceName),
+ };
+ }
+ bytes = doc.openedBytes;
+ } else {
+ bytes = await serializeEdits(doc, incremental);
+ }
+
+ // Throws rather than dropping them: a description the user wrote that the
+ // saved file silently lacks is worse than a save that reports it failed.
+ bytes = await applyStructureEdits(bytes, structureEdits);
+
+ // After the edits: when the content an element described was deleted, the
+ // repair removes the ParentTree slot an edit to that element is addressed by,
+ // and the edit would then fail the save.
+ const regenerated = doc.regeneratedPages();
+ if (regenerated.length > 0) {
+ try {
+ const repaired = await repairStructure(bytes, {
+ pages: regenerated,
+ original: doc.openedBytes,
+ });
+ if (repaired) bytes = repaired;
+ } catch {
+ /* the unrepaired tags are what every save wrote before this pass */
+ }
}
+ // Re-checked after the repairs: `PdfiumSave.serialize` validated its own
+ // output, but the passes since may have swapped in a different buffer, and
+ // these are the bytes the workspace file is overwritten with.
+ assertSavedPdf(bytes);
+ if (incremental) assertIncrementalAppend(bytes, doc.openedBytes);
+
+ return { blob: pdfBlob(bytes), filename: exportName(sourceName) };
+}
+
+async function serializeEdits(
+ doc: EditorDocument,
+ incremental: boolean,
+): Promise<Uint8Array> {
commitPendingFormRemovals(doc);
- // A signed document is appended to rather than rewritten, so the bytes the
- // signature covers are still there and still verify for their revision.
- const incremental = documentIsSigned(doc);
// Must be read AFTER serialize: serialize is what marks pages regenerated,
// so reading first always yielded an empty list and silently skipped the
// shading repair on the first save after an edit.
@@ -45,14 +90,7 @@ export async function exportToBlob(
/* the unrepaired save is still a correct save */
}
}
-
- // Re-checked after the shading repair: `PdfiumSave.serialize` validated its
- // own output, but `preserveShadings` may have swapped in a different buffer,
- // and these are the bytes the workspace file is overwritten with.
- assertSavedPdf(bytes);
- if (incremental) assertIncrementalAppend(bytes, doc.openedBytes);
-
- return { blob: pdfBlob(bytes), filename: exportName(sourceName) };
+ return bytes;
}
interface FormRemovalModule {
diff --git a/frontend/editor/src/proprietary/constants/featureFlags.ts b/frontend/editor/src/proprietary/constants/featureFlags.ts
deleted file mode 100644
index 73a7d2077d..0000000000
--- a/frontend/editor/src/proprietary/constants/featureFlags.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Proprietary-build feature gates. Shadows `core/constants/featureFlags.ts` in
- * the proprietary build (resolved via the `@app/*` alias), so flags here only
- * affect proprietary/SaaS builds — the open-source core build keeps the core
- * values.
- */
-
-// Refill an empty workbench from the tab's last session (survives the editor/processor switch).
-export const WORKBENCH_SESSION_RESTORE: boolean = true;