Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/generic/_appearance_stream.py: 16%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

367 statements  

1from __future__ import annotations 

2 

3import copy 

4from dataclasses import dataclass, field 

5from enum import IntEnum 

6from io import BytesIO 

7from operator import attrgetter 

8from typing import TYPE_CHECKING, Any, NamedTuple, cast 

9 

10from .._codecs import encoding_dict_from_named_encoding 

11from .._codecs.core_font_metrics import CORE_FONT_METRICS 

12from .._page import Transformation 

13from .._utils import is_char_rtl, logger_warning 

14from ..constants import AnnotationDictionaryAttributes, BorderStyles, FieldDictionaryAttributes, PageAttributes 

15from ..errors import PdfReadError 

16from ..generic import ( 

17 ArrayObject, 

18 ContentStream, 

19 DecodedStreamObject, 

20 DictionaryObject, 

21 FloatObject, 

22 IndirectObject, 

23 NameObject, 

24 NumberObject, 

25 RectangleObject, 

26 StreamObject, 

27) 

28from ..generic._base import ByteStringObject, TextStringObject 

29from ._color import Color, DeviceGray 

30from ._font import Font 

31 

32if TYPE_CHECKING: 

33 from pypdf._writer import PdfWriter 

34 

35 from .._page import PageObject 

36 

37try: 

38 import arabic_reshaper 

39 from bidi.algorithm import get_display 

40 HAS_RTL_SUPPORT = True 

41except ImportError: 

42 HAS_RTL_SUPPORT = False 

43 

44DEFAULT_FONT_SIZE_IN_MULTILINE = 12 

45 

46# "The glyph widths shall be measured in units in which 1000 units correspond to 1 unit in text space" 

47# (Table 111, PDF Specification 2.0) 

48TEXT_SPACE_TO_GLYPH_SPACE_FACTOR = 1000 

49 

50 

51@dataclass 

52class BaseStreamConfig: 

53 """A container representing the basic layout of an appearance stream.""" 

54 rectangle: RectangleObject = field(default_factory=lambda: RectangleObject((0.0, 0.0, 0.0, 0.0))) 

55 border_width: int = 1 # The width of the border in points 

56 border_style: str = BorderStyles.SOLID 

57 border_color: Color | None = None 

58 background_color: Color | None = None 

59 rotation: int = 0 

60 

61 

62class BaseStreamAppearance(DecodedStreamObject): 

63 """A class representing the very base of an appearance stream, that is, a rectangle and a border.""" 

64 

65 def _add_matrix(self, rotation: int) -> None: 

66 # We need to rotate our rectangle while keeping its origin to (0, 0). 

67 # Rotation goes counterclockwise. We want to know the furthest points to which we rotated left and down. 

68 # These will serve as our X and Y offsets to translate the entire object origin back to (0, 0). 

69 # If a corner rotates into negative space, that is our offset. If none does, the minimum is 0.0. 

70 matrix = Transformation().rotate(rotation) 

71 bottom_right_corner = (self._layout.rectangle.width, 0.0) 

72 top_left_corner = (0.0, self._layout.rectangle.height) 

73 top_right_corner = (self._layout.rectangle.width, self._layout.rectangle.height) 

74 rotated_bottom_right_corner = matrix.apply_on(bottom_right_corner) 

75 rotated_top_left_corner = matrix.apply_on(top_left_corner) 

76 rotated_top_right_corner = matrix.apply_on(top_right_corner) 

77 translation_x_offset = -min( 

78 0.0, rotated_bottom_right_corner[0], rotated_top_left_corner[0], rotated_top_right_corner[0] 

79 ) 

80 translation_y_offset = -min( 

81 0.0, rotated_bottom_right_corner[1], rotated_top_left_corner[1], rotated_top_right_corner[1] 

82 ) 

83 matrix = matrix.translate(translation_x_offset, translation_y_offset) 

84 self[NameObject("/Matrix")] = ArrayObject([FloatObject(round(i, 3)) for i in matrix.ctm]) 

85 

86 def _new_for_clone(self) -> BaseStreamAppearance: 

87 """Instantiate a blank object for ``clone()`` without running ``__init__``. 

88 

89 ``BaseStreamAppearance`` inherits this method from ``DictionaryObject``. 

90 ``DictionaryObject._new_for_clone`` checks whether a subclass requires 

91 constructor arguments and skips ``__init__`` for those that do. 

92 ``TextStreamAppearance.__init__`` can be called without constructor 

93 arguments, but running it during ``clone()`` would populate default 

94 dictionary entries and a default content stream that pollute the clone. 

95 This override calls ``__new__`` directly so cloning starts from an empty 

96 object. 

97 """ 

98 return self.__class__.__new__(self.__class__) 

99 

100 def __init__(self, layout: BaseStreamConfig | None) -> None: 

101 """ 

102 Takes the appearance stream layout as an argument. 

103 

104 Args: 

105 layout: The basic layout parameters. 

106 """ 

107 super().__init__() 

108 self._layout = layout or BaseStreamConfig() 

109 self[NameObject("/Type")] = NameObject("/XObject") 

110 self[NameObject("/Subtype")] = NameObject("/Form") 

111 self[NameObject("/BBox")] = self._layout.rectangle 

112 

113 # Define the rotation matrix 

114 rotation = self._layout.rotation % 360 

115 if rotation: 

