From c978b4e6cc5e15035f77ab1fe1facef4b6c25e7f Mon Sep 17 00:00:00 2001 From: Emil Sedgh Date: Sun, 26 Feb 2023 13:23:02 -0800 Subject: [PATCH 1/2] Some broken fields may include annotations in their Kids array that couldn't be found on any pages. Up until now we've been throwing an exception when dealing with such fields. But it appears that other PDF software are more resilient to this and gracefully ignore them. This commit ensures we'll do the same. Fixes #967,#1281,#1349 --- src/api/form/PDFForm.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/api/form/PDFForm.ts b/src/api/form/PDFForm.ts index e92c833fc..38073300a 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); @@ -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; } } From e0b8e31cd88b87bad7e8a8442226bb22faba8fca Mon Sep 17 00:00:00 2001 From: Emil Sedgh Date: Sun, 26 Feb 2023 13:34:41 -0800 Subject: [PATCH 2/2] Update Typecritp file to match the new undefined case --- src/api/form/PDFForm.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/form/PDFForm.ts b/src/api/form/PDFForm.ts index 38073300a..682247090 100644 --- a/src/api/form/PDFForm.ts +++ b/src/api/form/PDFForm.ts @@ -705,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) {