1"""manage the PDF transform stack during "layout" mode text extraction"""
2
3from collections import ChainMap, Counter
4from collections import ChainMap as ChainMapType
5from collections import Counter as CounterType
6from collections.abc import MutableMapping
7from typing import Any, Literal, Union
8
9from ...errors import PdfReadError
10from ...generic._font import Font
11from .. import mult
12from ._text_state_params import TextStateParams
13
14TextStateManagerKeyType = Union[int, Literal["is_text", "is_render"]]
15TextStateManagerChainMapType = ChainMapType[TextStateManagerKeyType, Union[float, bool]]
16TextStateManagerDictType = MutableMapping[TextStateManagerKeyType, Union[float, bool]]
17
18
19class TextStateManager:
20 """
21 Tracks the current text state including cm/tm/trm transformation matrices.
22
23 Attributes:
24 transform_stack (ChainMap): ChainMap of cm/tm transformation matrices
25 q_queue (Counter[int]): Counter of q operators
26 q_depth (List[int]): list of q operator nesting levels
27 Tc (float): character spacing
28 Tw (float): word spacing
29 Tz (int): horizontal scaling
30 TL (float): leading
31 Ts (float): text rise
32 font (Font): font object
33 font_size (int | float): font size
34
35 """
36
37 def __init__(self) -> None:
38 self.transform_stack: TextStateManagerChainMapType = ChainMap(
39 self.new_transform()
40 )
41 self.q_queue: CounterType[int] = Counter()
42 self.q_depth = [0]
43 self.Tc: float = 0.0
44 self.Tw: float = 0.0
45 self.Tz: float = 100.0
46 self.TL: float = 0.0
47 self.Ts: float = 0.0
48 self.font_stack: list[tuple[Font | None, int | float]] = []
49 self.font: Font | None = None
50 self.font_size: int | float = 0
51
52 def set_state_param(self, op: bytes, value: float | list[Any]) -> None:
53 """
54 Set a text state parameter. Supports Tc, Tz, Tw, TL, and Ts operators.
55
56 Args:
57 op: operator read from PDF stream as bytes. No action is taken
58 for unsupported operators (see supported operators above).
59 value (float | List[Any]): new parameter value. If a list,
60 value[0] is used.
61
62 """
63 if op not in [b"Tc", b"Tz", b"Tw", b"TL", b"Ts"]:
64 return
65 name = op.decode()
66 raw = (value[0] if value else None) if isinstance(value, list) else value
67 # a missing or non-numeric operand (e.g. a name from a malformed content
68 # stream) leaves the parameter unchanged, matching the ROB handling of Td/Tm/Tf
69 self.__setattr__(name, self._as_float(raw, getattr(self, name)))
70
71 def set_font(self, font: Font, size: float) -> None:
72 """
73 Set the current font and font_size.
74
75 Args:
76 font (Font): a layout mode Font
77 size (float): font size
78
79 """
80 self.font = font
81 self.font_size = size
82
83 def text_state_params(self, value: bytes | str = "") -> TextStateParams:
84 """
85 Create a TextStateParams instance to display a text string. Type[bytes] values
86 will be decoded implicitly.
87
88 Args:
89 value (str | bytes): text to associate with the captured state.
90
91 Raises:
92 PdfReadError: if font not set (no Tf operator in incoming pdf content stream)
93
94 Returns:
95 TextStateParams: current text state parameters
96
97 """
98 if not isinstance(self.font, Font):
99 raise PdfReadError(
100 "font not set: is PDF missing a Tf operator?"
101 ) # pragma: no cover
102 return TextStateParams(
103 value,
104 self.font,
105 self.font_size,
106 self.Tc,
107 self.Tw,
108 self.Tz,
109 self.TL,
110 self.Ts,
111 self.effective_transform,
112 )
113
114 @staticmethod
115 def _as_float(value: Any, default: float = 0.0) -> float:
116 """An operand as a float, or default if it is not a number
117 (e.g. a name from a malformed content stream).
118 """
119 try:
120 return float(value)
121 except (TypeError, ValueError):
122 return default
123
124 @staticmethod
125 def raw_transform(
126 _a: float = 1.0,
127 _b: float = 0.0,
128 _c: float = 0.0,
129 _d: float = 1.0,
130 _e: float = 0.0,
131 _f: float = 0.0,
132 ) -> TextStateManagerDictType:
133 """Only a/b/c/d/e/f matrix params"""
134 defaults = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
135 values = (_a, _b, _c, _d, _e, _f)
136 return dict(zip(range(6), (TextStateManager._as_float(v, d) for v, d in zip(values, defaults))))
137
138 @staticmethod
139 def new_transform(
140 _a: float = 1.0,
141 _b: float = 0.0,
142 _c: float = 0.0,
143 _d: float = 1.0,
144 _e: float = 0.0,
145 _f: float = 0.0,
146 *,
147 is_text: bool = False,
148 is_render: bool = False,
149 ) -> TextStateManagerDictType:
150 """Standard a/b/c/d/e/f matrix params + 'is_text' and 'is_render' keys"""
151 result = TextStateManager.raw_transform(_a, _b, _c, _d, _e, _f)
152 result.update({"is_text": is_text, "is_render": is_render})
153 return result
154
155 def reset_tm(self) -> TextStateManagerChainMapType:
156 """Clear all transforms from chainmap having is_text==True or is_render==True"""
157 while (
158 self.transform_stack.maps[0]["is_text"]
159 or self.transform_stack.maps[0]["is_render"]
160 ):
161 self.transform_stack = self.transform_stack.parents
162 return self.transform_stack
163
164 def reset_trm(self) -> TextStateManagerChainMapType:
165 """Clear all transforms from chainmap having is_render==True"""
166 while self.transform_stack.maps[0]["is_render"]:
167 self.transform_stack = self.transform_stack.parents
168 return self.transform_stack
169
170 def remove_q(self) -> TextStateManagerChainMapType:
171 """Rewind to stack prior state after closing a 'q' with internal 'cm' ops"""
172 self.font, self.font_size = self.font_stack.pop(-1)
173 self.transform_stack = self.reset_tm()
174 self.transform_stack.maps = self.transform_stack.maps[
175 self.q_queue.pop(self.q_depth.pop(), 0) :
176 ]
177 return self.transform_stack
178
179 def add_q(self) -> None:
180 """Add another level to q_queue"""
181 self.font_stack.append((self.font, self.font_size))
182 self.q_depth.append(len(self.q_depth))
183
184 def add_cm(self, *args: Any) -> TextStateManagerChainMapType:
185 """Concatenate an additional transform matrix"""
186 self.transform_stack = self.reset_tm()
187 self.q_queue.update(self.q_depth[-1:])
188 self.transform_stack = self.transform_stack.new_child(self.new_transform(*args))
189 return self.transform_stack
190
191 def _complete_matrix(self, operands: list[float]) -> list[float]:
192 """Adds a, b, c, and d to an "e/f only" operand set (e.g Td)"""
193 if len(operands) == 2: # this is a Td operator or equivalent
194 operands = [1.0, 0.0, 0.0, 1.0, *operands]
195 return operands
196
197 def add_tm(self, operands: list[float]) -> TextStateManagerChainMapType:
198 """Append a text transform matrix"""
199 # Build a new text transformation matrix from the supplied operands.
200 new_child = self.new_transform(*self._complete_matrix(operands), is_text=True)
201 # Get the most recently added transformation from the stack.
202 top = self.transform_stack.maps[0]
203
204 # If the current transformation is a text matrix and is not a rendering
205 # transformation, combine the matrices instead of adding another stack
206 # entry. This prevents unnecessary growth of the transform stack.
207 # Non-rendering transformations do not emit anything and thus can be merged.
208 if top.get("is_text") and not top.get("is_render"):
209 # Multiply the new matrix by the current top matrix, preserving the
210 # transformation order used when a new stack entry would be pushed.
211 combined = mult(list(new_child.values()), top)
212 # Replace the current top entry with the combined transformation.
213 # The existing stack structure is preserved rather than extended.
214 self.transform_stack.maps[0] = self.new_transform(*combined, is_text=True)
215 else:
216 # If the current transformation is not a suitable text matrix to
217 # combine with, push the new transformation onto the stack as before.
218 self.transform_stack = self.transform_stack.new_child(new_child)
219 return self.transform_stack
220
221 def add_trm(self, operands: list[float]) -> TextStateManagerChainMapType:
222 """Append a text rendering transform matrix"""
223 self.transform_stack = self.transform_stack.new_child(
224 self.new_transform(
225 *self._complete_matrix(operands), is_text=True, is_render=True
226 )
227 )
228 return self.transform_stack
229
230 @property
231 def effective_transform(self) -> list[float]:
232 """Current effective transform accounting for cm, tm, and trm transforms"""
233 eff_transform = [*self.transform_stack.maps[0].values()]
234 for transform in self.transform_stack.maps[1:]:
235 eff_transform = mult(eff_transform, transform)
236 return eff_transform