Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_cmap.py: 11%
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
1import re
2from binascii import Error as BinasciiError
3from binascii import unhexlify
4from functools import partial
5from hashlib import sha256
6from io import BytesIO
7from typing import Any, cast
9from ._codecs import adobe_glyphs, charset_encoding
10from ._utils import logger_error, logger_warning
11from .errors import LimitReachedError
12from .generic import (
13 ArrayObject,
14 DecodedStreamObject,
15 DictionaryObject,
16 PdfObject,
17 StreamObject,
18 is_null_or_none,
19)
20from .generic._data_structures import _FontFileEncoding
22_predefined_cmap: dict[str, str] = {
23 "/Identity-H": "utf-16-be",
24 "/Identity-V": "utf-16-be",
25 "/GB-EUC-H": "gbk",
26 "/GB-EUC-V": "gbk",
27 "/GBpc-EUC-H": "gb2312",
28 "/GBpc-EUC-V": "gb2312",
29 "/GBK-EUC-H": "gbk",
30 "/GBK-EUC-V": "gbk",
31 "/GBK2K-H": "gb18030",
32 "/GBK2K-V": "gb18030",
33 "/ETen-B5-H": "cp950",
34 "/ETen-B5-V": "cp950",
35 "/ETenms-B5-H": "cp950",
36 "/ETenms-B5-V": "cp950",
37 # Unicode-based CMaps: character codes are UTF-16BE, see
38 # ISO 32000-2:2020, 9.7.5.2, Note 1 and Table 116.
39 # (UniGB covers the GB18030-2000 character set but is not GB18030-encoded.)
40 "/UniCNS-UTF16-H": "utf-16-be",
41 "/UniCNS-UTF16-V": "utf-16-be",
42 "/UniGB-UTF16-H": "utf-16-be",
43 "/UniGB-UTF16-V": "utf-16-be",
44 # Japanese CMaps (PDF Reference 1.7, Appendix H)
45 "/90ms-RKSJ-H": "cp932", # Shift-JIS (JIS X 0208-1990), horizontal
46 "/90ms-RKSJ-V": "cp932", # Shift-JIS (JIS X 0208-1990), vertical
47 "/UniJIS-UTF16-H": "utf-16-be", # Unicode UTF-16BE -> JIS, horizontal
48 "/UniJIS-UTF16-V": "utf-16-be", # Unicode UTF-16BE -> JIS, vertical
49 # UCS2 in code
50}
53def get_encoding(
54 ft: DictionaryObject
55) -> tuple[str | dict[int, str], dict[Any, Any]]:
56 encoding = _parse_encoding(ft)
57 map_dict, int_entry = _parse_to_unicode(ft)
59 # Apply rule from PDF ref 1.7 §5.9.1, 1st bullet:
60 # if cmap not empty encoding should be discarded
61 # (here transformed into identity for those characters)
62 # If encoding is a string, it is expected to be an identity translation.
63 if isinstance(encoding, dict):
64 for x in int_entry:
65 if x <= 255:
66 encoding[x] = chr(x)
68 return encoding, map_dict
71def _parse_encoding(
72 ft: DictionaryObject
73) -> str | dict[int, str]:
74 encoding: str | list[str] | dict[int, str] = []
75 embedded_font_encoding: dict[int, str] = {}
77 enc: PdfObject | None = None
78 if "/Encoding" in ft:
79 enc = ft["/Encoding"] # Returns one of NameObject, DictionaryObject, or NullObject
81 has_no_encoding = is_null_or_none(enc)
82 has_no_base_encoding = isinstance(enc, DictionaryObject) and "/BaseEncoding" not in enc
84 # For embedded simple fonts, parse the font programme as a basis, but only when encoding is not defined
85 # or when base encoding is absent from an encoding dictionary.
86 if (
87 (has_no_encoding or has_no_base_encoding) and
88 ft.get("/Subtype", "") == "/Type1"
89 ):
90 embedded_font_encoding = _parse_encoding_from_embedded_font(ft)
92 # When ft["/Encoding"] is absent or cannot be used, use StandardEncoding as a basis, and add
93 # what the embedded font file encoding says, if present. See Table 114, PDF Reference 1.7 / 2.0
94 if has_no_encoding or (has_no_base_encoding and "/Differences" not in cast(DictionaryObject, enc)):
95 if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding:
96 # This will match Symbol and ZapfDingBats
97 encoding = dict(
98 zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])])
99 )
100 else:
101 # Set StandardEncoding as fallback option.
102 encoding = dict(
103 zip(range(256), charset_encoding["/StandardEncoding"])
104 )
105 # Overwrite the standard encoding with the encoding information from the embedded font file.
106 _correct_encoding(embedded_font_encoding, encoding)
107 return encoding
109 if isinstance(enc, str):
110 try:
111 # already done : enc = NameObject.unnumber(enc.encode()).decode()
112 # for #xx decoding
113 if enc in charset_encoding:
114 encoding = charset_encoding[enc].copy()
115 elif enc in _predefined_cmap:
116 encoding = _predefined_cmap[enc]
117 elif "-UCS2-" in enc:
118 encoding = "utf-16-be"
119 else:
120 raise KeyError("not found")
121 except KeyError:
122 encoding = (
123 "utf-16-be" if ft.get("/Subtype", "") == "/Type0" else charset_encoding["/StandardEncoding"].copy()
124 )
125 logger_error(
126 "Advanced encoding %(encoding)s not implemented yet, using %(new_encoding)s instead.",
127 source=__name__,
128 encoding=enc,
129 new_encoding=encoding
130 )
131 elif isinstance(enc, DictionaryObject) and "/BaseEncoding" in enc:
132 try:
133 encoding = charset_encoding[cast(str, enc["/BaseEncoding"])].copy()
134 except KeyError:
135 logger_error(
136 "Advanced encoding %(encoding)s not implemented yet",
137 source=__name__, encoding=encoding
138 )
139 encoding = charset_encoding["/StandardEncoding"].copy()
140 else:
141 encoding = charset_encoding["/StandardEncoding"].copy()
143 if isinstance(enc, DictionaryObject) and "/Differences" in enc:
144 # Overwrite the standard encoding with the encoding information from the embedded font file, if applicable.
145 _correct_encoding(embedded_font_encoding, encoding)
147 code: int = 0
148 differences = enc["/Differences"]
149 if not isinstance(differences, ArrayObject):
150 logger_warning(
151 "Font encoding differences are not an array: %(differences)s",
152 source=__name__,
153 differences=differences,
154 )
155 differences = ArrayObject()
156 for entry in differences:
157 entry = entry.get_object()
158 if isinstance(entry, int):
159 code = entry
160 elif isinstance(entry, str):
161 try:
162 if code < len(encoding):
163 encoding[code] = _glyph_name_to_unicode(entry) or entry
164 except MemoryError: # pragma: no cover # TODO: BLE001
165 raise
166 except Exception:
167 encoding[code] = entry
168 code += 1
169 else:
170 # Table 114 of the PDF 2.0 specification only allows character
171 # codes and glyph names here. Anything else would end up in the
172 # text and break the decoding later on.
173 logger_warning(
174 "Ignoring invalid font encoding difference: %(entry)s",
175 source=__name__,
176 entry=entry,
177 )
178 if isinstance(encoding, list):
179 encoding = dict(zip(range(256), encoding))
181 return encoding
184def _parse_to_unicode(
185 ft: DictionaryObject
186) -> tuple[dict[Any, Any], list[int]]:
187 # We store all character mappings in map_dict. In map_dict[-1] we store the byte length
188 # of the character codes (or CIDs) encoded inside the ToUnicode stream.
189 map_dict: dict[Any, Any] = {}
190 int_entry: list[int] = []
192 if "/ToUnicode" not in ft:
193 return map_dict, int_entry
195 process_rg: bool = False
196 process_char: bool = False
197 multiline_rg: (
198 tuple[int, int] | None
199 ) = None # tuple = (current_char, remaining size) ; cf #1285 for example of file
200 cm = prepare_cm(ft)
201 for line in cm.split(b"\n"):
202 process_rg, process_char, multiline_rg = process_cm_line(
203 line.strip(b" \t"),
204 process_rg,
205 process_char,
206 multiline_rg,
207 map_dict,
208 int_entry,
209 )
211 map_dict.pop(-1, None) # Don't pass the -1 key, we only used it to temporarily store encoding length
213 return map_dict, int_entry
216def prepare_cm(ft: DictionaryObject) -> bytes:
217 tu = ft["/ToUnicode"]
218 cm: bytes
219 if isinstance(tu, StreamObject):
220 cm = cast(DecodedStreamObject, ft["/ToUnicode"]).get_data()
221 else: # if (tu is None) or cast(str, tu).startswith("/Identity"):
222 # the full range 0000-FFFF will be processed
223 cm = b"beginbfrange\n<0000> <0001> <0000>\nendbfrange"
224 if isinstance(cm, str):
225 cm = cm.encode()
226 # we need to prepare cm before due to missing return line in pdf printed
227 # to pdf from word
228 cm = (
229 cm.strip()
230 .replace(b"beginbfchar", b"\nbeginbfchar\n")
231 .replace(b"endbfchar", b"\nendbfchar\n")
232 .replace(b"beginbfrange", b"\nbeginbfrange\n")
233 .replace(b"endbfrange", b"\nendbfrange\n")
234 .replace(b"<<", b"\n{\n") # text between << and >> not used but
235 .replace(b">>", b"\n}\n") # some solution to find it back
236 )
237 ll = cm.split(b"<")
238 for i in range(len(ll)):
239 j = ll[i].find(b">")
240 if j >= 0:
241 if j == 0:
242 # string is empty: stash a placeholder here (see below)
243 # see https://github.com/py-pdf/pypdf/issues/1111
244 content = b"."
245 else:
246 content = ll[i][:j].replace(b" ", b"")
247 ll[i] = content + b" " + ll[i][j + 1 :]
248 cm = (
249 (b" ".join(ll))
250 .replace(b"[", b" [ ")
251 .replace(b"]", b" ]\n ")
252 .replace(b"\r", b"\n")
253 )
254 return cm
257def process_cm_line(
258 line: bytes,
259 process_rg: bool,
260 process_char: bool,
261 multiline_rg: tuple[int, int] | None,
262 map_dict: dict[Any, Any],
263 int_entry: list[int],
264) -> tuple[bool, bool, tuple[int, int] | None]:
265 if line == b"" or line[0] == 37: # 37 = %
266 return process_rg, process_char, multiline_rg
267 line = line.replace(b"\t", b" ")
268 if b"beginbfrange" in line:
269 process_rg = True
270 elif b"endbfrange" in line:
271 process_rg = False
272 elif b"beginbfchar" in line:
273 process_char = True
274 elif b"endbfchar" in line:
275 process_char = False
276 elif process_rg:
277 try:
278 multiline_rg = parse_bfrange(line, map_dict, int_entry, multiline_rg)
279 except (ValueError, IndexError) as error:
280 logger_warning("Skipping broken line %(line)r: %(error)s", source=__name__, line=line, error=error)
281 elif process_char:
282 try:
283 parse_bfchar(line, map_dict, int_entry)
284 except ValueError as error:
285 logger_warning("Skipping broken line %(line)r: %(error)s", source=__name__, line=line, error=error)
286 return process_rg, process_char, multiline_rg
289# Usual values should be up to 65_536.
290MAPPING_DICTIONARY_SIZE_LIMIT = 100_000
292# Typical /ToUnicode CMaps use 1-4 byte source codes.
293# This is intentionally generous.
294# The actual limit is doubled, as each byte is represented by two hex characters.
295MAX_CMAP_CODE_BYTES = 8
296MAX_CMAP_STRING_BYTES = 512
297MAX_CMAP_CODE_BYTES_LIMIT = MAX_CMAP_CODE_BYTES * 2
298MAX_CMAP_STRING_BYTES_LIMIT = MAX_CMAP_STRING_BYTES * 2
301def _check_mapping_size(size: int) -> None:
302 if size > MAPPING_DICTIONARY_SIZE_LIMIT:
303 raise LimitReachedError(f"Maximum /ToUnicode size limit reached: {size} > {MAPPING_DICTIONARY_SIZE_LIMIT}.")
306def _check_token_length(token: bytes, limit: int) -> None:
307 token_length = len(token)
308 if token_length > limit:
309 description = {
310 MAX_CMAP_CODE_BYTES_LIMIT: "code",
311 MAX_CMAP_STRING_BYTES_LIMIT: "string",
312 }.get(limit, "token")
314 raise LimitReachedError(
315 f"Maximum /ToUnicode {description} length exceeded: {token_length} > {limit}."
316 )
319def __parse_bfrange__decode(map_dict: dict[Any, Any], code: int) -> str:
320 # `map_dict[-1]` is the number of bytes each source code occupies. Building
321 # the bytes directly with `int.to_bytes` avoids the hex round-trip of
322 # `unhexlify(b"%%0%dX" % (map_dict[-1] * 2) % code)` (format to hex, parse
323 # the hex back to bytes), which is measurably cheaper for large maps.
324 return code.to_bytes(map_dict[-1], "big").decode(
325 "charmap" if map_dict[-1] == 1 else "utf-16-be",
326 "surrogatepass",
327 )
330def parse_bfrange(
331 line: bytes,
332 map_dict: dict[Any, Any],
333 int_entry: list[int],
334 multiline_rg: tuple[int, int] | None,
335) -> tuple[int, int] | None:
336 entry_count = len(int_entry)
337 _check_mapping_size(entry_count)
339 # Bound tokenization to the range header, the remaining allowed
340 # destinations, and one extra token to detect a mapping-limit violation.
341 allowed_length = MAPPING_DICTIONARY_SIZE_LIMIT - entry_count
342 max_splits = 3 + max(allowed_length, 0) + 1
343 lst = line.split(maxsplit=max_splits)
345 closure_found = False
346 decode_utf16 = partial(bytes.decode, encoding="utf-16-be", errors="surrogatepass")
347 if multiline_rg is not None:
348 a = multiline_rg[0] # a, b not in the current line
349 b = multiline_rg[1]
350 for sq in lst:
351 if sq == b"]":
352 closure_found = True
353 break
354 _check_token_length(sq, limit=MAX_CMAP_STRING_BYTES_LIMIT)
355 entry_count += 1
356 _check_mapping_size(entry_count)
357 map_dict[
358 __parse_bfrange__decode(map_dict=map_dict, code=a)
359 ] = decode_utf16(unhexlify(sq))
360 int_entry.append(a)
361 a += 1
362 else:
363 _check_token_length(lst[0], limit=MAX_CMAP_CODE_BYTES_LIMIT)
364 _check_token_length(lst[1], limit=MAX_CMAP_CODE_BYTES_LIMIT)
365 a = int(lst[0], 16)
366 b = int(lst[1], 16)
367 if a < 0 or b < 0:
368 # int(token, 16) accepts a leading "-"; negative range bounds
369 # would leak an OverflowError from the to_bytes encoding below.
370 raise ValueError(f"Negative bfrange source range: {lst[0]!r} {lst[1]!r}")
371 nbi = max(len(lst[0]), len(lst[1]))
372 map_dict[-1] = (nbi + 1) // 2
373 if lst[2] == b"[":
374 for sq in lst[3:]:
375 if sq == b"]":
376 closure_found = True
377 break
378 _check_token_length(sq, limit=MAX_CMAP_STRING_BYTES_LIMIT)
379 entry_count += 1
380 _check_mapping_size(entry_count)
381 map_dict[
382 __parse_bfrange__decode(map_dict=map_dict, code=a)
383 ] = decode_utf16(unhexlify(sq))
384 int_entry.append(a)
385 a += 1
386 else: # case without list
387 _check_token_length(lst[2], limit=MAX_CMAP_STRING_BYTES_LIMIT)
388 c = int(lst[2], 16)
389 fmt2 = b"%%0%dX" % max(4, len(lst[2]))
390 closure_found = True
391 range_size = max(0, b - a + 1)
392 _check_mapping_size(entry_count + range_size) # This can be checked beforehand.
393 while a <= b:
394 destination = unhexlify(fmt2 % c)
395 _check_token_length(destination, limit=MAX_CMAP_CODE_BYTES_LIMIT)
396 map_dict[
397 __parse_bfrange__decode(map_dict=map_dict, code=a)
398 ] = decode_utf16(destination)
399 int_entry.append(a)
400 a += 1
401 c += 1
402 return None if closure_found else (a, b)
405# Match non-empty tokens using the same separator as the `parse_bfchar` split call.
406_NON_SPACE_RUN = re.compile(rb"[^ ]+")
409def parse_bfchar(line: bytes, map_dict: dict[Any, Any], int_entry: list[int]) -> None:
410 # Estimate the number of mappings using the number of separators.
411 # Only count tokens exactly when the estimate indicates that the mapping
412 # size limit might be exceeded. This avoids regex scanning for normal CMaps.
413 if len(int_entry) + (line.count(b" ") + 1) // 2 > MAPPING_DICTIONARY_SIZE_LIMIT:
414 token_count = sum(1 for _ in _NON_SPACE_RUN.finditer(line))
415 _check_mapping_size(len(int_entry) + token_count // 2)
417 lst = [x for x in line.split(b" ") if x]
418 lst_length = len(lst)
419 if lst_length == 0:
420 logger_warning("Skipping broken line %(line)r: Line is empty.", source=__name__, line=line)
421 return
422 if lst_length % 2:
423 logger_warning("Ignoring final token of odd-length line %(line)r.", source=__name__, line=line)
425 map_dict[-1] = len(lst[0]) // 2
427 for index in range(0, lst_length - 1, 2):
428 source = lst[index]
429 destination = lst[index + 1]
431 _check_token_length(source, limit=MAX_CMAP_CODE_BYTES_LIMIT)
433 map_to = ""
434 # placeholder (see above) means empty string
435 if destination != b".":
436 _check_token_length(destination, limit=MAX_CMAP_STRING_BYTES_LIMIT)
437 try:
438 map_to = unhexlify(destination).decode(
439 "charmap" if len(destination) < 4 else "utf-16-be", "surrogatepass"
440 ) # join is here as some cases where the code was split
441 except BinasciiError as exception:
442 logger_warning(
443 "Got invalid hex string: %(exception)s (%(destination)r)",
444 source=__name__,
445 exception=exception,
446 destination=destination,
447 )
448 map_dict[
449 unhexlify(source).decode(
450 "charmap" if map_dict[-1] == 1 else "utf-16-be", "surrogatepass"
451 )
452 ] = map_to
453 int_entry.append(int(source, 16))
456def _correct_encoding(
457 embedded_font_encoding: dict[int, str] | None,
458 encoding: dict[int, str] | list[str]
459) -> None:
460 if not embedded_font_encoding:
461 return
463 for character_code, unicode_code_point in embedded_font_encoding.items():
464 encoding[character_code] = unicode_code_point
467def _parse_encoding_from_embedded_font(font_dictionary: DictionaryObject) -> dict[int, str]:
468 """
469 Derive the encoding from an embedded font program, caching the result on its stream. See Table 126
470 about embedded font file organization in the PDF specification 1.7 for details
472 The encoding depends only on the decoded font data, and the same font program is reached from every
473 font dictionary, resource name and page referencing its stream. Parsing a font program with fontTools is
474 expensive, so each stream is parsed once and reused until its data changes, which a digest of the data
475 detects (a writer may replace the font program). See #4156.
476 """
477 if (
478 "/FontDescriptor" not in font_dictionary or
479 not isinstance(font_descriptor := font_dictionary["/FontDescriptor"], DictionaryObject)
480 ):
481 return {}
483 if not any(
484 (font_file := target) in font_descriptor
485 and isinstance(font_file_dict := cast(StreamObject, font_descriptor[font_file]), StreamObject)
486 for target in ("/FontFile", "/FontFile3")
487 ):
488 return {}
490 font_file_handlers = {
491 # A normal Type1 font file, can be part of a Type1 or MMType1 font dictionary.
492 "/FontFile": _derive_encoding_from_type1_font_file,
493 # A CFF Type1 font file, as part of a Type1 or MMType1 font dictionary.
494 "/FontFile3": _derive_encoding_from_cff_type1_font_file,
495 }
496 font_file_processor = font_file_handlers[font_file]
498 from .generic._font import HAS_FONTTOOLS # noqa: PLC0415
499 if font_file == "/FontFile3" and not HAS_FONTTOOLS:
500 logger_warning(
501 (
502 "fontTools is required to fully parse the encoding of a CFF Type1 font in font "
503 "dictionary %(font_dictionary)s, but is not installed. Consider installing "
504 "fontTools if you encounter encoding problems."
505 ),
506 source=__name__,
507 font_dictionary=font_dictionary,
508 )
509 return {}
511 if not (font_file_data := font_file_dict.get_data()):
512 return {}
514 digest = sha256(font_file_data).digest()
515 cached = font_file_dict._font_file_encoding
516 if cached is None or cached.digest != digest:
517 cached_encoding = font_file_processor(font_file_data)
518 cached = _FontFileEncoding(digest, cached_encoding)
519 font_file_dict._font_file_encoding = cached
520 return cached.embedded_font_encoding
523def _glyph_name_to_unicode(glyph_name: str) -> str | None:
524 try:
525 return adobe_glyphs[glyph_name]
526 except KeyError:
527 if glyph_name.startswith("/uni"):
528 code_point = glyph_name[4:]
529 elif glyph_name.startswith("/u"):
530 code_point = glyph_name[2:]
531 else:
532 return None
533 try:
534 return chr(int(code_point, 16))
535 except ValueError: # pragma: no cover
536 return None
539def _derive_encoding_from_cff_type1_font_file(font_data: bytes) -> dict[int, str]:
540 embedded_font_encoding: dict[int, str] = {}
541 try:
542 from fontTools.cffLib import CFFFontSet # noqa: PLC0415
543 cff_set = CFFFontSet()
544 cff_set.decompile(BytesIO(font_data), None)
545 cff_font = cff_set.topDictIndex[0]
546 cff_encoding = cff_font.Encoding
547 # Encoding can fall back to literal strings "StandardEncoding" or "ExpertEncoding", which we do not parse.
548 if isinstance(cff_encoding, str):
549 return embedded_font_encoding
550 for i in range(min(len(cff_encoding), 256)):
551 glyph_name = cff_encoding[i]
552 if not glyph_name or glyph_name == ".notdef":
553 continue
554 if unipoint := _glyph_name_to_unicode(f"/{glyph_name}"):
555 embedded_font_encoding[i] = unipoint
556 except MemoryError: # pragma: no cover # TODO: BLE001
557 raise
558 except Exception:
559 return embedded_font_encoding
560 else:
561 return embedded_font_encoding
564def _derive_encoding_from_type1_font_file(font_data: bytes) -> dict[int, str]:
565 embedded_font_encoding: dict[int, str] = {}
566 txt = font_data.split(b"eexec\n")[0] # Only the clear part
567 encoding_part = txt.split(b"/Encoding")
568 if len(encoding_part) < 2:
569 return embedded_font_encoding
570 txt = encoding_part[1] # To get the encoding part
571 lines = txt.replace(b"\r", b"\n").split(b"\n")
572 for li in lines:
573 # A line should be of format 'dup 63 /question put'
574 if li.startswith(b"dup"):
575 words = li.replace(b"/", b" /").split()
576 # We require four elements to parse a line:
577 # 1. "dup" (words[0]), which starts the code definition;
578 # 2. the character code (words[1]);
579 # 3. the glyph name (words[2]); and
580 # 4. "put" (words[3]), which ends the code definition.
581 if len(words) < 4 or words[3] != b"put":
582 continue
583 try:
584 i = int(words[1])
585 except ValueError:
586 continue
587 # Ensure the character code stays strictly within the 8-bit limit (0-255)
588 if 0 <= i <= 255 and (unipoint := _glyph_name_to_unicode(words[2].decode())):
589 embedded_font_encoding[i] = unipoint
591 return embedded_font_encoding