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

ENH: Accept hierarchical fields #1529

Merged
merged 7 commits into from
Jan 8, 2023
Merged
Show file tree
Hide file tree
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
60 changes: 53 additions & 7 deletions pypdf/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,20 @@ def getFields(
deprecation_with_replacement("getFields", "get_fields", "3.0.0")
return self.get_fields(tree, retval, fileobj)

def _get_qualified_field_name(self, parent: DictionaryObject) -> str:
if "/TM" in parent:
return cast(str, parent["/TM"])
elif "/Parent" in parent:
return (
self._get_qualified_field_name(
cast(DictionaryObject, parent["/Parent"])
)
+ "."
+ cast(str, parent["/T"])
)
else:
return cast(str, parent["/T"])

def _build_field(
self,
field: Union[TreeObject, DictionaryObject],
Expand All @@ -594,10 +608,19 @@ def _build_field(
) -> None:
self._check_kids(field, retval, fileobj)
try:
key = field["/TM"]
key = cast(str, field["/TM"])
except KeyError:
try:
key = field["/T"]
if "/Parent" in field:
key = (
self._get_qualified_field_name(
cast(DictionaryObject, field["/Parent"])
)
+ "."
)
else:
key = ""
key += cast(str, field["/T"])
except KeyError:
# Ignore no-name field for now
return
Expand Down Expand Up @@ -651,25 +674,48 @@ def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None:
# Field attribute is N/A or unknown, so don't write anything
pass

def get_form_text_fields(self) -> Dict[str, Any]:
def get_form_text_fields(self, full_qualified_name: bool = False) -> Dict[str, Any]:
pubpub-zz marked this conversation as resolved.
Show resolved Hide resolved
"""
Retrieve form fields from the document with textual data.

The key is the name of the form field, the value is the content of the
field.

If the document contains multiple form fields with the same name, the
second and following will get the suffix _2, _3, ...
second and following will get the suffix .2, .3, ...

full_qualified_name should be used to get full name
"""

def indexed_key(k: str, fields: dict) -> str:
if k not in fields:
return k
else:
return (
k
+ "."
+ str(sum([1 for kk in fields if kk.startswith(k + ".")]) + 2)
)

# Retrieve document form fields
formfields = self.get_fields()
if formfields is None:
return {}
return {
formfields[field]["/T"]: formfields[field].get("/V")
ff = {}
for field, value in formfields.items():
if value.get("/FT") == "/Tx":
if full_qualified_name:
ff[field] = value.get("/V")
else:
ff[indexed_key(cast(str, value["/T"]), ff)] = value.get("/V")
return ff
"""return {
(field if full_qualified_name else formfields[field]["/T"]): formfields[
field
].get("/V")
for field in formfields
if formfields[field].get("/FT") == "/Tx"
}
}"""

def getFormTextFields(self) -> Dict[str, Any]: # deprecated
"""
Expand Down
3 changes: 2 additions & 1 deletion pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1138,12 +1138,13 @@ class Field(TreeObject):
:meth:`get_fields()<pypdf.PdfReader.get_fields>`
"""

def __init__(self, data: Dict[str, Any]) -> None:
def __init__(self, data: DictionaryObject) -> None:
DictionaryObject.__init__(self)
field_attributes = (
FieldDictionaryAttributes.attributes()
+ CheckboxRadioButtonAttributes.attributes()
)
self.indirect_reference = data.indirect_reference
for attr in field_attributes:
try:
self[NameObject(attr)] = data[attr]
Expand Down
19 changes: 19 additions & 0 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,25 @@ def test_get_fields():
assert dict(fields["c1-1"]) == ({"/FT": "/Btn", "/T": "c1-1"})


def test_get_full_qualified_fields():
url = "https://github.com/py-pdf/PyPDF2/files/10142389/fields_with_dots.pdf"
name = "fields_with_dots.pdf"
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
fields = reader.get_form_text_fields(True)
assert fields is not None
assert "customer.name" in fields

fields = reader.get_form_text_fields(False)
assert fields is not None
assert "customer.name" not in fields
assert "name" in fields

fields = reader.get_fields(True)
assert fields is not None
assert "customer.name" in fields
assert fields["customer.name"]["/T"] == "name"


@pytest.mark.external
@pytest.mark.filterwarnings("ignore::pypdf.errors.PdfReadWarning")
def test_get_fields_read_else_block():
Expand Down