116 self._add_matrix(rotation) 

117 

118 ap_stream_parts = [] 

119 # Only add a background color when color is defined and not transparent 

120 if isinstance(self._layout.background_color, Color): 

121 ap_stream_parts.append( 

122 f"0 0 {self._layout.rectangle.width} {self._layout.rectangle.height} re\n" 

123 f"{self._layout.background_color.as_operator()}\n" 

124 "f\n" 

125 ) 

126 # Only add a border when border width is larger than 0, border 

127 # color is defined, and border color is not set to transparent. 

128 if self._layout.border_width > 0: 

129 if isinstance(self._layout.border_color, Color): 

130 border_width_string = f"{self._layout.border_width} w\n" if self._layout.border_width != 1 else "" 

131 ap_stream_parts.append( 

132 f"{self._layout.border_width} " 

133 f"{self._layout.border_width} " 

134 f"{self._layout.rectangle.width - 2 * self._layout.border_width} " 

135 f"{self._layout.rectangle.height - 2 * self._layout.border_width} re\n" 

136 f"{border_width_string}" 

137 f"{self._layout.border_color.as_operator(stroke=True)}\n" 

138 "s\n" 

139 ) 

140 else: 

141 # If we aren't drawing a border, then set border_width to 0. This means less margin to 

142 # take into account and results in larger font sizes. 

143 self._layout.border_width = 0 

144 if ap_stream_parts: 

145 ap_stream_parts.insert(0, "q\n") 

146 ap_stream_parts.append("Q\n") 

147 self._ap_stream_data = "".join(ap_stream_parts).encode() 

148 

149 

150class TextAlignment(IntEnum): 

151 """Defines the alignment options for text within a form field's appearance stream.""" 

152 

153 LEFT = 0 

154 CENTER = 1 

155 RIGHT = 2 

156 

157 

158class WidthWordGlyphs(NamedTuple): 

159 """A tuple of the unscaled width of a word (unencoded text) and the font-encoded glyphs that represent it.""" 

160 

161 width: float 

162 word: str 

163 glyphs: str 

164 

165 

166class TextStreamAppearance(BaseStreamAppearance): 

167 """ 

168 A class representing the appearance stream for a text-based form field. 

169 

170 This class generates the content stream (the `ap_stream_data`) that dictates 

171 how text is rendered within a form field's bounding box. It handles properties 

172 like font, font size, color, multiline text, and text selection highlighting. 

173 """ 

174 

175 def _scale_text( 

176 self, 

177 font: Font, 

178 font_size: float, 

179 leading_factor: float, 

180 field_width: float, 

181 field_height: float, 

182 paragraphs: list[list[WidthWordGlyphs]], 

183 min_font_size: float, 

184 font_size_step: float = 0.2 

185 ) -> tuple[list[WidthWordGlyphs], float]: 

186 """ 

187 Takes a piece of text and scales it to field_width or field_height, given font_name 

188 and font_size. Wraps text where necessary. 

189 

190 Args: 

191 font: The font to be used. 

192 font_size: The font size in points. 

193 leading_factor: The line distance. 

194 field_width: The width of the field in which to fit the text. 

195 field_height: The height of the field in which to fit the text. 

196 paragraphs: The list of text paragraphs to fit with the field, where each paragraph is a list 

197 of tuples of unscaled width, unencoded text, and glyphs (font-encoded text). 

198 min_font_size: The minimum font size at which to scale the text. 

199 font_size_step: The amount by which to decrement font size per step while scaling. 

200 

201 Returns: 

202 The text in the form of list of tuples, each tuple containing the length of a line 

203 and its contents, and the font_size for these lines and lengths. 

204 """ 

205 wrapped_lines = [] 

206 current_line_words: list[WidthWordGlyphs] = [] 

207 current_line_width: float = 0 

208 space_width = font.space_width * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR 

209 for paragraph in paragraphs: 

210 for i, width_word_glyphs in enumerate(paragraph): 

211 word_width = width_word_glyphs.width * font_size 

212 test_width = current_line_width + word_width + (space_width if i else 0) 

213 if test_width > field_width and current_line_words: 

214 wrapped_lines.append( 

215 WidthWordGlyphs( 

216 width=current_line_width, 

217 word=" ".join(map(attrgetter("word"), current_line_words)), 

218 glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words)) 

219 ) 

220 ) 

221 current_line_words = [width_word_glyphs] 

222 current_line_width = word_width 

223 elif not current_line_words and word_width > field_width: 

224 wrapped_lines.append( 

225 WidthWordGlyphs( 

226 width=word_width, 

227 word=width_word_glyphs.word, 

228 glyphs=width_word_glyphs.glyphs 

229 ) 

230 ) 

231 current_line_words = [] 

232 current_line_width = 0 

233 else: 

234 if current_line_words: 

235 current_line_width += space_width 

236 current_line_words.append(width_word_glyphs) 

237 current_line_width += word_width 

238 if current_line_words: 

239 wrapped_lines.append(WidthWordGlyphs( 

240 width=current_line_width, 

241 word=" ".join(map(attrgetter("word"), current_line_words)), 

242 glyphs=font.space_char.join(map(attrgetter("glyphs"), current_line_words)) 

243 )) 

244 current_line_words = [] 

245 current_line_width = 0 

246 # Estimate total height. 

247 estimated_total_height = font_size + (len(wrapped_lines) - 1) * leading_factor * font_size 

