Skip to content

Commit

Permalink
ROB: Robustify .set_data() (#2821)
Browse files Browse the repository at this point in the history
Cope with objects where the filter is ["/FlateDecode"] and/or where data has not been read yet.
  • Loading branch information
pubpub-zz authored Aug 29, 2024
1 parent 38ea8c5 commit 82eac7e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 4 additions & 2 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,10 +1013,12 @@ def get_data(self) -> bytes:
def set_data(self, data: bytes) -> None: # deprecated
from ..filters import FlateDecode

if self.get(SA.FILTER, "") == FT.FLATE_DECODE:
if self.get(SA.FILTER, "") in (FT.FLATE_DECODE, [FT.FLATE_DECODE]):
if not isinstance(data, bytes):
raise TypeError("data must be bytes")
assert self.decoded_self is not None
if self.decoded_self is None:
self.get_data() # to create self.decoded_self
assert self.decoded_self is not None, "mypy"
self.decoded_self.set_data(data)
super().set_data(FlateDecode.encode(data))
else:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1326,6 +1326,22 @@ def test_encodedstream_set_data():
assert cc[NameObject("/Test")] == "/MyTest"


@pytest.mark.enable_socket()
def test_set_data_2():
"""
Modify a stream not yet loaded and
where the filter is ["/FlateDecode"]
"""
url = "https://github.com/user-attachments/files/16796095/f5471sm-2.pdf"
name = "iss2780.pdf"
writer = PdfWriter(BytesIO(get_data_from_url(url, name=name)))
writer.root_object["/AcroForm"]["/XFA"][7].set_data(b"test")
assert writer.root_object["/AcroForm"]["/XFA"][7].get_object()["/Filter"] == [
"/FlateDecode"
]
assert writer.root_object["/AcroForm"]["/XFA"][7].get_object().get_data() == b"test"


@pytest.mark.enable_socket()
def test_calling_indirect_objects():
"""Cope with cases where attributes/items are called from indirectObject"""
Expand Down

0 comments on commit 82eac7e

Please sign in to comment.