Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_page_labels.py: 12%

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

168 statements  

1""" 

2Page labels are shown by PDF viewers as "the page number". 

3 

4A page has a numeric index, starting at 0. Additionally, the page 

5has a label. In the most simple case: 

6 

7 label = index + 1 

8 

9However, the title page and the table of contents might have Roman numerals as 

10page labels. This makes things more complicated. 

11 

12Example 1 

13--------- 

14 

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'} 

22 

23Example 2 

24--------- 

25The following is a document with pages labeled 

26i, ii, iii, iv, 1, 2, 3, A-8, A-9, ... 

27 

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 

44 

45 

46§12.4.2 PDF Specification 1.7 and 2.0 

47===================================== 

48 

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 string 

61from typing import TYPE_CHECKING, cast 

62 

63from ._protocols import PdfCommonDocProtocol 

64from ._utils import logger_warning 

65from .generic import ( 

66 ArrayObject, 

67 DictionaryObject, 

68 IndirectObject, 

69 NameObject, 

70 NullObject, 

71 NumberObject, 

72 is_null_or_none, 

73) 

74 

75if TYPE_CHECKING: 

76 from collections.abc import Callable 

77 

78# The largest number one can represent using the usual symbols 

79# and subtractive notation without additional conventions. 

80# Aligns with https://github.com/AA-Turner/roman-numerals/blob/master/python/roman_numerals/__init__.py 

81MAXIMUM_ROMAN_NUMERAL = 3_999 

82 

83# Allow values of up to 512 * 26 = 13_312 for the `/A` and `/a`. 

84# Please note that this limit is somehow arbitrary and some trade-off 

85# between rather restrictive <= 256 output bytes per label and the possibly 

86# unrealistic 1000 output bytes per label. 

87MAXIMUM_PAGE_LABEL_LENGTH = 512 

88 

89 

90def number2uppercase_roman_numeral(num: int) -> str: 

91 if num <= 0: 

92 raise ValueError("Expecting a positive number.") 

93 if num > MAXIMUM_ROMAN_NUMERAL: 

94 raise ValueError("Number is out of range.") 

95 roman = [ 

96 (1000, "M"), 

97 (900, "CM"), 

98 (500, "D"), 

99 (400, "CD"), 

100 (100, "C"), 

101 (90, "XC"), 

102 (50, "L"), 

103 (40, "XL"), 

104 (10, "X"), 

105 (9, "IX"), 

106 (5, "V"), 

107 (4, "IV"), 

108 (1, "I"), 

109 ] 

110 

111 result = [] 

112 for value, symbol in roman: 

113 count, num = divmod(num, value) 

114 result.append(symbol * count) 

115 

116 return "".join(result) 

117 

118 

119def number2lowercase_roman_numeral(number: int) -> str: 

120 return number2uppercase_roman_numeral(number).lower() 

121 

122 

123def number2uppercase_letter(number: int) -> str: 

124 if number <= 0: 

125 raise ValueError("Expecting a positive number.") 

126 # A to Z, then the same letter repeated: AA to ZZ, AAA to ZZZ, and so on. 

127 repetitions, position = divmod(number - 1, 26) 

128 length = repetitions + 1 

129 if length > MAXIMUM_PAGE_LABEL_LENGTH: 

130 raise ValueError("Number is too large.") 

131 return string.ascii_uppercase[position] * (repetitions + 1) 

132 

133 

134def number2lowercase_letter(number: int) -> str: 

135 return number2uppercase_letter(number).lower() 

136 

137 

138def get_label_from_nums(dictionary_object: DictionaryObject, index: int) -> str: 

139 # [Nums] shall be an array of the form 

140 # [ key_1 value_1 key_2 value_2 ... key_n value_n ] 

141 # where each key_i is an integer and the corresponding 

142 # value_i shall be the object associated with that key. 

143 # The keys shall be sorted in numerical order, 

144 # analogously to the arrangement of keys in a name tree 

145 # as described in 7.9.6, "Name Trees." 

146 nums = dictionary_object["/Nums"] 

147 if not isinstance(nums, ArrayObject): 

148 logger_warning( 

149 "Page label numbers are not an array: %(nums)s", 

150 source=__name__, 

151 nums=nums, 

152 ) 

153 return str(index + 1) # Fallback 

154 nums_length = len(nums) 

155 i = 0 

156 value = None 

157 start_index = 0 

158 while i < nums_length: 

159 if i + 1 >= nums_length: 

160 logger_warning( 

161 "Ignoring last /Nums key without a value.", source=__name__ 

162 ) 

163 break 

164 start_index = nums[i] 

165 value = nums[i + 1].get_object() 

166 if i + 2 == nums_length: 

167 break 

168 next_key = nums[i + 2] 

169 if not isinstance(next_key, (int, float)): 

170 logger_warning( 

171 "Ignoring malformed page label key %(key)r in /Nums.", 

172 source=__name__, 

173 key=next_key, 

174 ) 

175 return str(index + 1) # Fallback 

176 if next_key > index: 

177 break 

178 i += 2 

179 m: dict[str | None, Callable[[int], str]] = { 

180 None: lambda _: "", 

181 "/D": str, 

182 "/R": number2uppercase_roman_numeral, 

183 "/r": number2lowercase_roman_numeral, 

184 "/A": number2uppercase_letter, 

185 "/a": number2lowercase_letter, 

186 } 

187 # if /Nums array is not following the specification or if /Nums is empty 

188 if not isinstance(value, dict): 

189 return str(index + 1) # Fallback 

190 start = value.get("/St", 1) 

191 prefix = cast(str, value.get("/P", "")) 

192 mapping_function = m.get(value.get("/S")) 

193 if mapping_function is None: 

194 # Unknown /S numbering style; fall back to the page position. 

195 logger_warning( 

196 "Ignoring unknown page label numbering style %(style)r in /Nums.", 

197 source=__name__, 

198 style=value.get("/S"), 

199 ) 

200 return str(index + 1) # Fallback 

201 try: 

202 return prefix + mapping_function(index - start_index + start) 

203 except (TypeError, ValueError) as exception: 

204 # Malformed /St or /P value; fall back to the page position. 

205 logger_warning( 

206 "Ignoring malformed page label entry in /Nums (/St=%(start)r, /P=%(prefix)r): %(exception)s", 

207 source=__name__, 

208 start=start, 

209 prefix=prefix, 

210 exception=exception, 

211 ) 

212 return str(index + 1) # Fallback 

213 

214 

215def index2label(reader: PdfCommonDocProtocol, index: int) -> str: 

216 """ 

