Skip to content

update_page_form_field_values fails on pdf with same field on multiple pages. #2234

@oeble

Description

@oeble

I have this pdf file with some fields duplicated on multiple pages. When I try to fill any of those fields (for example, "n et p" using update_page_form_field_values, it fails with KeyError: '/AP'.

My wild guess is that it is because update_page_form_field_values takes one page to update while the same field is duplicated multiple times over the whole document.

Side note: pdftk handles this well, but I'm looking for a native Python solution.

Environment

$ python -m platform
Windows-10-10.0.22631-SP0

$ python -c "import pypdf;print(pypdf._debug_versions)"
pypdf==3.16.2, crypt_provider=('cryptography', '41.0.4'), PIL=none

Code + PDF

This is a minimal, complete example that shows the issue:

from pypdf import PdfReader, PdfWriter

reader = PdfReader("634_empty.pdf")
writer = PdfWriter()

# Fill the PDF
writer.append(reader)
fields = reader.get_fields()

page_1 = {
    "n et p": "test",
}

writer.update_page_form_field_values(writer.pages[1], page_1)

with open("test_output.pdf", "wb") as output_stream:
    writer.write(output_stream)

I'm sharing the pdf file that causes the issue, but I'm not the author, so I don't think it can be included in tests.

Traceback

This is the complete (redacted) Traceback I see:

Traceback (most recent call last):
  File "C:\..\dap_form.py", line 83, in validate_data
    fill_dap_pdf(v, "test_output.pdf")
  File "C:\..\dap_generate.py", line 45, in fill_dap_pdf
    writer.update_page_form_field_values(writer.pages[1], page_1)
  File "C:\..\venv\Lib\site-packages\pypdf\_writer.py", line 1072, in update_page_form_field_values
    value if value in k[AA.AP]["/N"] else "/Off"
                      ~^^^^^^^
  File "C:\..\venv\Lib\site-packages\pypdf\generic\_data_structures.py", line 320, in __getitem__
    return dict.__getitem__(self, key).get_object()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: '/AP'

Metadata

Metadata

Assignees

No one assigned

    Labels

    workflow-formsFrom a users perspective, forms is the affected feature/workflow

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions