Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/api/form/PDFForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,10 @@ export default class PDFForm {

for (let i = 0, len = widgets.length; i < len; i++) {
const widget = widgets[i];
const widgetRef = this.findWidgetAppearanceRef(field, widget);
const widgetRef = this.doc.context.getObjectRef(widget.dict);
if (widgetRef === undefined) {
throw new Error('Could not find PDFRef for widget annotation');
}

const page = this.findWidgetPage(widget);
pages.add(page);
Expand Down
35 changes: 35 additions & 0 deletions tests/api/form/PDFForm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ const getWidgets = (pdfDoc: PDFDocument) =>
const getRefs = (pdfDoc: PDFDocument) =>
pdfDoc.context.enumerateIndirectObjects().map(([ref]) => ref as PDFRef);

const getPageWidgetAnnotRefs = (pdfDoc: PDFDocument) =>
flatten(
pdfDoc.getPages().map((page) => {
const annots = page.node.Annots();
if (!annots) return [];
return annots.asArray().filter((annotRef) => {
const obj = pdfDoc.context.lookup(annotRef);
return (
obj instanceof PDFDict &&
obj.get(PDFName.of('Subtype')) === PDFName.of('Widget')
);
});
}),
);

const getApRefs = (widget: PDFWidgetAnnotation) => {
const onValue = widget.getOnValue() ?? PDFName.of('Yes');
const aps = widget.getAppearances();
Expand Down Expand Up @@ -328,6 +343,26 @@ describe(`PDFForm`, () => {
rgWidgetRefs.forEach((ref) => expect(refs2).not.toContain(ref));
});

it(`removes widget annotation refs from page Annots arrays`, async () => {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
const form = pdfDoc.getForm();

const tf = form.createTextField('example.text.field');
tf.addToPage(page, { x: 50, y: 50, width: 100, height: 20 });

const widgetRef = pdfDoc.context.getObjectRef(
tf.acroField.getWidgets()[0].dict,
);

expect(getPageWidgetAnnotRefs(pdfDoc)).toContain(widgetRef);

form.removeField(tf);

expect(getPageWidgetAnnotRefs(pdfDoc)).not.toContain(widgetRef);
expect(getPageWidgetAnnotRefs(pdfDoc)).toHaveLength(0);
});

it(`it cleans references of removed fields and their widgets when created with pdf-lib`, async () => {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
Expand Down
Loading