@@ -565,6 +565,17 @@ public void flattenFields() {
565
565
}
566
566
}
567
567
568
+ // In case of appearance resources and page resources are the same object, it would not be possible to add
569
+ // the xObject to the page resources. So in that case we would copy page resources and use the copy for
570
+ // xObject, so that circular reference is avoided.
571
+ // We copy beforehand firstly not to produce a copy every time, and secondly not to copy all the
572
+ // xObjects that have already been added to the page resources.
573
+ Map <Integer , PdfObject > initialPageResourceClones = new LinkedHashMap <>();
574
+ for (int i = 1 ; i <= document .getNumberOfPages (); i ++) {
575
+ PdfObject resources = document .getPage (i ).getPdfObject ().getAsDictionary (PdfName .Resources );
576
+ initialPageResourceClones .put (i , resources == null ? null : resources .clone ());
577
+ }
578
+
568
579
PdfPage page ;
569
580
for (PdfFormField field : fields ) {
570
581
page = getFieldPage (field .getPdfObject ());
@@ -604,6 +615,16 @@ public void flattenFields() {
604
615
throw new PdfException (PdfException .PageWasAlreadyFlushedUseAddFieldAppearanceToPageMethodInstead );
605
616
}
606
617
PdfCanvas canvas = new PdfCanvas (page );
618
+
619
+ // Here we avoid circular reference which might occur when page resources and the appearance xObject's
620
+ // resources are the same object
621
+ PdfObject xObjectResources = xObject .getPdfObject ().get (PdfName .Resources );
622
+ PdfObject pageResources = page .getResources ().getPdfObject ();
623
+ if (xObjectResources != null && pageResources != null &&
624
+ xObjectResources == pageResources ) {
625
+ xObject .getPdfObject ().put (PdfName .Resources , initialPageResourceClones .get (document .getPageNumber (page )));
626
+ }
627
+
607
628
canvas .addXObject (xObject , box .getX (), box .getY ());
608
629
}
609
630
}
0 commit comments