Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/generic/_font.py: 20%
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
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
1from __future__ import annotations
3import unicodedata
4from collections.abc import Sequence
5from dataclasses import dataclass, field
6from typing import TYPE_CHECKING, Any, ClassVar, cast
8from pypdf.generic import (
9 ArrayObject,
10 DictionaryObject,
11 FloatObject,
12 IndirectObject,
13 NameObject,
14 NumberObject,
15 PdfObject,
16 StreamObject,
17 TextStringObject,
18)
20from .._cmap import get_encoding
21from .._codecs import encoding_dict_from_named_encoding
22from .._codecs.adobe_glyphs import adobe_glyphs
23from .._utils import logger_warning
24from ..constants import FontFlags
25from ..errors import LimitReachedError, PdfReadError
27if TYPE_CHECKING:
28 from fontTools.ttLib.tables._h_e_a_d import table__h_e_a_d
29 from fontTools.ttLib.tables._p_o_s_t import table__p_o_s_t
30 from fontTools.ttLib.tables.DefaultTable import DefaultTable
31 from fontTools.ttLib.tables.O_S_2f_2 import table_O_S_2f_2
33 from .._writer import PdfWriter
35try:
36 from io import BytesIO
38 from fontTools.ttLib import TTFont
39 HAS_FONTTOOLS = True
40except ImportError:
41 HAS_FONTTOOLS = False
44# Limits.
45MAX_CID_WIDTH_ENTRY_COUNT = 65_536
46MAX_WIDTH_ENTRY_COUNT = 100_000
47# For a simple font, character codes are one-byte values, 0-255, so /Widths can have at most 256 meaningful entries.
48MAX_SIMPLE_FONT_CHARACTER_CODE = 255
51# Some constants from truetype font tables that we use:
52HEADER_MACSTYLE_ITALIC = 0x02
53OS2_FSSELECTION_ITALIC = 0x01
54OS2_PANOSE_BFAMILYTYPE_SCRIPT = 3
55OS2_PANOSE_BFAMILYTYPE_DECORATIVE = 4
56OS2_PANOSE_BFAMILYTYPE_PICTORIAL = 5
57OS2_PANOSE_BPROPORTION_MONOSPACED = 9
58OS2_SFAMILYSCLASS_SCRIPTS = 10
59OS2_SFAMILYSCLASS_SYMBOLIC = 12
62# Groups of CMap mappings cannot exceed 100 entries (Adobe CMap and CIDFont Files Specification 1.0, p. 49).
63CMAP_MAX_ENTRIES_PER_GROUP = 100
66@dataclass(frozen=True)
67class FontDescriptor:
68 """
69 Represents the FontDescriptor dictionary as defined in the PDF specification.
70 This contains both descriptive and metric information.
72 The defaults are derived from the mean values of the 14 core fonts, rounded
73 to 100.
74 """
76 _DEFAULT_BBOX: ClassVar[tuple[float, float, float, float]] = (-100.0, -200.0, 1000.0, 900.0)
78 name: str = "Unknown"
79 family: str = "Unknown"
80 weight: str = "Unknown"
82 ascent: float = 700.0
83 descent: float = -200.0
84 cap_height: float = 600.0
85 x_height: float = 500.0
86 italic_angle: float = 0.0 # Non-italic
87 flags: int = 32 # Non-serif, non-symbolic, not fixed width
88 bbox: tuple[float, float, float, float] = _DEFAULT_BBOX
89 font_file: StreamObject | None = None
91 def as_font_descriptor_resource(self) -> DictionaryObject:
92 font_descriptor_resource = DictionaryObject({
93 NameObject("/Type"): NameObject("/FontDescriptor"),
94 NameObject("/FontName"): NameObject(f"/{self.name}"),
95 NameObject("/Flags"): NumberObject(self.flags),
96 NameObject("/FontBBox"): ArrayObject([FloatObject(n) for n in self.bbox]),
97 NameObject("/ItalicAngle"): FloatObject(self.italic_angle),
98 NameObject("/Ascent"): FloatObject(self.ascent),
99 NameObject("/Descent"): FloatObject(self.descent),
100 NameObject("/CapHeight"): FloatObject(self.cap_height),
101 NameObject("/XHeight"): FloatObject(self.x_height),
102 })
104 if self.font_file:
105 # Add the stream. For now, we assume a TrueType font (FontFile2)
106 font_descriptor_resource[NameObject("/FontFile2")] = self.font_file
108 return font_descriptor_resource
111@dataclass(frozen=True)
112class CoreFontMetrics:
113 font_descriptor: FontDescriptor
114 character_widths: dict[str, float]
117@dataclass
118class Font:
119 """
120 A font object for use during text extraction and for producing
121 text appearance streams.
123 Attributes:
124 name: Font name, derived from ``font["/BaseFont"]``
125 character_map: The font's character map
126 encoding: Font encoding. Must be a dict for a simple font, and string otherwise.
127 sub_type: The font type, such as Type1, TrueType, or Type3.
128 font_descriptor: Font metrics, including a mapping of characters to widths
129 character_widths: A mapping of characters to widths
130 space_width: The width of a space, or an approximation
131 interpretable: Default True. If False, the font glyphs cannot
132 be translated to characters, e.g. Type3 fonts that do not define
133 a ``/ToUnicode`` mapping.
135 """
137 name: str
138 encoding: str | dict[int, str]
139 character_map: dict[Any, Any] = field(default_factory=dict)
140 sub_type: str = "Unknown"
141 font_descriptor: FontDescriptor = field(default_factory=FontDescriptor)
142 character_widths: dict[str, float] = field(default_factory=lambda: {"default": 500})
143 space_width: float | int = 250
144 space_char: str = " "
145 interpretable: bool = True
147 @staticmethod
148 def _collect_tt_t1_character_widths(
149 pdf_font_dict: DictionaryObject,
150 char_map: dict[Any, Any],
151 encoding: str | dict[int, str],
152 current_widths: dict[str, float]
153 ) -> None:
154 """Parses a TrueType or Type1 font's /Widths array from a font dictionary and updates character widths"""
155 widths_array = pdf_font_dict["/Widths"].get_object()
156 if not isinstance(widths_array, ArrayObject):
157 logger_warning(
158 "Expected an array for /Widths, got %(widths_array)s. Ignoring it.",
159 source=__name__,
160 widths_array=widths_array,
161 )
162 return
163 Font.__check_entry_count(
164 len(widths_array), MAX_SIMPLE_FONT_CHARACTER_CODE + 1
165 )
166 first_char = pdf_font_dict.get("/FirstChar", 0)
167 if not isinstance(first_char, (int, float)):
168 logger_warning(
169 "Ignoring invalid /FirstChar %(code)s.", source=__name__, code=first_char
170 )
171 return
172 first_char = int(first_char)
173 if first_char < 0:
174 logger_warning(
175 "Ignoring invalid /FirstChar %(code)d < 0.", source=__name__, code=first_char
176 )
177 return
178 for character_code, width in enumerate(widths_array, start=first_char):
179 if character_code > MAX_SIMPLE_FONT_CHARACTER_CODE:
180 logger_warning(
181 "Ignoring invalid character codes > %(limit)d (starting at %(code)d).",
182 source=__name__,
183 code=character_code,
184 limit=MAX_SIMPLE_FONT_CHARACTER_CODE
185 )
186 break
187 current_widths[chr(character_code)] = int(width)
189 @staticmethod
190 def __check_range_length(start: int, end: int) -> None:
191 if end < start:
192 raise LimitReachedError(
193 f"Invalid CID width range: {start}..{end}."
194 )
196 count = end - start
197 if count > MAX_CID_WIDTH_ENTRY_COUNT:
198 raise LimitReachedError(f"CID width range too large: {count} > {MAX_CID_WIDTH_ENTRY_COUNT}.")
200 @staticmethod
201 def __check_entry_count(count: int, limit: int = MAX_WIDTH_ENTRY_COUNT) -> None:
202 if count > limit:
203 raise LimitReachedError(f"Too many character widths: {count} > {limit}.")
205 @staticmethod
206 def _collect_cid_character_widths(d_font: DictionaryObject, current_widths: dict[str, float]) -> None:
207 """Parses the /W array from a DescendantFont dictionary and updates character widths."""
208 # /W width definitions have two valid formats which can be mixed and matched:
209 # (1) A character start index followed by a list of widths, e.g.
210 # `45 [500 600 700]` applies widths 500, 600, 700 to characters 45-47.
211 # (2) A character start index, a character stop index, and a width, e.g.
212 # `45 65 500` applies width 500 to characters 45-65.
213 skip_count = 0
214 entry_count = 0
215 _w = d_font.get("/W", ArrayObject()).get_object()
216 _w_length = len(_w)
217 for idx, w_entry in enumerate(_w):
218 if skip_count:
219 skip_count -= 1
220 continue
221 w_entry = w_entry.get_object()
222 if not isinstance(w_entry, (int, float)):
223 # We should never get here due to skip_count above. But
224 # sometimes we do.
225 logger_warning(
226 "Expected numeric value for width, got %(w_entry)s. Ignoring it.",
227 source=__name__,
228 w_entry=w_entry,
229 )
230 continue
231 # check for format (1): `int [int int int int ...]`
232 w_next_entry = _w[idx + 1].get_object() if idx + 1 < _w_length else None
233 if isinstance(w_next_entry, Sequence):
234 start_idx, width_list = int(w_entry), w_next_entry
235 stop_idx = start_idx + len(width_list)
236 Font.__check_range_length(start_idx, stop_idx)
237 entry_count += (stop_idx - start_idx)
238 Font.__check_entry_count(entry_count)
239 current_widths.update(
240 {
241 chr(_cidx): _width.get_object()
242 for _cidx, _width in zip(
243 range(start_idx, stop_idx, 1),
244 width_list,
245 )
246 }
247 )
248 skip_count = 1
249 # check for format (2): `int int int`
250 elif (
251 isinstance(w_next_entry, (int, float))
252 and idx + 2 < _w_length
253 and isinstance(_w[idx + 2].get_object(), (int, float))
254 ):
255 start_idx, stop_idx, const_width = (
256 int(w_entry),
257 int(w_next_entry),
258 _w[idx + 2].get_object(),
259 )
260 Font.__check_range_length(start_idx, stop_idx + 1)
261 entry_count += (stop_idx - start_idx + 1)
262 Font.__check_entry_count(entry_count)
263 current_widths.update(
264 {
265 chr(_cidx): const_width
266 for _cidx in range(
267 start_idx, stop_idx + 1, 1
268 )
269 }
270 )
271 skip_count = 2
272 else:
273 # This handles the case of out of bounds (reaching the end of the width definitions
274 # while expecting more elements).
275 logger_warning(
276 "Invalid font width definition. Last element: %(w_entry)s.",
277 source=__name__,
278 w_entry=w_entry,
279 )
281 @staticmethod
282 def _get_space_char(
283 encoding: str | dict[int, str],
284 character_map: dict[Any, Any],
285 ) -> str:
286 space_char = " "
287 for glyph_id, char_str in character_map.items():
288 if char_str == space_char:
289 return str(glyph_id)
291 if isinstance(encoding, dict):
292 for char_code, char_str in encoding.items():
293 if char_str == space_char:
294 return chr(char_code)
296 return space_char
298 @staticmethod
299 def _add_default_width(current_widths: dict[str, float], flags: int, space_char: str) -> None:
300 if not current_widths:
301 current_widths["default"] = 500
302 return
304 if space_char in current_widths and current_widths[space_char] != 0:
305 # Setting default to once or twice the space width, depending on fixed pitch
306 if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH:
307 current_widths["default"] = current_widths[space_char]
308 return
310 current_widths["default"] = int(2 * current_widths[space_char])
311 return
313 # Use the average width of existing glyph widths
314 valid_widths = [w for w in current_widths.values() if w > 0]
315 current_widths["default"] = sum(valid_widths) // len(valid_widths) if valid_widths else 500
317 @staticmethod
318 def _add_space_width(
319 character_widths: dict[str, float],
320 flags: int,
321 space_char: str
322 ) -> float:
323 space_width = character_widths.get(space_char, 0)
324 if space_width != 0:
325 return space_width
327 if (flags & FontFlags.FIXED_PITCH) == FontFlags.FIXED_PITCH:
328 return character_widths["default"]
330 return character_widths["default"] // 2
332 @staticmethod
333 def _parse_bbox(raw_bbox: Any) -> tuple[float, float, float, float] | None:
334 """
335 Convert a raw /FontBBox value into four floats.
337 Args:
338 raw_bbox: The raw /FontBBox value read from the PDF.
340 Returns:
341 The four bounding box values, or ``None`` when the value is not
342 a sequence of exactly four numbers, so that a malformed entry
343 falls back to the default bounding box rather than raising.
345 """
346 try:
347 bbox = [float(value) for value in raw_bbox]
348 except (TypeError, ValueError):
349 return None
350 if len(bbox) != 4:
351 return None
352 return bbox[0], bbox[1], bbox[2], bbox[3]
354 @staticmethod
355 def _parse_font_descriptor(font_descriptor_obj: DictionaryObject) -> dict[str, Any]:
356 font_descriptor_kwargs: dict[Any, Any] = {}
357 for source_key, target_key in [
358 ("/FontName", "name"),
359 ("/FontFamily", "family"),
360 ("/FontWeight", "weight"),
361 ("/Ascent", "ascent"),
362 ("/Descent", "descent"),
363 ("/CapHeight", "cap_height"),
364 ("/XHeight", "x_height"),
365 ("/ItalicAngle", "italic_angle"),
366 ("/Flags", "flags"),
367 ("/FontBBox", "bbox")
368 ]:
369 if source_key in font_descriptor_obj:
370 font_descriptor_kwargs[target_key] = font_descriptor_obj[source_key]
371 # Handle missing or malformed bbox gracefully - PDFs may have fonts without valid bounding boxes
372 if "bbox" in font_descriptor_kwargs:
373 bbox = Font._parse_bbox(font_descriptor_kwargs["bbox"])
374 if bbox is None:
375 del font_descriptor_kwargs["bbox"]
376 else:
377 font_descriptor_kwargs["bbox"] = bbox
379 # Find the binary stream for this font if there is one
380 for source_key in ["/FontFile", "/FontFile2", "/FontFile3"]:
381 if source_key in font_descriptor_obj:
382 if "font_file" in font_descriptor_kwargs:
383 raise PdfReadError(f"More than one /FontFile found in {font_descriptor_obj}")
385 try:
386 font_file = font_descriptor_obj[source_key].get_object()
387 font_descriptor_kwargs["font_file"] = font_file
388 except PdfReadError as exception:
389 logger_warning(
390 "Failed to get %(source_key)r in %(font_descriptor_obj)s: %(error)s",
391 source=__name__,
392 source_key=source_key,
393 font_descriptor_obj=font_descriptor_obj,
394 error=exception,
395 )
396 return font_descriptor_kwargs
398 @classmethod
399 def from_font_resource(
400 cls,
401 pdf_font_dict: DictionaryObject,
402 ) -> Font:
403 from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415
405 # Can collect base_font, name and encoding directly from font resource.
406 # A malformed resource may carry a non-string value here, so fall back
407 # to "Unknown" rather than failing on it.
408 base_font = pdf_font_dict.get("/BaseFont", "Unknown")
409 name = base_font.removeprefix("/") if isinstance(base_font, str) else "Unknown"
410 sub_type_value = pdf_font_dict.get("/Subtype", "Unknown")
411 sub_type = sub_type_value.removeprefix("/") if isinstance(sub_type_value, str) else "Unknown"
412 encoding, character_map = get_encoding(pdf_font_dict)
413 font_descriptor = None
414 character_widths: dict[str, float] = {}
415 interpretable = True
417 # Deal with fonts by type; Type1, TrueType and certain Type3
418 if pdf_font_dict.get("/Subtype") in ("/Type1", "/MMType1", "/TrueType", "/Type3"):
419 # Type3 fonts that do not specify a "/ToUnicode" mapping cannot be
420 # reliably converted into character codes unless all named chars
421 # in /CharProcs map to a standard adobe glyph. See §9.10.2 of the
422 # PDF 1.7 standard.
423 if sub_type == "Type3" and "/ToUnicode" not in pdf_font_dict:
424 interpretable = all(
425 cname in adobe_glyphs
426 for cname in pdf_font_dict.get("/CharProcs") or []
427 )
428 if interpretable: # Save some overhead if font is not interpretable
429 if "/Widths" in pdf_font_dict:
430 cls._collect_tt_t1_character_widths(
431 pdf_font_dict, character_map, encoding, character_widths
432 )
434 elif name in CORE_FONT_METRICS:
435 font_descriptor = CORE_FONT_METRICS[name].font_descriptor
436 for code, character in cast(dict[int, str], encoding).items():
437 # Look up the width using the glyph name from the encoding
438 if character in CORE_FONT_METRICS[name].character_widths:
439 character_widths[chr(code)] = CORE_FONT_METRICS[name].character_widths[character]
440 if "/FontDescriptor" in pdf_font_dict:
441 font_descriptor_obj = pdf_font_dict.get("/FontDescriptor", DictionaryObject()).get_object()
442 if "/MissingWidth" in font_descriptor_obj:
443 character_widths["default"] = cast(int, font_descriptor_obj["/MissingWidth"].get_object())
444 font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj))
445 elif "/FontBBox" in pdf_font_dict:
446 # For Type3 without Font Descriptor but with FontBBox, see Table 110 in the PDF specification 2.0
447 font_descriptor_kwargs: dict[str, Any] = {"name": name}
448 bbox = cls._parse_bbox(pdf_font_dict["/FontBBox"])
449 if bbox is not None:
450 font_descriptor_kwargs["bbox"] = bbox
451 font_descriptor = FontDescriptor(**font_descriptor_kwargs)
453 else:
454 # Composite font or CID font - CID fonts have a /W array mapping character codes
455 # to widths stashed in /DescendantFonts.
456 descendant_fonts = pdf_font_dict.get("/DescendantFonts", ArrayObject()).get_object()
457 if not isinstance(descendant_fonts, ArrayObject):
458 logger_warning(
459 "Expected an array for /DescendantFonts, got %(descendant_fonts)s. Ignoring it.",
460 source=__name__,
461 descendant_fonts=descendant_fonts,
462 )
463 descendant_fonts = ArrayObject()
464 elif len(descendant_fonts) > 1:
465 # A composite font has a single descendant font (ISO 32000-2:2020, 9.7.1).
466 logger_warning(
467 "Expected a single entry in /DescendantFonts, got %(count)d. Ignoring all but the first one.",
468 source=__name__,
469 count=len(descendant_fonts),
470 )
471 if descendant_fonts:
472 d_font = descendant_fonts[0].get_object()
473 if isinstance(d_font, DictionaryObject):
474 cls._collect_cid_character_widths(d_font=d_font, current_widths=character_widths)
475 if "/DW" in d_font:
476 character_widths["default"] = cast(int, d_font["/DW"].get_object())
477 font_descriptor_obj = d_font.get("/FontDescriptor", DictionaryObject()).get_object()
478 font_descriptor = FontDescriptor(**cls._parse_font_descriptor(font_descriptor_obj))
479 else:
480 logger_warning(
481 "Expected a dictionary for the descendant font, got %(d_font)s. Ignoring it.",
482 source=__name__,
483 d_font=d_font,
484 )
486 if not font_descriptor:
487 font_descriptor = FontDescriptor(name=name)
489 space_char = cls._get_space_char(encoding, character_map)
490 if character_widths.get("default", 0) == 0:
491 cls._add_default_width(character_widths, font_descriptor.flags, space_char)
492 space_width = cls._add_space_width(character_widths, font_descriptor.flags, space_char)
494 return cls(
495 name=name,
496 sub_type=sub_type,
497 encoding=encoding,
498 font_descriptor=font_descriptor,
499 character_map=character_map,
500 character_widths=character_widths,
501 space_width=space_width,
502 space_char=space_char,
503 interpretable=interpretable
504 )
506 @staticmethod
507 def _load_fonttools_table(table_name: str, is_critical: bool, tt_font_object: TTFont) -> DefaultTable | None:
508 """Once we have a TTFont object, we can try to get the necessary font tables from
509 which we collect the information to instantiate a Font class. However, some of
510 these tables might be missing from the embedded font file, and others might be
511 corrupt in some form and then throw a struct.error on decompilation. We decompile
512 all tables we need using this method to guard against fontTools exceptions.
514 This method distinguishes between optional tables and critical tables without which
515 we cannot instantiate a Font. For critical tables, raises PdfReadError if missing
516 OR if binary data is corrupt. For optional tables, it logs warnings instead.
517 """
518 try:
519 # tt_font.get() automatically triggers table.decompile() under the hood
520 table = tt_font_object.get(table_name)
521 if table is None:
522 if is_critical:
523 raise PdfReadError(f"Font file does not have a {table_name!r} table")
524 logger_warning(
525 "Optional font table %(table_name)r is missing from font file",
526 source=__name__,
527 table_name=table_name
528 )
529 return None
530 except Exception as exception:
531 if is_critical:
532 raise PdfReadError(
533 f"Font table {table_name!r} is corrupt or truncated: {exception}"
534 ) from exception
535 logger_warning(
536 "Optional font table %(table_name)r is corrupt and will be ignored: %(exception)s",
537 source=__name__,
538 table_name=table_name,
539 exception=exception
540 )
541 return None
542 return table
544 @staticmethod
545 def _get_font_flags_from_truetype_font_tables(
546 header_table: table__h_e_a_d,
547 postscript_table: table__p_o_s_t,
548 os2_table: table_O_S_2f_2
549 ) -> int:
550 # Get the font flags
551 if os2_table:
552 panose = os2_table.panose
553 # sFamilyClass is a two-byte field. The high byte describes the family class, whereas the low
554 # byte only describes the subclass. We only need the high byte, hence the bit shift below:
555 family_class = os2_table.sFamilyClass >> 8
556 flags: int = 0
558 # ITALIC
559 if header_table.macStyle & HEADER_MACSTYLE_ITALIC or (
560 os2_table and os2_table.fsSelection & OS2_FSSELECTION_ITALIC
561 ):
562 flags |= FontFlags.ITALIC
563 if postscript_table:
564 italic_angle = postscript_table.italicAngle
565 if italic_angle != 0.0:
566 flags |= FontFlags.ITALIC
568 # FIXED_PITCH
569 if (
570 (os2_table and panose.bProportion == OS2_PANOSE_BPROPORTION_MONOSPACED) or
571 (postscript_table and postscript_table.isFixedPitch > 0) # Actually 1, but originally (older TTF spec.
572 ): # version) any non-zero value signified monospace.
573 flags |= FontFlags.FIXED_PITCH
575 # SCRIPT
576 if os2_table and (
577 family_class == OS2_SFAMILYSCLASS_SCRIPTS or panose.bFamilyType == OS2_PANOSE_BFAMILYTYPE_SCRIPT
578 ):
579 flags |= FontFlags.SCRIPT
581 # SERIF
582 if os2_table and (
583 2 <= panose.bSerifStyle <= 10
584 or 1 <= family_class <= 5 or family_class == 7 # 6 is reserved, all 8 and above are not serif
585 ):
586 flags |= FontFlags.SERIF
588 # SYMBOLIC
589 if os2_table and (
590 family_class == OS2_SFAMILYSCLASS_SYMBOLIC or
591 panose.bFamilyType in {OS2_PANOSE_BFAMILYTYPE_DECORATIVE, OS2_PANOSE_BFAMILYTYPE_PICTORIAL}
592 ):
593 flags |= FontFlags.SYMBOLIC
594 else:
595 flags |= FontFlags.NONSYMBOLIC
597 return flags
599 @classmethod
600 def from_truetype_font_file(cls, font_file: BytesIO) -> Font:
601 if not HAS_FONTTOOLS:
602 raise ImportError("The 'fontTools' library is required to use 'from_truetype_font_file'")
603 try:
604 tt_font_object = TTFont(font_file)
605 except Exception as exception:
606 raise PdfReadError(f"Could not open font file: {exception}") from exception
607 with tt_font_object:
608 # See Chapter 6 of the TrueType reference manual for the definition of the head, OS/2 and post tables:
609 # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6head.html
610 # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html
611 # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
613 # Collect all font tables.
614 (
615 cmap_table,
616 header_table,
617 metrics_table,
618 horizontal_header_table,
619 name_table,
620 os2_table,
621 postscript_table
622 ) = (
623 cls._load_fonttools_table(
624 table_name=table_name,
625 is_critical=table_name in {"head", "hmtx", "cmap"},
626 tt_font_object=tt_font_object
627 )
628 for table_name in ("cmap", "head", "hmtx", "hhea", "name", "OS/2", "post")
629 )
631 if TYPE_CHECKING:
632 assert header_table is not None
633 assert metrics_table is not None
634 assert cmap_table is not None
636 # Get the scaling factor to convert font file's units per em to PDF's 1000 units per em
637 if (units_per_em := header_table.unitsPerEm) <= 0:
638 raise PdfReadError(f"Font file has an invalid unitsPerEm of {units_per_em}")
639 scale_factor = 1000.0 / units_per_em
641 # Get the font descriptor
642 font_descriptor_kwargs: dict[Any, Any] = {}
644 if name_table:
645 for name, getter in (
646 ("name", name_table.getBestFullName),
647 ("family", name_table.getBestFamilyName),
648 ("weight", name_table.getBestSubFamilyName)
649 ):
650 if (value := getter()) is not None:
651 font_descriptor_kwargs[name] = value
653 if horizontal_header_table:
654 font_descriptor_kwargs["ascent"] = int(round(horizontal_header_table.ascent * scale_factor, 0))
655 font_descriptor_kwargs["descent"] = int(round(horizontal_header_table.descent * scale_factor, 0))
657 if os2_table:
658 try:
659 font_descriptor_kwargs["cap_height"] = int(round(os2_table.sCapHeight * scale_factor, 0))
660 font_descriptor_kwargs["x_height"] = int(round(os2_table.sxHeight * scale_factor, 0))
661 except AttributeError:
662 pass
664 font_descriptor_kwargs["flags"] = cls._get_font_flags_from_truetype_font_tables(
665 header_table,
666 postscript_table,
667 os2_table
668 )
670 font_descriptor_kwargs["bbox"] = (
671 round(header_table.xMin * scale_factor, 0),
672 round(header_table.yMin * scale_factor, 0),
673 round(header_table.xMax * scale_factor, 0),
674 round(header_table.yMax * scale_factor, 0)
675 )
677 font_file_data = StreamObject()
678 font_file_raw_bytes = font_file.getvalue()
679 font_file_data.set_data(font_file_raw_bytes)
680 font_file_data.update({NameObject("/Length1"): NumberObject(len(font_file_raw_bytes))})
681 font_descriptor_kwargs["font_file"] = font_file_data
683 font_descriptor = FontDescriptor(**font_descriptor_kwargs)
684 encoding = "utf_16_be" # Assume unicode
686 character_widths: dict[str, float] = {}
687 character_map: dict[str, str] = {}
689 # Note that one glyph can be mapped to multiple unicode code points. However, buildReversedMin()
690 # creates a dictionary mapping glyphs to the minimum Unicode codepoint.
691 try:
692 reverse_cmap = cmap_table.buildReversedMin()
693 except AttributeError:
694 # Use buildReversed on fonttools < 4.57 and build a list of minimums from it
695 reverse_cmap = {k: min(r) for k, r in cmap_table.buildReversed().items()}
696 metrics = metrics_table.metrics
697 for gid, glyph in enumerate(tt_font_object.getGlyphOrder()):
698 # The following is to comply with how font_glyph_byte_map works in _appearance_stream.py
699 gid_key_string = gid.to_bytes(2, "big").decode("utf-16-be", "surrogatepass")
700 # Always map character width
701 character_widths[gid_key_string] = round(metrics[glyph][0] * scale_factor)
702 # Add GID to character_map when we can find it in the cmap
703 if (char_code := reverse_cmap.get(glyph)) is not None:
704 character_map[gid_key_string] = chr(char_code)
706 space_char = cls._get_space_char(encoding, character_map)
707 cls._add_default_width(character_widths, font_descriptor_kwargs["flags"], space_char)
708 space_width = cls._add_space_width(
709 character_widths, font_descriptor_kwargs["flags"], space_char
710 )
712 return cls(
713 name=font_descriptor.name,
714 sub_type="Type0",
715 encoding=encoding,
716 font_descriptor=font_descriptor,
717 character_map=character_map,
718 character_widths=character_widths,
719 space_width=space_width,
720 space_char=space_char,
721 interpretable=True
722 )
724 @classmethod
725 def from_core_font_name(cls, core_font_name: str = "/Helvetica") -> Font:
726 from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415
728 font_name = core_font_name.removeprefix("/")
729 core_font_metrics = CORE_FONT_METRICS[font_name]
730 win_ansi_encoding = encoding_dict_from_named_encoding("cp1252") # WinAnsiEncoding
732 font = cls(
733 name=font_name,
734 character_map={},
735 encoding=win_ansi_encoding,
736 sub_type="Type1",
737 font_descriptor=core_font_metrics.font_descriptor,
738 character_widths={
739 char: core_font_metrics.character_widths[character]
740 for code, character in win_ansi_encoding.items()
741 if (char := chr(code)) in core_font_metrics.character_widths
742 }
743 )
744 font.character_widths["default"] = core_font_metrics.character_widths["default"]
746 return font
748 def _get_typographic_maps(self) -> tuple[dict[str, str], dict[str, bytes]]:
749 """
750 Generates maps to translate input unicode text to bytes in two steps:
751 Unicode code point -> raw_character (reverse cmap) -> PDF bytes (encoding cmap).
752 """
753 reverse_cmap = {}
754 encoding_cmap = {}
755 if (
756 HAS_FONTTOOLS
757 and getattr(self.font_descriptor, "font_file", None)
758 and isinstance(self.encoding, str)
759 and (font_file_data := cast(StreamObject, self.font_descriptor.font_file).get_data()) is not None
760 ):
761 try:
762 tt_font_object = TTFont(BytesIO(font_file_data))
763 except MemoryError: # pragma: no cover # TODO: BLE001
764 raise
765 except Exception as exception: # Font file data is corrupt.
766 logger_warning("Could not open font file: %(exception)s", source=__name__, exception=exception)
767 else:
768 with tt_font_object:
769 # Read reverse_cmap and encoding_cmap from the font file if we can get a cmap
770 tt_font_cmap_table = self._load_fonttools_table(
771 table_name="cmap", is_critical=False, tt_font_object=tt_font_object
772 )
773 if tt_font_cmap_table and (best_cmap := tt_font_cmap_table.getBestCmap()):
774 for unicode_int, glyph_name in best_cmap.items():
775 gid = tt_font_object.getGlyphID(glyph_name)
776 gid_key_string = gid.to_bytes(2, "big").decode("utf-16-be", "surrogatepass")
777 unicode_char = chr(unicode_int)
778 reverse_cmap[unicode_char] = gid_key_string
779 encoding_cmap[gid_key_string] = gid_key_string.encode(self.encoding)
781 return reverse_cmap, encoding_cmap
783 if isinstance(self.encoding, str):
784 for glyph_id, unicode_char in self.character_map.items():
785 glyph_id_str = str(glyph_id)
786 reverse_cmap[unicode_char] = glyph_id_str
787 encoding_cmap[glyph_id_str] = glyph_id_str.encode(self.encoding)
788 else: # Encoding is a dict, which means we are dealing with a simple font
789 for character_code, unicode_char in self.encoding.items():
790 character_str = chr(character_code)
791 reverse_cmap[unicode_char] = character_str
792 encoding_cmap[character_str] = bytes((character_code,))
794 unicode_to_bytes = {
795 unicode_char: bytes((character_code,)) for character_code, unicode_char in self.encoding.items()
796 }
797 for character_code_str, unicode_char in self.character_map.items():
798 reverse_cmap[unicode_char] = character_code_str
799 encoding_cmap[character_code_str] = unicode_to_bytes.get(
800 unicode_char,
801 bytes((ord(character_code_str),))
802 )
804 return reverse_cmap, encoding_cmap
806 def _create_widths_list_and_unicode_stream(self) -> tuple[list[PdfObject], StreamObject]:
807 from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS # noqa: PLC0415
809 widths_list = []
810 unicode_map = []
811 bfchar_map: list[str] = []
813 # Composite/CID fonts use 4-hex digits, simple fonts use 2-hex digits
814 src_hex_format = "{cid:04X}" if self.sub_type == "Type0" else "{cid:02X}"
815 codespace_min = "0000" if self.sub_type == "Type0" else "00"
816 codespace_max = "FFFF" if self.sub_type == "Type0" else "FF"
817 cmap_name = "Adobe-Identity-UCS" if self.sub_type == "Type0" else "Custom-Simple-8Bit"
818 cid_system_info = (
819 "/CIDSystemInfo <<\n/Registry (Adobe)\n/Ordering (UCS)\n/Supplement 0\n>> def\n"
820 if self.sub_type == "Type0" else ""
821 )
823 # If we have self.character_map then use that. Otherwise fall back to self.encoding.
824 mapping_source = (self.character_map or cast(dict[int, str], self.encoding)).items()
826 # In the loop, src_id is the decoded GID string (the reverse unicode hack) or the character code
827 # and actual_char is the actual character.
828 for src_id, actual_char in mapping_source:
829 # Make sure that we do not include characters such as arabic presentation form characters.
830 # Note that, in some cases, unicodedata.normalize() might split a ligature, resulting
831 # in multiple characters.
832 normalized_chars = unicodedata.normalize("NFKC", actual_char)
833 cid = ord(src_id) if isinstance(src_id, str) else src_id
834 cid_hex = src_hex_format.format(cid=cid)
835 uni_hex = normalized_chars.encode("utf-16-be").hex().upper()
836 bfchar_map.append(f"<{cid_hex}> <{uni_hex}>")
838 # Width mapping, but not for the 14 Adobe code fonts, which are dealt with elsewhere.
839 if self.name not in CORE_FONT_METRICS:
840 # The widths (/W) array can have two formats:
841 # [first_cid [w1 w2 w3]] or [first last width]
842 # Here we choose the first format and simply provide one array with one width for every cid.
843 width = self.character_widths.get(cast(str, src_id), self.character_widths["default"])
844 widths_list.extend([NumberObject(cid), ArrayObject([NumberObject(width)])])
846 while partial_list := bfchar_map[:CMAP_MAX_ENTRIES_PER_GROUP]:
847 del bfchar_map[:CMAP_MAX_ENTRIES_PER_GROUP]
848 unicode_map.append(f"{len(partial_list)} beginbfchar")
849 unicode_map.extend(partial_list)
850 unicode_map.append("endbfchar")
852 # Create the /ToUnicode CMap Stream
853 to_unicode_stream = StreamObject()
854 to_unicode_stream.set_data(
855 (
856 "/CIDInit /ProcSet findresource begin\n"
857 "12 dict begin\n"
858 "begincmap\n"
859 f"{cid_system_info}"
860 f"/CMapName /{cmap_name} def\n"
861 f"/CMapType 2 def\n"
862 f"1 begincodespacerange <{codespace_min}> <{codespace_max}> endcodespacerange\n"
863 + "\n".join(unicode_map) + "\n"
864 "endcmap\n"
865 "CMapName currentdict /CMap defineresource pop\n"
866 "end end"
867 ).encode("ascii")
868 )
870 return widths_list, to_unicode_stream
872 def as_font_resource(self) -> DictionaryObject:
873 # If we have an embedded Truetype font, we assume that we need to produce a Type 2 CID font resource.
874 # We check that we are 16-bit encoded, that is, Type0.
875 if self.font_descriptor.font_file and self.sub_type == "Type0":
876 # Begin with creating the widths array (part of the descendant font) and the unicode cmap (part
877 # of the Type 0 font object).
878 widths_list, to_unicode_stream = self._create_widths_list_and_unicode_stream()
880 # Create the descendant font object
881 cid_font = DictionaryObject({
882 NameObject("/Type"): NameObject("/Font"),
883 NameObject("/Subtype"): NameObject("/CIDFontType2"),
884 NameObject("/BaseFont"): NameObject(f"/{self.name}"),
885 NameObject("/CIDSystemInfo"): DictionaryObject({
886 NameObject("/Registry"): TextStringObject("Adobe"),
887 NameObject("/Ordering"): TextStringObject("Identity"),
888 NameObject("/Supplement"): NumberObject(0)
889 }),
890 NameObject("/FontDescriptor"): self.font_descriptor.as_font_descriptor_resource(),
891 NameObject("/W"): ArrayObject(widths_list),
892 NameObject("/DW"): NumberObject(self.character_widths["default"]),
893 NameObject("/CIDToGIDMap"): NameObject("/Identity")
894 })
896 # Create the Type 0 font object
897 return DictionaryObject({
898 NameObject("/Type"): NameObject("/Font"),
899 NameObject("/Subtype"): NameObject("/Type0"),
900 NameObject("/BaseFont"): NameObject(f"/{self.name}"),
901 NameObject("/Encoding"): NameObject("/Identity-H"),
902 NameObject("/DescendantFonts"): ArrayObject([cid_font]),
903 NameObject("/ToUnicode"): to_unicode_stream,
904 })
906 # Fallback: Return a font resource for one of the 14 Adobe Core fonts.
907 win_ansi_encoding = encoding_dict_from_named_encoding("cp1252")
908 differences_list: list[NumberObject | NameObject] = []
909 reverse_adobe_glyphs = {value: key for key, value in adobe_glyphs.items()}
910 own_encoding: dict[int, str] = cast(dict[int, str], self.encoding)
911 for idx, character_code in win_ansi_encoding.items():
912 encoding_char = own_encoding.get(idx)
913 if encoding_char and encoding_char != character_code:
914 differences_list.extend([NumberObject(idx), NameObject(reverse_adobe_glyphs[encoding_char])])
916 if differences_list:
917 encoding: DictionaryObject | NameObject = DictionaryObject({
918 NameObject("/BaseEncoding"): NameObject("/WinAnsiEncoding"),
919 NameObject("/Differences"): ArrayObject(differences_list),
920 })
921 else:
922 encoding = NameObject("/WinAnsiEncoding")
924 simple_font = DictionaryObject({
925 NameObject("/Type"): NameObject("/Font"),
926 NameObject("/Subtype"): NameObject("/Type1"),
927 NameObject("/Name"): NameObject(f"/{self.name}"),
928 NameObject("/BaseFont"): NameObject(f"/{self.name}"),
929 NameObject("/Encoding"): encoding
930 })
932 if differences_list:
933 _, to_unicode_stream = self._create_widths_list_and_unicode_stream()
934 simple_font[NameObject("/ToUnicode")] = to_unicode_stream
936 return simple_font
938 def _add_to_writer(
939 self,
940 writer: PdfWriter,
941 target_resource_dict: DictionaryObject,
942 font_resource_name: NameObject
943 ) -> IndirectObject:
944 """
945 Some objects in a font resource need to be indirect objects. This method
946 ensures that ToUnicode, FontDescriptor, FontFile, and, ultimately, the font
947 resource itself, are registered with the PdfWriter instance as indirect objects.
948 """
949 font_resource = self.as_font_resource()
950 if "/ToUnicode" in font_resource:
951 font_resource[NameObject("/ToUnicode")] = writer._add_object(font_resource["/ToUnicode"])
953 if "/DescendantFonts" in font_resource:
954 descendant_fonts = cast(ArrayObject, font_resource["/DescendantFonts"])
955 font_resource_dict = cast(DictionaryObject, descendant_fonts[0])
956 else:
957 font_resource_dict = font_resource
959 if "/FontDescriptor" in font_resource_dict:
960 font_descriptor_obj = cast(DictionaryObject, font_resource_dict["/FontDescriptor"])
961 for key in ["/FontFile", "/FontFile2", "/FontFile3"]:
962 if key in font_descriptor_obj:
963 font_descriptor_obj[NameObject(key)] = writer._add_object(font_descriptor_obj[key])
964 font_resource_dict[NameObject("/FontDescriptor")] = writer._add_object(
965 font_resource_dict["/FontDescriptor"]
966 )
967 font_resource_ref = writer._add_object(font_resource)
968 target_resource_dict[font_resource_name] = font_resource_ref
969 return font_resource_ref
971 def get_text_width(self, text: str = "") -> float:
972 """Sum of character widths specified in PDF font for the supplied text."""
973 return sum(
974 [self.character_widths.get(char, self.character_widths["default"]) for char in text], 0.0
975 )
977 def can_encode(self, text: str) -> bool:
978 """Check whether the font is able to encode a text string."""
979 if self.character_map:
980 supported_chars = set(self.character_map.values())
981 return all(char in supported_chars for char in text)
983 if isinstance(self.encoding, dict):
984 supported_chars = set(self.encoding.values())
985 return all(char in supported_chars for char in text)
987 # Not a simple font (encoding is not a dict), and missing ToUnicode cmap (no character_map).
988 # Assume we cannot use this font for text encoding.
989 return False