248 if estimated_total_height > field_height: 

249 # Text overflows height; Retry with smaller font size. 

250 new_font_size = font_size - font_size_step 

251 if new_font_size >= min_font_size: 

252 return self._scale_text( 

253 font, 

254 new_font_size, 

255 leading_factor, 

256 field_width, 

257 field_height, 

258 paragraphs, 

259 min_font_size, 

260 font_size_step 

261 ) 

262 return wrapped_lines, round(font_size, 1) 

263 

264 def _generate_appearance_stream_data( 

265 self, 

266 text: str, 

267 selection: list[str] | None , 

268 font: Font, 

269 font_name: str = "/Helv", 

270 font_size: float = 0.0, 

271 font_color: Color | None = None, 

272 is_multiline: bool = False, 

273 alignment: TextAlignment = TextAlignment.LEFT, 

274 is_comb: bool = False, 

275 max_length: int | None = None 

276 ) -> bytes: 

277 """ 

278 Generates the raw bytes of the PDF appearance stream for a text field. 

279 

280 This private method assembles the PDF content stream operators to draw 

281 the provided text within the specified rectangle. It handles text positioning, 

282 font application, color, and special formatting like selected text. 

283 

284 Args: 

285 text: The text to be rendered in the form field. 

286 selection: An optional list of strings that should be highlighted as selected. 

287 font: The font to use. 

288 font_name: The name of the font resource to use (e.g., "/Helv"). 

289 font_size: The font size. If 0, it is automatically calculated 

290 based on whether the field is multiline or not. 

291 font_color: The color to apply to the font, represented as a class Color 

292 is_multiline: A boolean indicating if the text field is multiline. 

293 alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER. 

294 is_comb: Boolean that designates fixed-length fields, where every character 

295 fills one "cell", such as in a postcode. 

296 max_length: Used if is_comb is set. The maximum number of characters for a fixed- 

297 length field. 

298 

299 Returns: 

300 A byte string containing the PDF content stream data. 

301 

302 """ 

303 font_color = font_color or DeviceGray() 

304 rectangle = self._layout.rectangle 

305 leading_factor = ( 

306 (font.font_descriptor.bbox[3] - font.font_descriptor.bbox[1]) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR 

307 ) 

308 

309 # Set margins based on border width and style 

310 factor = 2 if self._layout.border_style in {"/B", "/I"} else 1 

311 margin = self._layout.border_width * factor 

312 field_height = rectangle.height - 2 * margin 

313 field_width = rectangle.width - 4 * max(margin, 1) 

314 

315 reverse_cmap, encoding_cmap = font._get_typographic_maps() 

316 

317 def _unicode_to_glyph_id(text: str, reverse_cmap: dict[str, str]) -> str: 

318 if HAS_RTL_SUPPORT: 

319 # Use arabic-reshaper and python-bidi to rearrange and shape text for the PDF engine 

320 reshaped_text = arabic_reshaper.reshape(text) 

321 visual_text = get_display(reshaped_text, base_dir="L") 

322 return "".join(reverse_cmap.get(char, char) for char in visual_text) 

323 

324 return "".join(reverse_cmap.get(char, char) for char in text) 

325 

326 

327 def _glyph_id_to_bytes(glyphs: str, encoding_cmap: dict[str, bytes]) -> list[bytes]: 

328 return [encoding_cmap.get( 

329 glyph_id, bytes((ord(glyph_id),)) if ord(glyph_id) < 256 else b"?" 

330 ) for glyph_id in glyphs] 

331 

332 # If font_size is 0, apply the logic for multiline or large-as-possible font 

333 if font_size == 0: 

334 min_font_size = 4.0 # The minimum font size 

335 if selection: # Don't wrap text when dealing with a /Ch field, in order to prevent problems 

336 is_multiline = False # with matching "selection" with "line" later on. 

337 if is_multiline: 

338 font_size = DEFAULT_FONT_SIZE_IN_MULTILINE 

339 # We create a list of paragraphs, here each paragraph is a list of tuples, where each WidthWordGlyphs 

340 # tuple signifies an unscaled word width, the word itself, and the glyphs that encode it. 

341 paragraphs: list[list[WidthWordGlyphs]] = [] 

342 for line in text.splitlines(): 

343 if not line.strip(): 

344 paragraphs.append([WidthWordGlyphs(width=0.0, word="", glyphs="")]) 

345 continue 

346 line_by_widths_words_glyphs: list[WidthWordGlyphs] = [] 

347 words = line.split(" ") 

348 for word in words: 

349 glyph_word = _unicode_to_glyph_id(word, reverse_cmap) 

350 line_by_widths_words_glyphs.append( 

351 WidthWordGlyphs( 

352 width=font.get_text_width(word) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, 

353 word=word, 

354 glyphs=glyph_word 

355 ) 

356 ) 

357 paragraphs.append(line_by_widths_words_glyphs) 

358 lines, font_size = self._scale_text( 

359 font, 

360 font_size, 

361 leading_factor, 

362 field_width, 

363 field_height, 

364 paragraphs, 

365 min_font_size 

366 ) 

367 else: 

368 max_vertical_size = field_height / leading_factor 

369 glyphs = _unicode_to_glyph_id(text, reverse_cmap) 

370 text_width_unscaled = font.get_text_width(glyphs) / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR 