217 See 7.9.7 "Number Trees". 

218 

219 Args: 

220 reader: The PdfReader 

221 index: The index of the page 

222 

223 Returns: 

224 The label of the page, e.g. "iv" or "4". 

225 

226 """ 

227 root = cast(DictionaryObject, reader.root_object) 

228 if "/PageLabels" not in root: 

229 return str(index + 1) # Fallback 

230 number_tree = root["/PageLabels"].get_object() 

231 if not isinstance(number_tree, DictionaryObject): 

232 logger_warning( 

233 "Page labels are not a dictionary: %(number_tree)s", 

234 source=__name__, 

235 number_tree=number_tree, 

236 ) 

237 return str(index + 1) # Fallback 

238 if "/Nums" in number_tree: 

239 return get_label_from_nums(number_tree, index) 

240 if "/Kids" in number_tree and not isinstance(number_tree["/Kids"], NullObject): 

241 # number_tree = {'/Kids': [IndirectObject(7333, 0, 140132998195856), ...]} 

242 # Limit maximum depth. 

243 level = 0 

244 while level < 100: 

245 kids = number_tree["/Kids"].get_object() 

246 if not isinstance(kids, ArrayObject): 

247 logger_warning( 

248 "Page label kids are not an array: %(kids)s", 

249 source=__name__, 

250 kids=kids, 

251 ) 

252 break 

253 for kid in kids: 

254 # kid = {'/Limits': [0, 63], '/Nums': [0, {'/P': 'C1'}, ...]} 

255 kid = kid.get_object() 

256 if not isinstance(kid, DictionaryObject): 

257 logger_warning( 

258 "Ignoring kid which is not a dictionary in /PageLabels.", 

259 source=__name__, 

260 ) 

261 continue 

262 limits = kid.get("/Limits", NullObject()).get_object() 

263 if not isinstance(limits, list) or len(limits) < 2: 

264 # Skip kids whose /Limits range is missing or malformed. 

265 logger_warning( 

266 "Ignoring kid with missing or malformed /Limits in /PageLabels.", 

267 source=__name__, 

268 ) 

269 continue 

270 if limits[0] <= index <= limits[1]: 

271 if not is_null_or_none(kid.get("/Kids", None)): 

272 # Recursive definition. 

273 level += 1 

274 if level == 100: # pragma: no cover 

275 raise NotImplementedError( 

276 "Too deep nesting is not supported." 

277 ) 

278 number_tree = kid 

279 # Exit the inner `for` loop and continue at the next level with the 

280 # next iteration of the `while` loop. 

281 break 

282 return get_label_from_nums(kid, index) 

283 else: 

284 # When there are no kids, make sure to exit the `while` loop directly 

285 # and continue with the fallback. 

286 break 

287 

288 logger_warning("Could not reliably determine page label for %(index)d.", source=__name__, index=index) 

289 return str(index + 1) # Fallback if neither /Nums nor /Kids is in the number_tree 

290 

291 

292def _get_single_pass_nums_length(nums: ArrayObject, page_count: int) -> int | None: 

293 """ 

294 Get how much of a flat ``/Nums`` array labels the first ``page_count`` pages. 

295 

