1"""Extract PDF text preserving the layout of the source PDF"""
2
3from collections.abc import Iterator
4from itertools import groupby
5from math import ceil
6from pathlib import Path
7from typing import Any, Literal, TypedDict
8
9from ..._utils import logger_warning
10from ...generic import ArrayObject
11from ...generic._font import Font
12from .. import LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS
13from ._text_state_manager import TextStateManager
14from ._text_state_params import TextStateParams
15
16WHITESPACE_LIMIT = 10_000
17NEWLINE_LIMIT = 1_000
18
19
20class BTGroup(TypedDict):
21 """
22 Dict describing a line of text rendered within a BT/ET operator pair.
23 If multiple text show operations render text on the same line, the text
24 will be combined into a single BTGroup dict.
25
26 Keys:
27 tx: x coordinate of first character in BTGroup
28 ty: y coordinate of first character in BTGroup
29 font_size: nominal font size
30 font_height: effective font height
31 text: rendered text
32 displaced_tx: x coordinate of last character in BTGroup
33 flip_sort: -1 if page is upside down, else 1
34 """
35
36 tx: float
37 ty: float
38 font_size: float
39 font_height: float
40 text: str
41 displaced_tx: float
42 flip_sort: Literal[-1, 1]
43
44
45def set_font_operation(state_mgr: TextStateManager, fonts: dict[str, Font], operands: list[Any]) -> None:
46 """
47 Apply a Tf (Set font and size) operation to a text state manager.
48
49 A missing font name resolves the same uninterpretable placeholder font as
50 an unknown one (see resolve_font()). A missing or non-numeric size leaves
51 the current size in place, matching the ROB handling of plain-mode Tf.
52
53 Args:
54 state_mgr: the text state manager to update
55 fonts: font dictionary as returned by PageObject._layout_mode_fonts()
56 operands: the Tf operator's operands: [name, size]
57
58 """
59 name = operands[0] if operands else ""
60 size = state_mgr._as_float(operands[1] if len(operands) > 1 else None, state_mgr.font_size)
61 state_mgr.set_font(resolve_font(fonts, name), size)
62
63
64def resolve_font(fonts: dict[str, Font], name: str) -> Font:
65 """
66 Resolve a Tf font name to a layout mode Font.
67
68 A content stream may select a font name that is not declared in the page
69 resources. Fall back to an uninterpretable font so extraction degrades to
70 the existing incomplete-output path instead of raising KeyError.
71
72 Args:
73 fonts: font dictionary as returned by PageObject._layout_mode_fonts()
74 name: font name supplied by a Tf operator
75
76 Returns:
77 Font: the matching font, or an uninterpretable placeholder font.
78
79 """
80 if name in fonts:
81 return fonts[name]
82 logger_warning(
83 "Font %(name)s is not in the page resources.",
84 name=name, source=__name__
85 )
86 return Font("Unknown", encoding={}, interpretable=False)
87
88
89def bt_group(tj_op: TextStateParams, rendered_text: str, displaced_tx: float) -> BTGroup:
90 """
91 BTGroup constructed from a TextStateParams instance, rendered text, and
92 displaced tx value.
93
94 Args:
95 tj_op (TextStateParams): TextStateParams instance
96 rendered_text (str): rendered text
97 displaced_tx (float): x coordinate of last character in BTGroup
98
99 """
100 return BTGroup(
101 tx=tj_op.tx,
102 ty=tj_op.ty,
103 font_size=tj_op.font_size,
104 font_height=tj_op.font_height,
105 text=rendered_text,
106 displaced_tx=displaced_tx,
107 flip_sort=-1 if tj_op.flip_vertical else 1,
108 )
109
110
111def _show_text_operand(
112 operands: list[Any], index: int, text_state_mgr: TextStateManager, tj_ops: list[TextStateParams]
113) -> None:
114 """Show the operand at index like Tj if it is a string. A missing or non-string operand shows no text."""
115 if index < len(operands) and isinstance(text := operands[index], (str, bytes)):
116 tj_ops.append(text_state_mgr.text_state_params(text))
117
118
119def recurse_to_target_op(
120 ops: Iterator[tuple[list[Any], bytes]],
121 text_state_mgr: TextStateManager,
122 end_target: Literal[b"Q", b"ET"],
123 fonts: dict[str, Font],
124 strip_rotated: bool = True,
125) -> tuple[list[BTGroup], list[TextStateParams]]:
126 """
127 Recurse operators between BT/ET and/or q/Q operators managing the transform
128 stack and capturing text positioning and rendering data.
129
130 Args:
131 ops: iterator of operators in content stream
132 text_state_mgr: a TextStateManager instance
133 end_target: Either b"Q" (ends b"q" op) or b"ET" (ends b"BT" op)
134 fonts: font dictionary as returned by PageObject._layout_mode_fonts()
135
136 Returns:
137 tuple: list of BTGroup dicts + list of TextStateParams dataclass instances.
138
139 """
140 # 1 entry per line of text rendered within each BT/ET operation.
141 bt_groups: list[BTGroup] = []
142
143 # 1 entry per text show operator (Tj/TJ/'/")
144 tj_ops: list[TextStateParams] = []
145
146 if end_target == b"Q":
147 # add new q level. cm's added at this level will be popped at next b'Q'
148 text_state_mgr.add_q()
149
150 for operands, op in ops:
151 # The loop is broken by the end target, or exits normally when there are no more ops.
152 if op == end_target:
153 if op == b"Q":
154 text_state_mgr.remove_q()
155 if op == b"ET":
156 if not tj_ops:
157 return bt_groups, tj_ops
158 _text = ""
159 bt_idx = 0 # idx of first tj in this bt group
160 last_displaced_tx = tj_ops[bt_idx].displaced_tx
161 last_ty = tj_ops[bt_idx].ty
162 for _idx, _tj in enumerate(
163 tj_ops
164 ): # ... build text from new Tj operators
165 if strip_rotated and _tj.rotated:
166 continue
167 if not _tj.font.interpretable: # generates warning
168 continue
169 # if the y position of the text is greater than the font height, assume
170 # the text is on a new line and start a new group
171 if abs(_tj.ty - last_ty) > _tj.font_height:
172 if _text.strip():
173 bt_groups.append(
174 bt_group(tj_ops[bt_idx], _text, last_displaced_tx)
175 )
176 bt_idx = _idx
177 _text = ""
178
179 # if the x position of the text is less than the last x position by
180 # more than 5 spaces widths, assume the text order should be flipped
181 # and start a new group
182 if (
183 last_displaced_tx - _tj.tx
184 > _tj.space_tx * LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS
185 ):
186 if _text.strip():
187 bt_groups.append(
188 bt_group(tj_ops[bt_idx], _text, last_displaced_tx)
189 )
190 bt_idx = _idx
191 last_displaced_tx = _tj.displaced_tx
192 _text = ""
193
194 # calculate excess x translation based on ending tx of previous Tj.
195 # multiply by bool (_idx != bt_idx) to ensure spaces aren't double
196 # applied to the first tj of a BTGroup in fixed_width_page().
197 excess_tx = round(_tj.tx - last_displaced_tx, 3) * (_idx != bt_idx)
198 # space_tx is measured in text space, while excess_tx is measured
199 # in page-space x coordinates. Convert the space width using the
200 # effective horizontal transform. This matters for PDFs that use
201 # Tf 1 and put the font size in Tm (e.g. Illustrator/InDesign/Figma).
202 # The backward-jump test above stays on text-space space_tx:
203 # scaling it splits same-line runs when a CTM scale < 1 makes
204 # 5 page-space widths tiny (resources/toy.pdf).
205 page_space_tx = _tj.space_tx * abs(_tj.transform[0])
206 # page_space_tx is 0 when Tz, font_size, or the horizontal scale is 0.
207 spaces = round(excess_tx / page_space_tx) if excess_tx > 0 and page_space_tx else 0
208 if spaces > WHITESPACE_LIMIT:
209 logger_warning(
210 "Limiting excessive whitespace from %(actual)d to %(limit)d characters.",
211 actual=spaces, limit=WHITESPACE_LIMIT, source=__name__
212 )
213 spaces = WHITESPACE_LIMIT
214 new_text = f'{" " * spaces}{_tj.text}'
215
216 last_ty = _tj.ty
217 _text = f"{_text}{new_text}"
218 last_displaced_tx = _tj.displaced_tx
219 if _text:
220 bt_groups.append(bt_group(tj_ops[bt_idx], _text, last_displaced_tx))
221 text_state_mgr.reset_tm()
222 break
223 if op == b"q" or (op == b"BT" and end_target == b"Q"):
224 bts, tjs = recurse_to_target_op(
225 ops, text_state_mgr, b"ET" if op == b"BT" else b"Q", fonts, strip_rotated
226 )
227 bt_groups.extend(bts)
228 tj_ops.extend(tjs)
229 elif op == b"cm":
230 text_state_mgr.add_cm(*operands)
231 elif op == b"BT":
232 # text objects cannot be nested and end at the first ET: a BT inside
233 # one only resets the text matrix, as in plain mode
234 text_state_mgr.reset_tm()
235 elif op == b"Tj" and operands and isinstance(operands[0], (str, bytes)):
236 tj_ops.append(text_state_mgr.text_state_params(operands[0]))
237 elif op == b"TJ" and operands and isinstance(operands[0], ArrayObject):
238 _tj = text_state_mgr.text_state_params()
239 # Only strings and numbers are valid TJ array items
240 for tj_op in (item for item in operands[0] if isinstance(item, (bytes, int, float))):
241 if isinstance(tj_op, bytes):
242 _tj = text_state_mgr.text_state_params(tj_op)
243 tj_ops.append(_tj)
244 else:
245 text_state_mgr.add_trm(_tj.displacement_matrix(td_offset=tj_op))
246 elif op == b"'":
247 # Move to the next line, then show the string if there is one, like Tj
248 text_state_mgr.reset_trm()
249 text_state_mgr.add_tm([0, -text_state_mgr.TL])
250 _show_text_operand(operands, 0, text_state_mgr, tj_ops)
251 elif op == b'"' and len(operands) >= 3:
252 text_state_mgr.reset_trm()
253 text_state_mgr.set_state_param(b"Tw", operands[0])
254 text_state_mgr.set_state_param(b"Tc", operands[1])
255 text_state_mgr.add_tm([0, -text_state_mgr.TL])
256 _show_text_operand(operands, 2, text_state_mgr, tj_ops)
257 elif op in (b"Td", b"Tm", b"TD", b"T*"):
258 text_state_mgr.reset_trm()
259 if op == b"Tm":
260 text_state_mgr.reset_tm()
261 elif op == b"TD" and len(operands) >= 2 and isinstance(operands[1], (int, float)):
262 # a missing or non-numeric ty leaves the leading unchanged; the
263 # translation itself is handled like Td below
264 text_state_mgr.set_state_param(b"TL", -operands[1])
265 elif op == b"T*":
266 operands = [0, -text_state_mgr.TL]
267 text_state_mgr.add_tm(operands)
268 elif op == b"Tf":
269 set_font_operation(text_state_mgr, fonts, operands)
270 else: # handle Tc, Tw, Tz, TL, and Ts operators
271 text_state_mgr.set_state_param(op, operands)
272 else:
273 logger_warning(
274 "Unbalanced target operations, expected %(end_target)r.",
275 source=__name__,
276 end_target=end_target,
277 )
278 return bt_groups, tj_ops
279
280
281def y_coordinate_groups(
282 bt_groups: list[BTGroup], debug_path: Path | None = None
283) -> dict[int, list[BTGroup]]:
284 """
285 Group text operations by rendered y coordinate, i.e. the line number.
286
287 Args:
288 bt_groups: list of dicts as returned by text_show_operations()
289 debug_path (Path, optional): Path to a directory for saving debug output.
290
291 Returns:
292 Dict[int, List[BTGroup]]: dict of lists of text rendered by each BT operator
293 keyed by y coordinate
294
295 """
296 ty_groups = {
297 ty: sorted(grp, key=lambda x: x["tx"])
298 for ty, grp in groupby(
299 bt_groups, key=lambda bt_grp: int(bt_grp["ty"] * bt_grp["flip_sort"])
300 )
301 }
302 # combine groups whose y coordinates differ by less than the effective font height
303 # (accounts for mixed fonts and other minor oddities)
304 last_ty = next(iter(ty_groups))
305 last_txs = {int(_t["tx"]) for _t in ty_groups[last_ty] if _t["text"].strip()}
306 for ty in list(ty_groups)[1:]:
307 fsz = min(ty_groups[_y][0]["font_height"] for _y in (ty, last_ty))
308 txs = {int(_t["tx"]) for _t in ty_groups[ty] if _t["text"].strip()}
309 # prevent merge if both groups are rendering in the same x position.
310 no_text_overlap = not (txs & last_txs)
311 offset_less_than_font_height = abs(ty - last_ty) < fsz
312 if no_text_overlap and offset_less_than_font_height:
313 ty_groups[last_ty] = sorted(
314 ty_groups.pop(ty) + ty_groups[last_ty], key=lambda x: x["tx"]
315 )
316 last_txs |= txs
317 else:
318 last_ty = ty
319 last_txs = txs
320 if debug_path: # pragma: no cover
321 import json # noqa: PLC0415
322
323 debug_path.joinpath("bt_groups.json").write_text(
324 json.dumps(ty_groups, indent=2, default=str), "utf-8"
325 )
326 return ty_groups
327
328
329def text_show_operations(
330 ops: Iterator[tuple[list[Any], bytes]],
331 fonts: dict[str, Font],
332 strip_rotated: bool = True,
333 debug_path: Path | None = None,
334) -> list[BTGroup]:
335 """
336 Extract text from BT/ET operator pairs.
337
338 Args:
339 ops (Iterator[Tuple[List, bytes]]): iterator of operators in content stream
340 fonts (Dict[str, Font]): font dictionary
341 strip_rotated: Removes text if rotated w.r.t. to the page. Defaults to True.
342 debug_path (Path, optional): Path to a directory for saving debug output.
343
344 Returns:
345 List[BTGroup]: list of dicts of text rendered by each BT operator
346
347 """
348 state_mgr = TextStateManager() # transformation stack manager
349 bt_groups: list[BTGroup] = [] # BT operator dict
350 tj_ops: list[TextStateParams] = [] # Tj/TJ operator data
351 for operands, op in ops:
352 if op in (b"BT", b"q"):
353 bts, tjs = recurse_to_target_op(
354 ops, state_mgr, b"ET" if op == b"BT" else b"Q", fonts, strip_rotated
355 )
356 bt_groups.extend(bts)
357 tj_ops.extend(tjs)
358 elif op == b"Tf":
359 set_font_operation(state_mgr, fonts, operands)
360 else: # set Tc, Tw, Tz, TL, and Ts if required. ignores all other ops
361 state_mgr.set_state_param(op, operands)
362
363 if any(tj.rotated for tj in tj_ops):
364 if strip_rotated:
365 logger_warning(
366 "Rotated text discovered. Output will be incomplete.", source=__name__
367 )
368 else:
369 logger_warning(
370 "Rotated text discovered. Layout will be degraded.", source=__name__
371 )
372 if not all(tj.font.interpretable for tj in tj_ops):
373 logger_warning(
374 "PDF contains an uninterpretable font. Output will be incomplete.", source=__name__
375 )
376
377 # left align the data, i.e. decrement all tx values by min(tx)
378 min_x = min((x["tx"] for x in bt_groups), default=0.0)
379 bt_groups = [
380 dict(ogrp, tx=ogrp["tx"] - min_x, displaced_tx=ogrp["displaced_tx"] - min_x) # type: ignore[misc]
381 for ogrp in sorted(
382 bt_groups, key=lambda x: (x["ty"] * x["flip_sort"], -x["tx"]), reverse=True
383 )
384 ]
385
386 if debug_path: # pragma: no cover
387 import json # noqa: PLC0415
388
389 debug_path.joinpath("bts.json").write_text(
390 json.dumps(bt_groups, indent=2, default=str), "utf-8"
391 )
392 debug_path.joinpath("tjs.json").write_text(
393 json.dumps(
394 tj_ops, indent=2, default=lambda x: getattr(x, "to_dict", str)(x)
395 ),
396 "utf-8",
397 )
398 return bt_groups
399
400
401def fixed_char_width(bt_groups: list[BTGroup], scale_weight: float = 1.25) -> float:
402 """
403 Calculate average character width weighted by the length of the rendered
404 text in each sample for conversion to fixed-width layout.
405
406 Args:
407 bt_groups (List[BTGroup]): List of dicts of text rendered by each
408 BT operator
409
410 Returns:
411 float: fixed character width
412
413 """
414 char_widths = []
415 for _bt in bt_groups:
416 _len = len(_bt["text"]) * scale_weight
417 char_widths.append(((_bt["displaced_tx"] - _bt["tx"]) / _len, _len))
418 return sum(_w * _l for _w, _l in char_widths) / sum(_l for _, _l in char_widths)
419
420
421def fixed_width_page(
422 ty_groups: dict[int, list[BTGroup]], char_width: float, space_vertically: bool, font_height_weight: float
423) -> str:
424 """
425 Generate page text from text operations grouped by rendered y coordinate.
426
427 Args:
428 ty_groups: dict of text show ops as returned by y_coordinate_groups()
429 char_width: fixed character width
430 space_vertically: include blank lines inferred from y distance + font height.
431 font_height_weight: multiplier for font height when calculating blank lines.
432
433 Returns:
434 str: page text in a fixed width format that closely adheres to the rendered
435 layout in the source pdf.
436
437 """
438 lines: list[str] = []
439 last_y_coord = 0
440 table = str.maketrans(dict.fromkeys(range(14, 32), " "))
441 for y_coord, line_data in ty_groups.items():
442 if space_vertically and lines:
443 fh = line_data[0]["font_height"]
444 blank_lines = 0 if fh == 0 else (
445 int(abs(y_coord - last_y_coord) / (fh * font_height_weight)) - 1
446 )
447 if blank_lines > NEWLINE_LIMIT:
448 logger_warning(
449 "Limiting excessive newlines from %(actual)d to %(limit)d.",
450 actual=blank_lines, limit=NEWLINE_LIMIT, source=__name__
451 )
452 blank_lines = NEWLINE_LIMIT
453 lines.extend([""] * blank_lines)
454
455 line_parts = [] # It uses a list to construct the line, avoiding string concatenation.
456 current_len = 0 # Track the size with int instead of len(str) overhead.
457 last_disp = 0.0
458 for bt_op in line_data:
459 tx = bt_op["tx"]
460 # Text drawn with no width (a font size or horizontal scaling of 0) has no column to align to.
461 offset = int(tx // char_width) if char_width else current_len
462 needed_spaces = offset - current_len
463 if needed_spaces > 0 and ceil(last_disp) < int(tx):
464 if needed_spaces > WHITESPACE_LIMIT:
465 logger_warning(
466 "Limiting excessive whitespace from %(actual)d to %(limit)d characters.",
467 actual=needed_spaces, limit=WHITESPACE_LIMIT, source=__name__
468 )
469 needed_spaces = WHITESPACE_LIMIT
470 padding = " " * needed_spaces
471 line_parts.append(padding)
472 current_len += needed_spaces
473
474 raw_text = bt_op["text"]
475 text = raw_text.translate(table)
476 line_parts.append(text)
477 current_len += len(text)
478 last_disp = bt_op["displaced_tx"]
479
480 full_line = "".join(line_parts).rstrip()
481 if full_line.strip() or (space_vertically and lines):
482 lines.append(full_line)
483
484 last_y_coord = y_coord
485
486 return "\n".join(lines)