edouard@3203: #!/usr/bin/env python edouard@3203: # -*- coding: utf-8 -*- edouard@3203: edouard@3203: # This file is part of Beremiz edouard@3203: # Copyright (C) 2021: Edouard TISSERANT edouard@3203: # edouard@3203: # See COPYING file for copyrights details. edouard@3203: edouard@3203: from __future__ import print_function edouard@3203: from base64 import b64encode edouard@3203: edouard@3203: from fontTools import ttLib edouard@3203: edouard@3203: def GetFontTypeAndFamilyName(filename): edouard@3203: """ edouard@3203: Getting font family, format and MIME type edouard@3203: """ edouard@3203: edouard@3203: familyname = None edouard@3203: formatname = None edouard@3203: mimetype = None edouard@3203: edouard@3203: font = ttLib.TTFont(filename) edouard@3203: # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html edouard@3203: for name in font["name"].names: edouard@3203: if name.nameID==1 and name.platformID in [0,3]: edouard@3203: familyname = name.toUnicode() edouard@3203: edouard@3203: if font.flavor : edouard@3203: # woff and woff2 edouard@3203: formatname = font.flavor edouard@3203: mimetype = "font/" + formatname edouard@3203: # conditions on sfntVersion was deduced from fontTools.ttLib.sfnt edouard@3203: elif font.sfntVersion in ("\x00\x01\x00\x00", "true"): edouard@3203: formatname = "truetype" edouard@3203: mimetype = "font/ttf" edouard@3203: elif font.sfntVersion == "OTTO": edouard@3203: formatname = "opentype" edouard@3203: mimetype = "font/otf" edouard@3203: edouard@3203: return familyname,formatname,mimetype edouard@3203: edouard@3203: def DataURIFromFile(filename, mimetype): edouard@3203: with open(filename, "rb") as fp: edouard@3203: data = fp.read() edouard@3203: return "".join([ edouard@3203: "data:", edouard@3203: mimetype, edouard@3203: ";base64,", edouard@3203: b64encode(data).strip()]) edouard@3203: edouard@3203: def GetCSSFontFaceFromFontFile(filename): edouard@3203: familyname, formatname, mimetype = GetFontTypeAndFamilyName(filename) edouard@3203: data_uri = DataURIFromFile(filename, mimetype) edouard@3203: css_font_face = \ edouard@3203: """ edouard@3203: @font-face {{ edouard@3203: font-family: "{}"; edouard@3203: src: url("{}") format("{}") edouard@3203: }} edouard@3203: """.format(familyname, data_uri, formatname) edouard@3203: return css_font_face edouard@3203: edouard@3203: edouard@3203: # tests edouard@3203: if __name__ == '__main__': edouard@3203: print(GetCSSFontFaceFromFontFile("/usr/share/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf")) edouard@3203: print(GetCSSFontFaceFromFontFile("/usr/share/fonts/opentype/urw-base35/NimbusSans-Regular.otf")) edouard@3203: print(GetCSSFontFaceFromFontFile("/usr/share/yelp/mathjax/fonts/HTML-CSS/TeX/woff/MathJax_SansSerif-Regular.woff"))