296 ``get_label_from_nums`` always reads the first pair, then stops at the first 

297 key above the page index, so only the array up to the first key at or above 

298 ``page_count`` after the first pair matters. Returns ``None`` unless that 

299 part consists of pairs of increasing integer keys and direct values, which 

300 is what lets ``index2labels`` read it once for all pages. 

301 """ 

302 nums_length = len(nums) 

303 previous = None 

304 for i in range(0, nums_length, 2): 

305 key = nums[i] 

306 if ( 

307 i + 1 >= nums_length 

308 or not isinstance(key, NumberObject) 

309 or isinstance(nums[i + 1], IndirectObject) 

310 or (previous is not None and key <= previous) 

311 ): 

312 return None 

313 if key >= page_count and i > 0: 

314 return i + 2 

315 previous = key 

316 return nums_length or None 

317 

318 

319def _index2labels_page_by_page(pdf: PdfCommonDocProtocol, page_count: int) -> list[str]: 

320 return [index2label(pdf, index) for index in range(page_count)] 

321 

322 

323def index2labels(pdf: PdfCommonDocProtocol, page_count: int) -> list[str]: 

324 """ 

325 Labels of the first ``page_count`` pages, as ``index2label`` would return them. 

326 

327 A flat ``/Nums`` array with integer keys in increasing order and direct 

328 values is walked once for all pages instead of from the start for every 

329 page. Any other number tree is resolved page by page. 

330 """ 

331 if page_count <= 0: 

332 return [] 

333 root = cast(DictionaryObject, pdf.root_object) 

334 if "/PageLabels" not in root: 

335 return _index2labels_page_by_page(pdf, page_count) 

336 number_tree = root["/PageLabels"].get_object() 

337 if not isinstance(number_tree, DictionaryObject) or "/Nums" not in number_tree: 

338 return _index2labels_page_by_page(pdf, page_count) 

339 nums = number_tree["/Nums"] 

340 if not isinstance(nums, ArrayObject): 

341 return _index2labels_page_by_page(pdf, page_count) 

342 nums_length = _get_single_pass_nums_length(nums, page_count) 

343 if nums_length is None: 

344 return _index2labels_page_by_page(pdf, page_count) 

345 

346 labels = [] 

347 position = 0 

348 for index in range(page_count): 

349 while position + 2 < nums_length and nums[position + 2] <= index: 

350 position += 2 

351 entry = DictionaryObject({NameObject("/Nums"): ArrayObject(nums[position : position + 2])}) 

352 labels.append(get_label_from_nums(entry, index)) 

353 return labels 

354 

355 

356def nums_insert( 

357 key: NumberObject, 

358 value: DictionaryObject, 

359 nums: ArrayObject, 

360) -> None: 

361 """ 

362 Insert a key, value pair in a Nums array. 

363 

364 See 7.9.7 "Number Trees". 

365 

366 Args: 

367 key: number key of the entry 

368 value: value of the entry 

369 nums: Nums array to modify 

370 

371 """ 

372 if len(nums) % 2 != 0: 

373 raise ValueError("A nums like array must have an even number of elements") 

374 

375 i = len(nums) 

376 while i != 0 and key <= nums[i - 2]: 

377 i = i - 2 

378 

379 if i < len(nums) and key == nums[i]: 

380 nums[i + 1] = value 

381 else: 

382 nums.insert(i, key) 

383 nums.insert(i + 1, value) 

384 

385 

386def nums_clear_range( 

387 key: NumberObject, 

388 page_index_to: int, 

389 nums: ArrayObject, 

390) -> None: 

391 """ 

392 Remove all entries in a number tree in a range after an entry. 

393 

394 See 7.9.7 "Number Trees". 

395 

396 Args: 

397 key: number key of the entry before the range 

398 page_index_to: The page index of the upper limit of the range 

399 nums: Nums array to modify 

400 

401 """ 

402 if len(nums) % 2 != 0: 

403 raise ValueError("A nums like array must have an even number of elements") 

404 if page_index_to < key: 

405 raise ValueError("page_index_to must be greater or equal than key") 

406 

407 i = nums.index(key) + 2 

408 while i < len(nums) and nums[i] <= page_index_to: 

409 nums.pop(i) 

410 nums.pop(i) 

411 

412 

413def nums_next( 

414 key: NumberObject, 

415 nums: ArrayObject, 

416) -> tuple[NumberObject | None, DictionaryObject | None]: 

417 """ 

418 Return the (key, value) pair of the entry after the given one. 

419 

420 See 7.9.7 "Number Trees". 

421 

422 Args: 

423 key: number key of the entry 

424 nums: Nums array 

425 

426 """ 

427 if len(nums) % 2 != 0: 

428 raise ValueError("A nums like array must have an even number of elements") 

429 

430 i = nums.index(key) + 2 

431 if i < len(nums): 

432 return nums[i], nums[i + 1] 

433 return None, None