Skip to content

Commit 0b7346a

Browse files
authored
BUG: Do not fail on choice field without /Opt key (#3540)
Closes #2838. According to the PDF 2.0 specification, the `/Opt` key is not required for choice fields.
1 parent daa108c commit 0b7346a

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

pypdf/_doc_common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,7 @@ def _build_field(
599599
fileobj.write("\n")
600600
retval[key] = Field(field)
601601
obj = retval[key].indirect_reference.get_object() # to get the full object
602-
if obj.get(FA.FT, "") == "/Ch":
602+
if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)):
603603
retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)]
604604
if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj:
605605
# Checkbox

tests/test_reader.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ def test_get_page_of_encrypted_file(pdffile, password, should_fail):
418418
"crazyones.pdf",
419419
{},
420420
None,
421-
),
421+
)
422422
],
423423
)
424424
def test_get_form(src, expected, expected_get_fields, txt_file_path):
@@ -448,6 +448,21 @@ def test_get_form(src, expected, expected_get_fields, txt_file_path):
448448
]
449449

450450

451+
@pytest.mark.enable_socket
452+
def test_reading_choice_field_without_opt_key():
453+
"""Tests reading a choice field in a PDF without an /Opt key."""
454+
url = "https://github.com/user-attachments/files/23853677/Musterservicevertrag-HNRAGB_Okt2022-Blanko.pdf"
455+
reader = PdfReader(BytesIO(get_data_from_url(url, name="Musterservicevertrag-HNRAGB_Okt2022-Blanko.pdf")))
456+
fields = reader.get_fields()
457+
458+
tn_anrede = fields.get("TN_Anrede")
459+
assert tn_anrede is not None
460+
461+
# Ensure that parsing of a choice field without /Opt key worked
462+
tn_anrede_opt = tn_anrede.get("/Opt")
463+
assert tn_anrede_opt is None
464+
465+
451466
@pytest.mark.parametrize(
452467
("src", "page_number"),
453468
[

0 commit comments

Comments
 (0)