371 max_horizontal_size = field_width / (text_width_unscaled or 1) 

372 font_size = round(max(min(max_vertical_size, max_horizontal_size), min_font_size), 1) 

373 lines = [WidthWordGlyphs(width=text_width_unscaled * font_size, word=text, glyphs=glyphs)] 

374 elif is_comb: 

375 if max_length and len(text) > max_length: 

376 logger_warning( 

377 ( 

378 "Length of text %(text)s exceeds maximum length (%(max_length)d) " 

379 "of field, input truncated." 

380 ), 

381 source=__name__, 

382 text=text, 

383 max_length=max_length, 

384 ) 

385 # We act as if each character is one line, because we draw it separately later on 

386 lines = [] 

387 for index, char in enumerate(text): 

388 if index < (max_length or len(text)): 

389 glyphs = _unicode_to_glyph_id(char, reverse_cmap) 

390 lines.append( 

391 WidthWordGlyphs( 

392 width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, 

393 word=char, 

394 glyphs=glyphs 

395 ) 

396 ) 

397 else: 

398 lines = [] 

399 for line in text.splitlines(): 

400 glyphs = _unicode_to_glyph_id(line, reverse_cmap) 

401 lines.append( 

402 WidthWordGlyphs( 

403 width=font.get_text_width(glyphs) * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR, 

404 word=line, 

405 glyphs=glyphs 

406 ) 

407 ) 

408 

409 # Set the vertical offset 

410 if is_multiline: 

411 y_offset = ( 

412 field_height + margin - font.font_descriptor.bbox[3] * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR 

413 ) 

414 else: 

415 y_offset = margin + ( 

416 (field_height - font.font_descriptor.ascent * font_size / TEXT_SPACE_TO_GLYPH_SPACE_FACTOR) / 2 

417 ) 

418 # font_name is in deserialized form here: it either comes from the Tf operands of /DA, where 

419 # NameObject parsing has already resolved any "#xx" escapes, or from the caller. renumber() 

420 # applies that escaping again, just as it does for the matching /Resources /Font key, so that 

421 # a name holding whitespace or a delimiter stays a single Tf operand instead of being split. 

422 escaped_font_name = NameObject(font_name).renumber().decode() 

423 default_appearance = f"{escaped_font_name} {font_size} Tf {font_color.as_operator()}" 

424 

425 ap_stream = bytearray() 

426 ap_stream += ( 

427 f"q\n/Tx BMC \nq\n" 

428 f"{2 * max(margin, 1)} {margin} " 

429 f"{round(field_width - 2 * max(margin, 1), 3)} {round(field_height - margin, 3)} re\n" 

430 f"W\nBT\n{default_appearance}\n" 

431 ).encode() 

432 current_x_pos: float = 0 # Initial virtual position within the text object. 

433 

434 selection_glyphs = _unicode_to_glyph_id("".join(selection), reverse_cmap) if selection else "" 

435 for line_number, (line_width, original_text, line) in enumerate(lines): 

436 if selection_glyphs and line in selection_glyphs: 

437 # Might be improved, but cannot find how to get fill working => replaced with lined box 

438 ap_stream += ( 

439 f"1 {round(y_offset - (line_number * font_size * leading_factor) - 1, 3)} " 

440 f"{rectangle.width - 2} {font_size + 2} re\n" 

441 f"0.5 0.5 0.5 rg s\n{default_appearance}\n" 

442 ).encode() 

443 

444 # Calculate the desired absolute starting X for the current line 

445 desired_abs_x_start: float = 0 

446 if is_comb and max_length: 

447 # Calculate the width of a cell for one character 

448 cell_width = rectangle.width / max_length 

449 # Space from the left edge of the cell to the character's baseline start 

450 # line_width here is the *actual* character width in points for the single character 'line' 

451 centering_offset_in_cell = (cell_width - line_width) / 2 

452 # Absolute start X = (Cell Index, i.e., line_number * Cell Width) + Centering Offset 

453 desired_abs_x_start = (line_number * cell_width) + centering_offset_in_cell 

454 elif alignment == TextAlignment.RIGHT: 

455 desired_abs_x_start = rectangle.width - max(margin, 1) * 2 - line_width 

456 elif alignment == TextAlignment.CENTER: 

457 desired_abs_x_start = (rectangle.width - line_width) / 2 

458 else: # Left aligned; default 

459 desired_abs_x_start = max(margin, 1) * 2 

460 # Calculate x_rel_offset: how much to move from the current_x_pos 

461 # to reach the desired_abs_x_start. 

462 x_rel_offset = desired_abs_x_start - current_x_pos 

463 

464 # Y-offset: 

465 y_rel_offset: float = 0 

466 if line_number == 0: 

467 y_rel_offset = y_offset # Initial vertical position 

468 elif is_comb: 

469 y_rel_offset = 0.0 # DO NOT move vertically for subsequent characters 

470 else: 

471 y_rel_offset = - font_size * leading_factor # Move down by line height 

472 

473 # Td is a relative translation (Tx and Ty). 

474 # It updates the current text position. 

475 ap_stream += f"{round(x_rel_offset, 3)} {round(y_rel_offset, 3)} Td\n".encode() 

476 # Update current_x_pos based on the Td operation for the next iteration. 

477 # This is the X position where the *current line* will start. 

478 current_x_pos = desired_abs_x_start 

479 

