modm_data.pdf2html.page
1# Copyright 2022, Niklas Hauser 2# SPDX-License-Identifier: MPL-2.0 3 4import logging 5import math 6import statistics 7from typing import Callable 8from functools import cached_property 9from collections import defaultdict 10from .table import Table 11from .figure import Figure 12from .line import CharLine 13from ..utils import Rectangle, Region, list_strip 14from ..pdf import Page as PdfPage, Character 15from anytree import Node 16 17 18_LOGGER = logging.getLogger(__name__) 19 20 21class Page(PdfPage): 22 def __init__(self, document, index: int): 23 super().__init__(document, index) 24 self._template = "default" 25 self.is_relevant: bool = True 26 """Is this page relevant for the conversion?""" 27 28 def _unicode_filter(self, code: int) -> int: 29 return code 30 31 def _link_target(self, char) -> str | None: 32 """The URL of the link of the character.""" 33 if char.objlink is not None: 34 if char.objlink.page_index >= 0: 35 return f"#page{char.objlink.page_index + 1}" 36 if char.objlink.url: 37 return char.objlink.url 38 return None if char.weblink is None else char.weblink.url 39 40 @cached_property 41 def _spacing(self) -> dict[str, float]: 42 content = 0.1 43 return { 44 # Horizontal spacing: left->right 45 "x_em": 0.01 * self.width, 46 "x_left": content * self.width, 47 "x_right": (1 - content) * self.width, 48 "x_content": 0.2 * self.width, 49 # Vertical spacing: bottom->top 50 "y_em": 0.01 * self.height, 51 # Max table line thickness 52 "y_tline": 0.005 * self.height, 53 # Max line height distance to detect paragraphs 54 "lh": 0.9, 55 # Max line height distance to detect super-/subscript 56 "sc": 0.3, 57 # Table header cell bold text threshold 58 "th": 0.3, 59 } 60 61 def _line_size(self, line: CharLine) -> str: 62 rsize = line.height 63 if rsize >= 17.5: 64 return "h1" 65 elif rsize >= 15.5: 66 return "h2" 67 elif rsize >= 13.5: 68 return "h3" 69 elif rsize >= 11.4: 70 return "h4" 71 elif rsize >= 8.5: 72 return "n" 73 else: 74 return "fn" 75 76 def _colors(self, color: int) -> str: 77 if 0xFF <= color <= 0xFF: 78 return "black" 79 if 0xFFFFFFFF <= color <= 0xFFFFFFFF: 80 return "white" 81 return "unknown" 82 83 @cached_property 84 def _areas(self) -> dict[str, list[Rectangle] | Rectangle]: 85 content = Rectangle(0.1, 0.1, 0.9, 0.9) 86 areas = {"content": [content]} 87 scaled_areas = {} 88 89 def _s(r): 90 return Rectangle(r.left * self.width, r.bottom * self.height, r.right * self.width, r.top * self.height) 91 92 for name, area in areas.items(): 93 scaled_areas[name] = [_s(r) for r in area] if isinstance(area, list) else _s(area) 94 return scaled_areas 95 96 @cached_property 97 def _overlines(self) -> list[Rectangle]: 98 """Thin horizontal paths that start and end on the glyphs directly below them, like negated signal names.""" 99 overlines = [] 100 boxes = [p.bbox for p in self.paths] 101 verticals = [b for b in boxes if b.height > b.width] 102 103 def _touches_vertical(x, y): 104 # Table borders and other rules end at a vertical line, overlines end at nothing 105 return any(v.left - 1 < x < v.right + 1 and v.bottom - 1 < y < v.top + 1 for v in verticals) 106 107 def _aligned(bbox, chars): 108 # The line starts and ends on glyph edges, it may end on a trailing space 109 return any(abs(c.bbox.left - bbox.left) < 1 for c in chars) and any( 110 abs(c.bbox.right - bbox.right) < 1 for c in chars 111 ) 112 113 # Underlines are often drawn in pieces per word and space, join pieces that touch end to end 114 lines = [] 115 for b in sorted((b for b in boxes if 0 < b.height < 1.5 and b.width > 1), key=lambda b: (round(b.y), b.left)): 116 if lines and abs(lines[-1].y - b.y) < 0.3 and b.left - lines[-1].right < 1: 117 last = lines[-1] 118 b = Rectangle(last.left, min(last.bottom, b.bottom), max(last.right, b.right), max(last.top, b.top)) 119 lines[-1] = b 120 else: 121 lines.append(b) 122 123 y_em = self._spacing["y_em"] 124 for bbox in lines: 125 if _touches_vertical(bbox.left, bbox.y) or _touches_vertical(bbox.right, bbox.y): 126 continue 127 below = Rectangle(bbox.left - 1, bbox.bottom - y_em, bbox.right + 1, bbox.bottom) 128 chars = [c for c in self.chars_in_area(below) if c.unicode not in {0xA, 0xD}] 129 glyphs = [c for c in chars if c.unicode != 0x20] 130 if not glyphs: 131 continue 132 # The overline sits right above the glyphs, a rule above text has a larger gap 133 if bbox.bottom - max(c.bbox.top for c in glyphs) > 0.25 * max(c.bbox.height for c in glyphs): 134 continue 135 if not _aligned(bbox, chars): 136 continue 137 # An underline of the text line above can sit just as close to the next line, but it lies inside the 138 # character boxes above, which reach down to the descent of the font 139 above = Rectangle(bbox.left - 1, bbox.top, bbox.right + 1, bbox.top + y_em) 140 uchars = [c for c in self.chars_in_area(above) if c.unicode not in {0xA, 0xD}] 141 if _aligned(bbox, uchars) and min(c.bbox.bottom for c in uchars) < bbox.top: 142 continue 143 overlines.append(bbox) 144 return overlines 145 146 def _is_overlined(self, char) -> bool: 147 mx = char.bbox.midpoint.x 148 return any( 149 o.left < mx < o.right and 0 <= o.bottom - char.bbox.top < self._spacing["y_em"] / 2 for o in self._overlines 150 ) 151 152 def _char_properties(self, line, char): 153 cp = { 154 "superscript": False, 155 "subscript": False, 156 "bold": any(frag in char.font for frag in {"Bold"}), 157 "italic": any(frag in char.font for frag in {"Italic", "Oblique"}), 158 # Code is set in a monospaced font like Courier, the text never is. Not by the fixed pitch flag of the 159 # font, which some PDFs also set for Arial, Times New Roman and symbol fonts 160 "code": any(frag in char.font.lower() for frag in ("courier", "mono", "consol")), 161 "link": self._link_target(char), 162 "overline": self._is_overlined(char), 163 "size": round(line.height), 164 "relsize": self._line_size(line), 165 "char": chr(char.unicode), 166 } 167 # Sub- and superscript use a smaller font, characters of the full size 168 # with a shifted baseline are labels next to multi-line text instead 169 if char.height >= 0.95 * line.height: 170 pass 171 elif line.rotation: 172 if char.origin.x < (line.origin - 0.25 * line.height): 173 cp["superscript"] = True 174 elif char.origin.x > (line.origin + 0.15 * line.height): 175 cp["subscript"] = True 176 elif char.origin.y > (line.origin + 0.25 * line.height): 177 cp["superscript"] = True 178 elif char.origin.y < (line.origin - 0.15 * line.height): 179 cp["subscript"] = True 180 return cp 181 182 def text_in_named_area(self, name: str, check_length: bool = True) -> str | None: 183 """ 184 Find all text in the named area. 185 186 :param name: the name of the area(s) to query. 187 :param check_length: assert that the text has a length. 188 :return: the concatenated text of the named area(s) or `None` if area not found. 189 """ 190 if name not in self._areas: 191 return None 192 text = "" 193 areas = self._areas[name] 194 if not isinstance(areas, list): 195 areas = [areas] 196 for area in areas: 197 text += self.text_in_area(area) 198 if check_length: 199 assert text 200 return text 201 202 def charlines_in_area( 203 self, area: Rectangle, predicate: Callable[[Character], bool] = None, rtol: float = None 204 ) -> list[CharLine]: 205 """ 206 Coalesce the characters in the area and predicate into lines. 207 208 1. Every character in the area is filtered by the `predicate`. 209 2. Character orientation is split into horizontal (left->right) and 210 vertical (bottom->top) character lines sorted by x or y position. 211 Lines containing only whitespace are discarded. 212 3. Overlapping character lines are merged into sub- and superscript 213 using `rtol * max(current_line.height, next_line.height)` as the 214 tolerance for checking if the lines overlap. 215 4. The characters in the merged lines are re-sorted by origin. 216 217 :param area: Area to search for characters. 218 :param predicate: Function to discard characters in the area or include all by default. 219 :param rtol: Relative tolerance to separate lines vertically or use `sc` spacing by default. 220 :return: A list of character lines sorted by x or y position. 221 """ 222 if rtol is None: 223 rtol = self._spacing["sc"] 224 # The lines keep the characters, which must know their links by then 225 self._link_characters() 226 # Split all chars into lines based on rounded origin 227 origin_lines_y = defaultdict(list) 228 origin_lines_x = defaultdict(list) 229 for char in self.chars_in_area(area): 230 # Ignore all characters we don't want 231 if predicate is not None and not predicate(char): 232 continue 233 # A watermark like "Obsolete Product(s)" is faint text written diagonally across the page 234 if 1 < char.rotation % 90 < 89: 235 rgb = [(char.fill >> shift) & 0xFF for shift in (24, 16, 8)] 236 if (char.fill & 0xFF) < 0x80 or min(rgb) > 0xC0: 237 continue 238 cunicode = self._unicode_filter(char.unicode) 239 if cunicode is None: 240 continue 241 char.unicode = cunicode 242 if char.unicode < 32 and char.unicode not in {0xA}: 243 continue 244 # Ignore characters without width that are not spaces 245 if not char.width and char.unicode not in {0xA, 0xD, 0x20}: 246 _LOGGER.error(f"Unknown char width for {char}: {char.bbox}") 247 # Split up the chars depending on the orientation 248 if 45 < char.rotation <= 135 or 225 < char.rotation <= 315: 249 origin_lines_x[round(char.origin.x, 1)].append(char) 250 elif char.rotation <= 45 or 135 < char.rotation <= 225 or 315 < char.rotation: 251 origin_lines_y[round(char.origin.y, 1)].append(char) 252 else: 253 _LOGGER.error("Unknown char rotation:", char, char.rotation) 254 255 # Convert characters into lines 256 bbox_lines_y = [] 257 for chars in origin_lines_y.values(): 258 # Remove lines with whitespace only 259 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 260 continue 261 origin = statistics.fmean(c.origin.y for c in chars) 262 line = CharLine( 263 self, 264 chars, 265 min(c.bbox.bottom for c in chars), 266 origin, 267 max(c.bbox.top for c in chars), 268 max(c.height for c in chars), 269 sort_origin=self.height - origin, 270 ) 271 bbox_lines_y.append(line) 272 # print(line, line.top, line.origin, line.bottom, line.height) 273 bbox_lines = sorted(bbox_lines_y, key=lambda line: line._sort_origin) 274 275 bbox_lines_x = [] 276 for chars in origin_lines_x.values(): 277 # Remove lines with whitespace only 278 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 279 continue 280 line = CharLine( 281 self, 282 chars, 283 min(c.bbox.left for c in chars), 284 statistics.fmean(c.origin.x for c in chars), 285 max(c.bbox.right for c in chars), 286 max(c.width for c in chars), 287 270 if sum(c.rotation for c in chars) <= 135 * len(chars) else 90, 288 ) 289 bbox_lines_x.append(line) 290 bbox_lines += sorted(bbox_lines_x, key=lambda line: line._sort_origin) 291 292 if not bbox_lines: 293 return [] 294 295 def _stacked(line0, line1) -> bool: 296 # Characters of the same font size, that overlap along the line by 297 # more than half their width, are printed on top of each other. 298 horizontal = not line0.rotation 299 300 def _spans(line): 301 chars = (c for c in line.chars if c.unicode not in {0x20, 0xA, 0xD}) 302 chars = (c for c in chars if math.isclose(c.height, line.height, rel_tol=0.01)) 303 return [(c.bbox.left, c.bbox.right) if horizontal else (c.bbox.bottom, c.bbox.top) for c in chars] 304 305 spans1 = _spans(line1) 306 for start0, stop0 in _spans(line0): 307 for start1, stop1 in spans1: 308 overlap = min(stop0, stop1) - max(start0, start1) 309 if overlap > 0.5 * min(stop0 - start0, stop1 - start1): 310 return True 311 return False 312 313 def _label(line0, line1) -> bool: 314 # A label of the same font size left of a multi-line text is 315 # vertically centered on the lines, so its baseline is shifted by 316 # more than a continuation of the line would be. 317 if line0.rotation or line1.rotation: 318 return False 319 offset = abs(line0._sort_origin - line1._sort_origin) 320 return offset > rtol * line0.height and ( 321 line0.bbox.right < line1.bbox.left or line1.bbox.right < line0.bbox.left 322 ) 323 324 # Merge lines that have overlapping bbox_lines 325 merged_lines = [] 326 current_line = bbox_lines[0] 327 for next_line in bbox_lines[1:]: 328 height = max(current_line.height, next_line.height) 329 same_height = math.isclose(current_line.height, next_line.height, rel_tol=0.01) 330 # Calculate overlap via normalize origin (increasing with line index) 331 if ( 332 # Horizontal and vertical lines have different sort origins 333 bool(current_line.rotation) == bool(next_line.rotation) 334 and (current_line._sort_origin + rtol * height) > (next_line._sort_origin - rtol * height) 335 # Lines of the same font size printed on top of each other are 336 # separate lines, like the numerator and denominator of a formula 337 and not (same_height and _stacked(current_line, next_line)) 338 and not (same_height and _label(current_line, next_line)) 339 ): 340 # The next line overlaps this one, we merge the shorter line 341 # (typically super- and subscript) into the taller line. Lines 342 # of the same font size continue each other with a slightly 343 # shifted baseline, so we merge them into the longer line. 344 if same_height: 345 use_current = len(current_line.chars) >= len(next_line.chars) 346 else: 347 use_current = current_line.height > next_line.height 348 line = current_line if use_current else next_line 349 current_line = CharLine( 350 self, 351 current_line.chars + next_line.chars, 352 line.bottom, 353 line.origin, 354 line.top, 355 height, 356 line.rotation, 357 sort_origin=line._sort_origin, 358 ) 359 else: 360 # The next line does not overlap the current line 361 merged_lines.append(current_line) 362 current_line = next_line 363 # append last line 364 merged_lines.append(current_line) 365 366 # Prepend labels to the first line of their multi-line text 367 labeled_lines = [] 368 for line in merged_lines: 369 prev = labeled_lines[-1] if labeled_lines else None 370 if ( 371 prev is not None 372 and not line.rotation 373 and math.isclose(prev.height, line.height, rel_tol=0.01) 374 and 0 < line._sort_origin - prev._sort_origin < line.height 375 and line.bbox.right < prev.bbox.left 376 ): 377 # Keep the spaces between the words of the label, but not around it 378 label = sorted((c for c in line.chars if c.unicode not in {0xA, 0xD}), key=lambda c: c.origin.x) 379 label = list_strip(label, lambda c: c.unicode == 0x20) 380 chars = label + [label[-1].generated_space()] + prev.chars 381 labeled_lines[-1] = CharLine( 382 self, chars, prev.bottom, prev.origin, prev.top, prev.height, sort_origin=prev._sort_origin 383 ) 384 else: 385 labeled_lines.append(line) 386 merged_lines = labeled_lines 387 388 # Sort all lines horizontally based on character origin 389 sorted_lines = [] 390 for line in merged_lines: 391 if line.rotation == 90: 392 393 def sort_key(char): 394 if char.unicode in {0xA, 0xD}: 395 return char.tbbox.midpoint.y - 1e9 396 return char.tbbox.midpoint.y 397 elif line.rotation == 270: 398 399 def sort_key(char): 400 if char.unicode in {0xA, 0xD}: 401 return -char.tbbox.midpoint.y + 1e9 402 return -char.tbbox.midpoint.y 403 else: 404 405 def sort_key(char): 406 if char.unicode in {0xA, 0xD}: 407 return char.origin.x + 1e9 408 return char.origin.x 409 410 chars = sorted(line.chars, key=sort_key) 411 if not line.rotation: 412 chars = self._chars_with_bullet_space(chars) 413 chars = self._chars_with_gap_spaces(chars, line.rotation) 414 sorted_lines.append( 415 CharLine( 416 self, 417 chars, 418 line.bottom, 419 line.origin, 420 line.top, 421 line.height, 422 line.rotation, 423 area.left, 424 sort_origin=line._sort_origin, 425 ) 426 ) 427 428 return sorted_lines 429 430 @staticmethod 431 def _chars_with_gap_spaces(chars: list, rotation: int) -> list: 432 # pdfium generates no spaces at the word gaps of fonts without a space 433 # glyph, so we insert them at gaps wider than the typical gap between 434 # the letters of a run of the same font, which may be letter-spaced. 435 def _span(char): 436 if not rotation: 437 return char.bbox.left, char.bbox.right 438 if rotation == 90: 439 return char.bbox.bottom, char.bbox.top 440 return -char.bbox.top, -char.bbox.bottom 441 442 runs, last, key = [], None, None 443 for index, char in enumerate(chars): 444 if char.unicode in {0x20, 0xA, 0xD}: 445 continue 446 start, stop = _span(char) 447 size = round(char.height, 1) 448 # Lines may interleave the characters of several baselines 449 baseline = round(char.origin.x if rotation else char.origin.y, 1) 450 if key != (char.font, size, baseline) or start - last > 0.5 * size: 451 runs.append((char, [])) 452 else: 453 runs[-1][1].append((start - last, index)) 454 key, last = (char.font, size, baseline), stop 455 456 spaces = [] 457 for first, gaps in runs: 458 if not gaps or first.has_space_glyph: 459 continue 460 size = first.height 461 letter_gap = statistics.median(g for g, _ in gaps) 462 spaces += [i for g, i in gaps if g > letter_gap + 0.15 * size and chars[i - 1].unicode != 0x20] 463 for index in sorted(spaces, reverse=True): 464 chars = chars[:index] + [chars[index].generated_space()] + chars[index:] 465 return chars 466 467 @staticmethod 468 def _chars_with_bullet_space(chars: list) -> list: 469 # Newer pdfium does not generate a space for every visual gap anymore, 470 # but the list detection relies on the one between bullet and text. 471 for ii, (bullet, char) in enumerate(zip(chars, chars[1:]), 1): 472 if bullet.unicode == 0x20: 473 continue 474 if ( 475 bullet.char in {"•", "–"} 476 and char.unicode not in {0x20, 0xA, 0xD} 477 and char.origin.x - bullet.bbox.right >= 0.25 * bullet.height 478 ): 479 return chars[:ii] + [char.generated_space()] + chars[ii:] 480 break 481 return chars 482 483 def graphic_bboxes_in_area( 484 self, area: Rectangle, with_graphics: bool = True 485 ) -> list[tuple[Rectangle, Table | Figure | None]]: 486 """ 487 Coalesce the graphics in the area into full width bounding boxes. 488 489 1. Group vertically overlapping graphics. 490 2. Widen the overlapped graphics bounding boxes to the edges of the area. 491 492 :param area: area to search for content. 493 :param with_graphics: search for graphics in the area. 494 :return: list of tuples (bounding box, graphic objects or `None`). 495 """ 496 if with_graphics: 497 graphics = self.graphics_in_area(area) 498 regions = [] 499 # Check if graphics bounding boxes overlap vertically and group them 500 for graphic in sorted(graphics, key=lambda g: (-g.bbox.top, g.bbox.x)): 501 gbbox = graphic.bbox.joined(graphic.cbbox) if graphic.cbbox else graphic.bbox 502 for reg in regions: 503 if reg.overlaps(gbbox.bottom, gbbox.top): 504 # They overlap, so merge them 505 reg.v0 = min(reg.v0, gbbox.bottom) 506 reg.v1 = max(reg.v1, gbbox.top) 507 reg.objs.append(graphic) 508 break 509 else: 510 regions.append(Region(gbbox.bottom, gbbox.top, graphic)) 511 512 # print(regions) 513 # Coalesce all overlapped graphics objects into full width areas 514 areas = [] 515 ypos = area.top 516 for reg in regions: 517 if ypos - reg.v1 > self._spacing["y_em"]: 518 areas.append((Rectangle(area.left, reg.v1, area.right, ypos), None)) 519 for obj in reg.objs: 520 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 521 areas.append((oarea, obj)) 522 ypos = reg.v0 523 areas.append((Rectangle(area.left, area.bottom, area.right, ypos), None)) 524 else: 525 areas = [(area, None)] 526 return areas 527 528 def objects_in_area(self, area: Rectangle, with_graphics: bool = True) -> list[CharLine | Table | Figure]: 529 """ 530 Find all content objects in this area. 531 532 :param area: area to search for content. 533 :param with_graphics: search for graphics in the area. 534 :return: list of content objects sorted top to bottom. 535 """ 536 areas = self.graphic_bboxes_in_area(area, with_graphics) 537 objects = [] 538 for narea, obj in areas: 539 if obj is None: 540 objects += self.charlines_in_area(narea) 541 else: 542 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 543 544 def predicate(c): 545 return not obj.bbox.contains(c.origin) 546 547 lines = self.charlines_in_area(oarea, predicate) 548 # print(obj, oarea, lines, [line.content for line in lines]) 549 objects += list(sorted(lines + [obj], key=lambda o: (-o.bbox.y, o.bbox.x))) 550 return objects 551 552 def graphics_in_area(self, area: Rectangle) -> list[Table | Figure]: 553 """ 554 Find all tables and figures in this area. 555 556 :param area: area to search for graphics. 557 :return: list of tables and figures. 558 """ 559 return [] 560 561 def ast_in_area(self, area: Rectangle, with_graphics: bool = True) -> Node: 562 """ 563 Convert the area content into an abstract syntax tree. 564 565 :param area: area to search for content. 566 :param with_graphics: including graphics in the area. 567 :return: An abstract syntax tree including the content formatting. 568 """ 569 return Node("area", obj=area, xpos=int(area.left), page=self) 570 571 @property 572 def content_ast(self) -> list[Node]: 573 """The abstract syntax trees in the content area.""" 574 ast = [] 575 with_graphics = True 576 for area in self._areas["content"]: 577 ast.append(self.ast_in_area(area, with_graphics=with_graphics)) 578 # Add a page node to the first leaf to keep track of where a page starts 579 first_leaf = next((n for n in iter(ast[0].descendants) if n.is_leaf), ast[0]) 580 Node("page", parent=first_leaf, xpos=first_leaf.xpos, number=self.number) 581 return ast 582 583 @property 584 def content_objects(self) -> list[CharLine | Table | Figure]: 585 """All objects in the content areas.""" 586 objs = [] 587 for area in self._areas["content"]: 588 objs.extend(self.objects_in_area(area)) 589 return objs 590 591 @property 592 def content_graphics(self) -> list[Table | Figure]: 593 """All graphics in the content areas.""" 594 objs = [] 595 for area in self._areas["content"]: 596 objs.extend(self.graphics_in_area(area)) 597 return objs 598 599 @property 600 def content_lines(self) -> list[CharLine]: 601 """All lines in the content areas.""" 602 objs = [] 603 for area in self._areas["content"]: 604 objs.extend(self.charlines_in_area(area)) 605 return objs 606 607 @property 608 def content_tables(self) -> list[Table]: 609 """All tables in the content areas.""" 610 return [o for o in self.content_graphics if isinstance(o, Table)] 611 612 @property 613 def content_figures(self) -> list[Figure]: 614 """All figures in the content areas.""" 615 return [o for o in self.content_graphics if isinstance(o, Figure)] 616 617 def __repr__(self) -> str: 618 return f"Page({self.number})"
22class Page(PdfPage): 23 def __init__(self, document, index: int): 24 super().__init__(document, index) 25 self._template = "default" 26 self.is_relevant: bool = True 27 """Is this page relevant for the conversion?""" 28 29 def _unicode_filter(self, code: int) -> int: 30 return code 31 32 def _link_target(self, char) -> str | None: 33 """The URL of the link of the character.""" 34 if char.objlink is not None: 35 if char.objlink.page_index >= 0: 36 return f"#page{char.objlink.page_index + 1}" 37 if char.objlink.url: 38 return char.objlink.url 39 return None if char.weblink is None else char.weblink.url 40 41 @cached_property 42 def _spacing(self) -> dict[str, float]: 43 content = 0.1 44 return { 45 # Horizontal spacing: left->right 46 "x_em": 0.01 * self.width, 47 "x_left": content * self.width, 48 "x_right": (1 - content) * self.width, 49 "x_content": 0.2 * self.width, 50 # Vertical spacing: bottom->top 51 "y_em": 0.01 * self.height, 52 # Max table line thickness 53 "y_tline": 0.005 * self.height, 54 # Max line height distance to detect paragraphs 55 "lh": 0.9, 56 # Max line height distance to detect super-/subscript 57 "sc": 0.3, 58 # Table header cell bold text threshold 59 "th": 0.3, 60 } 61 62 def _line_size(self, line: CharLine) -> str: 63 rsize = line.height 64 if rsize >= 17.5: 65 return "h1" 66 elif rsize >= 15.5: 67 return "h2" 68 elif rsize >= 13.5: 69 return "h3" 70 elif rsize >= 11.4: 71 return "h4" 72 elif rsize >= 8.5: 73 return "n" 74 else: 75 return "fn" 76 77 def _colors(self, color: int) -> str: 78 if 0xFF <= color <= 0xFF: 79 return "black" 80 if 0xFFFFFFFF <= color <= 0xFFFFFFFF: 81 return "white" 82 return "unknown" 83 84 @cached_property 85 def _areas(self) -> dict[str, list[Rectangle] | Rectangle]: 86 content = Rectangle(0.1, 0.1, 0.9, 0.9) 87 areas = {"content": [content]} 88 scaled_areas = {} 89 90 def _s(r): 91 return Rectangle(r.left * self.width, r.bottom * self.height, r.right * self.width, r.top * self.height) 92 93 for name, area in areas.items(): 94 scaled_areas[name] = [_s(r) for r in area] if isinstance(area, list) else _s(area) 95 return scaled_areas 96 97 @cached_property 98 def _overlines(self) -> list[Rectangle]: 99 """Thin horizontal paths that start and end on the glyphs directly below them, like negated signal names.""" 100 overlines = [] 101 boxes = [p.bbox for p in self.paths] 102 verticals = [b for b in boxes if b.height > b.width] 103 104 def _touches_vertical(x, y): 105 # Table borders and other rules end at a vertical line, overlines end at nothing 106 return any(v.left - 1 < x < v.right + 1 and v.bottom - 1 < y < v.top + 1 for v in verticals) 107 108 def _aligned(bbox, chars): 109 # The line starts and ends on glyph edges, it may end on a trailing space 110 return any(abs(c.bbox.left - bbox.left) < 1 for c in chars) and any( 111 abs(c.bbox.right - bbox.right) < 1 for c in chars 112 ) 113 114 # Underlines are often drawn in pieces per word and space, join pieces that touch end to end 115 lines = [] 116 for b in sorted((b for b in boxes if 0 < b.height < 1.5 and b.width > 1), key=lambda b: (round(b.y), b.left)): 117 if lines and abs(lines[-1].y - b.y) < 0.3 and b.left - lines[-1].right < 1: 118 last = lines[-1] 119 b = Rectangle(last.left, min(last.bottom, b.bottom), max(last.right, b.right), max(last.top, b.top)) 120 lines[-1] = b 121 else: 122 lines.append(b) 123 124 y_em = self._spacing["y_em"] 125 for bbox in lines: 126 if _touches_vertical(bbox.left, bbox.y) or _touches_vertical(bbox.right, bbox.y): 127 continue 128 below = Rectangle(bbox.left - 1, bbox.bottom - y_em, bbox.right + 1, bbox.bottom) 129 chars = [c for c in self.chars_in_area(below) if c.unicode not in {0xA, 0xD}] 130 glyphs = [c for c in chars if c.unicode != 0x20] 131 if not glyphs: 132 continue 133 # The overline sits right above the glyphs, a rule above text has a larger gap 134 if bbox.bottom - max(c.bbox.top for c in glyphs) > 0.25 * max(c.bbox.height for c in glyphs): 135 continue 136 if not _aligned(bbox, chars): 137 continue 138 # An underline of the text line above can sit just as close to the next line, but it lies inside the 139 # character boxes above, which reach down to the descent of the font 140 above = Rectangle(bbox.left - 1, bbox.top, bbox.right + 1, bbox.top + y_em) 141 uchars = [c for c in self.chars_in_area(above) if c.unicode not in {0xA, 0xD}] 142 if _aligned(bbox, uchars) and min(c.bbox.bottom for c in uchars) < bbox.top: 143 continue 144 overlines.append(bbox) 145 return overlines 146 147 def _is_overlined(self, char) -> bool: 148 mx = char.bbox.midpoint.x 149 return any( 150 o.left < mx < o.right and 0 <= o.bottom - char.bbox.top < self._spacing["y_em"] / 2 for o in self._overlines 151 ) 152 153 def _char_properties(self, line, char): 154 cp = { 155 "superscript": False, 156 "subscript": False, 157 "bold": any(frag in char.font for frag in {"Bold"}), 158 "italic": any(frag in char.font for frag in {"Italic", "Oblique"}), 159 # Code is set in a monospaced font like Courier, the text never is. Not by the fixed pitch flag of the 160 # font, which some PDFs also set for Arial, Times New Roman and symbol fonts 161 "code": any(frag in char.font.lower() for frag in ("courier", "mono", "consol")), 162 "link": self._link_target(char), 163 "overline": self._is_overlined(char), 164 "size": round(line.height), 165 "relsize": self._line_size(line), 166 "char": chr(char.unicode), 167 } 168 # Sub- and superscript use a smaller font, characters of the full size 169 # with a shifted baseline are labels next to multi-line text instead 170 if char.height >= 0.95 * line.height: 171 pass 172 elif line.rotation: 173 if char.origin.x < (line.origin - 0.25 * line.height): 174 cp["superscript"] = True 175 elif char.origin.x > (line.origin + 0.15 * line.height): 176 cp["subscript"] = True 177 elif char.origin.y > (line.origin + 0.25 * line.height): 178 cp["superscript"] = True 179 elif char.origin.y < (line.origin - 0.15 * line.height): 180 cp["subscript"] = True 181 return cp 182 183 def text_in_named_area(self, name: str, check_length: bool = True) -> str | None: 184 """ 185 Find all text in the named area. 186 187 :param name: the name of the area(s) to query. 188 :param check_length: assert that the text has a length. 189 :return: the concatenated text of the named area(s) or `None` if area not found. 190 """ 191 if name not in self._areas: 192 return None 193 text = "" 194 areas = self._areas[name] 195 if not isinstance(areas, list): 196 areas = [areas] 197 for area in areas: 198 text += self.text_in_area(area) 199 if check_length: 200 assert text 201 return text 202 203 def charlines_in_area( 204 self, area: Rectangle, predicate: Callable[[Character], bool] = None, rtol: float = None 205 ) -> list[CharLine]: 206 """ 207 Coalesce the characters in the area and predicate into lines. 208 209 1. Every character in the area is filtered by the `predicate`. 210 2. Character orientation is split into horizontal (left->right) and 211 vertical (bottom->top) character lines sorted by x or y position. 212 Lines containing only whitespace are discarded. 213 3. Overlapping character lines are merged into sub- and superscript 214 using `rtol * max(current_line.height, next_line.height)` as the 215 tolerance for checking if the lines overlap. 216 4. The characters in the merged lines are re-sorted by origin. 217 218 :param area: Area to search for characters. 219 :param predicate: Function to discard characters in the area or include all by default. 220 :param rtol: Relative tolerance to separate lines vertically or use `sc` spacing by default. 221 :return: A list of character lines sorted by x or y position. 222 """ 223 if rtol is None: 224 rtol = self._spacing["sc"] 225 # The lines keep the characters, which must know their links by then 226 self._link_characters() 227 # Split all chars into lines based on rounded origin 228 origin_lines_y = defaultdict(list) 229 origin_lines_x = defaultdict(list) 230 for char in self.chars_in_area(area): 231 # Ignore all characters we don't want 232 if predicate is not None and not predicate(char): 233 continue 234 # A watermark like "Obsolete Product(s)" is faint text written diagonally across the page 235 if 1 < char.rotation % 90 < 89: 236 rgb = [(char.fill >> shift) & 0xFF for shift in (24, 16, 8)] 237 if (char.fill & 0xFF) < 0x80 or min(rgb) > 0xC0: 238 continue 239 cunicode = self._unicode_filter(char.unicode) 240 if cunicode is None: 241 continue 242 char.unicode = cunicode 243 if char.unicode < 32 and char.unicode not in {0xA}: 244 continue 245 # Ignore characters without width that are not spaces 246 if not char.width and char.unicode not in {0xA, 0xD, 0x20}: 247 _LOGGER.error(f"Unknown char width for {char}: {char.bbox}") 248 # Split up the chars depending on the orientation 249 if 45 < char.rotation <= 135 or 225 < char.rotation <= 315: 250 origin_lines_x[round(char.origin.x, 1)].append(char) 251 elif char.rotation <= 45 or 135 < char.rotation <= 225 or 315 < char.rotation: 252 origin_lines_y[round(char.origin.y, 1)].append(char) 253 else: 254 _LOGGER.error("Unknown char rotation:", char, char.rotation) 255 256 # Convert characters into lines 257 bbox_lines_y = [] 258 for chars in origin_lines_y.values(): 259 # Remove lines with whitespace only 260 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 261 continue 262 origin = statistics.fmean(c.origin.y for c in chars) 263 line = CharLine( 264 self, 265 chars, 266 min(c.bbox.bottom for c in chars), 267 origin, 268 max(c.bbox.top for c in chars), 269 max(c.height for c in chars), 270 sort_origin=self.height - origin, 271 ) 272 bbox_lines_y.append(line) 273 # print(line, line.top, line.origin, line.bottom, line.height) 274 bbox_lines = sorted(bbox_lines_y, key=lambda line: line._sort_origin) 275 276 bbox_lines_x = [] 277 for chars in origin_lines_x.values(): 278 # Remove lines with whitespace only 279 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 280 continue 281 line = CharLine( 282 self, 283 chars, 284 min(c.bbox.left for c in chars), 285 statistics.fmean(c.origin.x for c in chars), 286 max(c.bbox.right for c in chars), 287 max(c.width for c in chars), 288 270 if sum(c.rotation for c in chars) <= 135 * len(chars) else 90, 289 ) 290 bbox_lines_x.append(line) 291 bbox_lines += sorted(bbox_lines_x, key=lambda line: line._sort_origin) 292 293 if not bbox_lines: 294 return [] 295 296 def _stacked(line0, line1) -> bool: 297 # Characters of the same font size, that overlap along the line by 298 # more than half their width, are printed on top of each other. 299 horizontal = not line0.rotation 300 301 def _spans(line): 302 chars = (c for c in line.chars if c.unicode not in {0x20, 0xA, 0xD}) 303 chars = (c for c in chars if math.isclose(c.height, line.height, rel_tol=0.01)) 304 return [(c.bbox.left, c.bbox.right) if horizontal else (c.bbox.bottom, c.bbox.top) for c in chars] 305 306 spans1 = _spans(line1) 307 for start0, stop0 in _spans(line0): 308 for start1, stop1 in spans1: 309 overlap = min(stop0, stop1) - max(start0, start1) 310 if overlap > 0.5 * min(stop0 - start0, stop1 - start1): 311 return True 312 return False 313 314 def _label(line0, line1) -> bool: 315 # A label of the same font size left of a multi-line text is 316 # vertically centered on the lines, so its baseline is shifted by 317 # more than a continuation of the line would be. 318 if line0.rotation or line1.rotation: 319 return False 320 offset = abs(line0._sort_origin - line1._sort_origin) 321 return offset > rtol * line0.height and ( 322 line0.bbox.right < line1.bbox.left or line1.bbox.right < line0.bbox.left 323 ) 324 325 # Merge lines that have overlapping bbox_lines 326 merged_lines = [] 327 current_line = bbox_lines[0] 328 for next_line in bbox_lines[1:]: 329 height = max(current_line.height, next_line.height) 330 same_height = math.isclose(current_line.height, next_line.height, rel_tol=0.01) 331 # Calculate overlap via normalize origin (increasing with line index) 332 if ( 333 # Horizontal and vertical lines have different sort origins 334 bool(current_line.rotation) == bool(next_line.rotation) 335 and (current_line._sort_origin + rtol * height) > (next_line._sort_origin - rtol * height) 336 # Lines of the same font size printed on top of each other are 337 # separate lines, like the numerator and denominator of a formula 338 and not (same_height and _stacked(current_line, next_line)) 339 and not (same_height and _label(current_line, next_line)) 340 ): 341 # The next line overlaps this one, we merge the shorter line 342 # (typically super- and subscript) into the taller line. Lines 343 # of the same font size continue each other with a slightly 344 # shifted baseline, so we merge them into the longer line. 345 if same_height: 346 use_current = len(current_line.chars) >= len(next_line.chars) 347 else: 348 use_current = current_line.height > next_line.height 349 line = current_line if use_current else next_line 350 current_line = CharLine( 351 self, 352 current_line.chars + next_line.chars, 353 line.bottom, 354 line.origin, 355 line.top, 356 height, 357 line.rotation, 358 sort_origin=line._sort_origin, 359 ) 360 else: 361 # The next line does not overlap the current line 362 merged_lines.append(current_line) 363 current_line = next_line 364 # append last line 365 merged_lines.append(current_line) 366 367 # Prepend labels to the first line of their multi-line text 368 labeled_lines = [] 369 for line in merged_lines: 370 prev = labeled_lines[-1] if labeled_lines else None 371 if ( 372 prev is not None 373 and not line.rotation 374 and math.isclose(prev.height, line.height, rel_tol=0.01) 375 and 0 < line._sort_origin - prev._sort_origin < line.height 376 and line.bbox.right < prev.bbox.left 377 ): 378 # Keep the spaces between the words of the label, but not around it 379 label = sorted((c for c in line.chars if c.unicode not in {0xA, 0xD}), key=lambda c: c.origin.x) 380 label = list_strip(label, lambda c: c.unicode == 0x20) 381 chars = label + [label[-1].generated_space()] + prev.chars 382 labeled_lines[-1] = CharLine( 383 self, chars, prev.bottom, prev.origin, prev.top, prev.height, sort_origin=prev._sort_origin 384 ) 385 else: 386 labeled_lines.append(line) 387 merged_lines = labeled_lines 388 389 # Sort all lines horizontally based on character origin 390 sorted_lines = [] 391 for line in merged_lines: 392 if line.rotation == 90: 393 394 def sort_key(char): 395 if char.unicode in {0xA, 0xD}: 396 return char.tbbox.midpoint.y - 1e9 397 return char.tbbox.midpoint.y 398 elif line.rotation == 270: 399 400 def sort_key(char): 401 if char.unicode in {0xA, 0xD}: 402 return -char.tbbox.midpoint.y + 1e9 403 return -char.tbbox.midpoint.y 404 else: 405 406 def sort_key(char): 407 if char.unicode in {0xA, 0xD}: 408 return char.origin.x + 1e9 409 return char.origin.x 410 411 chars = sorted(line.chars, key=sort_key) 412 if not line.rotation: 413 chars = self._chars_with_bullet_space(chars) 414 chars = self._chars_with_gap_spaces(chars, line.rotation) 415 sorted_lines.append( 416 CharLine( 417 self, 418 chars, 419 line.bottom, 420 line.origin, 421 line.top, 422 line.height, 423 line.rotation, 424 area.left, 425 sort_origin=line._sort_origin, 426 ) 427 ) 428 429 return sorted_lines 430 431 @staticmethod 432 def _chars_with_gap_spaces(chars: list, rotation: int) -> list: 433 # pdfium generates no spaces at the word gaps of fonts without a space 434 # glyph, so we insert them at gaps wider than the typical gap between 435 # the letters of a run of the same font, which may be letter-spaced. 436 def _span(char): 437 if not rotation: 438 return char.bbox.left, char.bbox.right 439 if rotation == 90: 440 return char.bbox.bottom, char.bbox.top 441 return -char.bbox.top, -char.bbox.bottom 442 443 runs, last, key = [], None, None 444 for index, char in enumerate(chars): 445 if char.unicode in {0x20, 0xA, 0xD}: 446 continue 447 start, stop = _span(char) 448 size = round(char.height, 1) 449 # Lines may interleave the characters of several baselines 450 baseline = round(char.origin.x if rotation else char.origin.y, 1) 451 if key != (char.font, size, baseline) or start - last > 0.5 * size: 452 runs.append((char, [])) 453 else: 454 runs[-1][1].append((start - last, index)) 455 key, last = (char.font, size, baseline), stop 456 457 spaces = [] 458 for first, gaps in runs: 459 if not gaps or first.has_space_glyph: 460 continue 461 size = first.height 462 letter_gap = statistics.median(g for g, _ in gaps) 463 spaces += [i for g, i in gaps if g > letter_gap + 0.15 * size and chars[i - 1].unicode != 0x20] 464 for index in sorted(spaces, reverse=True): 465 chars = chars[:index] + [chars[index].generated_space()] + chars[index:] 466 return chars 467 468 @staticmethod 469 def _chars_with_bullet_space(chars: list) -> list: 470 # Newer pdfium does not generate a space for every visual gap anymore, 471 # but the list detection relies on the one between bullet and text. 472 for ii, (bullet, char) in enumerate(zip(chars, chars[1:]), 1): 473 if bullet.unicode == 0x20: 474 continue 475 if ( 476 bullet.char in {"•", "–"} 477 and char.unicode not in {0x20, 0xA, 0xD} 478 and char.origin.x - bullet.bbox.right >= 0.25 * bullet.height 479 ): 480 return chars[:ii] + [char.generated_space()] + chars[ii:] 481 break 482 return chars 483 484 def graphic_bboxes_in_area( 485 self, area: Rectangle, with_graphics: bool = True 486 ) -> list[tuple[Rectangle, Table | Figure | None]]: 487 """ 488 Coalesce the graphics in the area into full width bounding boxes. 489 490 1. Group vertically overlapping graphics. 491 2. Widen the overlapped graphics bounding boxes to the edges of the area. 492 493 :param area: area to search for content. 494 :param with_graphics: search for graphics in the area. 495 :return: list of tuples (bounding box, graphic objects or `None`). 496 """ 497 if with_graphics: 498 graphics = self.graphics_in_area(area) 499 regions = [] 500 # Check if graphics bounding boxes overlap vertically and group them 501 for graphic in sorted(graphics, key=lambda g: (-g.bbox.top, g.bbox.x)): 502 gbbox = graphic.bbox.joined(graphic.cbbox) if graphic.cbbox else graphic.bbox 503 for reg in regions: 504 if reg.overlaps(gbbox.bottom, gbbox.top): 505 # They overlap, so merge them 506 reg.v0 = min(reg.v0, gbbox.bottom) 507 reg.v1 = max(reg.v1, gbbox.top) 508 reg.objs.append(graphic) 509 break 510 else: 511 regions.append(Region(gbbox.bottom, gbbox.top, graphic)) 512 513 # print(regions) 514 # Coalesce all overlapped graphics objects into full width areas 515 areas = [] 516 ypos = area.top 517 for reg in regions: 518 if ypos - reg.v1 > self._spacing["y_em"]: 519 areas.append((Rectangle(area.left, reg.v1, area.right, ypos), None)) 520 for obj in reg.objs: 521 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 522 areas.append((oarea, obj)) 523 ypos = reg.v0 524 areas.append((Rectangle(area.left, area.bottom, area.right, ypos), None)) 525 else: 526 areas = [(area, None)] 527 return areas 528 529 def objects_in_area(self, area: Rectangle, with_graphics: bool = True) -> list[CharLine | Table | Figure]: 530 """ 531 Find all content objects in this area. 532 533 :param area: area to search for content. 534 :param with_graphics: search for graphics in the area. 535 :return: list of content objects sorted top to bottom. 536 """ 537 areas = self.graphic_bboxes_in_area(area, with_graphics) 538 objects = [] 539 for narea, obj in areas: 540 if obj is None: 541 objects += self.charlines_in_area(narea) 542 else: 543 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 544 545 def predicate(c): 546 return not obj.bbox.contains(c.origin) 547 548 lines = self.charlines_in_area(oarea, predicate) 549 # print(obj, oarea, lines, [line.content for line in lines]) 550 objects += list(sorted(lines + [obj], key=lambda o: (-o.bbox.y, o.bbox.x))) 551 return objects 552 553 def graphics_in_area(self, area: Rectangle) -> list[Table | Figure]: 554 """ 555 Find all tables and figures in this area. 556 557 :param area: area to search for graphics. 558 :return: list of tables and figures. 559 """ 560 return [] 561 562 def ast_in_area(self, area: Rectangle, with_graphics: bool = True) -> Node: 563 """ 564 Convert the area content into an abstract syntax tree. 565 566 :param area: area to search for content. 567 :param with_graphics: including graphics in the area. 568 :return: An abstract syntax tree including the content formatting. 569 """ 570 return Node("area", obj=area, xpos=int(area.left), page=self) 571 572 @property 573 def content_ast(self) -> list[Node]: 574 """The abstract syntax trees in the content area.""" 575 ast = [] 576 with_graphics = True 577 for area in self._areas["content"]: 578 ast.append(self.ast_in_area(area, with_graphics=with_graphics)) 579 # Add a page node to the first leaf to keep track of where a page starts 580 first_leaf = next((n for n in iter(ast[0].descendants) if n.is_leaf), ast[0]) 581 Node("page", parent=first_leaf, xpos=first_leaf.xpos, number=self.number) 582 return ast 583 584 @property 585 def content_objects(self) -> list[CharLine | Table | Figure]: 586 """All objects in the content areas.""" 587 objs = [] 588 for area in self._areas["content"]: 589 objs.extend(self.objects_in_area(area)) 590 return objs 591 592 @property 593 def content_graphics(self) -> list[Table | Figure]: 594 """All graphics in the content areas.""" 595 objs = [] 596 for area in self._areas["content"]: 597 objs.extend(self.graphics_in_area(area)) 598 return objs 599 600 @property 601 def content_lines(self) -> list[CharLine]: 602 """All lines in the content areas.""" 603 objs = [] 604 for area in self._areas["content"]: 605 objs.extend(self.charlines_in_area(area)) 606 return objs 607 608 @property 609 def content_tables(self) -> list[Table]: 610 """All tables in the content areas.""" 611 return [o for o in self.content_graphics if isinstance(o, Table)] 612 613 @property 614 def content_figures(self) -> list[Figure]: 615 """All figures in the content areas.""" 616 return [o for o in self.content_graphics if isinstance(o, Figure)] 617 618 def __repr__(self) -> str: 619 return f"Page({self.number})"
This class provides low-level access to graphics and characters of the page and allows searching for characters in an area instead of just text.
23 def __init__(self, document, index: int): 24 super().__init__(document, index) 25 self._template = "default" 26 self.is_relevant: bool = True 27 """Is this page relevant for the conversion?"""
Parameters
- document: a PDF document.
- index: 0-index page number.
183 def text_in_named_area(self, name: str, check_length: bool = True) -> str | None: 184 """ 185 Find all text in the named area. 186 187 :param name: the name of the area(s) to query. 188 :param check_length: assert that the text has a length. 189 :return: the concatenated text of the named area(s) or `None` if area not found. 190 """ 191 if name not in self._areas: 192 return None 193 text = "" 194 areas = self._areas[name] 195 if not isinstance(areas, list): 196 areas = [areas] 197 for area in areas: 198 text += self.text_in_area(area) 199 if check_length: 200 assert text 201 return text
Find all text in the named area.
Parameters
- name: the name of the area(s) to query.
- check_length: assert that the text has a length.
Returns
the concatenated text of the named area(s) or
Noneif area not found.
203 def charlines_in_area( 204 self, area: Rectangle, predicate: Callable[[Character], bool] = None, rtol: float = None 205 ) -> list[CharLine]: 206 """ 207 Coalesce the characters in the area and predicate into lines. 208 209 1. Every character in the area is filtered by the `predicate`. 210 2. Character orientation is split into horizontal (left->right) and 211 vertical (bottom->top) character lines sorted by x or y position. 212 Lines containing only whitespace are discarded. 213 3. Overlapping character lines are merged into sub- and superscript 214 using `rtol * max(current_line.height, next_line.height)` as the 215 tolerance for checking if the lines overlap. 216 4. The characters in the merged lines are re-sorted by origin. 217 218 :param area: Area to search for characters. 219 :param predicate: Function to discard characters in the area or include all by default. 220 :param rtol: Relative tolerance to separate lines vertically or use `sc` spacing by default. 221 :return: A list of character lines sorted by x or y position. 222 """ 223 if rtol is None: 224 rtol = self._spacing["sc"] 225 # The lines keep the characters, which must know their links by then 226 self._link_characters() 227 # Split all chars into lines based on rounded origin 228 origin_lines_y = defaultdict(list) 229 origin_lines_x = defaultdict(list) 230 for char in self.chars_in_area(area): 231 # Ignore all characters we don't want 232 if predicate is not None and not predicate(char): 233 continue 234 # A watermark like "Obsolete Product(s)" is faint text written diagonally across the page 235 if 1 < char.rotation % 90 < 89: 236 rgb = [(char.fill >> shift) & 0xFF for shift in (24, 16, 8)] 237 if (char.fill & 0xFF) < 0x80 or min(rgb) > 0xC0: 238 continue 239 cunicode = self._unicode_filter(char.unicode) 240 if cunicode is None: 241 continue 242 char.unicode = cunicode 243 if char.unicode < 32 and char.unicode not in {0xA}: 244 continue 245 # Ignore characters without width that are not spaces 246 if not char.width and char.unicode not in {0xA, 0xD, 0x20}: 247 _LOGGER.error(f"Unknown char width for {char}: {char.bbox}") 248 # Split up the chars depending on the orientation 249 if 45 < char.rotation <= 135 or 225 < char.rotation <= 315: 250 origin_lines_x[round(char.origin.x, 1)].append(char) 251 elif char.rotation <= 45 or 135 < char.rotation <= 225 or 315 < char.rotation: 252 origin_lines_y[round(char.origin.y, 1)].append(char) 253 else: 254 _LOGGER.error("Unknown char rotation:", char, char.rotation) 255 256 # Convert characters into lines 257 bbox_lines_y = [] 258 for chars in origin_lines_y.values(): 259 # Remove lines with whitespace only 260 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 261 continue 262 origin = statistics.fmean(c.origin.y for c in chars) 263 line = CharLine( 264 self, 265 chars, 266 min(c.bbox.bottom for c in chars), 267 origin, 268 max(c.bbox.top for c in chars), 269 max(c.height for c in chars), 270 sort_origin=self.height - origin, 271 ) 272 bbox_lines_y.append(line) 273 # print(line, line.top, line.origin, line.bottom, line.height) 274 bbox_lines = sorted(bbox_lines_y, key=lambda line: line._sort_origin) 275 276 bbox_lines_x = [] 277 for chars in origin_lines_x.values(): 278 # Remove lines with whitespace only 279 if all(c.unicode in {0xA, 0xD, 0x20} for c in chars): 280 continue 281 line = CharLine( 282 self, 283 chars, 284 min(c.bbox.left for c in chars), 285 statistics.fmean(c.origin.x for c in chars), 286 max(c.bbox.right for c in chars), 287 max(c.width for c in chars), 288 270 if sum(c.rotation for c in chars) <= 135 * len(chars) else 90, 289 ) 290 bbox_lines_x.append(line) 291 bbox_lines += sorted(bbox_lines_x, key=lambda line: line._sort_origin) 292 293 if not bbox_lines: 294 return [] 295 296 def _stacked(line0, line1) -> bool: 297 # Characters of the same font size, that overlap along the line by 298 # more than half their width, are printed on top of each other. 299 horizontal = not line0.rotation 300 301 def _spans(line): 302 chars = (c for c in line.chars if c.unicode not in {0x20, 0xA, 0xD}) 303 chars = (c for c in chars if math.isclose(c.height, line.height, rel_tol=0.01)) 304 return [(c.bbox.left, c.bbox.right) if horizontal else (c.bbox.bottom, c.bbox.top) for c in chars] 305 306 spans1 = _spans(line1) 307 for start0, stop0 in _spans(line0): 308 for start1, stop1 in spans1: 309 overlap = min(stop0, stop1) - max(start0, start1) 310 if overlap > 0.5 * min(stop0 - start0, stop1 - start1): 311 return True 312 return False 313 314 def _label(line0, line1) -> bool: 315 # A label of the same font size left of a multi-line text is 316 # vertically centered on the lines, so its baseline is shifted by 317 # more than a continuation of the line would be. 318 if line0.rotation or line1.rotation: 319 return False 320 offset = abs(line0._sort_origin - line1._sort_origin) 321 return offset > rtol * line0.height and ( 322 line0.bbox.right < line1.bbox.left or line1.bbox.right < line0.bbox.left 323 ) 324 325 # Merge lines that have overlapping bbox_lines 326 merged_lines = [] 327 current_line = bbox_lines[0] 328 for next_line in bbox_lines[1:]: 329 height = max(current_line.height, next_line.height) 330 same_height = math.isclose(current_line.height, next_line.height, rel_tol=0.01) 331 # Calculate overlap via normalize origin (increasing with line index) 332 if ( 333 # Horizontal and vertical lines have different sort origins 334 bool(current_line.rotation) == bool(next_line.rotation) 335 and (current_line._sort_origin + rtol * height) > (next_line._sort_origin - rtol * height) 336 # Lines of the same font size printed on top of each other are 337 # separate lines, like the numerator and denominator of a formula 338 and not (same_height and _stacked(current_line, next_line)) 339 and not (same_height and _label(current_line, next_line)) 340 ): 341 # The next line overlaps this one, we merge the shorter line 342 # (typically super- and subscript) into the taller line. Lines 343 # of the same font size continue each other with a slightly 344 # shifted baseline, so we merge them into the longer line. 345 if same_height: 346 use_current = len(current_line.chars) >= len(next_line.chars) 347 else: 348 use_current = current_line.height > next_line.height 349 line = current_line if use_current else next_line 350 current_line = CharLine( 351 self, 352 current_line.chars + next_line.chars, 353 line.bottom, 354 line.origin, 355 line.top, 356 height, 357 line.rotation, 358 sort_origin=line._sort_origin, 359 ) 360 else: 361 # The next line does not overlap the current line 362 merged_lines.append(current_line) 363 current_line = next_line 364 # append last line 365 merged_lines.append(current_line) 366 367 # Prepend labels to the first line of their multi-line text 368 labeled_lines = [] 369 for line in merged_lines: 370 prev = labeled_lines[-1] if labeled_lines else None 371 if ( 372 prev is not None 373 and not line.rotation 374 and math.isclose(prev.height, line.height, rel_tol=0.01) 375 and 0 < line._sort_origin - prev._sort_origin < line.height 376 and line.bbox.right < prev.bbox.left 377 ): 378 # Keep the spaces between the words of the label, but not around it 379 label = sorted((c for c in line.chars if c.unicode not in {0xA, 0xD}), key=lambda c: c.origin.x) 380 label = list_strip(label, lambda c: c.unicode == 0x20) 381 chars = label + [label[-1].generated_space()] + prev.chars 382 labeled_lines[-1] = CharLine( 383 self, chars, prev.bottom, prev.origin, prev.top, prev.height, sort_origin=prev._sort_origin 384 ) 385 else: 386 labeled_lines.append(line) 387 merged_lines = labeled_lines 388 389 # Sort all lines horizontally based on character origin 390 sorted_lines = [] 391 for line in merged_lines: 392 if line.rotation == 90: 393 394 def sort_key(char): 395 if char.unicode in {0xA, 0xD}: 396 return char.tbbox.midpoint.y - 1e9 397 return char.tbbox.midpoint.y 398 elif line.rotation == 270: 399 400 def sort_key(char): 401 if char.unicode in {0xA, 0xD}: 402 return -char.tbbox.midpoint.y + 1e9 403 return -char.tbbox.midpoint.y 404 else: 405 406 def sort_key(char): 407 if char.unicode in {0xA, 0xD}: 408 return char.origin.x + 1e9 409 return char.origin.x 410 411 chars = sorted(line.chars, key=sort_key) 412 if not line.rotation: 413 chars = self._chars_with_bullet_space(chars) 414 chars = self._chars_with_gap_spaces(chars, line.rotation) 415 sorted_lines.append( 416 CharLine( 417 self, 418 chars, 419 line.bottom, 420 line.origin, 421 line.top, 422 line.height, 423 line.rotation, 424 area.left, 425 sort_origin=line._sort_origin, 426 ) 427 ) 428 429 return sorted_lines
Coalesce the characters in the area and predicate into lines.
- Every character in the area is filtered by the
predicate. - Character orientation is split into horizontal (left->right) and vertical (bottom->top) character lines sorted by x or y position. Lines containing only whitespace are discarded.
- Overlapping character lines are merged into sub- and superscript
using
rtol * max(current_line.height, next_line.height)as the tolerance for checking if the lines overlap. - The characters in the merged lines are re-sorted by origin.
Parameters
- area: Area to search for characters.
- predicate: Function to discard characters in the area or include all by default.
- rtol: Relative tolerance to separate lines vertically or use
scspacing by default.
Returns
A list of character lines sorted by x or y position.
484 def graphic_bboxes_in_area( 485 self, area: Rectangle, with_graphics: bool = True 486 ) -> list[tuple[Rectangle, Table | Figure | None]]: 487 """ 488 Coalesce the graphics in the area into full width bounding boxes. 489 490 1. Group vertically overlapping graphics. 491 2. Widen the overlapped graphics bounding boxes to the edges of the area. 492 493 :param area: area to search for content. 494 :param with_graphics: search for graphics in the area. 495 :return: list of tuples (bounding box, graphic objects or `None`). 496 """ 497 if with_graphics: 498 graphics = self.graphics_in_area(area) 499 regions = [] 500 # Check if graphics bounding boxes overlap vertically and group them 501 for graphic in sorted(graphics, key=lambda g: (-g.bbox.top, g.bbox.x)): 502 gbbox = graphic.bbox.joined(graphic.cbbox) if graphic.cbbox else graphic.bbox 503 for reg in regions: 504 if reg.overlaps(gbbox.bottom, gbbox.top): 505 # They overlap, so merge them 506 reg.v0 = min(reg.v0, gbbox.bottom) 507 reg.v1 = max(reg.v1, gbbox.top) 508 reg.objs.append(graphic) 509 break 510 else: 511 regions.append(Region(gbbox.bottom, gbbox.top, graphic)) 512 513 # print(regions) 514 # Coalesce all overlapped graphics objects into full width areas 515 areas = [] 516 ypos = area.top 517 for reg in regions: 518 if ypos - reg.v1 > self._spacing["y_em"]: 519 areas.append((Rectangle(area.left, reg.v1, area.right, ypos), None)) 520 for obj in reg.objs: 521 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 522 areas.append((oarea, obj)) 523 ypos = reg.v0 524 areas.append((Rectangle(area.left, area.bottom, area.right, ypos), None)) 525 else: 526 areas = [(area, None)] 527 return areas
Coalesce the graphics in the area into full width bounding boxes.
- Group vertically overlapping graphics.
- Widen the overlapped graphics bounding boxes to the edges of the area.
Parameters
- area: area to search for content.
- with_graphics: search for graphics in the area.
Returns
list of tuples (bounding box, graphic objects or
None).
529 def objects_in_area(self, area: Rectangle, with_graphics: bool = True) -> list[CharLine | Table | Figure]: 530 """ 531 Find all content objects in this area. 532 533 :param area: area to search for content. 534 :param with_graphics: search for graphics in the area. 535 :return: list of content objects sorted top to bottom. 536 """ 537 areas = self.graphic_bboxes_in_area(area, with_graphics) 538 objects = [] 539 for narea, obj in areas: 540 if obj is None: 541 objects += self.charlines_in_area(narea) 542 else: 543 oarea = obj.bbox.joined(obj.cbbox) if obj.cbbox else obj.bbox 544 545 def predicate(c): 546 return not obj.bbox.contains(c.origin) 547 548 lines = self.charlines_in_area(oarea, predicate) 549 # print(obj, oarea, lines, [line.content for line in lines]) 550 objects += list(sorted(lines + [obj], key=lambda o: (-o.bbox.y, o.bbox.x))) 551 return objects
Find all content objects in this area.
Parameters
- area: area to search for content.
- with_graphics: search for graphics in the area.
Returns
list of content objects sorted top to bottom.
553 def graphics_in_area(self, area: Rectangle) -> list[Table | Figure]: 554 """ 555 Find all tables and figures in this area. 556 557 :param area: area to search for graphics. 558 :return: list of tables and figures. 559 """ 560 return []
Find all tables and figures in this area.
Parameters
- area: area to search for graphics.
Returns
list of tables and figures.
562 def ast_in_area(self, area: Rectangle, with_graphics: bool = True) -> Node: 563 """ 564 Convert the area content into an abstract syntax tree. 565 566 :param area: area to search for content. 567 :param with_graphics: including graphics in the area. 568 :return: An abstract syntax tree including the content formatting. 569 """ 570 return Node("area", obj=area, xpos=int(area.left), page=self)
Convert the area content into an abstract syntax tree.
Parameters
- area: area to search for content.
- with_graphics: including graphics in the area.
Returns
An abstract syntax tree including the content formatting.
572 @property 573 def content_ast(self) -> list[Node]: 574 """The abstract syntax trees in the content area.""" 575 ast = [] 576 with_graphics = True 577 for area in self._areas["content"]: 578 ast.append(self.ast_in_area(area, with_graphics=with_graphics)) 579 # Add a page node to the first leaf to keep track of where a page starts 580 first_leaf = next((n for n in iter(ast[0].descendants) if n.is_leaf), ast[0]) 581 Node("page", parent=first_leaf, xpos=first_leaf.xpos, number=self.number) 582 return ast
The abstract syntax trees in the content area.
584 @property 585 def content_objects(self) -> list[CharLine | Table | Figure]: 586 """All objects in the content areas.""" 587 objs = [] 588 for area in self._areas["content"]: 589 objs.extend(self.objects_in_area(area)) 590 return objs
All objects in the content areas.
592 @property 593 def content_graphics(self) -> list[Table | Figure]: 594 """All graphics in the content areas.""" 595 objs = [] 596 for area in self._areas["content"]: 597 objs.extend(self.graphics_in_area(area)) 598 return objs
All graphics in the content areas.
600 @property 601 def content_lines(self) -> list[CharLine]: 602 """All lines in the content areas.""" 603 objs = [] 604 for area in self._areas["content"]: 605 objs.extend(self.charlines_in_area(area)) 606 return objs
All lines in the content areas.
608 @property 609 def content_tables(self) -> list[Table]: 610 """All tables in the content areas.""" 611 return [o for o in self.content_graphics if isinstance(o, Table)]
All tables in the content areas.
613 @property 614 def content_figures(self) -> list[Figure]: 615 """All figures in the content areas.""" 616 return [o for o in self.content_graphics if isinstance(o, Figure)]
All figures in the content areas.
Inherited Members
- modm_data.pdf.page.Page
- index
- number
- label
- width
- height
- rotation
- bbox
- char_count
- char
- chars
- objlinks
- weblinks
- chars_in_area
- text_in_area
- structures
- find
- paths
- images
- graphic_clusters
- pypdfium2._helpers.page.PdfPage
- raw
- formenv
- parent
- get_width
- get_height
- get_size
- get_rotation
- set_rotation
- get_mediabox
- set_mediabox
- get_cropbox
- set_cropbox
- get_bleedbox
- set_bleedbox
- get_trimbox
- set_trimbox
- get_artbox
- set_artbox
- get_bbox
- get_textpage
- insert_obj
- remove_obj
- gen_content
- get_objects
- flatten
- render
- pypdfium2.internal.bases.AutoCloseable
- close