Skip to content

Commit

Permalink
ENH: Add outline_count property (#1129)
Browse files Browse the repository at this point in the history
Enables retrieval of "/Count" attribute of outline item in PdfReader.outlines by implementing property outline_count.

Closes #1122
  • Loading branch information
mtd91429 authored Jul 18, 2022
1 parent 33634d4 commit 25cba33
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
6 changes: 5 additions & 1 deletion PyPDF2/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,7 @@ def _build_outline(self, node: DictionaryObject) -> Optional[Destination]:
else:
raise PdfReadError(f"Unexpected destination {dest!r}")

# if outline created, add color and format if present
# if outline created, add color, format, and child count if present
if outline:
if "/C" in node:
# Color of outline in (R, G, B) with values ranging 0.0-1.0
Expand All @@ -847,6 +847,10 @@ def _build_outline(self, node: DictionaryObject) -> Optional[Destination]:
# specifies style characteristics bold and/or italic
# 1=italic, 2=bold, 3=both
outline[NameObject("/F")] = node["/F"]
if "/Count" in node:
# absolute value = num. visible children
# positive = open/unfolded, negative = closed/folded
outline[NameObject("/Count")] = node["/Count"]

return outline

Expand Down
10 changes: 10 additions & 0 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,16 @@ def font_format(self) -> Optional[OutlineFontFlag]:
"""Read-only property accessing the font type. 1=italic, 2=bold, 3=both"""
return self.get("/F", 0)

@property
def outline_count(self) -> Optional[int]:
"""
Read-only property accessing the outline count.
positive = expanded
negative = collapsed
absolute value = number of visible descendents at all levels
"""
return self.get("/Count", None)


class Bookmark(Destination):
def write_to_stream(
Expand Down
58 changes: 58 additions & 0 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -933,3 +933,61 @@ def get_titles_only(outlines, results=None):
"Twenty-seventh",
],
]


def test_outline_count():
reader = PdfReader(EXTERNAL_ROOT / "014-outlines/mistitled_outlines_example.pdf")

def get_counts_only(outlines, results=None):
if results is None:
results = []
if isinstance(outlines, list):
for outline in outlines:
if isinstance(outline, Destination):
results.append(outline.outline_count)
else:
results.append(get_counts_only(outline))
else:
raise ValueError(f"got {type(outlines)}")
return results
assert get_counts_only(reader.outlines) == [
5,
[
None,
None,
2,
[
None,
None,
],
-2,
[
None,
None,
],
],
4,
[
None,
None,
None,
None,
],
-2,
[
None,
None,
],
None,
8,
[
None,
None,
None,
None,
None,
None,
None,
None,
],
]

0 comments on commit 25cba33

Please sign in to comment.