480 is_rtl = any(is_char_rtl(char) for char in line) 

481 

482 encoded_line = _glyph_id_to_bytes(line, encoding_cmap) 

483 if is_rtl: 

484 # Encode input text as UTF-16BE with a BOM, so that the input text is returned 

485 # in the right direction when copying text from the resulting PDF 

486 bom_text = b"\xfe\xff" + original_text.encode("utf-16-be") 

487 hex_original_text = bom_text.hex().upper() 

488 ap_stream += f"/Span << /ActualText <{hex_original_text}> >> BDC\n".encode() 

489 if font.sub_type == "Type0": # 16-bit font 

490 ap_stream += b"<" + (b"".join(encoded_line)).hex().encode() + b"> Tj\n" 

491 else: # Simple font, 8-bit encoded. 

492 # Escape parentheses (PDF 1.7 reference, table 3.2, Literal Strings) 

493 line_as_bytes = ( 

494 b"".join(encoded_line) 

495 .replace(b"\\", b"\\\\") 

496 .replace(b"(", br"\(") 

497 .replace(b")", br"\)") 

498 ) 

499 ap_stream += b"(" + line_as_bytes + b") Tj\n" 

500 if is_rtl: 

501 ap_stream += b"EMC\n" 

502 ap_stream += b"ET\nQ\nEMC\nQ\n" 

503 

504 return bytes(ap_stream) 

505 

506 def __init__( 

507 self, 

508 layout: BaseStreamConfig | None = None, 

509 text: str = "", 

510 selection: list[str] | None = None, 

511 font: Font | None = None, 

512 font_resource: DictionaryObject | IndirectObject | None = None, 

513 font_name: str = "/Helv", 

514 font_size: float = 0.0, 

515 font_color: Color | None = None, 

516 is_multiline: bool = False, 

517 alignment: TextAlignment = TextAlignment.LEFT, 

518 is_comb: bool = False, 

519 max_length: int | None = None 

520 ) -> None: 

521 """ 

522 Initializes a TextStreamAppearance object. 

523 

524 This constructor creates a new PDF stream object configured as an XObject 

525 of subtype Form. It uses the `_generate_appearance_stream_data` method to 

526 generate the content for the stream. 

527 

528 Args: 

529 layout: The basic layout parameters. 

530 text: The text to be rendered in the form field. 

531 selection: An optional list of strings that should be highlighted as selected. 

532 font: A Font object. Falls back to Type 1 Helvetica if not given. 

533 font_resource: An optional variable that represents a PDF font dictionary. Falls back 

534 to Type 1 Helvetica if not given. 

535 font_name: The name of the font resource, e.g., "/Helv". 

536 font_size: The font size. If 0, it's auto-calculated. 

537 font_color: The font color string. 

538 is_multiline: A boolean indicating if the text field is multiline. 

539 alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER. 

540 is_comb: Boolean that designates fixed-length fields, where every character 

541 fills one "cell", such as in a postcode. 

542 max_length: Used if is_comb is set. The maximum number of characters for a fixed- 

543 length field. 

544 

545 """ 

546 super().__init__(layout) 

547 

548 if not font or not font_resource: 

549 font_name = "/Helv" 

550 font = Font.from_core_font_name() 

551 font_resource = font.as_font_resource() 

552 

553 self._ap_stream_data += self._generate_appearance_stream_data( 

554 text, 

555 selection, 

556 font, 

557 font_name=font_name, 

558 font_size=font_size, 

559 font_color=font_color or DeviceGray(), 

560 is_multiline=is_multiline, 

561 alignment=alignment, 

562 is_comb=is_comb, 

563 max_length=max_length 

564 ) 

565 

566 self.set_data(ByteStringObject(self._ap_stream_data)) 

567 self[NameObject("/Length")] = NumberObject(len(self._ap_stream_data)) 

568 # Update Resources with font information 

569 self[NameObject("/Resources")] = DictionaryObject({ 

570 NameObject("/Font"): DictionaryObject({ 

571 NameObject(font_name): getattr(font_resource, "indirect_reference", font_resource) 

572 }) 

573 }) 

574 

575 @staticmethod 

576 def _find_annotation_font_resource( 

577 font_name: str, 

578 annotation: DictionaryObject, 

579 acro_form: DictionaryObject, 

580 text: str 

581 ) -> tuple[str, Font]: 

582 # Try to find a resource dictionary for the font by examining the annotation and, if that fails, 

583 # the AcroForm resources dictionary 

584 acro_form_resources: Any = cast( 

585 DictionaryObject, 

586 annotation.get_inherited( 

587 "/DR", 

588 acro_form.get("/DR", DictionaryObject()), 

589 ), 

590 ) 

591 acro_form_font_resources = acro_form_resources.get("/Font", DictionaryObject()) 

592 font_resource = acro_form_font_resources.get(font_name, None) 

593 if font_resource: 

594 font = Font.from_font_resource(font_resource.get_object()) 

595 else: 

596 # Normally, we should have found a font resource by now. However, when a user has provided a specific 

597 # font name, we may not have found the associated font resource among the AcroForm resources. Also, in 

598 # case of the 14 Adobe Core fonts, we may be expected to construct a font resource ourselves. 

599 if font_name.removeprefix("/") not in CORE_FONT_METRICS: 

600 # Default to Helvetica if we haven't found a font resource and cannot construct one ourselves. 

