#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Have Text Editor maintain existing accessibility tags on save (#8447)
James Bruntonfa8c22d9f87a
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.tsnew file mode 100644index 0000000000..d228d9cd27--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts@@ -0,0 +1,184 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";+import path from "path";++// Editing text in a tagged PDF must keep it in the structure tree. The editor+// re-creates the objects it edits, and an object created without the original's+// marked-content ID is text assistive technology can no longer reach, while the+// element that described it points at nothing.++const FIXTURE = path.join(+ import.meta.dirname,+ "../test-fixtures/tagged-sample.pdf",+);++interface TagAudit {+ untaggedText: number;+ contentMcids: number[];+ treeMcids: number[];+}++// Reads the open document through the editor's own PDFium; after a reopen that+// is exactly what was saved.+const AUDIT = (): TagAudit => {+ type Fn = (...args: number[]) => number;+ const doc = (+ window as unknown as {+ __editor_store: {+ document: {+ module: Record<string, Fn>;+ page: (i: number) => { pagePtr: number };+ };+ };+ }+ ).__editor_store.document;+ const m = doc.module;+ const pagePtr = doc.page(0).pagePtr;++ let untaggedText = 0;+ const content = new Set<number>();+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {+ const obj = m.FPDFPage_GetObject(pagePtr, i);+ if (m.FPDFPageObj_GetType(obj) === 1 && m.FPDFPageObj_CountMarks(obj) === 0)+ untaggedText++;+ const id = m.FPDFPageObj_GetMarkedContentID(obj);+ if (id >= 0) content.add(id);+ }++ const tree = new Set<number>();+ const walk = (el: number) => {+ for (let i = 0; i < m.FPDF_StructElement_GetMarkedContentIdCount(el); i++) {+ const id = m.FPDF_StructElement_GetMarkedContentIdAtIndex(el, i);+ if (id >= 0) tree.add(id);+ }+ for (let i = 0; i < m.FPDF_StructElement_CountChildren(el); i++) {+ const kid = m.FPDF_StructElement_GetChildAtIndex(el, i);+ if (kid) walk(kid);+ }+ };+ const root = m.FPDF_StructTree_GetForPage(pagePtr);+ for (let i = 0; i < m.FPDF_StructTree_CountChildren(root); i++)+ walk(m.FPDF_StructTree_GetChildAtIndex(root, i));+ m.FPDF_StructTree_Close(root);++ const sorted = (s: Set<number>) => [...s].sort((a, b) => a - b);+ return {+ untaggedText,+ contentMcids: sorted(content),+ treeMcids: sorted(tree),+ };+};++const RUN_ID = (needle: string) => {+ const runs = (+ window as unknown as {+ __editor_store: {+ state: { pages: { runs: { id: string; text: string }[] }[] };+ };+ }+ ).__editor_store.state.pages[0].runs;+ return runs.find((r) => r.text.includes(needle))?.id ?? null;+};++async function typeInto(+ page: import("@playwright/test").Page,+ runId: string,+ text: string,+ mode: "append" | "replace",+) {+ await page.evaluate(+ ({ id, text, mode }) => {+ const el = document.querySelector<HTMLElement>(+ `[data-testid="pdf-editor-run-${id}"]`,+ );+ if (!el) throw new Error("run missing");+ el.focus();+ const range = document.createRange();+ range.selectNodeContents(el);+ if (mode === "append") range.collapse(false);+ const sel = window.getSelection();+ if (!sel) throw new Error("no selection api");+ sel.removeAllRanges();+ sel.addRange(range);+ document.execCommand("insertText", false, text);+ },+ { id: runId, text, mode },+ );+ await page.waitForTimeout(450);+}++async function saveAndReopen(page: import("@playwright/test").Page) {+ const downloaded = page.waitForEvent("download", { timeout: 30_000 });+ 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";+ await (await downloaded).saveAs(saved);+ await page.evaluate(() => {+ const w = window as unknown as {+ __editor_store?: { document: unknown };+ __prev_document?: unknown;+ };+ w.__prev_document = w.__editor_store?.document;+ });+ await page+ .locator('[data-testid="pdf-editor-file-input"]')+ .setInputFiles(saved);+ await page.waitForFunction(+ () => {+ const w = window as unknown as {+ __editor_store?: {+ document: unknown;+ state: { pages: { runs: unknown[] }[] };+ };+ __prev_document?: unknown;+ };+ const s = w.__editor_store;+ if (!s?.document || s.document === w.__prev_document) return false;+ return (s.state.pages[0]?.runs.length ?? 0) > 0;+ },+ undefined,+ { timeout: 30_000 },+ );+ await page.waitForTimeout(1200);+}++test.describe("PDF text editor - tagged documents", () => {+ test("edited text stays in the structure tree", async ({ page }) => {+ test.setTimeout(120_000);+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({+ timeout: 15_000,+ });+ await page+ .locator('[data-testid="pdf-editor-file-input"]')+ .setInputFiles(FIXTURE);+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({+ timeout: 30_000,+ });+ await page.waitForTimeout(1800);++ expect(await page.evaluate(AUDIT)).toEqual({+ untaggedText: 0,+ contentMcids: [0, 1, 2],+ treeMcids: [0, 1, 2],+ });++ const heading = await page.evaluate(RUN_ID, "Quarterly report");+ const paragraph = await page.evaluate(RUN_ID, "product line");+ expect(heading, "heading run").not.toBeNull();+ expect(paragraph, "paragraph run").not.toBeNull();++ // A whole-text replace re-emits the run; an append edits it in place.+ await typeInto(page, heading!, "Annual summary", "replace");+ 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],+ });+ });+});diff --git a/frontend/editor/src/core/tests/test-fixtures/generate-tagged-sample.mts b/frontend/editor/src/core/tests/test-fixtures/generate-tagged-sample.mtsnew file mode 100644index 0000000000..edd7c89ac5--- /dev/null+++ b/frontend/editor/src/core/tests/test-fixtures/generate-tagged-sample.mts@@ -0,0 +1,130 @@+import process from "node:process";+// One-off script: generate `tagged-sample.pdf`, a tagged page whose text, image+// and page number are each tied into the structure tree the way a word+// processor's accessible export ties them: a heading (MCID 0), a two-line+// paragraph in ONE marked-content sequence (MCID 1), a described figure+// (MCID 2), and a page number marked as a pagination artifact.+//+// Run with: npx tsx generate-tagged-sample.mts+import { writeFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { dirname, join } from "node:path";+import {+ PDFDocument,+ PDFName,+ PDFNumber,+ type PDFObject,+ PDFRawStream,+ type PDFRef,+ PDFString,+ StandardFonts,+} from "@cantoo/pdf-lib";++const __dirname = dirname(fileURLToPath(import.meta.url));++const CONTENT = [+ "/H1 <</MCID 0>> BDC BT /F2 28 Tf 72 700 Td (Quarterly report) Tj ET EMC",+ "/P <</MCID 1>> BDC",+ "BT /F1 14 Tf 72 660 Td (Revenue grew in every region this quarter,) Tj ET",+ "BT /F1 14 Tf 72 642 Td (led by demand for the new product line.) Tj ET",+ "EMC",+ "/Figure <</MCID 2>> BDC q 120 0 0 80 72 520 cm /Im1 Do Q EMC",+ "/Artifact <</Type /Pagination>> BDC BT /F1 10 Tf 300 40 Td (Page 1) Tj ET EMC",+ "",+].join("\n");++async function main() {+ const doc = await PDFDocument.create();+ const ctx = doc.context;+ const regular = await doc.embedFont(StandardFonts.Helvetica);+ const bold = await doc.embedFont(StandardFonts.HelveticaBold);+ const page = doc.addPage([612, 792]);+ page.node.setFontDictionary(PDFName.of("F1"), regular.ref);+ page.node.setFontDictionary(PDFName.of("F2"), bold.ref);++ // 2x2 RGB swatch: the figure only has to exist, not to look like anything.+ const pixels = Uint8Array.from([+ 200, 60, 60, 60, 160, 60, 60, 60, 200, 220, 180, 40,+ ]);+ const image = ctx.register(+ PDFRawStream.of(+ ctx.obj({+ Type: "XObject",+ Subtype: "Image",+ Width: 2,+ Height: 2,+ ColorSpace: "DeviceRGB",+ BitsPerComponent: 8,+ Length: pixels.length,+ }),+ pixels,+ ),+ );+ page.node.setXObject(PDFName.of("Im1"), image);++ const content = new TextEncoder().encode(CONTENT);+ page.node.set(+ PDFName.of("Contents"),+ ctx.register(PDFRawStream.of(ctx.obj({ Length: content.length }), content)),+ );+ page.node.set(PDFName.of("StructParents"), PDFNumber.of(0));++ const rootRef = ctx.nextRef();+ const documentRef = ctx.nextRef();+ const element = (+ type: string,+ mcid: number,+ extra: Record<string, PDFObject> = {},+ ): PDFRef =>+ ctx.register(+ ctx.obj({+ Type: "StructElem",+ S: type,+ P: documentRef,+ Pg: page.ref,+ K: mcid,+ ...extra,+ }),+ );+ const heading = element("H1", 0);+ const paragraph = element("P", 1);+ const figure = element("Figure", 2, {+ Alt: PDFString.of("Bar chart of revenue by region"),+ });+ ctx.assign(+ documentRef,+ ctx.obj({+ Type: "StructElem",+ S: "Document",+ P: rootRef,+ K: [heading, paragraph, figure],+ }),+ );+ const parentTree = ctx.register(+ ctx.obj({ Nums: [0, [heading, paragraph, figure]] }),+ );+ ctx.assign(+ rootRef,+ ctx.obj({+ Type: "StructTreeRoot",+ K: documentRef,+ ParentTree: parentTree,+ ParentTreeNextKey: 1,+ }),+ );++ doc.catalog.set(PDFName.of("StructTreeRoot"), rootRef);+ doc.catalog.set(PDFName.of("MarkInfo"), ctx.obj({ Marked: true }));+ doc.catalog.set(PDFName.of("Lang"), PDFString.of("en-US"));+ doc.setTitle("Quarterly report");++ const bytes = await doc.save();+ const out = join(__dirname, "tagged-sample.pdf");+ writeFileSync(out, bytes);+ console.log(`wrote ${out} (${bytes.length} bytes)`);+}++main().catch((err: unknown) => {+ console.error(err);+ process.exit(1);+});diff --git a/frontend/editor/src/core/tests/test-fixtures/tagged-sample.pdf b/frontend/editor/src/core/tests/test-fixtures/tagged-sample.pdfnew file mode 100644index 0000000000..251d0a8487--- /dev/null+++ b/frontend/editor/src/core/tests/test-fixtures/tagged-sample.pdf@@ -0,0 +1,110 @@+%PDF-1.7+%����++1 0 obj+<<+/Type /Pages+/Kids [ 6 0 R ]+/Count 1+>>+endobj++2 0 obj+<<+/Type /Catalog+/Pages 1 0 R+/StructTreeRoot 9 0 R+/MarkInfo <<+/Marked true+>>+/Lang (en-US)+>>+endobj++6 0 obj+<<+/Type /Page+/Parent 1 0 R+/Resources <<+/Font <<+/F1 4 0 R+/F2 5 0 R+>>+/XObject <<+/Im1 7 0 R+>>+/ExtGState <<+>>+>>+/MediaBox [ 0 0 612 792 ]+/Annots [ ]+/Contents 8 0 R+/StructParents 0+>>+endobj++7 0 obj+<<+/Type /XObject+/Subtype /Image+/Width 2+/Height 2+/ColorSpace /DeviceRGB+/BitsPerComponent 8+/Length 12+>>+stream+�<<<�<<<�ܴ(+endstream+endobj++8 0 obj+<<+/Length 379+>>+stream+/H1 <</MCID 0>> BDC BT /F2 28 Tf 72 700 Td (Quarterly report) Tj ET EMC+/P <</MCID 1>> BDC+BT /F1 14 Tf 72 660 Td (Revenue grew in every region this quarter,) Tj ET+BT /F1 14 Tf 72 642 Td (led by demand for the new product line.) Tj ET+EMC+/Figure <</MCID 2>> BDC q 120 0 0 80 72 520 cm /Im1 Do Q EMC+/Artifact <</Type /Pagination>> BDC BT /F1 10 Tf 300 40 Td (Page 1) Tj ET EMC++endstream+endobj++15 0 obj+<<+/Filter /FlateDecode+/Type /ObjStm+/N 9+/First 58+/Length 428+>>+stream+x��SKk�@��W�19��]I++�IL�I��y�dmY�B��;�G�vJo=���� !�8T�������$)H �8� E�BHu\$Q+����f�Uda^�E�� ��X4��X߲�,�}Ω�,I4+ǒ1\r�D'C�����؟��Z�k��6� ��\?+0�g|�E ��]V:���F����aG��:��Jg���z��i�o��]C�~��x�F��`{�$���x�_L��`��MlO?DaZ�������@��#��;j���U���̮n� ��v��)���_V���5죳]嶖����Ǐ���]Zj�����B��ӭ��OhyC�+"3Uw �{ß�C���+��_�*����Hw�c|Pۃ���b��\�e�E��,��U�X6�V��ꭴ�+Xz��#x9��系�&�w�#o�g7v��F!+endstream+endobj++16 0 obj+<<+/Size 17+/Root 2 0 R+/Info 3 0 R+/Filter /FlateDecode+/Type /XRef+/Length 64+/W [ 1 2 2 ]+/Index [ 0 17 ]+>>+stream+x�%�1�0���D JP�!����K�`N�A���L�7��$���L5�9̩2��-�v+endstream+endobj++startxref+1520+%%EOF\ No newline at end of filediff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tagMarks.test.tsnew file mode 100644index 0000000000..069a4eb314--- /dev/null+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts@@ -0,0 +1,282 @@+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+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 { PdfiumSave } from "@app/tools/pdfTextEditor/pdfium/PdfiumSave";+import {+ applyTagMarks,+ copyTagMarks,+ readTagMarks,+} from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import { emitTextLine } from "@app/tools/pdfTextEditor/commands/editTextHelpers";+import { allowConsole } from "@app/tests/failOnConsole";+import {+ buildClassicPdf,+ streamBody,+} from "@app/tools/pdfTextEditor/__tests__/pdfFixtures";++// Runs against the real PDFium build: whether the generator writes a mark back+// out is the behaviour under test, and a mock would only restate the intent.++const FPDF_PAGEOBJ_TEXT = 1;+const FPDF_PAGEOBJ_PATH = 2;+const FPDF_PAGEOBJ_IMAGE = 3;++// A paragraph (MCID 0) whose second line sits in an /ActualText span, a figure+// (MCID 1) and an artifact rule.+const CONTENT =+ "/P <</MCID 0>> BDC BT /F1 24 Tf 72 700 Td (Hello) Tj ET " ++ "/Span <</ActualText (fi)>> BDC BT /F1 24 Tf 72 670 Td (fi) Tj ET EMC EMC\n" ++ "/Figure <</MCID 1>> BDC q 100 0 0 100 72 500 cm /Im1 Do Q EMC\n" ++ "/Artifact BMC 0 0 1 rg 10 10 50 5 re f EMC\n";++function taggedPdf(): 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 612 792] /Contents 4 0 R /StructParents 0 " ++ "/Resources << /Font << /F1 5 0 R >> /XObject << /Im1 10 0 R >> >> >>",+ },+ { num: 4, body: streamBody("", CONTENT) },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 11 0 R /ParentTreeNextKey 1 >>",+ },+ {+ num: 7,+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 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 1 /Alt (A grey square) >>",+ },+ {+ num: 10,+ body: streamBody(+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",+ "\x80",+ ),+ },+ { num: 11, body: "<< /Nums [0 [8 0 R 9 0 R]] >>" },+ ],+ 1,+ );+}++const opened: EditorDocument[] = [];++async function open(bytes: Uint8Array): Promise<EditorDocument> {+ const doc = await EditorDocument.open(bytes);+ opened.push(doc);+ return doc;+}++function objects(m: WrappedPdfiumModule, pagePtr: number): number[] {+ const out: number[] = [];+ const n = m.FPDFPage_CountObjects(pagePtr);+ for (let i = 0; i < n; i++) out.push(m.FPDFPage_GetObject(pagePtr, i));+ return out;+}++function ofType(m: WrappedPdfiumModule, pagePtr: number, type: number) {+ return objects(m, pagePtr).filter((p) => m.FPDFPageObj_GetType(p) === type);+}++/** MCIDs the page's structure tree refers to. */+function treeMcids(m: WrappedPdfiumModule, pagePtr: number): number[] {+ const tree = m.FPDF_StructTree_GetForPage(pagePtr);+ const out: number[] = [];+ const walk = (el: number) => {+ const n = m.FPDF_StructElement_GetMarkedContentIdCount(el);+ for (let i = 0; i < n; i++) {+ const id = m.FPDF_StructElement_GetMarkedContentIdAtIndex(el, i);+ if (id >= 0) out.push(id);+ }+ const kids = m.FPDF_StructElement_CountChildren(el);+ for (let i = 0; i < kids; i++) {+ const kid = m.FPDF_StructElement_GetChildAtIndex(el, i);+ if (kid) walk(kid);+ }+ };+ for (let i = 0; i < m.FPDF_StructTree_CountChildren(tree); i++) {+ walk(m.FPDF_StructTree_GetChildAtIndex(tree, i));+ }+ m.FPDF_StructTree_Close(tree);+ return out.sort();+}++/** MCIDs the page's content carries. */+function contentMcids(m: WrappedPdfiumModule, pagePtr: number): number[] {+ const ids = objects(m, pagePtr)+ .map((p) => m.FPDFPageObj_GetMarkedContentID(p))+ .filter((id) => id >= 0);+ return [...new Set(ids)].sort();+}++function newText(doc: EditorDocument, text: string, y: number): number {+ const m = doc.module;+ const ptr = m.FPDFPageObj_NewTextObj(doc.docPtr, "Helvetica", 24);+ 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, 72, y);+ return ptr;+}++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();+});++// jsdom has no 2D canvas, so text measurement falls back and says so.+const NO_CANVAS = /HTMLCanvasElement's getContext\(\) method/;++describe("PdfiumTagMarks", () => {+ test("reads only the tags that place content in the structure tree", async () => {+ const doc = await open(taggedPdf());+ const m = doc.module;+ const page = doc.page(0);++ const [hello, ligature] = ofType(m, page.pagePtr, FPDF_PAGEOBJ_TEXT);+ expect(readTagMarks(m, hello)).toEqual([{ name: "P", mcid: 0 }]);+ // The /ActualText span describes the original glyphs, so it is dropped.+ expect(readTagMarks(m, ligature)).toEqual([{ name: "P", mcid: 0 }]);++ const [image] = ofType(m, page.pagePtr, FPDF_PAGEOBJ_IMAGE);+ expect(readTagMarks(m, image)).toEqual([{ name: "Figure", mcid: 1 }]);++ const [rule] = ofType(m, page.pagePtr, FPDF_PAGEOBJ_PATH);+ expect(readTagMarks(m, rule)).toEqual([{ name: "Artifact", mcid: null }]);+ });++ test("a replacement object keeps the tag through a save", async () => {+ const doc = await open(taggedPdf());+ const m = doc.module;+ const page = doc.page(0);+ const texts = ofType(m, page.pagePtr, FPDF_PAGEOBJ_TEXT);++ for (const [i, old] of texts.entries()) {+ const replacement = newText(doc, `Edited ${i}`, 700 - i * 30);+ copyTagMarks(m, doc.docPtr, old, replacement);+ m.FPDFPage_RemoveObject(page.pagePtr, old);+ m.FPDFPageObj_Destroy(old);+ m.FPDFPage_InsertObject(page.pagePtr, replacement);+ }+ page.markDirty();++ const saved = await open(PdfiumSave.serialize(doc));+ const savedPage = saved.page(0);+ for (const ptr of ofType(m, savedPage.pagePtr, FPDF_PAGEOBJ_TEXT)) {+ expect(m.FPDFPageObj_GetMarkedContentID(ptr)).toBe(0);+ }+ expect(contentMcids(m, savedPage.pagePtr)).toEqual(+ treeMcids(m, savedPage.pagePtr),+ );+ });++ test("an object that already carries a mark is not tagged again", async () => {+ const doc = await open(taggedPdf());+ const m = doc.module;+ const ptr = newText(doc, "Fresh", 400);+ const tags = [{ name: "P", mcid: 0 }];++ applyTagMarks(m, doc.docPtr, [ptr], tags);+ applyTagMarks(m, doc.docPtr, [ptr], tags);++ expect(m.FPDFPageObj_CountMarks(ptr)).toBe(1);+ m.FPDFPageObj_Destroy(ptr);+ });++ test("emitTextLine tags each object it creates exactly once", async () => {+ allowConsole.error(NO_CANVAS);+ const doc = await open(taggedPdf());+ const m = doc.module;+ const page = doc.page(0);++ const ptrs = emitTextLine({+ doc,+ page,+ text: "several words on one line",+ x: 72,+ y: 400,+ fontSize: 12,+ fill: { r: 0, g: 0, b: 0, a: 255 },+ originalFontPtr: 0,+ fallbackFamily: "Helvetica",+ tagMarks: [{ name: "P", mcid: 0 }],+ });++ expect(ptrs.length).toBeGreaterThan(1);+ for (const ptr of ptrs) {+ expect(m.FPDFPageObj_CountMarks(ptr)).toBe(1);+ expect(readTagMarks(m, ptr)).toEqual([{ name: "P", mcid: 0 }]);+ }+ });++ test("new content emitted with no tags stays untagged", async () => {+ allowConsole.error(NO_CANVAS);+ const doc = await open(taggedPdf());+ const m = doc.module;+ const page = doc.page(0);++ const ptrs = emitTextLine({+ doc,+ page,+ text: "Inserted",+ x: 72,+ y: 300,+ fontSize: 12,+ fill: { r: 0, g: 0, b: 0, a: 255 },+ originalFontPtr: 0,+ fallbackFamily: "Helvetica",+ tagMarks: [],+ });++ for (const ptr of ptrs) expect(m.FPDFPageObj_CountMarks(ptr)).toBe(0);+ });+});diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.tsindex cf23cc59df..e00d7abf29 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts@@ -661,6 +661,7 @@ export class EditTextCommand implements Command {fontSize: rem.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: 0,charSpacingPt: run.charSpacingPt,fallbackFamily,@@ -883,6 +884,7 @@ export class EditTextCommand implements Command {// omitting this forced every restored object back to fill: undo on// invisible OCR text stamped visible glyphs over the scan....inkFromRun(run),+ tagMarks: run.tagMarks,});if (ptrs.length === 0) continue;lineAnchorPtrs.push(ptrs[0]);@@ -1027,6 +1029,7 @@ export class EditTextCommand implements Command {fontSize: run.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: reuseFontPtr,originalFontSubset: run.fontSubset,charSpacingPt: run.charSpacingPt,@@ -1167,6 +1170,7 @@ export class EditTextCommand implements Command {fontSize: run.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: 0,charSpacingPt: run.charSpacingPt,fallbackFamily,@@ -1264,6 +1268,7 @@ export class EditTextCommand implements Command {fontSize: line.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: 0,charSpacingPt: run.charSpacingPt,fallbackFamily,diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.tsindex be71a9142b..2f8e114be5 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts@@ -10,6 +10,7 @@ import {embedJpegImageOnPage,} from "@app/utils/pdfiumBitmapUtils";import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";+import { copyTagMarks } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";interface ZOrderModule {FPDFPage_InsertObjectAtIndex?: (@@ -136,6 +137,10 @@ export class ReplaceImageCommand implements Command {// The embed helpers write an axis-aligned (w,0,0,h,x,y) box, which flips// the image on a rotated page; the captured matrix is the truth here.setImageMatrix(m, objPtr, matrix);+ // Untagged, the new image drops out of the structure tree and the Figure+ // describing the old one points at nothing. A form's MCIDs are not the+ // page's, so a nested original's tags cannot move to page level.+ if (!nested) copyTagMarks(m, doc.docPtr, this.prevObjPtr, objPtr);// Detach only: the old object carries the original pixels for undo, so// destroying it would leave this command's undo entry pointing at free memory.if (nested) setActive(m, this.prevObjPtr, false);diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.tsindex e505272db0..b74176f798 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts@@ -6,6 +6,7 @@ import {type ParagraphLineSlot,TextRun,} from "@app/tools/pdfTextEditor/model/TextRun";+import { readTagMarks } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";/** Split a paragraph-grouped run back into one editable run per source line. */interface RepSnapshot {@@ -94,6 +95,11 @@ export class UngroupParagraphCommand implements Command {renderMode: rep.renderMode,});r.containerPtr = containers[i] ?? 0;+ // Each line keeps its own object's tags: lines grouped into one paragraph+ // can belong to different structure elements, such as list items.+ if (!r.containerPtr) {+ r.tagMarks = ptrs[i] ? readTagMarks(doc.module, ptrs[i]) : rep.tagMarks;+ }newRuns.push(r);}this.createdRunIds = newRuns.map((r) => r.id);diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.tsindex a9b0e4eeef..4cc3b38214 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts@@ -18,6 +18,10 @@ import {import { getActiveCharcodeStrategy } from "@app/tools/pdfTextEditor/charcode/CharcodeStrategy";import { emitFallbackTextObject } from "@app/tools/pdfTextEditor/util/fallbackFont";import { emitDeviceFontTextObject } from "@app/tools/pdfTextEditor/util/deviceFontEmbed";+import {+ applyTagMarks,+ type TagMark,+} from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import { nearestStandardFont } from "@app/tools/pdfTextEditor/util/fontFamily";import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";@@ -262,6 +266,9 @@ interface CreatedTextOptions {strokeWidth?: number;/** The run's on-page rotation (normalised cos/sin of its text matrix). */rotation?: { cos: number; sin: number };+ // Required so every emit decides: a re-emit of existing text passes the+ // run's tags, new content passes none.+ tagMarks: readonly TagMark[];// Extra advance per glyph in PDF points - the source run's rendered// letter-spacing (Tc), inferred at read time.charSpacingPt?: number;@@ -675,6 +682,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {// Every successful emit funnels through here, so this is the one place to// re-apply the source run's ink state - new objects default to a flat fill.applyInkState(m, ptrs, opts);+ applyTagMarks(m, opts.doc.docPtr, ptrs, opts.tagMarks);return ptrs;};@@ -1479,6 +1487,7 @@ export function emitRunLines(opts: {fallbackFamily: opts.fallbackFamily,// Keep the run's rotation on re-emit (no-op for upright text).rotation: rot,+ tagMarks: opts.run.tagMarks,});out.push({ ptrs, text, texts, x: origin.x, y: origin.y });}diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.tsindex 9b05fdb6c3..daf0cc888c 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts@@ -759,6 +759,7 @@ export function applyPartialEditPlan(fontSize: run.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: modFontPtr,originalFontSubset: run.fontSubset,charSpacingPt: run.charSpacingPt,@@ -850,6 +851,7 @@ export function applyPartialEditPlan(fontSize: run.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: borrowedFontPtr,originalFontSubset: run.fontSubset,charSpacingPt: run.charSpacingPt,@@ -893,6 +895,7 @@ export function applyPartialEditPlan(fontSize: run.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: 0,charSpacingPt: run.charSpacingPt,fallbackFamily,@@ -1314,6 +1317,7 @@ export function applyParagraphEditPlan(fontSize: slot.fontSize,fill: run.fill,...inkFromRun(run),+ tagMarks: run.tagMarks,originalFontPtr: reuseFontPtr,originalFontSubset: slot.fontSubset,charSpacingPt: run.charSpacingPt,diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/scanStyle.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/scanStyle.tsindex 1f32a5ed16..2f1ad02394 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/scanStyle.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/scanStyle.ts@@ -58,6 +58,7 @@ export function spanOf(fill: BLACK,originalFontPtr: 0,fallbackFamily: family,+ tagMarks: [],});const span = measureObjSpanPt(doc.module, ptrs);for (const p of ptrs) removeAndDestroyObject(doc.module, page.pagePtr, p);@@ -160,6 +161,9 @@ export function placeText(fill: p.fill,originalFontPtr: 0,fallbackFamily: p.family,+ // The invisible OCR layer carries the run's tags; tagging this visible+ // copy as well would have assistive technology read the words twice.+ tagMarks: [],// Fill and stroke (Tr 2): blur makes scanned strokes heavier than any bold....(p.weight? { renderMode: 2, stroke: p.fill, strokeWidth: p.weight }diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/scanTextEdit.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/scanTextEdit.tsindex d8fd68a7ba..6c8ea854f1 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/scanTextEdit.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/scanTextEdit.ts@@ -16,6 +16,7 @@ import {type LayoutWord,} from "@app/tools/pdfTextEditor/commands/scanLayout";import { createBitmapImageObject } from "@app/utils/pdfiumBitmapUtils";+import type { TagMark } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {emitFillRect,emitTextLine,@@ -596,6 +597,7 @@ function emitInvisible(word: ScanWord,x: number,baseline: number,+ tagMarks: readonly TagMark[],): number[] {const ptrs = emitTextLine({doc,@@ -608,6 +610,7 @@ function emitInvisible(originalFontPtr: state.fontPtr,fallbackFamily: "Helvetica",renderMode: INVISIBLE,+ tagMarks,});opaqueStroke(doc.module, ptrs);return ptrs;@@ -796,6 +799,7 @@ export function renderScanEdit(originalFontPtr: 0,fallbackFamily: st.family,renderMode: INVISIBLE,+ tagMarks: run.tagMarks,});opaqueStroke(m, hidden);state.created.push(soft, ...hidden);@@ -879,7 +883,15 @@ export function renderScanEdit(m.FPDFPage_InsertObject(page.pagePtr, img);state.created.push(img);}- const hidden = emitInvisible(doc, page, state, sw, k.x, k.baseline);+ const hidden = emitInvisible(+ doc,+ page,+ state,+ sw,+ k.x,+ k.baseline,+ run.tagMarks,+ );state.created.push(...hidden);state.textPtrs.push(...hidden);}@@ -907,6 +919,7 @@ export function renderScanEdit(word,word.x,line.baseline,+ run.tagMarks,);word.ptr = back[0] ?? 0;word.extraPtrs = back.slice(1);diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.tsindex 231fad759f..100d600f5b 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts@@ -1,4 +1,5 @@import type { ScanEditState } from "@app/tools/pdfTextEditor/commands/scanTextEdit";+import type { TagMark } from "@app/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import type {Affine,PageRect,@@ -79,6 +80,9 @@ export class TextRun {containerPtr: number;/** If the run was extracted from a form xobject. */topLevelContainerPtr: number;+ // Structure tags every object that re-emits this run's text must carry, or+ // the structure tree is left pointing at content that no longer exists.+ tagMarks: readonly TagMark[];// When ParagraphGrouper merged multiple line groups into this run, the// average vertical distance between consecutive baselines (in PDF points).paragraphLineHeight: number;@@ -147,6 +151,7 @@ export class TextRun {this.mergedFromCharStarts = [];this.containerPtr = init.containerPtr ?? 0;this.topLevelContainerPtr = init.topLevelContainerPtr ?? 0;+ this.tagMarks = [];this.paragraphLineHeight = 0;this.paragraphMemberPtrs = [];this.paragraphMemberContainers = [];diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.tsnew file mode 100644index 0000000000..d51e150e17--- /dev/null+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts@@ -0,0 +1,91 @@+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";++const MCID = "MCID";+const ARTIFACT = "Artifact";++/**+ * A marked-content tag that links a page object to the structure tree, or+ * excludes it from the tree as an artifact (ISO 32000-1 14.7.4, 14.8.2.2).+ */+export interface TagMark {+ name: string;+ /** The ID the structure tree refers to the content by; null for an artifact. */+ mcid: number | null;+}++/**+ * The tags on a page object, outermost first. Only tags that place content in+ * the structure tree are kept: an /ActualText or /Alt span describes the+ * original glyphs, so it must not follow edited text. Never throws: an+ * object whose marks cannot be read reads as untagged.+ */+export function readTagMarks(+ m: WrappedPdfiumModule,+ objPtr: number,+): TagMark[] {+ const tags: TagMark[] = [];+ try {+ const count = m.FPDFPageObj_CountMarks(objPtr);+ for (let i = 0; i < count; i++) {+ const mark = m.FPDFPageObj_GetMark(objPtr, i);+ if (!mark) continue;+ const name = markName(m, mark);+ const mcid = markMcid(m, mark);+ if (mcid !== null || name === ARTIFACT) tags.push({ name, mcid });+ }+ } catch {+ return [];+ }+ return tags;+}++/**+ * Give newly created objects the tags of the content they replace. Objects+ * that already carry a mark are left alone: PDFium appends a mark on every+ * call, and an emit that applies tags at more than one level would nest the+ * same tag twice.+ */+export function applyTagMarks(+ m: WrappedPdfiumModule,+ docPtr: number,+ ptrs: readonly number[],+ tags: readonly TagMark[],+): void {+ if (tags.length === 0) return;+ for (const ptr of ptrs) {+ if (!ptr || m.FPDFPageObj_CountMarks(ptr) > 0) continue;+ for (const tag of tags) {+ const mark = m.FPDFPageObj_AddMark(ptr, tag.name);+ if (mark && tag.mcid !== null) {+ m.FPDFPageObjMark_SetIntParam(docPtr, ptr, mark, MCID, tag.mcid);+ }+ }+ }+}++/** Carry `from`'s tags onto its replacement `to`. */+export function copyTagMarks(+ m: WrappedPdfiumModule,+ docPtr: number,+ from: number,+ to: number,+): void {+ applyTagMarks(m, docPtr, [to], readTagMarks(m, from));+}++function markName(m: WrappedPdfiumModule, mark: number): string {+ const lenPtr = scratchPtr(m, SCRATCH.tagNameLen, 4);+ if (!m.FPDFPageObjMark_GetName(mark, 0, 0, lenPtr)) return "";+ const byteLen = m.pdfium.getValue(lenPtr, "i32");+ if (byteLen <= 2) return "";+ const buf = scratchPtr(m, SCRATCH.tagName, byteLen);+ if (!m.FPDFPageObjMark_GetName(mark, buf, byteLen, lenPtr)) return "";+ return m.pdfium.UTF16ToString(buf);+}++function markMcid(m: WrappedPdfiumModule, mark: number): number | null {+ const out = scratchPtr(m, SCRATCH.tagMcid, 4);+ if (!m.FPDFPageObjMark_GetParamIntValue(mark, MCID, out)) return null;+ return m.pdfium.getValue(out, "i32");+}diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.tsindex c4574a88b3..6cb67d29eb 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts@@ -18,6 +18,7 @@ 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";/** PDFium page-object type constants - mirrors `public/fpdf_edit.h`. */const FPDF_PAGEOBJ_TEXT = 1;@@ -413,6 +414,9 @@ function walkObjects(if (run) {run.containerPtr = containerPtr;run.topLevelContainerPtr = topLevelContainerPtr;+ // A form's MCIDs resolve against its own /StructParents, not the+ // page's, so carrying them onto page-level re-emits would mis-tag.+ if (path.length === 0) run.tagMarks = readTagMarks(m, objPtr);runs.push(run);}} else if (type === FPDF_PAGEOBJ_PATH) {diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.tsindex 4ed39852c4..0008ef984c 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts@@ -87,6 +87,9 @@ export const SCRATCH = {readerSize: key(),reflowText: key(),charcodes: key(),+ tagName: key(),+ tagNameLen: key(),+ tagMcid: key(),} as const;/** Structural minimum: any wrapper that exposes PDFium's wasm allocator. */