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 dataclasses import dataclass
32from typing import Any, NamedTuple
33
34from .._codecs import encoding_dict_from_named_encoding
35from ..generic import DictionaryObject, TextStringObject
36from ..generic._font import Font, FontDescriptor
37from . import OrientationNotFoundError, crlf_space_check, get_display_str, get_text_operands, mult
38
39
40def _get_number_operand(operands: list[Any], index: int, default: float) -> float:
41 """Return the operand at index as a float, or default if it is missing or not a number."""
42 if index < len(operands) and isinstance(operands[index], (int, float)):
43 return float(operands[index])
44 return default
45
46
47class _FontState(NamedTuple):
48 """Font values the line and word-gap checks use for the text shown before a move."""
49
50 font_resource: DictionaryObject | None
51 font_size: float
52 space_width: float
53 str_height: float
54
55
56@dataclass
57class _PendingMove:
58 """A Td, Tm or T* that no text has been shown after yet."""
59
60 str_widths: float # Width of the text shown before the first of the moves
61 font_state: _FontState # Font values at the first of the moves
62
63
64class TextExtraction:
65 """
66 A class to handle PDF text extraction operations.
67
68 This class encapsulates all the state and operations needed for extracting
69 text from PDF content streams, replacing the nested functions and nonlocal
70 variables in the original implementation.
71 """
72
73 def __init__(self) -> None:
74 # Text extraction state variables
75 self.cm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
76 self.tm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
77 self.cm_stack: list[
78 tuple[
79 list[float],
80 DictionaryObject | None,
81 Font,
82 float,
83 float,
84 float,
85 float,
86 float,
87 ]
88 ] = []
89
90 # Store the last modified matrices; can be an intermediate position
91 self.cm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
92 self.tm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
93
94 # Store the position at the beginning of building the text
95 self.memo_cm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
96 self.memo_tm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
97
98 self.char_scale = 1.0
99 self.char_spacing = 0.0
100 self.word_spacing = 0.0
101 self._space_width: float = 500.0 # will be set correctly at first Tf
102 # Right after a Tf, a word gap is a gap in either the previous or the new font.
103 self._previous_font_space: float | None = None
104 self._actual_str_size: dict[str, float] = {
105 "str_widths": 0.0,
106 "str_height": 0.0,
107 } # will be set to string length calculation result
108 self.TL = 0.0
109 self.font_size = 12.0 # init just in case of
110 # (axis index, min, max) of baselines kept on the current extracted line.
111 self._line_span: tuple[int, float, float] | None = None
112 # A Td, Tm or T* that no text has been shown after yet, see process_operation.
113 self._pending_move: _PendingMove | None = None
114
115 # Text extraction variables
116 self.text: str = ""
117 self.output: str = ""
118 self.rtl_dir: bool = False # right-to-left
119 self.font_resource: DictionaryObject | None = None
120 self.font = Font(
121 name = "NotInitialized",
122 sub_type="Unknown",
123 encoding=encoding_dict_from_named_encoding("cp1252"), # WinAnsiEncoding
124 font_descriptor=FontDescriptor(),
125 )
126 self.orientations: tuple[int, ...] = (0, 90, 180, 270)
127 self.visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None
128 self.font_resources: dict[str, DictionaryObject] = {}
129 self.fonts: dict[str, Font] = {}
130
131 self.operation_handlers = {
132 b"BT": self._handle_bt,
133 b"ET": self._handle_et,
134 b"q": self._handle_save_graphics_state,
135 b"Q": self._handle_restore_graphics_state,
136 b"cm": self._handle_cm,
137 b"Tz": self._handle_tz,
138 b"Tc": self._handle_tc,
139 b"Tw": self._handle_tw,
140 b"TL": self._handle_tl,
141 b"Tf": self._handle_tf,
142 b"Td": self._handle_td,
143 b"Tm": self._handle_tm,
144 b"T*": self._handle_t_star,
145 b"Tj": self._handle_tj_operation,
146 }
147
148 def initialize_extraction(
149 self,
150 orientations: tuple[int, ...] = (0, 90, 180, 270),
151 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
152 font_resources: dict[str, DictionaryObject] | None = None,
153 fonts: dict[str, Font] | None = None
154 ) -> None:
155 """Initialize the extractor with extraction parameters."""
156 self.orientations = orientations
157 self.visitor_text = visitor_text
158 self.font_resources = font_resources or {}
159 self.fonts = fonts or {}
160
161 # Reset state
162 self.text = ""
163 self.output = ""
164 self.rtl_dir = False
165 self._line_span = None
166 self._pending_move = None
167
168 def compute_str_widths(self, str_widths: float) -> float:
169 return str_widths / 1000
170
171 def process_operation(self, operator: bytes, operands: list[Any]) -> None:
172 if operator in self.operation_handlers:
173 handler = self.operation_handlers[operator]
174 if operator == b"Tj" and self._pending_move is not None:
175 pending_move = self._pending_move
176 self._pending_move = None
177 self._post_process_text_operation(pending_move.str_widths, pending_move.font_state)
178 str_widths = handler(operands)
179
180 # Post-process operations that affect text positioning. A move only matters once
181 # text is shown from the new position, so it is compared then: a move that is not
182 # followed by text, like the T* that ends each text object written by ReportLab,
183 # must not break the line when the next text object continues on it.
184 # The font values are taken at the first move, as when moves were compared right away,
185 # so a smaller font set before a superscript does not make its rise a line break.
186 if operator in {b"Td", b"Tm", b"T*"}:
187 if self._pending_move is None:
188 self._pending_move = _PendingMove(str_widths or 0.0, self._font_state())
189 else:
190 self._pending_move.str_widths += str_widths or 0.0
191 elif operator == b"Tj":
192 self._post_process_text_operation(str_widths or 0.0)
193
194 def process_tj_offset(self, offset: float, space_width: float) -> None:
195 """Add a space for a word gap in a TJ array and count the offset in the text width."""
196 # The offset moved the pen, so it counts towards the width and the added space does not.
197 # Like the glyph widths, it is scaled horizontally.
198 str_widths = self._actual_str_size["str_widths"] - offset * self.font_size * self.char_scale
199 # A Tf just before this TJ has already moved the text to the output.
200 previous = self.text or self.output
201 # A positive offset moves the next glyph back (kerning), so only a negative one can be a gap.
202 if -offset >= space_width and previous and previous[-1] not in " \n":
203 self.process_operation(b"Tj", [" "])
204 self._actual_str_size["str_widths"] = str_widths
205
206 def _font_state(self) -> _FontState:
207 """Return the font values the line and word-gap checks use for the current text."""
208 space_width = self.font_size * self._space_width
209 if self._previous_font_space is not None:
210 space_width = min(space_width, self._previous_font_space)
211 return _FontState(self.font_resource, self.font_size, space_width, self._actual_str_size["str_height"])
212
213 def _post_process_text_operation(self, str_widths: float, font_state: _FontState | None = None) -> None:
214 """Handle common post-processing for text positioning operations."""
215 text_was_empty = self.text == ""
216 if font_state is None:
217 font_state = self._font_state()
218 try:
219 self.text, self.output, self.cm_prev, self.tm_prev, self._line_span = crlf_space_check(
220 self.text,
221 (self.cm_prev, self.tm_prev),
222 (self.cm_matrix, self.tm_matrix),
223 (self.memo_cm, self.memo_tm),
224 font_state.font_resource,
225 self.orientations,
226 self.output,
227 font_state.font_size,
228 self.visitor_text,
229 str_widths,
230 self.compute_str_widths(font_state.space_width),
231 font_state.str_height,
232 self._line_span,
233 )
234 if text_was_empty or self.text == "":
235 self.memo_cm = self.cm_matrix.copy()
236 self.memo_tm = self.tm_matrix.copy()
237 except OrientationNotFoundError:
238 pass
239
240 def _handle_tj(
241 self,
242 text: str,
243 operands: list[str | TextStringObject],
244 cm_matrix: list[float],
245 tm_matrix: list[float],
246 font_resource: DictionaryObject | None,
247 font: Font,
248 orientations: tuple[int, ...],
249 font_size: float,
250 rtl_dir: bool,
251 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None,
252 actual_str_size: dict[str, float],
253 ) -> tuple[str, bool, dict[str, float]]:
254 text_operands, is_str_operands, font_widths, glyph_count, space_count = get_text_operands(
255 operands, cm_matrix, tm_matrix, font, orientations
256 )
257 if is_str_operands:
258 text += text_operands
259 else:
260 text, rtl_dir, completed = get_display_str(
261 text,
262 cm_matrix,
263 tm_matrix, # text matrix
264 font_resource,
265 font,
266 text_operands,
267 font_size,
268 rtl_dir,
269 visitor_text,
270 )
271 self.output += completed
272 # Character and word spacing are given in unscaled text space units,
273 # while the widths are kept in thousandths of them. Horizontal scaling
274 # applies to the whole advance (Section 9.4.4 of the PDF 2.0 specification).
275 spacing = self.char_spacing * glyph_count + self.word_spacing * space_count
276 actual_str_size["str_widths"] += (font_widths * font_size + spacing * 1000) * self.char_scale
277 actual_str_size["str_height"] = font_size
278 return text, rtl_dir, actual_str_size
279
280 def _flush_text(self) -> None:
281 """Flush accumulated text to output and call visitor if present."""
282 self.output += self.text
283 if self.visitor_text is not None:
284 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
285 self.text = ""
286 self.memo_cm = self.cm_matrix.copy()
287 self.memo_tm = self.tm_matrix.copy()
288
289 # Operation handlers
290
291 def _handle_bt(self, operands: list[Any]) -> None:
292 """Handle BT (Begin Text) operation - Table 5.4 page 405."""
293 self.tm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
294 self._flush_text()
295
296 def _handle_et(self, operands: list[Any]) -> None:
297 """Handle ET (End Text) operation - Table 5.4 page 405."""
298 self._flush_text()
299
300 def _handle_save_graphics_state(self, operands: list[Any]) -> None:
301 """Handle q (Save graphics state) operation - Table 4.7 page 219."""
302 self.cm_stack.append(
303 (
304 self.cm_matrix,
305 self.font_resource,
306 self.font,
307 self.font_size,
308 self.char_scale,
309 self.char_spacing,
310 self.word_spacing,
311 self.TL,
312 )
313 )
314
315 def _handle_restore_graphics_state(self, operands: list[Any]) -> None:
316 """Handle Q (Restore graphics state) operation - Table 4.7 page 219."""
317 try:
318 (
319 self.cm_matrix,
320 self.font_resource,
321 self.font,
322 self.font_size,
323 self.char_scale,
324 self.char_spacing,
325 self.word_spacing,
326 self.TL,
327 ) = self.cm_stack.pop()
328 except MemoryError: # pragma: no cover # TODO: BLE001
329 raise
330 except Exception:
331 self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
332
333 def _handle_cm(self, operands: list[Any]) -> None:
334 """Handle cm (Modify current matrix) operation - Table 4.7 page 219."""
335 self.output += self.text
336 if self.visitor_text is not None:
337 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
338 self.text = ""
339 try:
340 self.cm_matrix = mult([float(operand) for operand in operands[:6]], self.cm_matrix)
341 except MemoryError: # pragma: no cover # TODO: BLE001
342 raise
343 except Exception:
344 self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
345 self.memo_cm = self.cm_matrix.copy()
346 self.memo_tm = self.tm_matrix.copy()
347
348 def _handle_tz(self, operands: list[Any]) -> None:
349 """Handle Tz (Set horizontal text scaling) operation - Table 5.2 page 398."""
350 self.char_scale = _get_number_operand(operands, 0, 100.0) / 100
351
352 def _handle_tc(self, operands: list[Any]) -> None:
353 """Handle Tc (Set character spacing) operation - Table 5.2 page 398."""
354 self.char_spacing = _get_number_operand(operands, 0, 0.0)
355
356 def _handle_tw(self, operands: list[Any]) -> None:
357 """Handle Tw (Set word spacing) operation - Table 5.2 page 398."""
358 self.word_spacing = _get_number_operand(operands, 0, 0.0)
359
360 def _handle_tl(self, operands: list[Any]) -> None:
361 """Handle TL (Set Text Leading) operation - Table 5.2 page 398."""
362 # The leading is measured in unscaled text space units (PDF 32000-1, 9.3.5)
363 # and T* applies the text matrix to it, so it must not be scaled here.
364 self.TL = _get_number_operand(operands, 0, 0.0)
365
366 def _handle_tf(self, operands: list[Any]) -> None:
367 """Handle Tf (Set font size) operation - Table 5.2 page 398."""
368 if self.text != "":
369 self._previous_font_space = self.font_size * self._space_width
370 self.output += self.text # .translate(cmap)
371 if self.visitor_text is not None:
372 self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
373 self.text = ""
374 self.memo_cm = self.cm_matrix.copy()
375 self.memo_tm = self.tm_matrix.copy()
376 try:
377 self.font_resource = self.font_resources[operands[0]]
378 self.font = self.fonts[operands[0]]
379 except (KeyError, IndexError): # font not found / operand missing
380 self.font_resource = None
381 font_descriptor = FontDescriptor()
382 self.font = Font(
383 "Unknown",
384 space_width=250,
385 encoding=dict.fromkeys(range(256), "�"),
386 font_descriptor=font_descriptor,
387 character_map={},
388 )
389
390 self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space...
391 try:
392 self.font_size = float(operands[1])
393 except MemoryError: # pragma: no cover # TODO: BLE001
394 raise
395 except Exception:
396 pass # keep previous size
397
398 def _handle_td(self, operands: list[Any]) -> float:
399 """Handle Td (Move text position) operation - Table 5.5 page 406."""
400 # A special case is a translating only tm:
401 # tm = [1, 0, 0, 1, e, f]
402 # i.e. tm[4] += tx, tm[5] += ty.
403 tx = _get_number_operand(operands, 0, 0.0)
404 ty = _get_number_operand(operands, 1, 0.0)
405 self.tm_matrix[4] += tx * self.tm_matrix[0] + ty * self.tm_matrix[2]
406 self.tm_matrix[5] += tx * self.tm_matrix[1] + ty * self.tm_matrix[3]
407 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
408 self._actual_str_size["str_widths"] = 0.0
409 return str_widths
410
411 def _handle_tm(self, operands: list[Any]) -> float:
412 """Handle Tm (Set text matrix) operation - Table 5.5 page 406."""
413 try:
414 tm_matrix = [float(operand) for operand in operands[:6]]
415 except (TypeError, ValueError):
416 tm_matrix = []
417 # Fall back to the identity matrix when Tm carries the wrong number of
418 # operands, mirroring _handle_cm, so the text matrix stays a six-element
419 # list and later positioning operators do not read past its end.
420 self.tm_matrix = tm_matrix if len(tm_matrix) == 6 else [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
421 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
422 self._actual_str_size["str_widths"] = 0.0
423 return str_widths
424
425 def _handle_t_star(self, operands: list[Any]) -> float:
426 """Handle T* (Move to next line) operation - Table 5.5 page 406."""
427 self.tm_matrix[4] -= self.TL * self.tm_matrix[2]
428 self.tm_matrix[5] -= self.TL * self.tm_matrix[3]
429 str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
430 self._actual_str_size["str_widths"] = 0.0
431 return str_widths
432
433 def _handle_tj_operation(self, operands: list[Any]) -> float:
434 """Handle Tj (Show text) operation - Table 5.5 page 406."""
435 if not operands or not isinstance(operands[0], (str, bytes)):
436 return 0.0
437 self._previous_font_space = None
438 self.text, self.rtl_dir, self._actual_str_size = self._handle_tj(
439 self.text,
440 operands,
441 self.cm_matrix,
442 self.tm_matrix,
443 self.font_resource,
444 self.font,
445 self.orientations,
446 self.font_size,
447 self.rtl_dir,
448 self.visitor_text,
449 self._actual_str_size,
450 )
451 return 0.0 # str_widths will be handled in post-processing