Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add with ... as ... usage #1117

Closed
wants to merge 34 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
a2b7b55
Add `with ... as ...` usage (#1108)
JianzhengLuo Jul 15, 2022
2a88bd5
Update PyPDF2/_merger.py according to @MasterOdin's suggestions
JianzhengLuo Jul 15, 2022
b6d0351
Update PyPDF2/_merger.py according to @MasterOdin's suggestions
JianzhengLuo Jul 15, 2022
80813aa
Update PyPDF2/_merger.py according to @MasterOdin's suggestions
JianzhengLuo Jul 16, 2022
e6ec1f6
Update PyPDF2/_merger.py according to @MasterOdin's suggestions
JianzhengLuo Jul 16, 2022
386be5b
Update PyPDF2/_merger.py according to @MasterOdin's suggestions
JianzhengLuo Jul 16, 2022
31786bb
Sorry, I forgot to run before committing, so didn't notice that `Trac…
JianzhengLuo Jul 16, 2022
ae1bec0
Modify the wrong closing place that cause.
JianzhengLuo Jul 16, 2022
0b7c64e
Merge branch 'main' into add-with-as-usage-#1108
JianzhengLuo Jul 17, 2022
b695113
Modify PyPDF2/_writer.py according to @MasterOdin's suggestions
JianzhengLuo Jul 18, 2022
58797c2
Modify PyPDF2/_writer.py according to @MasterOdin's suggestions
JianzhengLuo Jul 18, 2022
1caa9ec
Modify PyPDF2/_writer.py according to @MasterOdin's suggestions
JianzhengLuo Jul 18, 2022
4fbe3cc
Modify PyPDF2/_writer.py according to @MasterOdin's suggestions
JianzhengLuo Jul 18, 2022
d598e8a
Modify PyPDF2/_writer.py according to @MasterOdin's suggestions
JianzhengLuo Jul 18, 2022
7ecf9ff
Merge branch 'add-with-as-usage-#1108' of https://github.com/Jianzhen…
JianzhengLuo Jul 18, 2022
562ebc7
Merge branch 'main' into add-with-as-usage-#1108
Jul 19, 2022
519dad1
Fix accident
JianzhengLuo Jul 21, 2022
336053a
Merge branch 'add-with-as-usage-#1108' of https://github.com/Jianzhen…
JianzhengLuo Jul 21, 2022
90af68a
Fix error raising while using half traditional usage
JianzhengLuo Jul 21, 2022
0f67658
Add a unit test (Problems still exist, please help.)
JianzhengLuo Jul 21, 2022
a6f973e
Update PyPDF2/_merger.py according to @MartinThoma's suggestions
JianzhengLuo Jul 21, 2022
580ad8c
Modify PyPDF2/_merger.py according to flake8
JianzhengLuo Jul 21, 2022
bf264bc
Modify to compatible with the existing usage
JianzhengLuo Jul 21, 2022
c705300
Modify to compatible with the with .. as ... usage
JianzhengLuo Jul 21, 2022
2940589
Removed a meaningless annotation
JianzhengLuo Jul 21, 2022
cda38ac
Fixed wrong test function names
JianzhengLuo Jul 21, 2022
0b18198
Fixed those I can fix only.
JianzhengLuo Jul 22, 2022
62f970f
Removed useless `else` section
JianzhengLuo Jul 22, 2022
d85c91b
Renamed argument name `fileobj` back to `stream` to keep the existing…
JianzhengLuo Jul 22, 2022
5cd3f3e
Modified annoation for `PdfWriter().write()` and `PdfWriter().write_s…
JianzhengLuo Jul 22, 2022
a7346ef
Switched `fileobj` and `strict` in initializing `PdfWriter()` to keep…
JianzhengLuo Jul 23, 2022
d3e62ee
Modified annoation to make the it match the arguments
JianzhengLuo Jul 23, 2022
59be94d
Modified undefined name `fileobj`
JianzhengLuo Jul 24, 2022
092f209
Merge branch 'main' into add-with-as-usage-#1108
MartinThoma Aug 1, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions PyPDF2/_merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
# POSSIBILITY OF SUCH DAMAGE.

from io import BytesIO, FileIO, IOBase
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast, Type

from ._encryption import Encryption
from ._page import PageObject
Expand All @@ -51,6 +51,7 @@
)
from .pagerange import PageRange, PageRangeSpec
from .types import FitType, LayoutType, OutlinesType, PagemodeType, ZoomArgType
from types import TracebackType

ERR_CLOSED_WRITER = "close() was called and thus the writer cannot be used anymore"

Expand All @@ -75,20 +76,33 @@ class PdfMerger:
See the functions :meth:`merge()<merge>` (or :meth:`append()<append>`)
and :meth:`write()<write>` for usage information.

:param fileobj: Output file. Can be a filename or any kind of
file-like object.
:param bool strict: Determines whether user should be warned of all
problems and also causes some correctable problems to be fatal.
Defaults to ``False``.
"""

def __init__(self, strict: bool = False) -> None:
def __init__(self, fileobj: StrByteType = "", strict: bool = False) -> None:
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved
self.inputs: List[Tuple[Any, PdfReader, bool]] = []
self.pages: List[Any] = []
self.output: Optional[PdfWriter] = PdfWriter()
self.bookmarks: OutlinesType = []
self.named_dests: List[Any] = []
self.id_count = 0
self.fileobj = fileobj
self.strict = strict

# There is nothing to do.
def __enter__(self) -> "PdfMerger":
return self

# Write to the fileobj and close the merger.
def __exit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException],
traceback: Optional[TracebackType]) -> None:
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved
self.write(self.fileobj)
self.close()

def merge(
self,
position: int,
Expand Down Expand Up @@ -252,10 +266,6 @@ def write(self, fileobj: StrByteType) -> None:
"""
if self.output is None:
raise RuntimeError(ERR_CLOSED_WRITER)
my_file = False
if isinstance(fileobj, str):
fileobj = FileIO(fileobj, "wb")
my_file = True
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved

# Add pages to the PdfWriter
# The commented out line below was replaced with the two lines below it
Expand All @@ -276,9 +286,6 @@ def write(self, fileobj: StrByteType) -> None:
# Write the output to the file
self.output.write(fileobj)

if my_file:
fileobj.close()

JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved
def close(self) -> None:
"""Shut all file descriptors (input and output) and clear all memory usage."""
self.pages = []
Expand Down
38 changes: 35 additions & 3 deletions PyPDF2/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
Tuple,
Union,
cast,
Type
)

from PyPDF2.errors import PdfReadWarning
Expand All @@ -59,6 +60,7 @@
_get_max_pdf_version_header,
b_,
deprecate_with_replacement,
StrByteType
)
from .constants import AnnotationDictionaryAttributes
from .constants import CatalogAttributes as CA
Expand Down Expand Up @@ -107,6 +109,9 @@
ZoomArgsType,
ZoomArgType,
)
from io import FileIO
from types import TracebackType


logger = logging.getLogger(__name__)

Expand All @@ -121,7 +126,7 @@ class PdfWriter:
class (typically :class:`PdfReader<PyPDF2.PdfReader>`).
"""

def __init__(self) -> None:
def __init__(self, fileobj: StrByteType = "") -> None:
self._header = b"%PDF-1.3"
self._objects: List[Optional[PdfObject]] = [] # array of indirect objects
self._idnum_hash: Dict[bytes, IndirectObject] = {}
Expand Down Expand Up @@ -158,6 +163,16 @@ def __init__(self) -> None:
)
self._root: Optional[IndirectObject] = None
self._root_object = root
self.fileobj = fileobj

# Nothing to do.
def __enter__(self) -> "PdfWriter":
return self

# Write to the fileobj.
def __exit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException],
traceback: Optional[TracebackType]) -> None:
self.write(self.fileobj)

@property
def pdf_header(self) -> bytes:
Expand Down Expand Up @@ -763,7 +778,7 @@ def encrypt(
self._encrypt = self._add_object(encrypt)
self._encrypt_key = key

def write(self, stream: StreamType) -> None:
def write_stream(self, stream: StreamType) -> None:
"""
Write the collection of pages added to this object out as a PDF file.

Expand Down Expand Up @@ -794,6 +809,23 @@ def write(self, stream: StreamType) -> None:
self._write_trailer(stream)
stream.write(b_(f"\nstartxref\n{xref_location}\n%%EOF\n")) # eof

def write(self, fileobj: StrByteType) -> None:
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved
my_file = False

if fileobj == "":
raise ValueError(f"Output(fileobj={fileobj}) is empty.")

if isinstance(fileobj, str):
fileobj = FileIO(fileobj, "wb")
my_file = True
else:
pass
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved

self.write_stream(fileobj)

if my_file:
fileobj.close()

def _write_header(self, stream: StreamType) -> List[int]:
object_positions = []
stream.write(self.pdf_header + b"\n")
Expand Down Expand Up @@ -1601,7 +1633,7 @@ def _get_page_layout(self) -> Optional[LayoutType]:

def getPageLayout(self) -> Optional[LayoutType]: # pragma: no cover
"""
.. deprecated:: 1.28.0
.. deprecated:: 1.28.0raise
JianzhengLuo marked this conversation as resolved.
Show resolved Hide resolved

Use :py:attr:`page_layout` instead.
"""
Expand Down