601 logger_warning( 

602 "Font dictionary for %(font_name)s not found; defaulting to Helvetica.", 

603 source=__name__, 

604 font_name=font_name, 

605 ) 

606 font_name = "/Helvetica" 

607 font = Font.from_core_font_name(font_name) 

608 

609 # If we have found a font resource, it still might not be able to encode the text value we received. 

610 encodable = font.can_encode(text) 

611 

612 if not encodable: 

613 # If we have a font file, we can try to produce a new font resource with an encoding 

614 # that does include the necessary characters. We only try this for a TrueType font, meaning 

615 # that, in PDF terms, it is a simple, 8-bit encoded font. 

616 if font.font_descriptor.font_file and font.sub_type == "TrueType": 

617 try: 

618 font = font.from_truetype_font_file(BytesIO(font.font_descriptor.font_file.get_data())) 

619 font_name = "/PYPDF1" # This means we most probably do not clash with an existing font name 

620 encodable = font.can_encode(text) 

621 except (ImportError, PdfReadError) as exception: 

622 logger_warning( 

623 "Unable to use embedded font for encoding: %(exception)s", 

624 source=__name__, 

625 exception=exception, 

626 ) 

627 

628 # If it's one of the unembedded 14 Adobe Core Fonts, we can test other supported encodings 

629 elif font.sub_type == "Type1" and font.name in CORE_FONT_METRICS: 

630 core_font_metrics = CORE_FONT_METRICS[font.name] 

631 test_encodings = { 

632 "cp1250", # Central / Eastern European 

633 "cp1252", # Western European 

634 "cp1254", # Turkish 

635 "cp1257", # Baltic Rim 

636 "iso8859_15" # Western European ISO Alternate 

637 } 

638 for encoding in test_encodings: 

639 test_font = copy.copy(font) 

640 test_font.encoding = encoding_dict_from_named_encoding(encoding) 

641 encodable = test_font.can_encode(text) 

642 if encodable: 

643 font = test_font 

644 font.character_widths.clear() 

645 for code, character in test_font.encoding.items(): 

646 # Look up the width using the glyph name from the encoding 

647 if character in core_font_metrics.character_widths: 

648 font.character_widths[chr(code)] = core_font_metrics.character_widths[character] 

649 font.character_widths["default"] = core_font_metrics.character_widths["default"] 

650 font_name = "/PYPDF1" + encoding 

651 break 

652 

653 if not encodable: 

654 logger_warning( 

655 ( 

656 "Text string '%(text)s' contains characters not supported by font encoding. " 

657 "This may result in text corruption. " 

658 "Consider calling writer.update_page_form_field_values with auto_regenerate=True." 

659 ), 

660 source=__name__, 

661 text=text, 

662 ) 

663 

664 return font_name, font 

665 

666 @staticmethod 

667 def _sync_appearance_stream_font_resources( 

668 writer: PdfWriter, 

669 font_name: str, 

670 font: Font, 

671 target_resource_dict: DictionaryObject, 

672 page: PageObject | None = None 

673 ) -> IndirectObject: 

674 """ 

675 Unified helper to sync fonts from an AP stream to a target resource dictionary (e.g., AcroForm /DR). 

676 Will sync to page resources as well when page is added to the arguments. 

677 """ 

678 target_fonts = target_resource_dict.setdefault(NameObject("/Font"), DictionaryObject()).get_object() 

679 if font_name not in target_fonts: 

680 font_resource_reference = font._add_to_writer( 

681 writer, 

682 target_fonts, 

683 NameObject(font_name) 

684 ) 

685 else: 

686 font_resource_reference = target_fonts[font_name] 

687 

688 if page: 

689 page_fonts_resource = cast(DictionaryObject, page[PageAttributes.RESOURCES]).setdefault( 

690 NameObject("/Font"), DictionaryObject() 

691 ).get_object() 

692 if font_name not in page_fonts_resource: 

693 page_fonts_resource[NameObject(font_name)] = getattr( 

694 font_resource_reference, "indirect_reference", font_resource_reference 

695 ) 

696 

697 return font_resource_reference 

698 

699 @staticmethod 

700 def _parse_default_appearance( 

701 default_appearance: TextStringObject | ByteStringObject, 

702 ) -> tuple[str | None, float, Color | None]: 

703 """ 

704 Read the font name, font size and font color from a default appearance string. 

705 

706 A default appearance is a content stream fragment of graphics and text state operators, such as 

707 `/a1.0 gs 0 0 0 rg /Helv 10 Tf` (Section 12.7.4.3 "Variable text" of the PDF 2.0 specification). 

708 Where an operator occurs more than once, the last one is in effect. Operators other than `Tf` and 

709 the non-stroking color operators are ignored. 

710 

711 Args: 

712 default_appearance: The /DA string of a variable text field. 

713 

714 Returns: 

715 The font name and font size of the last complete Tf operator, or None and 0 if there is none, 

716 and the color of the last complete color operator, or None if there is none. 

717 """ 

718 stream = ContentStream(None, None) 

719 stream.set_data(default_appearance.original_bytes) 

720 try: 

721 operations = stream.operations 

722 except PdfReadError: 

723 # Ignore a malformed default appearance altogether. 

724 return None, 0.0, None 

725 

726 font_name: str | None = None 

727 font_size = 0.0 

728 font_color: Color | None = None 

