Merge pull request #22447 from calixteman/flatten-struct-tree

Update the structure tree when flattening annotations (bug 2075337)
This commit is contained in:
calixteman
2026-11-15 15:41:13 +01:00
committed by GitHub
3 changed files with 633 additions and 17 deletions
+305 -15
View File
@@ -23,6 +23,7 @@ import {
} from "../shared/util.js";
import {
ChangesXRefWrapper,
escapePDFName,
getInheritableProperty,
IDENTITY_MATRIX,
lookupMatrix,
@@ -35,6 +36,7 @@ import {
EOF,
isCmd,
isName,
isRefsEqual,
Name,
Ref,
RefMap,
@@ -46,6 +48,7 @@ import { Stream, StringStream } from "./stream.js";
import { BaseStream } from "./base_stream.js";
import { EvaluatorPreprocessor } from "./evaluator.js";
import { numberToPDFString } from "./writer.js";
import { NumberTree } from "./name_number_tree.js";
// Their appearances are drawn in the page content, but the annotations are
// kept, with an empty appearance, so that they stay interactive.
@@ -89,6 +92,8 @@ class PageAnnotationFlattener {
#page;
#structTree;
#task;
constructor({
@@ -97,6 +102,7 @@ class PageAnnotationFlattener {
changes,
flattenForms,
intent,
structTree,
getResources,
}) {
this.#page = page;
@@ -105,6 +111,7 @@ class PageAnnotationFlattener {
this.#changesXref = new ChangesXRefWrapper(changes, page.xref);
this.#flattenForms = flattenForms;
this.#intent = intent;
this.#structTree = structTree;
this.#getResources = getResources;
}
@@ -120,8 +127,8 @@ class PageAnnotationFlattener {
/**
* Draw appearances visible for the intent. Call after saving annotations.
* @returns {Promise<object>} Widget presence before/after flattening
* (`hadWidgets`/`hasWidgets`) and removed refs (`removed`). Presence is
* conservative if flattening is skipped.
* (`hadWidgets`/`hasWidgets`), removed refs (`removed`), and structure
* tags (`tags`). Presence is conservative if flattening is skipped.
*/
async flatten(handler, task) {
const page = this.#page;
@@ -129,6 +136,7 @@ class PageAnnotationFlattener {
const annotationStorage = this.#annotationStorage;
const flattenForms = this.#flattenForms;
const intent = this.#intent;
const structTree = this.#structTree;
const { xref } = page;
if (!(page.ref instanceof Ref)) {
@@ -136,14 +144,19 @@ class PageAnnotationFlattener {
const hasWidgets = (await page._parsedAnnotations).some(
annotation => annotation instanceof WidgetAnnotation
);
return { hadWidgets: hasWidgets, hasWidgets, removed: null };
return { hadWidgets: hasWidgets, hasWidgets, removed: null, tags: null };
}
const pageDict = changes.get(page.ref)?.data || page.pageDict.clone();
const annotations = changes.has(page.ref)
? pageDict.get("Annots")
: page.annotations;
if (!Array.isArray(annotations) || annotations.length === 0) {
return { hadWidgets: false, hasWidgets: false, removed: null };
return {
hadWidgets: false,
hasWidgets: false,
removed: null,
tags: null,
};
}
// Parsed annotations supply visibility and generated appearances.
@@ -160,6 +173,7 @@ class PageAnnotationFlattener {
const kept = [];
const removed = new RefSet();
const removedPopups = new RefSet();
const tags = [];
const interactive = [];
let hasWidgets = false,
hadWidgets = false;
@@ -227,7 +241,7 @@ class PageAnnotationFlattener {
) {
// Clear retained appearances after drawing them in page content.
if (appearance && annotation instanceof Ref) {
flattened.push({ appearance, oc: dict.getRaw("OC") });
flattened.push({ appearance, oc: dict.getRaw("OC"), tag: null });
interactive.push({ annotation, dict });
}
kept.push({ annotation });
@@ -245,15 +259,21 @@ class PageAnnotationFlattener {
continue;
}
// Remove drawn annotations and widgets hidden for this intent.
let tag = null;
if (annotation instanceof Ref) {
removed.put(annotation);
const popup = dict.getRaw("Popup");
if (popup instanceof Ref) {
removedPopups.put(popup);
}
tag = structTree?.getTag(dict) ?? null;
if (tag) {
tag.annotation = annotation;
tags.push(tag);
}
}
if (appearance) {
flattened.push({ appearance, oc: dict.getRaw("OC") });
flattened.push({ appearance, oc: dict.getRaw("OC"), tag });
}
}
@@ -276,14 +296,14 @@ class PageAnnotationFlattener {
newAnnotations.length === annotations.length &&
flattened.length === 0
) {
return { hadWidgets, hasWidgets, removed: null };
return { hadWidgets, hasWidgets, removed: null, tags: null };
}
if (
flattened.length > 0 &&
!(await this.#drawFlattenedAppearances(pageDict, flattened))
) {
// Keep annotations if the page content cannot be isolated.
return { hadWidgets, hasWidgets: hadWidgets, removed: null };
return { hadWidgets, hasWidgets: hadWidgets, removed: null, tags: null };
}
pageDict.set("Annots", newAnnotations);
@@ -308,7 +328,7 @@ class PageAnnotationFlattener {
changes.put(page.ref, {
data: pageDict,
});
return { hadWidgets, hasWidgets, removed };
return { hadWidgets, hasWidgets, removed, tags };
}
/**
@@ -318,6 +338,7 @@ class PageAnnotationFlattener {
async #drawFlattenedAppearances(pageDict, flattened) {
const { xref } = this.#page;
const changes = this.#changes;
const structTree = this.#structTree;
let contentStream, unbalanced, resources;
try {
contentStream = await this.#page.getContentStream();
@@ -328,7 +349,8 @@ class PageAnnotationFlattener {
warn(`flattenAnnotations - cannot parse the page content: "${ex}".`);
return false;
}
const { saves, unmatchedRestores, markedContent, inText } = unbalanced;
const { saves, unmatchedRestores, markedContent, inText, lastMCID } =
unbalanced;
let contents;
if (unmatchedRestores > 0) {
// Unmatched Qs would consume the wrapper's save instead of being ignored.
@@ -391,11 +413,17 @@ class PageAnnotationFlattener {
};
const buffer = [];
for (const { appearance, oc } of flattened) {
let mcid = structTree?.getNextMCID(pageDict, lastMCID);
for (const { appearance, oc, tag } of flattened) {
const transform = appearance.transform.map(numberToPDFString).join(" ");
const name = addResource("XObject", "FlatAnnot", appearance.ref);
const ocName = oc ? addResource("Properties", "FlatOC", oc) : null;
// Link the structure element to this marked content.
if (tag?.type) {
tag.mcid = mcid++;
buffer.push(`/${escapePDFName(tag.type)} <</MCID ${tag.mcid}>> BDC`);
}
if (ocName) {
buffer.push(`/OC /${ocName} BDC`);
}
@@ -403,6 +431,9 @@ class PageAnnotationFlattener {
if (ocName) {
buffer.push("EMC");
}
if (tag?.type) {
buffer.push("EMC");
}
}
for (const [key, dict] of newResources) {
resources.set(key, dict);
@@ -554,13 +585,17 @@ class PageAnnotationFlattener {
}
}
/** Track unbalanced graphics/text/marked-content state. */
/**
* Track unbalanced graphics/text/marked-content state and the largest inline
* MCID.
*/
function getUnbalancedOperators(stream, xref) {
const result = {
saves: 0,
unmatchedRestores: 0,
markedContent: 0,
inText: false,
lastMCID: -1,
};
const preprocessor = new EvaluatorPreprocessor(stream, xref);
const operation = {
@@ -590,8 +625,16 @@ function getUnbalancedOperators(stream, xref) {
case OPS.endText:
result.inText = false;
break;
case OPS.beginMarkedContentProps: {
const props = operation.args[1];
const mcid = props instanceof Dict ? props.get("MCID") : null;
if (Number.isInteger(mcid) && mcid > result.lastMCID) {
result.lastMCID = mcid;
}
result.markedContent++;
break;
}
case OPS.beginMarkedContent:
case OPS.beginMarkedContentProps:
result.markedContent++;
break;
case OPS.endMarkedContent:
@@ -677,9 +720,10 @@ function isSelfContained(obj) {
: !Array.isArray(obj) || obj.every(isSelfContained);
}
/** Return the AcroForm dictionary to retain. */
/** Update structure tags and return the AcroForm dictionary to retain. */
async function finalizeFlattening({
results,
structTree,
manager,
acroForm,
acroFormRef,
@@ -697,6 +741,14 @@ async function finalizeFlattening({
return null;
}
};
if (structTree) {
for (const { pageRef, tags } of results) {
if (tags?.length > 0 && pageRef instanceof Ref) {
structTree.update({ pageRef, tags });
}
}
structTree.save();
}
const removed = new RefSet();
for (const result of results) {
for (const ref of result.removed ?? []) {
@@ -879,4 +931,242 @@ function pruneChanges({ changes, removed, removeFields, xref, getDict }) {
}
}
export { finalizeFlattening, PageAnnotationFlattener };
/**
* Replace annotation OBJRs with marked-content references to their drawings.
* For unreadable parent trees, remove the OBJRs without adding references.
*/
class StructTreeFlattener {
#changes;
#changesXref;
// The entries of the parent tree.
#entries = null;
#isModified = false;
#numberTree = null;
#parentTree = null;
#parentTreeRef = null;
#root;
#rootRef;
#xref;
constructor({ changes, root, rootRef, xref }) {
this.#changes = changes;
this.#changesXref = new ChangesXRefWrapper(changes, xref);
this.#root = root;
this.#rootRef = rootRef;
this.#xref = xref;
const parentTreeRef = root.getRaw("ParentTree");
const parentTree = this.#fetch(parentTreeRef);
if (!(parentTree instanceof Dict)) {
return;
}
const numberTree = new NumberTree(parentTreeRef, this.#changesXref);
try {
// A tree with kids is rewritten flat when saving.
this.#entries = numberTree.getAll(/* isRaw = */ true);
} catch (ex) {
warn(`StructTreeFlattener: cannot read the parent tree: "${ex}".`);
this.#numberTree = numberTree;
return;
}
for (const key of this.#entries.keys()) {
if (!Number.isInteger(key)) {
this.#entries.delete(key);
}
}
this.#parentTree = parentTree;
this.#parentTreeRef = parentTreeRef;
}
static create({ catalogRef, changes, xref }) {
try {
const changesXref = new ChangesXRefWrapper(changes, xref);
const rootRef = changesXref
.fetchIfRef(catalogRef)
?.getRaw("StructTreeRoot");
const root = changesXref.fetchIfRef(rootRef);
return rootRef instanceof Ref && root instanceof Dict
? new StructTreeFlattener({ changes, root, rootRef, xref })
: null;
} catch (ex) {
warn(`StructTreeFlattener: "${ex}".`);
return null;
}
}
#fetch(obj) {
return this.#changesXref.fetchIfRef(obj);
}
/**
* @returns {object | null} The structure element of the annotation (`ref`),
* and its type (`type`) when its marked content can be referenced.
*/
getTag(annotationDict) {
try {
const structParent = annotationDict.get("StructParent");
if (!Number.isInteger(structParent)) {
return null;
}
const ref = this.#entries
? this.#entries.get(structParent)
: this.#numberTree?.getRaw(structParent);
const element = this.#fetch(ref);
if (!(ref instanceof Ref) || !(element instanceof Dict)) {
return null;
}
const type = element.get("S");
return {
ref,
structParent,
type: this.#entries && type instanceof Name ? type.name : null,
};
} catch (ex) {
warn(`StructTreeFlattener.getTag: "${ex}".`);
return null;
}
}
/**
* @returns {number} The first marked content id to use in the page content.
*/
getNextMCID(pageDict, lastMCID) {
const parents = this.#fetch(
this.#entries?.get(pageDict.get("StructParents"))
);
return Math.max(lastMCID + 1, Array.isArray(parents) ? parents.length : 0);
}
/**
* @param {object} params
* @param {Ref} params.pageRef
* @param {Array<object>} params.tags - The tags of the removed annotations,
* with the marked content id (`mcid`) of the ones drawn in the page.
*/
update({ pageRef, tags }) {
const xref = this.#xref;
let parents = null;
for (const { annotation, mcid, ref, structParent } of tags) {
try {
let mcr = null;
if (this.#entries && Number.isInteger(mcid)) {
mcr = new Dict(xref);
mcr.set("Type", Name.get("MCR"));
mcr.set("Pg", pageRef);
mcr.set("MCID", mcid);
parents ??= this.#getParents(pageRef);
while (parents.length < mcid) {
parents.push(null);
}
parents[mcid] = ref;
}
this.#replaceObjectReference(ref, annotation, mcr);
if (this.#entries?.delete(structParent)) {
this.#isModified = true;
}
} catch (ex) {
warn(`StructTreeFlattener.update: "${ex}".`);
}
}
}
// Copy or create the page's parent-tree entry.
#getParents(pageRef) {
const pageDict = this.#changes.get(pageRef).data;
let key = pageDict.get("StructParents");
let parents = this.#fetch(this.#entries.get(key));
if (Number.isInteger(key) && Array.isArray(parents)) {
parents = parents.slice();
} else {
key = this.#root.get("ParentTreeNextKey");
if (!Number.isInteger(key) || key < 0) {
key = 0;
}
for (const entryKey of this.#entries.keys()) {
key = Math.max(key, entryKey + 1);
}
this.#root = this.#root.clone();
this.#root.set("ParentTreeNextKey", key + 1);
pageDict.set("StructParents", key);
parents = [];
}
this.#entries.set(key, parents);
this.#isModified = true;
return parents;
}
#replaceObjectReference(ref, annotation, replacement) {
const element = this.#fetch(ref);
if (!(element instanceof Dict)) {
return;
}
const rawKids = element.getRaw("K");
const kids = this.#fetch(rawKids);
const newKids = [];
let found = false;
for (const kid of Array.isArray(kids) ? kids : [rawKids]) {
let obj;
try {
obj = this.#fetch(kid);
} catch (ex) {
// Keep unreadable kids as they are.
warn(`StructTreeFlattener: cannot read a structure kid: "${ex}".`);
}
const objRef =
obj instanceof Dict && isName(obj.get("Type"), "OBJR")
? obj.getRaw("Obj")
: null;
if (
objRef instanceof Ref &&
annotation instanceof Ref &&
isRefsEqual(objRef, annotation)
) {
found = true;
if (replacement) {
newKids.push(replacement);
}
continue;
}
newKids.push(kid);
}
if (found) {
const newElement = element.clone();
newElement.set("K", newKids);
this.#changes.put(ref, { data: newElement });
}
}
save() {
if (!this.#isModified) {
return;
}
const xref = this.#xref;
const nums = [];
for (const key of [...this.#entries.keys()].sort((a, b) => a - b)) {
nums.push(key, this.#entries.get(key));
}
const parentTree = this.#parentTree.clone();
parentTree.delete("Kids");
parentTree.delete("Limits");
parentTree.set("Nums", nums);
let parentTreeRef = this.#parentTreeRef;
if (!(parentTreeRef instanceof Ref)) {
parentTreeRef = xref.getNewTemporaryRef();
this.#root = this.#root.clone();
this.#root.set("ParentTree", parentTreeRef);
}
this.#changes.put(parentTreeRef, { data: parentTree });
this.#changes.put(this.#rootRef, { data: this.#root });
}
}
export { finalizeFlattening, PageAnnotationFlattener, StructTreeFlattener };
+11 -2
View File
@@ -29,11 +29,11 @@ import {
XRefParseException,
} from "./core_utils.js";
import { Dict, isDict, Ref, RefMap } from "./primitives.js";
import { finalizeFlattening, StructTreeFlattener } from "./flattener.js";
import { LocalPdfManager, NetworkPdfManager } from "./pdf_manager.js";
import { MessageHandler, wrapReason } from "../shared/message_handler.js";
import { AnnotationFactory } from "./annotation.js";
import { clearGlobalCaches } from "./cleanup_helper.js";
import { finalizeFlattening } from "./flattener.js";
import { importPrintedAppearances } from "./editor/print_appearances.js";
import { incrementalUpdate } from "./writer.js";
import { PDFEditor } from "./editor/pdf_editor.js";
@@ -693,17 +693,24 @@ class WorkerMessageHandler {
flattenForms,
intent,
}) {
const structTree = StructTreeFlattener.create({
catalogRef,
changes,
xref,
});
const promises = [];
for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
promises.push(
runPageTask(manager, pageIndex, "Flatten", async (page, task) => {
try {
return await page.flattenAnnotations(handler, task, {
const result = await page.flattenAnnotations(handler, task, {
annotationStorage,
changes,
flattenForms,
intent,
structTree,
});
return { ...result, pageRef: page.ref };
} catch (reason) {
// Continue saving and retain the form if flattening fails.
warn(
@@ -717,6 +724,7 @@ class WorkerMessageHandler {
const results = await Promise.all(promises);
return finalizeFlattening({
results,
structTree,
manager,
acroForm,
acroFormRef,
@@ -815,6 +823,7 @@ class WorkerMessageHandler {
let structTreeRoot;
if (newAnnotationsByPage) {
// Create annotation tags before flattening updates their references.
if (!_structTreeRoot) {
if (
await StructTreeRoot.canCreateStructureTree({
+317
View File
@@ -689,6 +689,268 @@ describe("api flattening", function () {
await loadingTask.destroy();
});
it("save a tagged pdf flattened and check that the structure element of an annotation references its drawing", async function () {
const content =
"/P <</MCID 0>> BDC BT /F1 10 Tf 10 100 Td (Text) Tj ET EMC";
const appearance = "0 0 10 10 re f";
let loadingTask = getDocument({
data: assemblePdf([
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R " +
"/MarkInfo << /Marked true >> >>\nendobj\n",
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " +
"/StructParents 0 /Resources << /Font << /F1 4 0 R >> >> " +
"/Contents 5 0 R /Annots [6 0 R] >>\nendobj\n",
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n" +
"endobj\n",
`5 0 obj\n<< /Length ${content.length} >>\n` +
`stream\n${content}\nendstream\nendobj\n`,
"6 0 obj\n<< /Type /Annot /Subtype /Stamp /F 4 /Rect [10 10 20 20] " +
"/StructParent 1 /AP << /N 10 0 R >> >>\nendobj\n",
"7 0 obj\n<< /Type /StructTreeRoot /K [8 0 R 9 0 R] " +
"/ParentTree << /Nums [0 [8 0 R] 1 9 0 R] >> " +
"/ParentTreeNextKey 2 >>\nendobj\n",
"8 0 obj\n<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>\n" +
"endobj\n",
"9 0 obj\n<< /Type /StructElem /S /Figure /Alt (Stamp alt) " +
"/P 7 0 R /Pg 3 0 R /K << /Type /OBJR /Obj 6 0 R >> >>\nendobj\n",
"10 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] " +
`/Length ${appearance.length} >>\n` +
`stream\n${appearance}\nendstream\nendobj\n`,
]),
});
let pdfDoc = await loadingTask.promise;
const data = await pdfDoc.saveDocument({ flatten: true });
await loadingTask.destroy();
loadingTask = getDocument({ data });
pdfDoc = await loadingTask.promise;
const page = await pdfDoc.getPage(1);
expect(await page.getAnnotations({ intent: "any" })).toEqual([]);
// Assign MCID 1 to the stamp after the page's existing MCID 0.
expect(await page.getStructTree()).toEqual({
role: "Root",
children: [
{ role: "P", children: [{ type: "content", id: "p3R_mc0" }] },
{
role: "Figure",
alt: "Stamp alt",
children: [{ type: "content", id: "p3R_mc1" }],
},
],
});
const { items } = await page.getTextContent({
includeMarkedContent: true,
});
expect(
items
.filter(({ type }) => type === "beginMarkedContentProps")
.map(({ tag, id }) => [tag, id])
).toEqual([
["P", "p3R_mc0"],
["Figure", "p3R_mc1"],
]);
await loadingTask.destroy();
});
// 13 1 R has the wrong generation, so fetching it throws.
for (const unreadableKid of ["", "13 1 R "]) {
it(`flatten a tagged pdf with a parent tree having kids${unreadableKid ? " and an unreadable structure kid" : ""}`, async function () {
const content =
"/P <</MCID 0>> BDC BT /F1 10 Tf 10 100 Td (Text) Tj ET EMC";
const appearance = "0 0 10 10 re f";
const pdfData = assemblePdf([
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R " +
"/MarkInfo << /Marked true >> >>\nendobj\n",
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " +
"/StructParents 0 /Resources << /Font << /F1 4 0 R >> >> " +
"/Contents 5 0 R /Annots [6 0 R] >>\nendobj\n",
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n" +
"endobj\n",
`5 0 obj\n<< /Length ${content.length} >>\n` +
`stream\n${content}\nendstream\nendobj\n`,
"6 0 obj\n<< /Type /Annot /Subtype /Stamp /F 4 /Rect [10 10 20 20] " +
"/StructParent 1 /AP << /N 10 0 R >> >>\nendobj\n",
"7 0 obj\n<< /Type /StructTreeRoot /K [8 0 R 9 0 R] " +
"/ParentTree << /Kids [11 0 R 12 0 R] >> /ParentTreeNextKey 2 >>\n" +
"endobj\n",
"8 0 obj\n<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>\n" +
"endobj\n",
"9 0 obj\n<< /Type /StructElem /S /Figure /Alt (Stamp alt) " +
"/P 7 0 R /Pg 3 0 R /K " +
`[${unreadableKid}<< /Type /OBJR /Obj 6 0 R >>] >>\nendobj\n`,
"10 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] " +
`/Length ${appearance.length} >>\n` +
`stream\n${appearance}\nendstream\nendobj\n`,
"11 0 obj\n<< /Limits [0 0] /Nums [0 [8 0 R]] >>\nendobj\n",
"12 0 obj\n<< /Limits [1 1] /Nums [1 9 0 R] >>\nendobj\n",
...(unreadableKid ? ["13 0 obj\nnull\nendobj\n"] : []),
]);
let loadingTask = getDocument({ data: pdfData.slice() });
let pdfDoc = await loadingTask.promise;
const data = await pdfDoc.saveDocument({ flatten: true });
await loadingTask.destroy();
// Rewrite the parent tree flat, with 9R as the stamp's MCID parent.
const newData = bytesToString(data.subarray(pdfData.length));
const parentTreeNum = +newData.match(/\/ParentTree (\d+) 0 R/)[1];
expect(newData).toContain(
`${parentTreeNum} 0 obj\n<< /Nums [0 [8 0 R 9 0 R]]>>`
);
// Preserve the unreadable kid and replace the annotation's OBJR.
expect(newData).toContain(
`/K [${unreadableKid}<< /Type /MCR /Pg 3 0 R /MCID 1>>]`
);
loadingTask = getDocument({ data });
pdfDoc = await loadingTask.promise;
const page = await pdfDoc.getPage(1);
expect(await page.getAnnotations({ intent: "any" })).toEqual([]);
const { items } = await page.getTextContent({
includeMarkedContent: true,
});
expect(
items
.filter(({ type }) => type === "beginMarkedContentProps")
.map(({ tag, id }) => [tag, id])
).toEqual([
["P", "p3R_mc0"],
["Figure", "p3R_mc1"],
]);
await loadingTask.destroy();
});
}
it("save a tagged pdf flattened and check that a structure element with several kids references the drawing", async function () {
const content =
"/P <</MCID 0>> BDC BT /F1 10 Tf 10 100 Td (Text) Tj ET EMC " +
"/Span <</MCID 1>> BDC BT /F1 10 Tf 10 120 Td (Caption) Tj ET EMC";
const appearance = "0 0 10 10 re f";
let loadingTask = getDocument({
data: assemblePdf([
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R " +
"/MarkInfo << /Marked true >> >>\nendobj\n",
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " +
"/StructParents 0 /Resources << /Font << /F1 4 0 R >> >> " +
"/Contents 5 0 R /Annots [6 0 R 11 0 R] >>\nendobj\n",
"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n" +
"endobj\n",
`5 0 obj\n<< /Length ${content.length} >>\n` +
`stream\n${content}\nendstream\nendobj\n`,
"6 0 obj\n<< /Type /Annot /Subtype /Stamp /F 4 /Rect [10 10 20 20] " +
"/StructParent 1 /AP << /N 10 0 R >> >>\nendobj\n",
"7 0 obj\n<< /Type /StructTreeRoot /K [8 0 R 9 0 R 12 0 R] " +
"/ParentTree << /Nums [0 [8 0 R 9 0 R] 1 9 0 R 2 12 0 R] >> " +
"/ParentTreeNextKey 3 >>\nendobj\n",
"8 0 obj\n<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>\n" +
"endobj\n",
// MCID 1 is the caption; the OBJR references the stamp.
"9 0 obj\n<< /Type /StructElem /S /Figure /Alt (Stamp alt) " +
"/P 7 0 R /Pg 3 0 R /K [1 << /Type /OBJR /Obj 6 0 R >>] >>\n" +
"endobj\n",
"10 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] " +
`/Length ${appearance.length} >>\n` +
`stream\n${appearance}\nendstream\nendobj\n`,
// A link without appearance is kept.
"11 0 obj\n<< /Type /Annot /Subtype /Link /Rect [100 10 120 20] " +
"/StructParent 2 /A << /S /URI /URI (https://mozilla.org) >> >>\n" +
"endobj\n",
"12 0 obj\n<< /Type /StructElem /S /Link /P 7 0 R /Pg 3 0 R " +
"/K << /Type /OBJR /Obj 11 0 R >> >>\nendobj\n",
]),
});
let pdfDoc = await loadingTask.promise;
const data = await pdfDoc.saveDocument({ flatten: true });
await loadingTask.destroy();
// Keep the link's parent-tree entry; remove the stamp's.
expect(bytesToString(data)).toContain(
"/Nums [0 [8 0 R 9 0 R 9 0 R] 2 12 0 R]"
);
loadingTask = getDocument({ data });
pdfDoc = await loadingTask.promise;
const page = await pdfDoc.getPage(1);
expect(
(await page.getAnnotations({ intent: "any" })).map(({ id }) => id)
).toEqual(["11R"]);
expect(await page.getStructTree()).toEqual({
role: "Root",
children: [
{ role: "P", children: [{ type: "content", id: "p3R_mc0" }] },
{
role: "Figure",
alt: "Stamp alt",
children: [
{ type: "content", id: "p3R_mc1" },
{ type: "content", id: "p3R_mc2" },
],
},
{
role: "Link",
children: [{ type: "annotation", id: "pdfjs_internal_id_11R" }],
},
],
});
const { items } = await page.getTextContent({
includeMarkedContent: true,
});
expect(
items
.filter(({ type }) => type === "beginMarkedContentProps")
.map(({ tag, id }) => [tag, id])
).toEqual([
["P", "p3R_mc0"],
["Span", "p3R_mc1"],
["Figure", "p3R_mc2"],
]);
await loadingTask.destroy();
});
it("write a new annotation with an alt text, save the pdf flattened and check that the alt text is kept", async function () {
let loadingTask = getDocument(buildGetDocumentParams("empty.pdf"));
let pdfDoc = await loadingTask.promise;
addInkEditor(pdfDoc.annotationStorage, {
accessibilityData: { type: "Figure", alt: "My ink alt" },
});
const data = await pdfDoc.saveDocument({ flatten: true });
await loadingTask.destroy();
loadingTask = getDocument({ data });
pdfDoc = await loadingTask.promise;
const page = await pdfDoc.getPage(1);
expect(await page.getAnnotations({ intent: "any" })).toEqual([]);
const { items } = await page.getTextContent({
includeMarkedContent: true,
});
const marks = items.filter(
({ type }) => type === "beginMarkedContentProps"
);
expect(marks.map(({ tag }) => tag)).toEqual(["Figure"]);
expect((await page.getStructTree()).children).toEqual([
{
role: "Figure",
alt: "My ink alt",
children: [{ type: "content", id: marks[0].id }],
},
]);
await loadingTask.destroy();
});
it("save the pdf flattened without any modification and check that the annotations are drawn in the page content", async function () {
let loadingTask = getDocument(buildGetDocumentParams("issue14438.pdf"));
let pdfDoc = await loadingTask.promise;
@@ -1081,6 +1343,61 @@ describe("api flattening", function () {
}
});
it("save the pdf flattened and check that a page which can't be flattened is kept with the form", async function () {
const appearance = "BT /F1 10 Tf (Hello) Tj ET";
let loadingTask = getDocument({
data: assemblePdf([
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 9 0 R " +
"/AcroForm << /Fields [7 0 R] >> >>\nendobj\n",
"2 0 obj\n<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>\nendobj\n",
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " +
"/StructParents 0 /Annots [6 0 R 7 0 R] >>\nendobj\n",
"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " +
"/Annots [8 0 R] >>\nendobj\n",
"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\n" +
"endobj\n",
"6 0 obj\n<< /Type /Annot /Subtype /Stamp /F 4 " +
"/Rect [10 10 60 60] /AP << /N 11 0 R >> >>\nendobj\n",
"7 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (Text) " +
"/V (Value) /F 4 /Rect [10 100 60 150] /AP << /N 11 0 R >> >>\n" +
"endobj\n",
"8 0 obj\n<< /Type /Annot /Subtype /Stamp /F 4 " +
"/Rect [10 10 60 60] /AP << /N 11 0 R >> >>\nendobj\n",
"9 0 obj\n<< /Type /StructTreeRoot " +
"/ParentTree << /Nums [0 10 0 R] >> >>\nendobj\n",
// Xref entry 10 points to object 99, so fetching 10R fails.
"99 0 obj\n[]\nendobj\n",
"11 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 50 50] " +
"/Resources << /Font << /F1 5 0 R >> >> " +
`/Length ${appearance.length} >>\n` +
`stream\n${appearance}\nendstream\nendobj\n`,
]),
});
let pdfDoc = await loadingTask.promise;
const data = await pdfDoc.saveDocument({ flatten: true });
await loadingTask.destroy();
loadingTask = getDocument({ data });
pdfDoc = await loadingTask.promise;
// The failing page keeps its annotations, hence the form.
expect([...(await pdfDoc.getFieldObjects()).keys()]).toEqual(["Text"]);
const [page1, page2] = await Promise.all([
pdfDoc.getPage(1),
pdfDoc.getPage(2),
]);
expect(
(await page1.getAnnotations({ intent: "any" })).map(({ id }) => id)
).toEqual(["6R", "7R"]);
expect((await page1.getTextContent()).items).toEqual([]);
expect(await page2.getAnnotations({ intent: "any" })).toEqual([]);
const { items } = await page2.getTextContent();
expect(items.map(({ str }) => str)).toEqual(["Hello"]);
await loadingTask.destroy();
});
it("save the pdf flattened and check that the resources of the content stream are kept", async function () {
let loadingTask = getDocument(buildGetDocumentParams("issue18894.pdf"));
let pdfDoc = await loadingTask.promise;