Skip to content

Commit

Permalink
Remove code duplication
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinThoma committed Jun 16, 2022
1 parent a38f3a1 commit a154923
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 61 deletions.
44 changes: 13 additions & 31 deletions PyPDF2/_merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@
NumberObject,
TextStringObject,
TreeObject,
createStringObject,
_create_bookmark,
)
from .pagerange import PageRange, PageRangeSpec
from .types import (
BookmarkTypes,
FitType,
LayoutType,
OutlinesType,
PagemodeType,
Expand Down Expand Up @@ -590,7 +591,7 @@ def _associate_bookmarks_to_pages(
if pageno is not None:
b[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError("Unresolved bookmark '{}'".format(b["/Title"]))
raise ValueError(f"Unresolved bookmark '{b['/Title']}'")

def find_bookmark(
self,
Expand Down Expand Up @@ -621,8 +622,8 @@ def addBookmark(
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: str = "/Fit",
*args: ZoomArgType,
fit: FitType = "/Fit",
*args: ZoomArgsType,
) -> IndirectObject: # pragma: no cover
"""
.. deprecated:: 1.28.0
Expand All @@ -641,8 +642,8 @@ def add_bookmark(
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: str = "/Fit",
*args: ZoomArgType,
fit: FitType = "/Fit",
*args: ZoomArgsType,
) -> IndirectObject:
"""
Add a bookmark to this PDF file.
Expand All @@ -656,7 +657,7 @@ def add_bookmark(
:param bool bold: Bookmark is bold
:param bool italic: Bookmark is italic
:param str fit: The fit of the destination page. See
:meth:`addLink()<addLin>` for details.
:meth:`addLink()<addLink>` for details.
"""
if self.output is None:
raise RuntimeError(ERR_CLOSED_WRITER)
Expand Down Expand Up @@ -687,32 +688,13 @@ def add_bookmark(
if parent is None:
parent = outline_ref

bookmark = TreeObject()
bookmark = _create_bookmark(action_ref, title, color, italic, bold)

bookmark.update(
{
NameObject("/A"): action_ref,
NameObject("/Title"): createStringObject(title),
}
)

if color is not None:
bookmark.update(
{NameObject("/C"): ArrayObject([FloatObject(c) for c in color])}
)

format_flag = 0
if italic:
format_flag += 1
if bold:
format_flag += 2
if format_flag:
bookmark.update({NameObject("/F"): NumberObject(format_flag)})

bookmark_ref = self.output._add_object(bookmark)
parent = cast(Bookmark, parent.get_object())
assert parent is not None, "hint for mypy"
parent.add_child(bookmark_ref, self.output)
bookmark_ref = self.output._add_object(bookmark)
parent_obj = cast(Bookmark, parent.get_object())
assert parent_obj is not None, "hint for mypy"
parent_obj.add_child(bookmark_ref, self.output)

return bookmark_ref

Expand Down
16 changes: 8 additions & 8 deletions PyPDF2/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -1228,8 +1228,8 @@ def read(self, stream: StreamType) -> None:
)

# read all cross reference tables and their trailers
self.xref: Dict[Any, Any] = {}
self.xref_objStm: Dict[Any, Any] = {}
self.xref: Dict[int, Dict[Any, Any]] = {}
self.xref_objStm: Dict[int, Tuple[Any, Any]] = {}
self.trailer = DictionaryObject()
while True:
# load the xref table
Expand Down Expand Up @@ -1302,11 +1302,11 @@ def read(self, stream: StreamType) -> None:
# if not zero-indexed, verify that the table is correct; change it if necessary
if self.xref_index and not self.strict:
loc = stream.tell()
for gen in self.xref:
for gen, xref_entry in self.xref.items():
if gen == 65535:
continue
for id in self.xref[gen]:
stream.seek(self.xref[gen][id], 0)
for id in xref_entry:
stream.seek(xref_entry[id], 0)
try:
pid, _pgen = self.read_object_header(stream)
except ValueError:
Expand Down Expand Up @@ -1440,7 +1440,7 @@ def get_entry(i: int) -> Union[int, Tuple[int, ...]]:

def used_before(num: int, generation: Union[int, Tuple[int, ...]]) -> bool:
# We move backwards through the xrefs, don't replace any.
return num in self.xref.get(generation, []) or num in self.xref_objStm
return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore

# Iterate through each subsection
self._read_xref_subsections(idx_pairs, get_entry, used_before)
Expand Down Expand Up @@ -1519,9 +1519,9 @@ def _read_xref_subsections(
byte_offset = get_entry(1)
generation = get_entry(2)
if generation not in self.xref:
self.xref[generation] = {}
self.xref[generation] = {} # type: ignore
if not used_before(num, generation):
self.xref[generation][num] = byte_offset
self.xref[generation][num] = byte_offset # type: ignore
elif xref_type == 2:
# compressed objects
objstr_num = get_entry(1)
Expand Down
23 changes: 2 additions & 21 deletions PyPDF2/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
StreamObject,
TextStringObject,
TreeObject,
_create_bookmark,
createStringObject,
)
from .types import (
Expand Down Expand Up @@ -1078,27 +1079,7 @@ def add_bookmark(
if parent is None:
parent = outline_ref

bookmark = TreeObject()

bookmark.update(
{
NameObject("/A"): action_ref,
NameObject("/Title"): createStringObject(title),
}
)

if color is not None:
bookmark.update(
{NameObject("/C"): ArrayObject([FloatObject(c) for c in color])}
)

format_flag = 0
if italic:
format_flag += 1
if bold:
format_flag += 2
if format_flag:
bookmark.update({NameObject("/F"): NumberObject(format_flag)})
bookmark = _create_bookmark(action_ref, title, color, italic, bold)

bookmark_ref = self._add_object(bookmark)

Expand Down
2 changes: 1 addition & 1 deletion PyPDF2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _decode_png_prediction(data: str, columns: int) -> str:
rowdata[i] = (rowdata[i] + paeth) % 256
else:
# unsupported PNG filter
raise PdfReadError("Unsupported PNG filter %r" % filter_byte)
raise PdfReadError(f"Unsupported PNG filter {filter_byte!r}")
prev_rowdata = tuple(rowdata)
output.write("".join([chr(x) for x in rowdata[1:]]))
return output.getvalue()
Expand Down
31 changes: 31 additions & 0 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1904,6 +1904,37 @@ def createStringObject(
raise TypeError("createStringObject should have str or unicode arg")


def _create_bookmark(
action_ref: IndirectObject,
title: str,
color: Optional[Tuple[float, float, float]],
italic: bool,
bold: bool,
) -> TreeObject:
bookmark = TreeObject()

bookmark.update(
{
NameObject("/A"): action_ref,
NameObject("/Title"): createStringObject(title),
}
)

if color is not None:
bookmark.update(
{NameObject("/C"): ArrayObject([FloatObject(c) for c in color])}
)

format_flag = 0
if italic:
format_flag += 1
if bold:
format_flag += 2
if format_flag:
bookmark.update({NameObject("/F"): NumberObject(format_flag)})
return bookmark


def encode_pdfdocencoding(unicode_string: str) -> bytes:
retval = b""
for c in unicode_string:
Expand Down

0 comments on commit a154923

Please sign in to comment.