729 for operands, operator in operations: 

730 if operator == b"Tf": 

731 if len(operands) == 2 and isinstance(operands[0], NameObject) and isinstance(operands[1], (int, float)): 

732 font_name, font_size = str(operands[0]), float(operands[1]) 

733 elif (color := Color.from_normalized_values(operands, operator.decode("latin-1"))) is not None: 

734 font_color = color 

735 return font_name, font_size, font_color 

736 

737 @classmethod 

738 def from_text_annotation( 

739 cls, 

740 writer: PdfWriter, 

741 page: PageObject, 

742 flatten: bool, 

743 acro_form: DictionaryObject, # _root_object[CatalogAttributes.ACRO_FORM]) 

744 field: DictionaryObject, 

745 annotation: DictionaryObject, 

746 user_font_name: str = "", 

747 user_font_size: float = -1, 

748 ) -> TextStreamAppearance: 

749 """ 

750 Creates a TextStreamAppearance object from a text field annotation. 

751 

752 This class method is a factory for creating a `TextStreamAppearance` 

753 instance by extracting all necessary information (bounding box, font, 

754 text content, etc.) from the PDF field and annotation dictionaries. 

755 It respects inheritance for properties like default appearance (`/DA`). 

756 

757 Args: 

758 writer: The PdfWriter instance that we are creating text stream appearances for. 

759 page: The page that we are processing annotations for. 

760 flatten: Whether we flatten text annotations or not. If true, add new font resource 

761 to the page font resources. Otherwise, add them to the AcroForm resources. 

762 acro_form: The root AcroForm dictionary from the PDF catalog. 

763 field: The field dictionary object. 

764 annotation: The widget annotation dictionary object associated with the field. 

765 user_font_name: An optional user-provided font name to override the 

766 default. Defaults to an empty string. 

767 user_font_size: An optional user-provided font size to override the 

768 default. A value of -1 indicates no override. 

769 

770 Returns: 

771 A new `TextStreamAppearance` instance configured for the given field. 

772 

773 """ 

774 # Calculate rectangle dimensions 

775 _rectangle = cast(RectangleObject, annotation[AnnotationDictionaryAttributes.Rect]) 

776 # Normalize the rectangle, apply page rotation if applicable 

777 if page.get_inherited("/Rotate") in {90, 270}: 

778 rectangle = RectangleObject((0, 0, abs(_rectangle[3] - _rectangle[1]), abs(_rectangle[2] - _rectangle[0]))) 

779 else: 

780 rectangle = RectangleObject((0, 0, abs(_rectangle[2] - _rectangle[0]), abs(_rectangle[3] - _rectangle[1]))) 

781 

782 # Get default appearance dictionary from annotation 

783 default_appearance = annotation.get_inherited( 

784 AnnotationDictionaryAttributes.DA, 

785 acro_form.get(AnnotationDictionaryAttributes.DA, None), 

786 ) 

787 if not default_appearance: 

788 # Create a default appearance if none was found in the annotation 

789 default_appearance = TextStringObject("/Helv 0 Tf 0 g") 

790 else: 

791 default_appearance = default_appearance.get_object() 

792 

793 # Retrieve field text and selected values 

794 field_flags = field.get(FieldDictionaryAttributes.Ff, 0) 

795 if ( 

796 field.get(FieldDictionaryAttributes.FT, "/Tx") == "/Ch" and 

797 field_flags & FieldDictionaryAttributes.FfBits.Combo == 0 

798 ): 

799 text = "\n".join(annotation.get_inherited(FieldDictionaryAttributes.Opt, [])) 

800 selection = field.get("/V", []) 

801 if not isinstance(selection, list): 

802 selection = [selection] 

803 else: # /Tx 

804 text = field.get("/V", "") 

805 selection = [] 

806 

807 # Derive font name, size and color from the default appearance. Also set 

808 # user-provided font name and font size in the default appearance, if given. 

809 # For a font name, this presumes that we can find an associated font resource 

810 # dictionary. 

811 # As per the PDF spec: 

812 # "At a minimum, the string [that is, default_appearance] shall include a Tf (text 

813 # font) operator along with its two operands, font and size" (Section 12.7.4.3 

814 # "Variable text" of the PDF 2.0 specification). 

815 da_font_name, font_size, font_color = cls._parse_default_appearance(default_appearance) 

816 if da_font_name is None: 

817 logger_warning( 

818 ( 

819 "Could not read a complete Tf operator from the default appearance %(default_appearance)r; " 

820 "defaulting to /Helv 0 Tf." 

821 ), 

822 source=__name__, 

823 default_appearance=str(default_appearance), 

824 ) 

825 da_font_name, font_size = "/Helv", 0.0 

826 # Determine the font name to use, prioritizing the user's input 

827 if user_font_name: 

828 font_name = user_font_name 

829 else: 

830 font_name = da_font_name 

831 # Determine the font size to use, prioritizing the user's input 

832 if user_font_size > 0: 

833 font_size = user_font_size 

834 

835 font_name, font = cls._find_annotation_font_resource(font_name, annotation, acro_form, text) 

836 

837 # Change the /DA information if we changed the font name 

838 if font_name != da_font_name: 

839 annotation[NameObject("/DA")] = TextStringObject(default_appearance.replace(da_font_name, font_name)) 

840 

841 # Synchronise font resources 

