forked from py-pdf/fpdf2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfonts.py
3264 lines (3162 loc) · 63.1 KB
/
fonts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Font-related classes & constants.
Includes the definition of the character widths of all PDF standard fonts.
The contents of this module are internal to fpdf2, and not part of the public API.
They may change at any time without prior warning or any deprecation period,
in non-backward-compatible ways.
"""
import re, warnings
import logging
from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass, replace
from functools import lru_cache
from typing import List, Optional, Tuple, Union
from fontTools import ttLib
from fontTools.pens.ttGlyphPen import TTGlyphPen
try:
import uharfbuzz as hb
# pylint: disable=no-member
class HarfBuzzFont(hb.Font):
"uharfbuzz.Font than can be deepcopied"
# cf. issue #1075, avoids: TypeError: no default __reduce__ due to non-trivial __cinit__
def __deepcopy__(self, _memo):
return self
except ImportError:
hb = None
from .deprecation import get_stack_level
from .drawing import convert_to_device_color, DeviceGray, DeviceRGB
from .enums import FontDescriptorFlags, TextEmphasis, Align
from .syntax import Name, PDFObject
from .util import escape_parens
LOGGER = logging.getLogger(__name__)
@dataclass
class FontFace:
"""
Represent basic font styling properties.
This is a subset of `fpdf.graphics_state.GraphicsStateMixin` properties.
"""
__slots__ = ( # RAM usage optimization
"family",
"emphasis",
"size_pt",
"color",
"fill_color",
)
family: Optional[str]
emphasis: Optional[TextEmphasis] # None means "no override"
# Whereas "" means "no emphasis"
# This can be a combination: B | U
size_pt: Optional[int]
# Colors are single number grey scales or (red, green, blue) tuples:
color: Optional[Union[DeviceGray, DeviceRGB]]
fill_color: Optional[Union[DeviceGray, DeviceRGB]]
def __init__(
self, family=None, emphasis=None, size_pt=None, color=None, fill_color=None
):
self.family = family
self.emphasis = None if emphasis is None else TextEmphasis.coerce(emphasis)
self.size_pt = size_pt
self.color = None if color is None else convert_to_device_color(color)
self.fill_color = (
None if fill_color is None else convert_to_device_color(fill_color)
)
replace = replace
@staticmethod
def _override(current_value, override_value):
"""Override the current value if an override value is provided"""
return current_value if override_value is None else override_value
@staticmethod
def combine(default_style, override_style):
"""
Create a combined FontFace with all the supplied features of the two styles. When both
the default and override styles provide a feature, prefer the override style.
Override specified FontFace style features
Override this FontFace's values with the values of `other`.
Values of `other` that are None in this FontFace will be kept unchanged.
"""
if override_style is None:
return default_style
if default_style is None:
return override_style
if not isinstance(override_style, FontFace):
raise TypeError(f"Cannot combine FontFace with {type(override_style)}")
if not isinstance(default_style, FontFace):
raise TypeError(f"Cannot combine FontFace with {type(default_style)}")
return FontFace(
family=FontFace._override(default_style.family, override_style.family),
emphasis=FontFace._override(
default_style.emphasis,
override_style.emphasis,
),
size_pt=FontFace._override(default_style.size_pt, override_style.size_pt),
color=FontFace._override(default_style.color, override_style.color),
fill_color=FontFace._override(
default_style.fill_color, override_style.fill_color
),
)
class TextStyle(FontFace):
"""
Subclass of `FontFace` that allows to specify vertical & horizontal spacing
"""
def __init__(
self,
font_family: Optional[str] = None, # None means "no override"
# Whereas "" means "no emphasis"
font_style: Optional[str] = None,
font_size_pt: Optional[int] = None,
color: Union[int, tuple] = None, # grey scale or (red, green, blue),
fill_color: Union[int, tuple] = None, # grey scale or (red, green, blue),
underline: bool = False,
t_margin: Optional[int] = None,
l_margin: Union[Optional[int], Optional[Align], Optional[str]] = None,
b_margin: Optional[int] = None,
):
super().__init__(
font_family,
((font_style or "") + "U") if underline else font_style,
font_size_pt,
color,
fill_color,
)
self.t_margin = t_margin or 0
if isinstance(l_margin, (int, float)):
self.l_margin = l_margin
elif l_margin:
self.l_margin = Align.coerce(l_margin)
else:
self.l_margin = 0
self.b_margin = b_margin or 0
def __repr__(self):
return (
super().__repr__()[:-1]
+ f", t_margin={self.t_margin}, l_margin={self.l_margin}, b_margin={self.b_margin})"
)
def replace(
self,
/,
font_family=None,
emphasis=None,
font_size_pt=None,
color=None,
fill_color=None,
t_margin=None,
l_margin=None,
b_margin=None,
):
return TextStyle(
font_family=font_family or self.family,
font_style=self.emphasis if emphasis is None else emphasis.style,
font_size_pt=font_size_pt or self.size_pt,
color=color or self.color,
fill_color=fill_color or self.fill_color,
t_margin=self.t_margin if t_margin is None else t_margin,
l_margin=self.l_margin if l_margin is None else l_margin,
b_margin=self.b_margin if b_margin is None else b_margin,
)
class TitleStyle(TextStyle):
def __init__(self, *args, **kwargs):
warnings.warn(
(
"fpdf.TitleStyle is deprecated since 2.8.0."
" It has been replaced by fpdf.TextStyle."
),
DeprecationWarning,
stacklevel=get_stack_level(),
)
super().__init__(*args, **kwargs)
__pdoc__ = {"TitleStyle": False} # Replaced by TextStyle
class CoreFont:
# RAM usage optimization:
__slots__ = (
"i",
"type",
"name",
"sp",
"ss",
"up",
"ut",
"cw",
"fontkey",
"emphasis",
)
def __init__(self, fpdf, fontkey, style):
self.i = len(fpdf.fonts) + 1
self.type = "core"
self.name = CORE_FONTS[fontkey]
self.sp = 250 # strikethrough horizontal position
self.ss = 50 # strikethrough size (height)
self.up = -100 # underline horizontal position
self.ut = 50 # underline height
self.cw = CORE_FONTS_CHARWIDTHS[fontkey]
self.fontkey = fontkey
self.emphasis = TextEmphasis.coerce(style)
def get_text_width(self, text, font_size_pt, _):
return (len(text), sum(self.cw[c] for c in text) * font_size_pt * 0.001)
# Disabling this check - method kept as is to have same method/signature on CoreConf and TTFFont:
# pylint: disable=no-self-use
def encode_text(self, text):
return f"({escape_parens(text)}) Tj"
def __repr__(self):
return f"CoreFont(i={self.i}, fontkey={self.fontkey})"
class TTFFont:
__slots__ = ( # RAM usage optimization
"i",
"type",
"name",
"desc",
"glyph_ids",
"hbfont",
"sp",
"ss",
"up",
"ut",
"cw",
"ttffile",
"fontkey",
"emphasis",
"scale",
"subset",
"cmap",
"ttfont",
"missing_glyphs",
)
def __init__(self, fpdf, font_file_path, fontkey, style):
self.i = len(fpdf.fonts) + 1
self.type = "TTF"
self.ttffile = font_file_path
self.fontkey = fontkey
# recalcTimestamp=False means that it doesn't modify the "modified" timestamp in head table
# if we leave recalcTimestamp=True the tests will break every time
self.ttfont = ttLib.TTFont(
self.ttffile, recalcTimestamp=False, fontNumber=0, lazy=True
)
self.scale = 1000 / self.ttfont["head"].unitsPerEm
# check if the font is a TrueType and missing a .notdef glyph
# if it is missing, provide a fallback glyph
if "glyf" in self.ttfont and ".notdef" not in self.ttfont["glyf"]:
LOGGER.warning(
(
"TrueType Font '%s' is missing the '.notdef' glyph. "
"Fallback glyph will be provided."
),
self.fontkey,
)
# draw a diagonal cross .notdef glyph
(xMin, xMax, yMin, yMax) = (
self.ttfont["head"].xMin,
self.ttfont["head"].xMax,
self.ttfont["head"].yMin,
self.ttfont["head"].yMax,
)
pen = TTGlyphPen(self.ttfont["glyf"])
pen.moveTo((xMin, yMin))
pen.lineTo((xMax, yMin))
pen.lineTo((xMax, yMax))
pen.lineTo((xMin, yMax))
pen.closePath()
pen.moveTo((xMin, yMin))
pen.lineTo((xMax, yMax))
pen.closePath()
pen.moveTo((xMax, yMin))
pen.lineTo((xMin, yMax))
pen.closePath()
self.ttfont["glyf"][".notdef"] = pen.glyph()
self.ttfont["hmtx"][".notdef"] = (xMax - xMin, yMax - yMin)
default_width = round(self.scale * self.ttfont["hmtx"].metrics[".notdef"][0])
os2_table = self.ttfont["OS/2"]
post_table = self.ttfont["post"]
try:
cap_height = os2_table.sCapHeight
except AttributeError:
cap_height = self.ttfont["hhea"].ascent
# entry for the PDF font descriptor specifying various characteristics of the font
flags = FontDescriptorFlags.SYMBOLIC
if post_table.isFixedPitch:
flags |= FontDescriptorFlags.FIXED_PITCH
if post_table.italicAngle != 0:
flags |= FontDescriptorFlags.ITALIC
if os2_table.usWeightClass >= 600:
flags |= FontDescriptorFlags.FORCE_BOLD
self.desc = PDFFontDescriptor(
ascent=round(self.ttfont["hhea"].ascent * self.scale),
descent=round(self.ttfont["hhea"].descent * self.scale),
cap_height=round(cap_height * self.scale),
flags=flags,
font_b_box=(
f"[{self.ttfont['head'].xMin * self.scale:.0f} {self.ttfont['head'].yMin * self.scale:.0f}"
f" {self.ttfont['head'].xMax * self.scale:.0f} {self.ttfont['head'].yMax * self.scale:.0f}]"
),
italic_angle=int(post_table.italicAngle),
stem_v=round(50 + int(pow((os2_table.usWeightClass / 65), 2))),
missing_width=default_width,
)
# a map unicode_char -> char_width
self.cw = defaultdict(lambda: default_width)
# fonttools cmap = unicode char to glyph name
# saving only the keys we have a tuple with
# the unicode characters available on the font
self.cmap = self.ttfont.getBestCmap()
# saving a list of glyph ids to char to allow
# subset by unicode (regular) and by glyph
# (shaped with harfbuz)
self.glyph_ids = {}
for char in self.cmap:
# take glyph associated to char
glyph = self.cmap[char]
# take width associated to glyph
w = self.ttfont["hmtx"].metrics[glyph][0]
# probably this check could be deleted
if w == 65535:
w = 0
self.cw[char] = round(self.scale * w + 0.001) # ROUND_HALF_UP
self.glyph_ids[char] = self.ttfont.getGlyphID(glyph)
self.missing_glyphs = []
# include numbers in the subset! (if alias present)
# ensure that alias is mapped 1-by-1 additionally (must be replaceable)
sbarr = "\x00 \r\n"
if fpdf.str_alias_nb_pages:
sbarr += "0123456789"
sbarr += fpdf.str_alias_nb_pages
self.name = re.sub("[ ()]", "", self.ttfont["name"].getBestFullName())
self.up = round(post_table.underlinePosition * self.scale)
self.ut = round(post_table.underlineThickness * self.scale)
self.sp = round(os2_table.yStrikeoutPosition * self.scale)
self.ss = round(os2_table.yStrikeoutSize * self.scale)
self.emphasis = TextEmphasis.coerce(style)
self.subset = SubsetMap(self, [ord(char) for char in sbarr])
def __repr__(self):
return f"TTFFont(i={self.i}, fontkey={self.fontkey})"
def close(self):
self.ttfont.close()
self.hbfont = None
def get_text_width(self, text, font_size_pt, text_shaping_parms):
if text_shaping_parms:
return self.shaped_text_width(text, font_size_pt, text_shaping_parms)
return (len(text), sum(self.cw[ord(c)] for c in text) * font_size_pt * 0.001)
def shaped_text_width(self, text, font_size_pt, text_shaping_parms):
"""
When texts are shaped, the length of a string is not always the sum of all individual character widths
This method will invoke harfbuzz to perform the text shaping and return the sum of "x_advance"
and "x_offset" for each glyph. This method works for "left to right" or "right to left" texts.
"""
_, glyph_positions = self.perform_harfbuzz_shaping(
text, font_size_pt, text_shaping_parms
)
# If there is nothing to render (harfbuzz returns None), we return 0 text width
if glyph_positions is None:
return (0, 0)
text_width = 0
for pos in glyph_positions:
text_width += (
round(self.scale * pos.x_advance + 0.001) * font_size_pt * 0.001
)
return (len(glyph_positions), text_width)
# Disabling this check - looks like cython confuses pylint:
# pylint: disable=no-member
def perform_harfbuzz_shaping(self, text, font_size_pt, text_shaping_parms):
"""
This method invokes Harfbuzz to perform text shaping of the input string
"""
if not hasattr(self, "hbfont"):
self.hbfont = HarfBuzzFont(hb.Face(hb.Blob.from_file_path(self.ttffile)))
self.hbfont.ptem = font_size_pt
buf = hb.Buffer()
buf.cluster_level = 1
buf.add_str("".join(text))
buf.guess_segment_properties()
features = text_shaping_parms["features"]
if text_shaping_parms["fragment_direction"]:
buf.direction = text_shaping_parms["fragment_direction"].value
if text_shaping_parms["script"]:
buf.script = text_shaping_parms["script"]
if text_shaping_parms["language"]:
buf.language = text_shaping_parms["language"]
hb.shape(self.hbfont, buf, features)
return buf.glyph_infos, buf.glyph_positions
def encode_text(self, text):
txt_mapped = ""
for char in text:
uni = ord(char)
# Instead of adding the actual character to the stream its code is
# mapped to a position in the font's subset
txt_mapped += chr(self.subset.pick(uni))
return f'({escape_parens(txt_mapped.encode("utf-16-be").decode("latin-1"))}) Tj'
def shape_text(self, text, font_size_pt, text_shaping_parms):
"""
This method will invoke harfbuzz for text shaping, include the mapping code
of the glyphs on the subset and map input characters to the cluster codes
"""
if len(text) == 0:
return []
glyph_infos, glyph_positions = self.perform_harfbuzz_shaping(
text, font_size_pt, text_shaping_parms
)
text_info = []
# Find cluster gaps
# Ex: text = "ABCD"
# glyph infos has cluster: 0, 2, 3 - it means A and B are together on the first glyph
# (ligature or substitution) - the glyph should have both unicodes and it should be translated
# properly on the CID to GID mapping
#
def get_cluster_from_text_index(cluster_list, index):
pos = bisect_left(cluster_list, index)
if pos == 0:
return cluster_list[0]
if pos == len(cluster_list) or cluster_list[pos] != index:
return cluster_list[pos - 1]
return cluster_list[pos]
cluster_list = list(sorted(int(gi.cluster) for gi in glyph_infos))
cluster_mapping = {}
for i in range(len(text)):
cl = get_cluster_from_text_index(cluster_list, i)
if cl in cluster_mapping:
cluster_mapping[cl].append(i)
else:
cluster_mapping[cl] = [i]
for cluster_seq, gi in enumerate(glyph_infos):
unicode = []
if gi.cluster in cluster_mapping:
unicode = [ord(text[i]) for i in cluster_mapping[gi.cluster]]
cluster_mapping.pop(gi.cluster)
gname = self.ttfont.getGlyphName(gi.codepoint)
gwidth = round(self.scale * self.ttfont["hmtx"].metrics[gname][0])
glyph = self.subset.get_glyph(
glyph=gi.codepoint,
unicode=tuple(unicode),
glyph_name=gname,
glyph_width=gwidth,
)
force_positioning = False
if (
gwidth != glyph_positions[cluster_seq].x_advance
or glyph_positions[cluster_seq].x_offset != 0
or glyph_positions[cluster_seq].y_offset != 0
or glyph_positions[cluster_seq].y_advance != 0
):
force_positioning = True
text_info.append(
{
"mapped_char": self.subset.pick_glyph(glyph),
"x_advance": glyph_positions[cluster_seq].x_advance,
"y_advance": glyph_positions[cluster_seq].y_advance,
"x_offset": glyph_positions[cluster_seq].x_offset,
"y_offset": glyph_positions[cluster_seq].y_offset,
"force_positioning": force_positioning,
}
)
return text_info
class PDFFontDescriptor(PDFObject):
def __init__(
self,
ascent,
descent,
cap_height,
flags,
font_b_box,
italic_angle,
stem_v,
missing_width,
):
super().__init__()
self.type = Name("FontDescriptor")
self.ascent = ascent
self.descent = descent
self.cap_height = cap_height
self.flags = flags
self.font_b_box = font_b_box
self.italic_angle = italic_angle
self.stem_v = stem_v
self.missing_width = missing_width
self.font_name = None
@dataclass(order=True)
class Glyph:
"""
This represents one glyph on the font
Unicode is a tuple because ligatures or character substitution
can map a sequence of unicode characters to a single glyph
"""
# RAM usage optimization:
__slots__ = ("glyph_id", "unicode", "glyph_name", "glyph_width")
glyph_id: int
unicode: Tuple
glyph_name: str
glyph_width: int
def __hash__(self):
return self.glyph_id
class SubsetMap:
"""
Holds a mapping of used characters and their position in the font's subset
Characters that must be mapped on their actual unicode must be part of the
`identities` list during object instanciation. These non-negative values should
only appear once in the list. `pick()` can be used to get the characters
corresponding position in the subset. If it's not yet part of the object, a new
position is acquired automatically. This implementation always tries to return
the lowest possible representation.
"""
def __init__(self, font: TTFFont, identities: List[int]):
super().__init__()
self.font = font
self._next = 0
# sort list to ease deletion once _next
# becomes higher than first reservation
self._reserved = sorted(identities)
# Maps Glyph instances to character IDs (integers):
self._char_id_per_glyph = {}
for x in self._reserved:
glyph = self.get_glyph(unicode=x)
if glyph:
self._char_id_per_glyph[glyph] = int(x)
def __repr__(self):
return (
f"SubsetMap(font={self.font}, _next={self._next},"
f" _reserved={self._reserved}, _char_id_per_glyph={self._char_id_per_glyph})"
)
def __len__(self):
return len(self._char_id_per_glyph)
def items(self):
for glyph, char_id in self._char_id_per_glyph.items():
yield glyph, char_id
# pylint: disable=method-cache-max-size-none
@lru_cache(maxsize=None)
def pick(self, unicode: int):
glyph = self.get_glyph(unicode=unicode)
if glyph is None and unicode not in self.font.missing_glyphs:
self.font.missing_glyphs.append(unicode)
return self.pick_glyph(glyph)
def pick_glyph(self, glyph):
char_id = self._char_id_per_glyph.get(glyph)
if glyph and char_id is None:
while self._next in self._reserved:
self._next += 1
if self._next > self._reserved[0]:
del self._reserved[0]
char_id = self._next
self._char_id_per_glyph[glyph] = char_id
self._next += 1
return char_id
# pylint: disable=method-cache-max-size-none
@lru_cache(maxsize=None)
def get_glyph(
self, glyph=None, unicode=None, glyph_name=None, glyph_width=None
) -> Glyph:
if glyph:
return Glyph(glyph, tuple(unicode), glyph_name, glyph_width)
glyph_id = self.font.glyph_ids.get(unicode)
if isinstance(unicode, int) and glyph_id is not None:
return Glyph(
glyph_id,
(unicode,),
self.font.cmap[unicode],
self.font.cw[unicode],
)
if unicode == 0x00:
glyph_id = next(iter(self.font.cmap))
return Glyph(glyph_id, (0x00,), ".notdef", 0)
return None
def get_all_glyph_names(self):
return [glyph.glyph_name for glyph in self._char_id_per_glyph]
# Standard fonts
CORE_FONTS = {
"courier": "Courier",
"courierB": "Courier-Bold",
"courierI": "Courier-Oblique",
"courierBI": "Courier-BoldOblique",
"helvetica": "Helvetica",
"helveticaB": "Helvetica-Bold",
"helveticaI": "Helvetica-Oblique",
"helveticaBI": "Helvetica-BoldOblique",
"times": "Times-Roman",
"timesB": "Times-Bold",
"timesI": "Times-Italic",
"timesBI": "Times-BoldItalic",
"symbol": "Symbol",
"zapfdingbats": "ZapfDingbats",
}
COURIER_FONT = {chr(i): 600 for i in range(256)}
CORE_FONTS_CHARWIDTHS = {
"courier": COURIER_FONT,
"courierB": COURIER_FONT,
"courierI": COURIER_FONT,
"courierBI": COURIER_FONT,
}
CORE_FONTS_CHARWIDTHS["helvetica"] = {
"\x00": 278,
"\x01": 278,
"\x02": 278,
"\x03": 278,
"\x04": 278,
"\x05": 278,
"\x06": 278,
"\x07": 278,
"\x08": 278,
"\t": 278,
"\n": 278,
"\x0b": 278,
"\x0c": 278,
"\r": 278,
"\x0e": 278,
"\x0f": 278,
"\x10": 278,
"\x11": 278,
"\x12": 278,
"\x13": 278,
"\x14": 278,
"\x15": 278,
"\x16": 278,
"\x17": 278,
"\x18": 278,
"\x19": 278,
"\x1a": 278,
"\x1b": 278,
"\x1c": 278,
"\x1d": 278,
"\x1e": 278,
"\x1f": 278,
" ": 278,
"!": 278,
'"': 355,
"#": 556,
"$": 556,
"%": 889,
"&": 667,
"'": 191,
"(": 333,
")": 333,
"*": 389,
"+": 584,
",": 278,
"-": 333,
".": 278,
"/": 278,
"0": 556,
"1": 556,
"2": 556,
"3": 556,
"4": 556,
"5": 556,
"6": 556,
"7": 556,
"8": 556,
"9": 556,
":": 278,
";": 278,
"<": 584,
"=": 584,
">": 584,
"?": 556,
"@": 1015,
"A": 667,
"B": 667,
"C": 722,
"D": 722,
"E": 667,
"F": 611,
"G": 778,
"H": 722,
"I": 278,
"J": 500,
"K": 667,
"L": 556,
"M": 833,
"N": 722,
"O": 778,
"P": 667,
"Q": 778,
"R": 722,
"S": 667,
"T": 611,
"U": 722,
"V": 667,
"W": 944,
"X": 667,
"Y": 667,
"Z": 611,
"[": 278,
"\\": 278,
"]": 278,
"^": 469,
"_": 556,
"`": 333,
"a": 556,
"b": 556,
"c": 500,
"d": 556,
"e": 556,
"f": 278,
"g": 556,
"h": 556,
"i": 222,
"j": 222,
"k": 500,
"l": 222,
"m": 833,
"n": 556,
"o": 556,
"p": 556,
"q": 556,
"r": 333,
"s": 500,
"t": 278,
"u": 556,
"v": 500,
"w": 722,
"x": 500,
"y": 500,
"z": 500,
"{": 334,
"|": 260,
"}": 334,
"~": 584,
"\x7f": 350,
"\x80": 556,
"\x81": 350,
"\x82": 222,
"\x83": 556,
"\x84": 333,
"\x85": 1000,
"\x86": 556,
"\x87": 556,
"\x88": 333,
"\x89": 1000,
"\x8a": 667,
"\x8b": 333,
"\x8c": 1000,
"\x8d": 350,
"\x8e": 611,
"\x8f": 350,
"\x90": 350,
"\x91": 222,
"\x92": 222,
"\x93": 333,
"\x94": 333,
"\x95": 350,
"\x96": 556,
"\x97": 1000,
"\x98": 333,
"\x99": 1000,
"\x9a": 500,
"\x9b": 333,
"\x9c": 944,
"\x9d": 350,
"\x9e": 500,
"\x9f": 667,
"\xa0": 278,
"\xa1": 333,
"\xa2": 556,
"\xa3": 556,
"\xa4": 556,
"\xa5": 556,
"\xa6": 260,
"\xa7": 556,
"\xa8": 333,
"\xa9": 737,
"\xaa": 370,
"\xab": 556,
"\xac": 584,
"\xad": 333,
"\xae": 737,
"\xaf": 333,
"\xb0": 400,
"\xb1": 584,
"\xb2": 333,
"\xb3": 333,
"\xb4": 333,
"\xb5": 556,
"\xb6": 537,
"\xb7": 278,
"\xb8": 333,
"\xb9": 333,
"\xba": 365,
"\xbb": 556,
"\xbc": 834,
"\xbd": 834,
"\xbe": 834,
"\xbf": 611,
"\xc0": 667,
"\xc1": 667,
"\xc2": 667,
"\xc3": 667,
"\xc4": 667,
"\xc5": 667,
"\xc6": 1000,
"\xc7": 722,
"\xc8": 667,
"\xc9": 667,
"\xca": 667,
"\xcb": 667,
"\xcc": 278,
"\xcd": 278,
"\xce": 278,
"\xcf": 278,
"\xd0": 722,
"\xd1": 722,
"\xd2": 778,
"\xd3": 778,
"\xd4": 778,
"\xd5": 778,
"\xd6": 778,
"\xd7": 584,
"\xd8": 778,
"\xd9": 722,
"\xda": 722,
"\xdb": 722,
"\xdc": 722,
"\xdd": 667,
"\xde": 667,
"\xdf": 611,
"\xe0": 556,
"\xe1": 556,
"\xe2": 556,
"\xe3": 556,
"\xe4": 556,
"\xe5": 556,
"\xe6": 889,
"\xe7": 500,
"\xe8": 556,
"\xe9": 556,
"\xea": 556,
"\xeb": 556,
"\xec": 278,
"\xed": 278,
"\xee": 278,
"\xef": 278,
"\xf0": 556,
"\xf1": 556,
"\xf2": 556,
"\xf3": 556,
"\xf4": 556,
"\xf5": 556,
"\xf6": 556,
"\xf7": 584,
"\xf8": 611,
"\xf9": 556,
"\xfa": 556,
"\xfb": 556,
"\xfc": 556,
"\xfd": 500,
"\xfe": 556,
"\xff": 500,
}
CORE_FONTS_CHARWIDTHS["helveticaB"] = {
"\x00": 278,
"\x01": 278,
"\x02": 278,
"\x03": 278,
"\x04": 278,
"\x05": 278,
"\x06": 278,
"\x07": 278,
"\x08": 278,
"\t": 278,
"\n": 278,
"\x0b": 278,
"\x0c": 278,
"\r": 278,
"\x0e": 278,
"\x0f": 278,
"\x10": 278,
"\x11": 278,
"\x12": 278,
"\x13": 278,
"\x14": 278,
"\x15": 278,
"\x16": 278,
"\x17": 278,
"\x18": 278,
"\x19": 278,
"\x1a": 278,
"\x1b": 278,
"\x1c": 278,
"\x1d": 278,
"\x1e": 278,
"\x1f": 278,
" ": 278,
"!": 333,
'"': 474,
"#": 556,
"$": 556,
"%": 889,
"&": 722,
"'": 238,
"(": 333,
")": 333,
"*": 389,
"+": 584,
",": 278,
"-": 333,
".": 278,
"/": 278,
"0": 556,
"1": 556,
"2": 556,
"3": 556,
"4": 556,
"5": 556,
"6": 556,
"7": 556,
"8": 556,
"9": 556,
":": 333,
";": 333,
"<": 584,
"=": 584,
">": 584,
"?": 611,
"@": 975,