Skip to content

Commit

Permalink
Improvements based on code review comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexaryn committed Oct 21, 2024
1 parent 5568450 commit a905bac
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
15 changes: 8 additions & 7 deletions pypdf/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,9 @@ def _get_clone_from(
or Path(str(fileobj)).stat().st_size == 0
):
cloning = False
if isinstance(fileobj, (IO, BytesIO)):
if isinstance(fileobj, (IOBase, BytesIO)):
t = fileobj.tell()
fileobj.seek(-1, 2)
fileobj.seek(0, 2)
if fileobj.tell() == 0:
cloning = False
fileobj.seek(t, 0)
Expand All @@ -249,6 +249,7 @@ def _get_clone_from(
# to prevent overwriting
self.temp_fileobj = fileobj
self.fileobj = ""
self.cloned = False
# The root of our page tree node.
pages = DictionaryObject()
pages.update(
Expand All @@ -266,6 +267,7 @@ def _get_clone_from(
if not isinstance(clone_from, PdfReader):
clone_from = PdfReader(clone_from)
self.clone_document_from_reader(clone_from)
self.cloned = True
else:
self._pages = self._add_object(pages)
# root object
Expand Down Expand Up @@ -352,9 +354,11 @@ def xmp_metadata(self, value: Optional[XmpInformation]) -> None:
return self.root_object.xmp_metadata # type: ignore

def __enter__(self) -> "PdfWriter":
"""Store that writer is initialized by 'with'."""
"""Store how writer is initialized by 'with'."""
c: bool = self.cloned
t = self.temp_fileobj
self.__init__() # type: ignore
self.cloned = c
self.fileobj = t # type: ignore
return self

Expand All @@ -365,11 +369,8 @@ def __exit__(
traceback: Optional[TracebackType],
) -> None:
"""Write data to the fileobj."""
if self.fileobj:
if self.fileobj and not self.cloned:
self.write(self.fileobj)
close_attr = getattr(self.fileobj, "close", None)
if callable(close_attr):
self.fileobj.close() # type: ignore[attr-defined]

def _repr_mimebundle_(
self,
Expand Down
24 changes: 21 additions & 3 deletions tests/test_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2485,9 +2485,27 @@ def test_append_pdf_with_dest_without_page(caplog):
def test_stream_not_closed():
"""Tests for #2905"""
src = RESOURCE_ROOT / "pdflatex-outline.pdf"
with NamedTemporaryFile() as tmp:
with NamedTemporaryFile(suffix=".pdf") as tmp:
with PdfReader(src) as reader, PdfWriter() as writer:
for i in range(4):
writer.add_page(reader.pages[i])
writer.add_page(reader.pages[0])
writer.write(tmp)
assert not tmp.file.closed

with NamedTemporaryFile(suffix=".pdf") as target:
with PdfWriter(target.file) as writer:
writer.add_blank_page(100, 100)
assert not target.file.closed

with open(src, "rb") as fileobj:
with PdfWriter(fileobj) as writer:
pass
assert not fileobj.closed


def test_auto_write():
"""Another test for #2905"""
with NamedTemporaryFile(suffix=".pdf", delete_on_close=False) as tmp:
tmp.close()
with PdfWriter(tmp.name) as writer:
writer.add_blank_page(100, 100)
assert Path(tmp.name).stat().st_size > 0

0 comments on commit a905bac

Please sign in to comment.