842 font_resource_reference = cls._sync_appearance_stream_font_resources( 

843 writer, 

844 font_name, 

845 font, 

846 acro_form.setdefault(NameObject("/DR"), DictionaryObject()), 

847 page if flatten else None, 

848 ) 

849 

850 # Retrieve formatting information 

851 is_comb = False 

852 max_length = None 

853 if field_flags & FieldDictionaryAttributes.FfBits.Comb: 

854 is_comb = True 

855 max_length = annotation.get("/MaxLen") 

856 is_multiline = False 

857 if field_flags & FieldDictionaryAttributes.FfBits.Multiline: 

858 is_multiline = True 

859 alignment = field.get("/Q", TextAlignment.LEFT) 

860 border_width = 1 

861 border_style = BorderStyles.SOLID 

862 if "/BS" in field: 

863 border_width = cast(DictionaryObject, field["/BS"]).get("/W", border_width) 

864 border_style = cast(DictionaryObject, field["/BS"]).get("/S", border_style) 

865 

866 rotation = 0 

867 border_color: Color | None = None 

868 background_color: Color | None = None 

869 appearance_characteristics = field.get_inherited("/MK", None) 

870 if isinstance(appearance_characteristics, DictionaryObject): 

871 rotation = int(appearance_characteristics.get("/R", 0)) 

872 # Color.from_normalized_values([]) results in None for a "/BC" or "/BG" value of [] 

873 border_color = Color.from_normalized_values(appearance_characteristics.get("/BC")) 

874 background_color = Color.from_normalized_values(appearance_characteristics.get("/BG")) 

875 

876 # Create the TextStreamAppearance instance 

877 layout = BaseStreamConfig( 

878 rectangle=rectangle, 

879 border_width=border_width, 

880 border_style=border_style, 

881 border_color=border_color, 

882 background_color=background_color, 

883 rotation=rotation 

884 ) 

885 

886 new_appearance_stream = cls( 

887 layout, 

888 text, 

889 selection, 

890 font, 

891 font_resource_reference, 

892 font_name=font_name, 

893 font_size=font_size, 

894 font_color=font_color, 

895 is_multiline=is_multiline, 

896 alignment=alignment, 

897 is_comb=is_comb, 

898 max_length=max_length 

899 ) 

900 

901 if AnnotationDictionaryAttributes.AP in annotation: 

902 for key, value in ( 

903 cast(DictionaryObject, annotation[AnnotationDictionaryAttributes.AP]).get("/N", {}).items() 

904 ): 

905 if key in {"/BBox", "/Length", "/Subtype", "/Type", "/Filter"}: 

906 continue 

907 # Don't overwrite font resources added by TextAppearanceStream.__init__ 

908 if key == "/Resources": 

909 if "/Font" not in value: 

910 value.get_object()[NameObject("/Font")] = DictionaryObject() 

911 value["/Font"].get_object()[NameObject(font_name)] = getattr( 

912 font_resource_reference, "indirect_reference", font_resource_reference 

913 ) 

914 else: 

915 new_appearance_stream[key] = value 

916 

917 return new_appearance_stream 

918 

919 

920def transform_annotation_appearance(annotation_obj: DictionaryObject, transformation: Transformation) -> None: 

921 """ 

922 Compose `transformation` into an annotation's /AP /N appearance stream(s), in place. 

923 

924 Repositioning/resizing an annotation's /Rect alone is not enough: per 

925 the appearance-stream algorithm (PDF 2.0, 12.5.5), a viewer fits the 

926 appearance's /BBox (as mapped by its own /Matrix) into /Rect using an 

927 axis-aligned scale, never a rotation. Left alone, rotating or shearing 

928 a page therefore stretches/skews the untouched appearance content into 

929 the new, differently-shaped /Rect instead of rotating it. Composing the 

930 transform into /Matrix (rather than overwriting it) keeps the rendered 

931 content consistent with the rest of the transformed page while 

932 preserving whatever the annotation already had. Handles both a single 

933 appearance stream and the multi-state /AP /N dict used by 

934 checkbox/radio-button widgets. 

935 """ 

936 if "/AP" not in annotation_obj: 

937 return 

938 ap = cast(DictionaryObject, annotation_obj["/AP"]) 

939 if "/N" not in ap: 

940 return 

941 # __getitem__ already resolves indirect references, so this is never None. 

942 normal_ap = ap["/N"] 

943 # /N is a single appearance stream for most annotations, but for 

944 # widgets with multiple states (checkboxes, radio buttons) it is 

945 # instead a dict of named sub-streams, one per state. Only a stream 

946 # carries its own /BBox/Matrix. 

947 state_aps = ( 

948 normal_ap.values() 

949 if isinstance(normal_ap, DictionaryObject) and not isinstance(normal_ap, StreamObject) 

950 else [normal_ap] 

951 ) 

952 for state_ap in state_aps: 

953 # get_object() is always safe to call: PdfObject.get_object() just 

954 # returns self when the object is already resolved. 

955 state_obj = state_ap.get_object() 

956 if not isinstance(state_obj, StreamObject): 

957 continue 

958 old_matrix = tuple(state_obj.get("/Matrix", (1, 0, 0, 1, 0, 0))) 

959 state_obj[NameObject("/Matrix")] = ArrayObject( 

960 FloatObject(x) for x in Transformation(old_matrix).transform(transformation).ctm 

961 )