|
1 #!/usr/bin/env python |
|
2 # -*- coding: utf-8 -*- |
|
3 |
|
4 # This file is part of Beremiz |
|
5 # Copyright (C) 2021: Edouard TISSERANT |
|
6 # |
|
7 # See COPYING file for copyrights details. |
|
8 |
|
9 from __future__ import print_function |
|
10 from base64 import b64encode |
|
11 |
|
12 from fontTools import ttLib |
|
13 |
|
14 def GetFontTypeAndFamilyName(filename): |
|
15 """ |
|
16 Getting font family, format and MIME type |
|
17 """ |
|
18 |
|
19 familyname = None |
|
20 formatname = None |
|
21 mimetype = None |
|
22 |
|
23 font = ttLib.TTFont(filename) |
|
24 # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html |
|
25 for name in font["name"].names: |
|
26 if name.nameID==1 and name.platformID in [0,3]: |
|
27 familyname = name.toUnicode() |
|
28 |
|
29 if font.flavor : |
|
30 # woff and woff2 |
|
31 formatname = font.flavor |
|
32 mimetype = "font/" + formatname |
|
33 # conditions on sfntVersion was deduced from fontTools.ttLib.sfnt |
|
34 elif font.sfntVersion in ("\x00\x01\x00\x00", "true"): |
|
35 formatname = "truetype" |
|
36 mimetype = "font/ttf" |
|
37 elif font.sfntVersion == "OTTO": |
|
38 formatname = "opentype" |
|
39 mimetype = "font/otf" |
|
40 |
|
41 return familyname,formatname,mimetype |
|
42 |
|
43 def DataURIFromFile(filename, mimetype): |
|
44 with open(filename, "rb") as fp: |
|
45 data = fp.read() |
|
46 return "".join([ |
|
47 "data:", |
|
48 mimetype, |
|
49 ";base64,", |
|
50 b64encode(data).strip()]) |
|
51 |
|
52 def GetCSSFontFaceFromFontFile(filename): |
|
53 familyname, formatname, mimetype = GetFontTypeAndFamilyName(filename) |
|
54 data_uri = DataURIFromFile(filename, mimetype) |
|
55 css_font_face = \ |
|
56 """ |
|
57 @font-face {{ |
|
58 font-family: "{}"; |
|
59 src: url("{}") format("{}") |
|
60 }} |
|
61 """.format(familyname, data_uri, formatname) |
|
62 return css_font_face |
|
63 |
|
64 |
|
65 # tests |
|
66 if __name__ == '__main__': |
|
67 print(GetCSSFontFaceFromFontFile("/usr/share/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf")) |
|
68 print(GetCSSFontFaceFromFontFile("/usr/share/fonts/opentype/urw-base35/NimbusSans-Regular.otf")) |
|
69 print(GetCSSFontFaceFromFontFile("/usr/share/yelp/mathjax/fonts/HTML-CSS/TeX/woff/MathJax_SansSerif-Regular.woff")) |