Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_page_labels.py: 14%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2Page labels are shown by PDF viewers as "the page number".
4A page has a numeric index, starting at 0. Additionally, the page
5has a label. In the most simple case:
7 label = index + 1
9However, the title page and the table of contents might have Roman numerals as
10page labels. This makes things more complicated.
12Example 1
13---------
15>>> reader.root_object["/PageLabels"]["/Nums"]
16[0, IndirectObject(18, 0, 139929798197504),
17 8, IndirectObject(19, 0, 139929798197504)]
18>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][1])
19{'/S': '/r'}
20>>> reader.get_object(reader.root_object["/PageLabels"]["/Nums"][3])
21{'/S': '/D'}
23Example 2
24---------
25The following is a document with pages labeled
26i, ii, iii, iv, 1, 2, 3, A-8, A-9, ...
281 0 obj
29 << /Type /Catalog
30 /PageLabels << /Nums [
31 0 << /S /r >>
32 4 << /S /D >>
33 7 << /S /D
34 /P ( A- )
35 /St 8
36 >>
37 % A number tree containing
38 % three page label dictionaries
39 ]
40 >>
41 ...
42 >>
43endobj
46§12.4.2 PDF Specification 1.7 and 2.0
47=====================================
49Entries in a page label dictionary
50----------------------------------
51The /S key:
52D Decimal Arabic numerals
53R Uppercase Roman numerals
54r Lowercase Roman numerals
55A Uppercase letters (A to Z for the first 26 pages,
56 AA to ZZ for the next 26, and so on)
57a Lowercase letters (a to z for the first 26 pages,
58 aa to zz for the next 26, and so on)
59"""
60import math
61import string
62from bisect import bisect_left, bisect_right
63from collections.abc import Callable, Iterable
64from typing import Any, NamedTuple, cast
66from ._protocols import PdfCommonDocProtocol
67from ._utils import logger_warning
68from .generic import (
69 ArrayObject,
70 DictionaryObject,
71 NullObject,
72 NumberObject,
73 TextStringObject,
74 is_null_or_none,
75)
77# The largest number one can represent using the usual symbols
78# and subtractive notation without additional conventions.
79# Aligns with https://github.com/AA-Turner/roman-numerals/blob/master/python/roman_numerals/__init__.py
80MAXIMUM_ROMAN_NUMERAL = 3_999
82# Allow values of up to 512 * 26 = 13_312 for the `/A` and `/a`.
83# Please note that this limit is somehow arbitrary and some trade-off
84# between rather restrictive <= 256 output bytes per label and the possibly
85# unrealistic 1000 output bytes per label.
86MAXIMUM_PAGE_LABEL_LENGTH = 512
89def number2decimal_arabic_numeral(number: int) -> str:
90 # A page label is a page *number*, so reject the non-positive values the
91 # other styles already reject. Without this, a malformed /St or a /Nums
92 # range which does not start at the first page gives labels like "0".
93 if number <= 0:
94 raise ValueError("Expecting a positive number.")
95 return str(number)
98def number2uppercase_roman_numeral(num: int) -> str:
99 if num <= 0:
100 raise ValueError("Expecting a positive number.")
101 if num > MAXIMUM_ROMAN_NUMERAL:
102 raise ValueError("Number is out of range.")
103 roman = [
104 (1000, "M"),
105 (900, "CM"),
106 (500, "D"),
107 (400, "CD"),
108 (100, "C"),
109 (90, "XC"),
110 (50, "L"),
111 (40, "XL"),
112 (10, "X"),
113 (9, "IX"),
114 (5, "V"),
115 (4, "IV"),
116 (1, "I"),
117 ]
119 result = []
120 for value, symbol in roman:
121 count, num = divmod(num, value)
122 result.append(symbol * count)
124 return "".join(result)
127def number2lowercase_roman_numeral(number: int) -> str:
128 return number2uppercase_roman_numeral(number).lower()
131def number2uppercase_letter(number: int) -> str:
132 if number <= 0:
133 raise ValueError("Expecting a positive number.")
134 # A to Z, then the same letter repeated: AA to ZZ, AAA to ZZZ, and so on.
135 repetitions, position = divmod(number - 1, 26)
136 length = repetitions + 1
137 if length > MAXIMUM_PAGE_LABEL_LENGTH:
138 raise ValueError("Number is too large.")
139 return string.ascii_uppercase[position] * (repetitions + 1)
142def number2lowercase_letter(number: int) -> str:
143 return number2uppercase_letter(number).lower()
146_NUMBERING_STYLES: dict[str | None, Callable[[int], str]] = {
147 None: lambda _: "",
148 "/D": number2decimal_arabic_numeral,
149 "/R": number2uppercase_roman_numeral,
150 "/r": number2lowercase_roman_numeral,
151 "/A": number2uppercase_letter,
152 "/a": number2lowercase_letter,
153}
156def _get_label(value: Any, start_index: Any, index: int) -> str:
157 # if /Nums array is not following the specification or if /Nums is empty
158 if not isinstance(value, dict):
159 return str(index + 1) # Fallback
160 # Any of these entries may be an indirect reference, which dict.get hands
161 # back as-is rather than resolving the way __getitem__ does. /Limits is
162 # already read that way below. The fallbacks are PdfObjects themselves so
163 # that every value can be resolved the same way.
164 start = value.get("/St", NumberObject(1)).get_object()
165 prefix = cast(str, value.get("/P", TextStringObject("")).get_object())
166 style = value.get("/S", NullObject()).get_object()
167 # A null /S is equivalent to omitting it (ISO 32000-1, 7.3.9).
168 mapping_function = _NUMBERING_STYLES.get(
169 None if isinstance(style, NullObject) else style
170 )
171 if mapping_function is None:
172 # Unknown /S numbering style; fall back to the page position.
173 logger_warning(
174 "Ignoring unknown page label numbering style %(style)r in /Nums.",
175 source=__name__,
176 style=style,
177 )
178 return str(index + 1) # Fallback
180 try:
181 label = prefix + mapping_function(index - start_index + start)
182 if len(label) > MAXIMUM_PAGE_LABEL_LENGTH:
183 raise ValueError("Page label is too long.")
184 except (TypeError, ValueError) as exception:
185 # Malformed /St or /P value or too large value; fall back to the page position.
186 logger_warning(
187 "Ignoring malformed page label entry in /Nums (/St=%(start)r, /P=%(prefix)r): %(exception)s",
188 source=__name__,
189 start=start,
190 prefix=prefix,
191 exception=exception,
192 )
193 else:
194 return label
196 return str(index + 1) # Fallback
199def get_label_from_nums(dictionary_object: DictionaryObject, index: int) -> str:
200 # [Nums] shall be an array of the form
201 # [ key_1 value_1 key_2 value_2 ... key_n value_n ]
202 # where each key_i is an integer and the corresponding
203 # value_i shall be the object associated with that key.
204 # The keys shall be sorted in numerical order,
205 # analogously to the arrangement of keys in a name tree
206 # as described in 7.9.6, "Name Trees."
207 nums = dictionary_object["/Nums"]
208 if not isinstance(nums, ArrayObject):
209 logger_warning(
210 "Page label numbers are not an array: %(nums)s",
211 source=__name__,
212 nums=nums,
213 )
214 return str(index + 1) # Fallback
215 nums_length = len(nums)
216 i = 0
217 value = None
218 start_index = 0
219 while i < nums_length:
220 if i + 1 >= nums_length:
221 logger_warning(
222 "Ignoring last /Nums key without a value.", source=__name__
223 )
224 break
225 start_index = nums[i]
226 value = nums[i + 1].get_object()
227 if i + 2 == nums_length:
228 break
229 next_key = nums[i + 2]
230 if not isinstance(next_key, (int, float)):
231 logger_warning(
232 "Ignoring malformed page label key %(key)r in /Nums.",
233 source=__name__,
234 key=next_key,
235 )
236 return str(index + 1) # Fallback
237 if next_key > index:
238 break
239 i += 2
240 return _get_label(value, start_index, index)
243def index2label(reader: PdfCommonDocProtocol, index: int) -> str:
244 """
245 See 7.9.7 "Number Trees".
247 Args:
248 reader: The PdfReader
249 index: The index of the page
251 Returns:
252 The label of the page, e.g. "iv" or "4".
254 """
255 root = cast(DictionaryObject, reader.root_object)
256 if "/PageLabels" not in root:
257 return str(index + 1) # Fallback
258 number_tree = root["/PageLabels"].get_object()
259 if not isinstance(number_tree, DictionaryObject):
260 logger_warning(
261 "Page labels are not a dictionary: %(number_tree)s",
262 source=__name__,
263 number_tree=number_tree,
264 )
265 return str(index + 1) # Fallback
266 if "/Nums" in number_tree:
267 return get_label_from_nums(number_tree, index)
268 if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject):
269 # number_tree = {'/Kids': [IndirectObject(7333, 0, 140132998195856), ...]}
270 # Limit maximum depth.
271 level = 0
272 while level < 100:
273 kids = number_tree["/Kids"].get_object()
274 if not isinstance(kids, ArrayObject):
275 logger_warning(
276 "Page label kids are not an array: %(kids)s",
277 source=__name__,
278 kids=kids,
279 )
280 break
281 # The keys are page indices where a labelling range starts, so a page
282 # between the /Limits of two kids belongs to the range started by the
283 # largest key before it, the last key of the preceding kid.
284 preceding_kid = None
285 for kid in kids:
286 # kid = {'/Limits': [0, 63], '/Nums': [0, {'/P': 'C1'}, ...]}
287 kid = kid.get_object()
288 if not isinstance(kid, DictionaryObject):
289 logger_warning(
290 "Ignoring kid which is not a dictionary in /PageLabels.",
291 source=__name__,
292 )
293 continue
294 limits = kid.get("/Limits", NullObject()).get_object()
295 if not isinstance(limits, list) or len(limits) < 2:
296 # Skip kids whose /Limits range is missing or malformed.
297 logger_warning(
298 "Ignoring kid with missing or malformed /Limits in /PageLabels.",
299 source=__name__,
300 )
301 continue
302 if limits[0] <= index <= limits[1]:
303 break
304 if limits[0] <= index:
305 preceding_kid = kid
306 else:
307 if preceding_kid is None:
308 # When no kid starts at or before the index, make sure to exit the
309 # `while` loop directly and continue with the fallback.
310 break
311 kid = preceding_kid
312 if not is_null_or_none(kid.get("/Kids", None)):
313 # Recursive definition.
314 level += 1
315 if level == 100: # pragma: no cover
316 raise NotImplementedError("Too deep nesting is not supported.")
317 number_tree = kid
318 # Continue at the next level with the next iteration of the `while` loop.
319 continue
320 return get_label_from_nums(kid, index)
322 logger_warning("Could not reliably determine page label for %(index)d.", source=__name__, index=index)
323 return str(index + 1) # Fallback if neither /Nums nor /Kids is in the number_tree
326def _get_labels_for_page_indexes(nums: ArrayObject, indexes: Iterable[int]) -> list[str]:
327 """
328 Labels for increasing page indexes, as ``get_label_from_nums`` would return them.
330 ``get_label_from_nums`` stops at the first pair whose next key is above the page index.
331 As that pair can only move forward when the page index grows, the array is read once
332 for all pages instead of from the start for every page, and each value is resolved
333 when its pair is first reached.
334 """
335 nums_length = len(nums)
336 labels = []
337 i = 0
338 resolved = -1
339 start_index: Any = 0
340 value: Any = None
341 for index in indexes:
342 is_key_malformed = False
343 while i < nums_length:
344 if i + 1 >= nums_length:
345 logger_warning("Ignoring last /Nums key without a value.", source=__name__)
346 break
347 if resolved != i:
348 start_index = nums[i]
349 value = nums[i + 1].get_object()
350 resolved = i
351 if i + 2 == nums_length:
352 break
353 next_key = nums[i + 2]
354 if not isinstance(next_key, (int, float)):
355 logger_warning(
356 "Ignoring malformed page label key %(key)r in /Nums.",
357 source=__name__,
358 key=next_key,
359 )
360 is_key_malformed = True
361 break
362 if next_key > index:
363 break
364 i += 2
365 labels.append(str(index + 1) if is_key_malformed else _get_label(value, start_index, index))
366 return labels
369def _get_page_range(limits: list[Any], page_count: int) -> tuple[int, int] | None:
370 """Get the first and last page index between the two ``/Limits`` values, if any."""
371 low, high = limits[0], limits[1]
372 if low >= page_count or high < 0:
373 return None
374 last_page = page_count - 1
375 first = 0 if low <= 0 else math.ceil(low)
376 last = last_page if high >= last_page else math.floor(high)
377 return (first, last) if first <= last else None
380class _FirstKidFinder:
381 """
382 Find the kid ``index2label`` picks for a page index: the first kid in order whose
383 ``/Limits`` contain it.
385 Like ``index2label``, kids are read in order and only as far as needed. The pages
386 covered by the kids read so far are kept as sorted ranges, so that each kid is read
387 once instead of once per page. A kid which cannot be read is returned as the
388 exception, which ``index2label`` raises for every page that reaches this kid.
389 """
391 def __init__(self, kids: ArrayObject, page_count: int) -> None:
392 self._kids = kids
393 self._kid_count = len(kids)
394 self._page_count = page_count
395 self._next_kid = 0
396 # Pages covered by any kid read so far, as merged ranges.
397 self._covered_starts: list[int] = []
398 self._covered_ends: list[int] = []
399 # Ranges of pages with the same first kid.
400 self._starts: list[int] = []
401 self._ends: list[int] = []
402 self._first_kids: list[DictionaryObject | Exception] = []
403 # Kids read so far with valid /Limits and their lower limits, in order.
404 self._read_kids: list[DictionaryObject] = []
405 self._read_lows: list[float] = []
407 def find(self, index: int) -> DictionaryObject | Exception | None:
408 while True:
409 position = bisect_right(self._starts, index) - 1
410 if position >= 0 and index <= self._ends[position]:
411 return self._first_kids[position]
412 if self._next_kid >= self._kid_count:
413 return None
414 kid_range = self._read_kid(self._kids[self._next_kid])
415 self._next_kid += 1
416 if kid_range is not None:
417 self._cover(*kid_range)
419 def find_preceding(self, index: int) -> DictionaryObject | None:
420 """
421 Find the kid ``index2label`` picks for a page index no kid contains: the last
422 kid in order whose ``/Limits`` start before it. Only valid once ``find`` has
423 returned ``None`` for the index, which means that all kids have been read.
424 """
425 position = bisect_right(self._read_lows, index) - 1
426 if position < 0:
427 return None
428 return self._read_kids[position]
430 def _read_kid(self, kid: Any) -> tuple[int, int, DictionaryObject | Exception] | None:
431 try:
432 kid = kid.get_object()
433 limits = kid.get("/Limits", NullObject()).get_object() if isinstance(kid, DictionaryObject) else None
434 except MemoryError: # pragma: no cover # TODO: BLE001
435 raise
436 except Exception as exception:
437 return 0, self._page_count - 1, exception
438 if not isinstance(kid, DictionaryObject):
439 logger_warning("Ignoring kid which is not a dictionary in /PageLabels.", source=__name__)
440 return None
441 if (
442 not isinstance(limits, list)
443 or len(limits) < 2
444 or not all(isinstance(limit, (int, float)) for limit in limits[:2])
445 ):
446 logger_warning("Ignoring kid with missing or malformed /Limits in /PageLabels.", source=__name__)
447 return None
448 self._read_kids.append(kid)
449 self._read_lows.append(limits[0])
450 page_range = _get_page_range(limits, self._page_count)
451 return None if page_range is None else (*page_range, kid)
453 def _cover(self, first: int, last: int, kid: DictionaryObject | Exception) -> None:
454 """Make ``kid`` the first kid of the pages from ``first`` to ``last`` which no earlier kid covers."""
455 start = bisect_left(self._covered_ends, first)
456 end = bisect_right(self._covered_starts, last)
457 gaps = []
458 position = first
459 for covered_start, covered_end in zip(self._covered_starts[start:end], self._covered_ends[start:end]):
460 if covered_start > position:
461 gaps.append((position, covered_start - 1))
462 position = max(position, covered_end + 1)
463 if position <= last:
464 gaps.append((position, last))
465 if start < end:
466 first = min(first, self._covered_starts[start])
467 last = max(last, self._covered_ends[end - 1])
468 self._covered_starts[start:end] = [first]
469 self._covered_ends[start:end] = [last]
470 for gap_start, gap_end in gaps:
471 position = bisect_left(self._starts, gap_start)
472 self._starts.insert(position, gap_start)
473 self._ends.insert(position, gap_end)
474 self._first_kids.insert(position, kid)
477class _TreeNode(NamedTuple):
478 """A node of a ``/Kids`` number tree with the page indexes reaching it."""
480 node: DictionaryObject
481 indexes: list[int]
482 level: int
485class _KidPages(NamedTuple):
486 """A kid with the page indexes it is picked for."""
488 kid: DictionaryObject
489 indexes: list[int]
492class _LeafPages(NamedTuple):
493 """A leaf with its ``/Nums`` array, if it is one, and the page indexes it labels."""
495 nums: ArrayObject | None
496 leaf: DictionaryObject
497 indexes: list[int]
500def _get_labels_from_kids(number_tree: DictionaryObject, page_count: int) -> list[str]:
501 """
502 Labels of the first ``page_count`` pages of a ``/Kids`` number tree, as ``index2label`` would return them.
504 Instead of walking the tree from the root for every page, each ``/Kids`` array is
505 indexed once and each ``/Nums`` array is read once for all of its pages. Warnings
506 about malformed kids are logged once per array instead of once per page.
507 """
508 # The finders keep their /Kids arrays, so the ids stay unique.
509 finders: dict[int, _FirstKidFinder] = {}
510 leaves: dict[int, _LeafPages] = {}
511 unmatched: list[int] = []
512 nodes = [_TreeNode(number_tree, list(range(page_count)), 0)]
513 while nodes:
514 node = nodes.pop()
515 kids = node.node["/Kids"].get_object()
516 if not isinstance(kids, ArrayObject):
517 logger_warning("Page label kids are not an array: %(kids)s", source=__name__, kids=kids)
518 unmatched.extend(node.indexes)
519 continue
520 if id(kids) not in finders:
521 finders[id(kids)] = _FirstKidFinder(kids, page_count)
522 finder = finders[id(kids)]
523 kid_pages: dict[int, _KidPages] = {}
524 for index in node.indexes:
525 kid = finder.find(index)
526 if isinstance(kid, Exception):
527 raise kid
528 if kid is None:
529 kid = finder.find_preceding(index)
530 if kid is None:
531 unmatched.append(index)
532 else:
533 kid_pages.setdefault(id(kid), _KidPages(kid, [])).indexes.append(index)
534 for kid, indexes in kid_pages.values():
535 if not is_null_or_none(kid.get("/Kids", None)):
536 # Same nesting limit as in index2label().
537 if node.level + 1 == 100: # pragma: no cover
538 raise NotImplementedError("Too deep nesting is not supported.")
539 nodes.append(_TreeNode(kid, indexes, node.level + 1))
540 continue
541 # Leaves sharing a /Nums array are read together.
542 nums = kid["/Nums"]
543 if isinstance(nums, ArrayObject):
544 leaves.setdefault(id(nums), _LeafPages(nums, kid, [])).indexes.extend(indexes)
545 else:
546 leaves.setdefault(id(kid), _LeafPages(None, kid, [])).indexes.extend(indexes)
548 labels = [""] * page_count
549 for leaf_nums, leaf, leaf_indexes in leaves.values():
550 leaf_indexes.sort()
551 leaf_labels = (
552 _get_labels_for_page_indexes(leaf_nums, leaf_indexes)
553 if leaf_nums is not None
554 else [get_label_from_nums(leaf, index) for index in leaf_indexes]
555 )
556 for index, label in zip(leaf_indexes, leaf_labels):
557 labels[index] = label
558 for index in sorted(unmatched):
559 logger_warning("Could not reliably determine page label for %(index)d.", source=__name__, index=index)
560 labels[index] = str(index + 1)
561 return labels
564def _index2labels_page_by_page(pdf: PdfCommonDocProtocol, page_count: int) -> list[str]:
565 return [index2label(pdf, index) for index in range(page_count)]
568def index2labels(pdf: PdfCommonDocProtocol, page_count: int) -> list[str]:
569 """
570 Labels of the first ``page_count`` pages, as ``index2label`` would return them.
572 Number trees are read once for all pages instead of from the start for every page.
573 """
574 if page_count <= 0:
575 return []
576 root = cast(DictionaryObject, pdf.root_object)
577 if "/PageLabels" not in root:
578 return _index2labels_page_by_page(pdf, page_count)
579 number_tree = root["/PageLabels"].get_object()
580 if not isinstance(number_tree, DictionaryObject):
581 return _index2labels_page_by_page(pdf, page_count)
582 if "/Nums" in number_tree:
583 nums = number_tree["/Nums"]
584 if not isinstance(nums, ArrayObject):
585 return [get_label_from_nums(number_tree, index) for index in range(page_count)]
586 return _get_labels_for_page_indexes(nums, range(page_count))
587 if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject):
588 return _get_labels_from_kids(number_tree, page_count)
589 return _index2labels_page_by_page(pdf, page_count)
592def nums_insert(
593 key: NumberObject,
594 value: DictionaryObject,
595 nums: ArrayObject,
596) -> None:
597 """
598 Insert a key, value pair in a Nums array.
600 See 7.9.7 "Number Trees".
602 Args:
603 key: number key of the entry
604 value: value of the entry
605 nums: Nums array to modify
607 """
608 if len(nums) % 2 != 0:
609 raise ValueError("A nums like array must have an even number of elements")
611 i = len(nums)
612 while i != 0 and key <= nums[i - 2]:
613 i = i - 2
615 if i < len(nums) and key == nums[i]:
616 nums[i + 1] = value
617 else:
618 nums.insert(i, key)
619 nums.insert(i + 1, value)
622def nums_clear_range(
623 key: NumberObject,
624 page_index_to: int,
625 nums: ArrayObject,
626) -> None:
627 """
628 Remove all entries in a number tree in a range after an entry.
630 See 7.9.7 "Number Trees".
632 Args:
633 key: number key of the entry before the range
634 page_index_to: The page index of the upper limit of the range
635 nums: Nums array to modify
637 """
638 if len(nums) % 2 != 0:
639 raise ValueError("A nums like array must have an even number of elements")
640 if page_index_to < key:
641 raise ValueError("page_index_to must be greater or equal than key")
643 i = nums.index(key) + 2
644 while i < len(nums) and nums[i] <= page_index_to:
645 nums.pop(i)
646 nums.pop(i)
649def nums_next(
650 key: NumberObject,
651 nums: ArrayObject,
652) -> tuple[NumberObject | None, DictionaryObject | None]:
653 """
654 Return the (key, value) pair of the entry after the given one.
656 See 7.9.7 "Number Trees".
658 Args:
659 key: number key of the entry
660 nums: Nums array
662 """
663 if len(nums) % 2 != 0:
664 raise ValueError("A nums like array must have an even number of elements")
666 i = nums.index(key) + 2
667 if i < len(nums):
668 return nums[i], nums[i + 1]
669 return None, None