1# Copyright (c) 2006, Mathieu Fenniak
2# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3#
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10# * Redistributions of source code must retain the above copyright notice,
11# this list of conditions and the following disclaimer.
12# * Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation
14# and/or other materials provided with the distribution.
15# * The name of the author may not be used to endorse or promote products
16# derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29
30from collections.abc import Callable
31from typing import Any
32
33from .._codecs import encoding_dict_from_named_encoding
34from ..generic import DictionaryObject, TextStringObject
35from ..generic._font import Font, FontDescriptor
36from . import OrientationNotFoundError, crlf_space_check, get_display_str, get_text_operands, mult
37
38
39def _get_number_operand(operands: list[Any], index: int, default: float) -> float:
40 """Return the operand at index as a float, or default if it is missing or not a number."""
41 if index < len(operands) and isinstance(operands[index], (int, float)):
42 return float(operands[index])
43 return default
44
45
46class TextExtraction:
47 """
48 A class to handle PDF text extraction operations.
49
50 This class encapsulates all the state and operations needed for extracting
51 text from PDF content streams, replacing the nested functions and nonlocal
52 variables in the original implementation.
53 """
54
55 def __init__(self) -> None:
56 # Text extraction state variables
57 self.cm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
58 self.tm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
59 self.cm_stack: list[
60 tuple[
61 list[float],
62 DictionaryObject | None,
63 Font,
64 float,
65 float,
66 float,
67 float,
68 ]
69 ] = []
70
71 # Store the last modified matrices; can be an intermediate position
72 self.cm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
73 self.tm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
74
75 # Store the position at the beginning of building the text
76 self.memo_cm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
77 self.memo_tm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
78
79 self.char_scale = 1.0
80 self.space_scale = 1.0
81 self._space_width: float = 500.0 # will be set correctly at first Tf
82 self._actual_str_size: dict[str, float] = {
83 "str_widths": 0.0,
84 "str_height": 0.0,
85 } # will be set to string length calculation result
86 self.TL = 0.0
87 self.font_size = 12.0 # init just in case of
88 # (axis index, min, max) of baselines kept on the current extracted line.
89 self._line_span: tuple[int, float, float] | None = None
90
91 # Text extraction variables
92 self.text: str = ""
93 self.output: str = ""
94 self.rtl_dir: bool = False # right-to-left
95 self.font_resource: DictionaryObject | None = None
96 self.font = Font(
97 name = "NotInitialized",
98 sub_type="Unknown",
99 encoding=encoding_dict_from_named_encoding("cp1252"), # WinAnsiEncoding
100 font_descriptor=FontDescriptor(),
101 )
102 self.orientations: tuple[int, ...] = (0, 90, 180, 270)
103 self.visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None
104 self.font_resources: dict[str, DictionaryObject] = {}
105 self.fonts: dict[str, Font] = {}
106
107 self.operation_handlers = {
108 b"BT": self._handle_bt,
109 b"ET": self._handle_et,
110 b"q": self._handle_save_graphics_state,
111 b"Q": self._handle_restore_graphics_state,
112 b"cm": self._handle_cm,
113 b"Tz": self._handle_tz,
114 b"Tw": self._handle_tw,
115 b"TL": self._handle_tl,
116 b"Tf": self._handle_tf,
117 b"Td": self._handle_td,
118 b"Tm": self._handle_tm,
119 b"T*": self._handle_t_star,
120 b"Tj": self._handle_tj_operation,
121 }
122
123 def initialize_extraction(
124 self,
125 orientations: tuple[int, ...] = (0, 90, 180, 270),
126 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
127 font_resources: dict[str, DictionaryObject] | None = None,
128 fonts: dict[str, Font] | None = None
129 ) -> None:
130 """Initialize the extractor with extraction parameters."""
131 self.orientations = orientations
132 self.visitor_text = visitor_text
133 self.font_resources = font_resources or {}
134 self.fonts = fonts or {}
135
136 # Reset state
137 self.text = ""
138 self.output = ""
139 self.rtl_dir = False
140 self._line_span = None
141
142 def compute_str_widths(self, str_widths: float) -> float:
143 return str_widths / 1000
144
145 def process_operation(self, operator: bytes, operands: list[Any]) -> None:
146 if operator in self.operation_handlers:
147 handler = self.operation_handlers[operator]
148 str_widths = handler(operands)
149
150 # Post-process operations that affect text positioning
151 if operator in {b"Td", b"Tm", b"T*", b"Tj"}:
152 self._post_process_text_operation(str_widths or 0.0)
153
154 def _post_process_text_operation(self, str_widths: float) -> None:
155 """Handle common post-processing for text positioning operations."""
156 text_was_empty = self.text == ""
157 try:
158 self.text, self.output, self.cm_prev, self.tm_prev, self._line_span = crlf_space_check(
159 self.text,
160 (self.cm_prev, self.tm_prev),
161 (self.cm_matrix, self.tm_matrix),
162 (self.memo_cm, self.memo_tm),
163 self.font_resource,
164 self.orientations,
165 self.output,
166 self.font_size,
167 self.visitor_text,
168 str_widths,
169 self.compute_str_widths(self.font_size * self._space_width),
170 self._actual_str_size["str_height"],
171 self._line_span,
172 )
173 if text_was_empty or self.text == "":
174 self.memo_cm = self.cm_matrix.copy()
175 self.memo_tm = self.tm_matrix.copy()
176 except OrientationNotFoundError:
177 pass
178
179 def _handle_tj(
180 self,
181 text: str,
182 operands: list[str | TextStringObject],
183 cm_matrix: list[float],
184 tm_matrix: list[float],
185 font_resource: DictionaryObject | None,
186 font: Font,
187 orientations: tuple[int, ...],
188 font_size: float,
189 rtl_dir: bool,
190 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None,
191 actual_str_size: dict[str, float],
192 ) -> tuple[str, bool, dict[str, float]]:
193 text_operands, is_str_operands, font_widths = get_text_operands(
194 operands, cm_matrix, tm_matrix, font, orientations
195 )
196 if is_str_operands:
197 text += text_operands
198 else:
199 text, rtl_dir, completed = get_display_str(
200 text,
201 cm_matrix,
202 tm_matrix, # text matrix
203 font_resource,
204 font,
205 text_operands,
206 font_size,
207 rtl_dir,
208 visitor_text,
209 )
210 self.output += completed
211 actual_str_size["str_widths"] += font_widths * font_size
212 actual_str_size["str_height"] = font_size
213 return text, rtl_dir, actual_str_size
214
215 def _flush_text(self) -> None:
216 """Flush accumulated text to output and call visitor if present."""
217 self.output += self.text
218 if self.visitor_text is not None:
219 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
220 self.text = ""
221 self.memo_cm = self.cm_matrix.copy()
222 self.memo_tm = self.tm_matrix.copy()
223
224 # Operation handlers
225
226 def _handle_bt(self, operands: list[Any]) -> None:
227 """Handle BT (Begin Text) operation - Table 5.4 page 405."""
228 self.tm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
229 self._flush_text()
230
231 def _handle_et(self, operands: list[Any]) -> None:
232 """Handle ET (End Text) operation - Table 5.4 page 405."""
233 self._flush_text()
234
235 def _handle_save_graphics_state(self, operands: list[Any]) -> None:
236 """Handle q (Save graphics state) operation - Table 4.7 page 219."""
237 self.cm_stack.append(
238 (
239 self.cm_matrix,
240 self.font_resource,
241 self.font,
242 self.font_size,
243 self.char_scale,
244 self.space_scale,
245 self.TL,
246 )
247 )
248
249 def _handle_restore_graphics_state(self, operands: list[Any]) -> None:
250 """Handle Q (Restore graphics state) operation - Table 4.7 page 219."""
251 try:
252 (
253 self.cm_matrix,
254 self.font_resource,
255 self.font,
256 self.font_size,
257 self.char_scale,
258 self.space_scale,
259 self.TL,
260 ) = self.cm_stack.pop()
261 except MemoryError: # pragma: no cover # TODO: BLE001
262 raise
263 except Exception:
264 self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
265
266 def _handle_cm(self, operands: list[Any]) -> None:
267 """Handle cm (Modify current matrix) operation - Table 4.7 page 219."""
268 self.output += self.text
269 if self.visitor_text is not None:
270 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
271 self.text = ""
272 try:
273 self.cm_matrix = mult([float(operand) for operand in operands[:6]], self.cm_matrix)
274 except MemoryError: # pragma: no cover # TODO: BLE001
275 raise
276 except Exception:
277 self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
278 self.memo_cm = self.cm_matrix.copy()
279 self.memo_tm = self.tm_matrix.copy()
280
281 def _handle_tz(self, operands: list[Any]) -> None:
282 """Handle Tz (Set horizontal text scaling) operation - Table 5.2 page 398."""
283 self.char_scale = _get_number_operand(operands, 0, 100.0) / 100
284
285 def _handle_tw(self, operands: list[Any]) -> None:
286 """Handle Tw (Set word spacing) operation - Table 5.2 page 398."""
287 self.space_scale = 1.0 + _get_number_operand(operands, 0, 0.0)
288
289 def _handle_tl(self, operands: list[Any]) -> None:
290 """Handle TL (Set Text Leading) operation - Table 5.2 page 398."""
291 # The leading is measured in unscaled text space units (PDF 32000-1, 9.3.5)
292 # and T* applies the text matrix to it, so it must not be scaled here.
293 self.TL = _get_number_operand(operands, 0, 0.0)
294
295 def _handle_tf(self, operands: list[Any]) -> None:
296 """Handle Tf (Set font size) operation - Table 5.2 page 398."""
297 if self.text != "":
298 self.output += self.text # .translate(cmap)
299 if self.visitor_text is not None:
300 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
301 self.text = ""
302 self.memo_cm = self.cm_matrix.copy()
303 self.memo_tm = self.tm_matrix.copy()
304 try:
305 self.font_resource = self.font_resources[operands[0]]
306 self.font = self.fonts[operands[0]]
307 except (KeyError, IndexError): # font not found / operand missing
308 self.font_resource = None
309 font_descriptor = FontDescriptor()
310 self.font = Font(
311 "Unknown",
312 space_width=250,
313 encoding=dict.fromkeys(range(256), "�"),
314 font_descriptor=font_descriptor,
315 character_map={},
316 )
317
318 self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space...
319 try:
320 self.font_size = float(operands[1])
321 except MemoryError: # pragma: no cover # TODO: BLE001
322 raise
323 except Exception:
324 pass # keep previous size
325
326 def _handle_td(self, operands: list[Any]) -> float:
327 """Handle Td (Move text position) operation - Table 5.5 page 406."""
328 # A special case is a translating only tm:
329 # tm = [1, 0, 0, 1, e, f]
330 # i.e. tm[4] += tx, tm[5] += ty.
331 tx = _get_number_operand(operands, 0, 0.0)
332 ty = _get_number_operand(operands, 1, 0.0)
333 self.tm_matrix[4] += tx * self.tm_matrix[0] + ty * self.tm_matrix[2]
334 self.tm_matrix[5] += tx * self.tm_matrix[1] + ty * self.tm_matrix[3]
335 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
336 self._actual_str_size["str_widths"] = 0.0
337 return str_widths
338
339 def _handle_tm(self, operands: list[Any]) -> float:
340 """Handle Tm (Set text matrix) operation - Table 5.5 page 406."""
341 try:
342 tm_matrix = [float(operand) for operand in operands[:6]]
343 except (TypeError, ValueError):
344 tm_matrix = []
345 # Fall back to the identity matrix when Tm carries the wrong number of
346 # operands, mirroring _handle_cm, so the text matrix stays a six-element
347 # list and later positioning operators do not read past its end.
348 self.tm_matrix = tm_matrix if len(tm_matrix) == 6 else [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
349 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
350 self._actual_str_size["str_widths"] = 0.0
351 return str_widths
352
353 def _handle_t_star(self, operands: list[Any]) -> float:
354 """Handle T* (Move to next line) operation - Table 5.5 page 406."""
355 self.tm_matrix[4] -= self.TL * self.tm_matrix[2]
356 self.tm_matrix[5] -= self.TL * self.tm_matrix[3]
357 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
358 self._actual_str_size["str_widths"] = 0.0
359 return str_widths
360
361 def _handle_tj_operation(self, operands: list[Any]) -> float:
362 """Handle Tj (Show text) operation - Table 5.5 page 406."""
363 if not operands or not isinstance(operands[0], (str, bytes)):
364 return 0.0
365 self.text, self.rtl_dir, self._actual_str_size = self._handle_tj(
366 self.text,
367 operands,
368 self.cm_matrix,
369 self.tm_matrix,
370 self.font_resource,
371 self.font,
372 self.orientations,
373 self.font_size,
374 self.rtl_dir,
375 self.visitor_text,
376 self._actual_str_size,
377 )
378 return 0.0 # str_widths will be handled in post-processing