diff --git a/src/api/form/PDFForm.ts b/src/api/form/PDFForm.ts index e92c833fc..682247090 100644 --- a/src/api/form/PDFForm.ts +++ b/src/api/form/PDFForm.ts @@ -548,6 +548,9 @@ export default class PDFForm { for (let j = 0, lenWidgets = widgets.length; j < lenWidgets; j++) { const widget = widgets[j]; const page = this.findWidgetPage(widget); + if (page === undefined) { + continue; + } const widgetRef = this.findWidgetAppearanceRef(field, widget); const xObjectKey = page.node.newXObject('FlatWidget', widgetRef); @@ -587,6 +590,10 @@ export default class PDFForm { const widgetRef = this.findWidgetAppearanceRef(field, widget); const page = this.findWidgetPage(widget); + if (page === undefined) { + continue; + } + pages.add(page); page.node.removeAnnot(widgetRef); @@ -698,7 +705,7 @@ export default class PDFForm { return this.defaultFontCache.access(); } - private findWidgetPage(widget: PDFWidgetAnnotation): PDFPage { + private findWidgetPage(widget: PDFWidgetAnnotation): PDFPage | undefined { const pageRef = widget.P(); let page = this.doc.getPages().find((x) => x.ref === pageRef); if (page === undefined) { @@ -709,8 +716,13 @@ export default class PDFForm { page = this.doc.findPageForAnnotationRef(widgetRef); + /* + * In some broken PDF's there may be widgets that don't exist on any page. + * We used to throw an error in such cases but it appears that other + * PDF readers just ignore such PDF's. + */ if (page === undefined) { - throw new Error(`Could not find page for PDFRef ${widgetRef}`); + return undefined; } }