/
findfonts.py
executable file
·409 lines (354 loc) · 13 KB
/
findfonts.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
"""
Scan a list of folders and find all .afm files,
then create rst2pdf-ready font-aliases.
"""
from __future__ import unicode_literals
import os
import subprocess
import sys
from fnmatch import fnmatch
import six
from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import (
FF_FORCEBOLD,
FF_ITALIC,
TTFError,
TTFont,
TTFontFile,
)
from rst2pdf.log import log
flist = []
afmList = []
pfbList = {}
ttfList = []
# Aliases defined by GhostScript, so if you use Palatino or whatever you
# may get **something**. They are family name aliases.
Alias = {
"itc bookman": "urw bookman l",
"itc avant garde gothic": "urw gothic l",
"palatino": "urw palladio l",
"new century schoolbook": "century schoolbook l",
"itc zapf chancery": "urw chancery l",
}
# Standard PDF fonts, so no need to embed them
Ignored = ["times", "itc zapf dingbats", "symbol", "helvetica", "courier"]
fonts = {}
families = {}
fontMappings = {}
def make_string(b):
if isinstance(b, bytes):
return b.decode('utf-8')
return b
def loadFonts():
"""
Search the system and build lists of available fonts.
"""
if not any([afmList, pfbList, ttfList]):
# FIXME: When we drop support por py2, use recursive globs
for folder in flist:
for root, _, files in os.walk(folder):
for f in files:
if fnmatch(f, "*.ttf") or fnmatch(f, "*.ttc"):
ttfList.append(os.path.join(root, f))
elif fnmatch(f, "*.afm"):
afmList.append(os.path.join(root, f))
elif fnmatch(f, "*.pfb"):
pfbList[f[:-4]] = os.path.join(root, f)
for ttf in ttfList:
try:
font = TTFontFile(ttf)
except TTFError:
log.warning("Error processing %s", ttf)
continue
family = make_string(font.familyName.lower())
fontName = make_string(font.name).lower()
baseName = os.path.basename(ttf)[:-4]
fullName = make_string(font.fullName).lower()
for k in (fontName, fullName, fullName.replace("italic", "oblique")):
fonts[k] = (ttf, ttf, family)
bold = FF_FORCEBOLD == FF_FORCEBOLD & font.flags
italic = FF_ITALIC == FF_ITALIC & font.flags
# And we can try to build/fill the family mapping
if family not in families:
families[family] = [fontName, fontName, fontName, fontName]
if bold and italic:
families[family][3] = fontName
elif bold:
families[family][1] = fontName
elif italic:
families[family][2] = fontName
# FIXME: what happens if there are Demi and Medium
# weights? We get a random one.
else:
families[family][0] = fontName
# Now we have full afm and pbf lists, process the
# afm list to figure out family name, weight and if
# it's italic or not, as well as where the
# matching pfb file is
for afm in afmList:
family = None
fontName = None
italic = False
bold = False
for line in open(afm, "r"):
line = line.strip()
if line.startswith("StartCharMetrics"):
break
elif line.startswith("FamilyName"):
family = line.split(" ", 1)[1].lower()
elif line.startswith("FontName"):
fontName = line.split(" ")[1]
elif line.startswith("FullName"):
fullName = line.split(" ", 1)[1]
elif line.startswith("Weight"):
bold = line.split(" ")[1] == "Bold"
elif line.startswith("ItalicAngle"):
italic = line.split(" ")[1] != "0.0"
baseName = os.path.basename(afm)[:-4]
if family in Ignored or family in Alias:
continue
if baseName not in pfbList:
log.info("afm file without matching pfb file: %s" % baseName)
continue
# So now we have a font we know we can embed.
for n in (fontName.lower(), fullName.lower(), fullName.lower().replace("italic", "oblique")):
fonts[n] = (afm, pfbList[baseName], family)
# And we can try to build/fill the family mapping
if family not in families:
families[family] = [fontName, fontName, fontName, fontName]
if bold and italic:
families[family][3] = fontName
elif bold:
families[family][1] = fontName
elif italic:
families[family][2] = fontName
# FIXME: what happens if there are Demi and Medium
# weights? We get a random one.
else:
families[family][0] = fontName
def findFont(fname):
loadFonts()
# So now we are sure we know the families and font
# names. Well, return some data!
fname = fname.lower()
if fname in fonts:
font = fonts[fname.lower()]
else:
if fname in Alias:
fname = Alias[fname]
if fname in families:
font = fonts[families[fname][0].lower()]
else:
return None
return font
def findTTFont(fname):
def get_family(query):
data = make_string(subprocess.check_output(["fc-match", query]))
if six.PY2:
data = data.decode("UTF-8")
for line in data.splitlines():
line = line.strip()
if not line:
continue
family = line.split('"')[1].replace('"', "")
if family:
return family
return None
def get_fname(query):
data = make_string(subprocess.check_output(["fc-match", "-v", query]))
for line in data.splitlines():
line = line.strip()
if line.startswith("file: "):
return line.split('"')[1]
return None
def get_variants(family):
variants = [
get_fname(family + ":style=Roman"),
get_fname(family + ":style=Bold"),
get_fname(family + ":style=Oblique"),
get_fname(family + ":style=Bold Oblique"),
]
if variants[2] == variants[0]:
variants[2] = get_fname(family + ":style=Italic")
if variants[3] == variants[0]:
variants[3] = get_fname(family + ":style=Bold Italic")
if variants[0].endswith(".pfb") or variants[0].endswith(".gz"):
return None
return variants
if os.name != "nt":
family = get_family(fname)
if not family:
log.error("Unknown font: %s", fname)
return None
return get_variants(family)
else:
# lookup required font in registry lookup, alternative approach
# is to let loadFont() traverse windows font directory or use
# ctypes with EnumFontFamiliesEx
def get_nt_fname(ftname):
if six.PY3:
import winreg as _w
else:
import _winreg as _w
fontkey = _w.OpenKey(
_w.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",
)
fontname = ftname + " (TrueType)"
try:
fname = _w.QueryValueEx(fontkey, fontname)[0]
if os.path.isabs(fname):
fontkey.close()
return fname
fontdir = os.environ.get("SystemRoot", "C:\\Windows")
fontdir += "\\Fonts"
fontkey.Close()
return fontdir + "\\" + fname
except WindowsError:
fontkey.Close()
return None
family, pos = guessFont(fname)
fontfile = get_nt_fname(fname)
if not fontfile:
if pos == 0:
fontfile = get_nt_fname(family)
elif pos == 1:
fontfile = get_nt_fname(family + " Bold")
elif pos == 2:
fontfile = get_nt_fname(family + " Italic") or get_nt_fname(
family + " Oblique"
)
else:
fontfile = get_nt_fname(family + " Bold Italic") or get_nt_fname(
family + " Bold Oblique"
)
if not fontfile:
log.error("Unknown font: %s", fname)
return None
family, pos = guessFont(fname)
variants = [
get_nt_fname(family) or fontfile,
get_nt_fname(family + " Bold") or fontfile,
get_nt_fname(family + " Italic")
or get_nt_fname(family + " Oblique")
or fontfile,
get_nt_fname(family + " Bold Italic")
or get_nt_fname(family + " Bold Oblique")
or fontfile,
]
return variants
def autoEmbed(fname):
"""Given a font name, does a best-effort of embedding
said font and its variants.
Returns a list of the font names it registered with ReportLab.
"""
log.info("Trying to embed %s" % fname)
fontList = []
variants = []
f = findFont(fname)
if f: # We have this font located
if f[0].lower().endswith(".afm"): # Type 1 font
family = families[f[2]]
# Register the whole family of faces
faces = [
pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2]) for fn in family
]
for face in faces:
pdfmetrics.registerTypeFace(face)
for face, name in zip(faces, family):
fontList.append(name)
font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
log.info("Registering font: %s from %s" % (name, face.getFontFiles()))
pdfmetrics.registerFont(font)
# Map the variants
regular, italic, bold, bolditalic = family
for n in fname, regular:
addMapping(n, 0, 0, regular)
addMapping(n, 0, 1, italic)
addMapping(n, 1, 0, bold)
addMapping(n, 1, 1, bolditalic)
log.info("Embedding as %s" % fontList)
return fontList
else: # A TTF font
variants = [fonts[x.lower()][0] for x in families[f[2]]]
if not variants: # Try fc-match
variants = findTTFont(fname)
# It is a TT Font and we found it using fc-match (or found *something*)
if variants:
for variant in variants:
vname = os.path.basename(variant)[:-4]
try:
if vname not in pdfmetrics._fonts:
_font = TTFont(vname, variant)
log.info("Registering font: %s from %s" % (vname, variant))
pdfmetrics.registerFont(_font)
except TTFError:
log.error("Error registering font: %s from %s" % (vname, variant))
else:
fontList.append(vname)
regular, bold, italic, bolditalic = [
os.path.basename(variant)[:-4] for variant in variants
]
addMapping(regular, 0, 0, regular)
addMapping(regular, 0, 1, italic)
addMapping(regular, 1, 0, bold)
addMapping(regular, 1, 1, bolditalic)
log.info("Embedding via findTTFont as %s" % fontList)
return fontList
def guessFont(fname):
"""Given a font name like "Tahoma-BoldOblique", "Bitstream Charter Italic"
or "Perpetua Bold Italic" guess what it means.
Returns (family, x) where x is
0: regular
1: bold
2: italic
3: bolditalic
"""
italic = 0
bold = 0
if "-" not in fname:
sfx = {
"Bold": 1,
"Bold Italic": 3,
"Bold Oblique": 3,
"Italic": 2,
"Oblique": 2,
}
for key in sfx:
if fname.endswith(" " + key):
return fname.rpartition(key)[0], sfx[key]
return fname, 0
else:
family, mod = fname.rsplit("-", 1)
mod = mod.lower()
if "oblique" in mod or "italic" in mod:
italic = 1
if "bold" in mod:
bold = 1
if bold + italic == 0: # Not really a modifier
return fname, 0
return family, bold + 2 * italic
def main():
global flist
if len(sys.argv) != 2:
print("Usage: findfonts.py fontName")
sys.exit(1)
if os.name == "nt":
flist = [".", os.environ.get("SystemRoot", "C:\\Windows") + "\\Fonts"]
else:
flist = [".", "/usr/share/fonts", "/usr/share/texmf-dist/fonts"]
fname = make_string(sys.argv[1])
fn, _ = guessFont(fname)
f = findFont(fn)
if not f:
f = findTTFont(fn)
if f:
print(f)
else:
print("Unknown font %s" % fname)
if __name__ == "__main__":
main()