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 5209fcd
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pypdf/_reader.py
Expand Up @@ -35,6 +35,7 @@
from datetime import datetime
from io import BytesIO, FileIO, UnsupportedOperation
from pathlib import Path
from types import TracebackType
from typing import (
Any,
Callable,
Expand All @@ -45,6 +46,7 @@
Mapping,
Optional,
Tuple,
Type,
Union,
cast,
)
Expand Down Expand Up @@ -312,8 +314,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 +353,20 @@ def close(self) -> None:
"""Close the underlying file handle"""
self.stream.close()

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

Check warning on line 358 in pypdf/_reader.py

View check run for this annotation

Codecov / codecov/patch

pypdf/_reader.py#L358

Added line #L358 was not covered by tests

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()

Check warning on line 368 in pypdf/_reader.py

View check run for this annotation

Codecov / codecov/patch

pypdf/_reader.py#L368

Added line #L368 was not covered by tests

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

0 comments on commit 5209fcd

Please sign in to comment.