diff --git a/pypdf/_page.py b/pypdf/_page.py index 4ddbfb62d..4d53d1b54 100644 --- a/pypdf/_page.py +++ b/pypdf/_page.py @@ -701,7 +701,11 @@ def get_contents(self) -> Optional[ContentStream]: ``/Contents`` is optional, as described in PDF Reference 7.7.3.3 """ if PG.CONTENTS in self: - return self[PG.CONTENTS].get_object() # type: ignore + try: + pdf = cast(IndirectObject, self.indirect_reference).pdf + except AttributeError: + pdf = None + return ContentStream(self[PG.CONTENTS].get_object(), pdf) else: return None @@ -819,7 +823,6 @@ def _merge_page( page2content = page2.get_contents() if page2content is not None: - page2content = ContentStream(page2content, self.pdf) rect = getattr(page2, MERGE_CROP_BOX) page2content.operations.insert( 0, @@ -955,7 +958,6 @@ def _merge_page_writer( page2content = page2.get_contents() if page2content is not None: - page2content = ContentStream(page2content, self.pdf) rect = getattr(page2, MERGE_CROP_BOX) page2content.operations.insert( 0, @@ -1491,12 +1493,7 @@ def compress_content_streams(self) -> None: """ content = self.get_contents() if content is not None: - content_obj: Any - if not isinstance(content, ContentStream): - content_obj = ContentStream(content, self.pdf) - else: - content_obj = content - content_obj = content_obj.flate_encode() + content_obj = content.flate_encode() try: content.indirect_reference.pdf._objects[ # type: ignore content.indirect_reference.idnum - 1 # type: ignore diff --git a/tests/test_page.py b/tests/test_page.py index 6916207cd..a7fa50364 100644 --- a/tests/test_page.py +++ b/tests/test_page.py @@ -264,7 +264,9 @@ def test_compress_content_streams(pdf_path, password): writer = PdfWriter() if password: reader.decrypt(password) + assert isinstance(reader.pages[0].get_contents(), ContentStream) writer.clone_document_from_reader(reader) + assert isinstance(writer.pages[0].get_contents(), ContentStream) for page in writer.pages: page.compress_content_streams() @@ -330,7 +332,10 @@ def test_page_scale(): def test_add_transformation_on_page_without_contents(): page = PageObject() + assert page.get_contents() is None page.add_transformation(Transformation()) + page[NameObject("/Contents")] = ContentStream(None, None) + assert isinstance(page.get_contents(), ContentStream) @pytest.mark.enable_socket()