--- a/scripts/fill_form.py +++ b/scripts/fill_form.py @@ -81,9 +81,33 @@ writer.update_page_form_field_values( writer.pages[page_num], str_data, + auto_regenerate=False, ) + except TypeError: + # Older pypdf without auto_regenerate + try: + writer.update_page_form_field_values( + writer.pages[page_num], + str_data, + ) + except Exception as e: + logger.warning("Could not fill fields on page %d: %s", page_num + 1, e) except Exception as e: logger.warning("Could not fill fields on page %d: %s", page_num + 1, e) + + # Fallback: directly update field objects for any missed fields + from pypdf.generic import NameObject, TextStringObject, ArrayObject + if hasattr(writer, '_root_object') and '/AcroForm' in writer._root_object: + acroform = writer._root_object['/AcroForm'] + form_fields = acroform.get('/Fields', ArrayObject()) + for field_ref in form_fields: + field_obj = field_ref.get_object() + field_name = str(field_obj.get('/T', '')) + if field_name in str_data: + current_val = str(field_obj.get('/V', '')) + if not current_val: + logger.info("Patching missed field: %s = %s", field_name, str_data[field_name]) + field_obj[NameObject('/V')] = TextStringObject(str_data[field_name]) else: logger.info("No AcroForm fields found; adding text annotations as overlay") try: