Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make pdf-lib more graceful like other pdf software #1407

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
16 changes: 14 additions & 2 deletions src/api/form/PDFForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
}
}

Expand Down