Skip to content

Commit

Permalink
fixup! PI: Don't load entire file into memory when passed file name
Browse files Browse the repository at this point in the history
  • Loading branch information
mjsir911 committed Mar 21, 2024
1 parent 294da34 commit b105b76
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pypdf/_reader.py
Expand Up @@ -312,8 +312,10 @@ def __init__(
__name__,
)

self._we_opened = False
if isinstance(stream, (str, Path)):
stream = FileIO(stream, "rb")
self._we_opened = True
weakref.finalize(self, stream.close)

self.read(stream)
Expand Down Expand Up @@ -349,6 +351,20 @@ def close(self) -> None:
"""Close the underlying file handle"""
self.stream.close()

def __enter__(self) -> "PdfReader":
"""Use PdfReader as context manager"""
return self

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
"""Write data to the fileobj."""
if self._we_opened:
self.close()

@property
def root_object(self) -> DictionaryObject:
"""Provide access to "/Root". standardized with PdfWriter."""
Expand Down

0 comments on commit b105b76

Please sign in to comment.