def generateFont(outputFile, listGlyphs): print 'glyph files: ' + str(len(listGlyphs)) font = fontforge.font() font.fontname = os.path.splitext(os.path.basename(outputFile))[0] dict_glyphmaps = {} # add chars for fileName in listGlyphs: #codepoint = char = font.createChar(int(fileName.split('.')[0])) char.importOutlines(fileName) # if importOutlines not changed the char, probably the char contains errors if not char.changed: print 'file with error: ' + fileName continue # align in left char.left_side_bearing = 0 # set width x_max = char.boundingBox()[2] char.width = char.vwidth = x_max # add glyphmap basename = os.path.splitext(os.path.basename(fileName))[0] dict_glyphmaps[basename] = int(fileName.split('.')[0]) #codePoint += 1 font.generate(outputFile) print 'Generate font: ' + outputFile return dict_glyphmaps
def convert(self, theme): fontname = self.options.fontname if not fontname: fontname = theme file_prefix = path.join(self.options.output, theme) # create empty font self.font = font = fontforge.font() #file_prefix = 'icons' # set font names font.fontname = fontname font.familyname = self.options.familyname font.fullname = ' '.join([ self.options.familyname, fontname ]) # import svgs files = self.collect_glyphs(theme) for f in files: self.import_glyph(f) #font.generate("fonts/%s.pfb" % file_prefix, flags=["tfm", "afm"]) # type1 with tfm/afm #font.generate("fonts/%s.otf" % file_prefix) # opentype font.generate("%s.ttf" % file_prefix) # truetype font.generate("%s.svg" % file_prefix) # svg font.generate("%s.woff" % file_prefix) # svg fontforge.printSetup('pdf-file', '%s-preview.pdf' % file_prefix) font.printSample('fontdisplay', 14)
def create(aName): print("Generating %s.otf..." % aName, end="") # Create a new font. font = fontforge.font() font.encoding = "UnicodeFull" font.fontname = aName font.familyname = aName font.fullname = aName # License the font under OFL. font.copyright = "Copyright (c) 2016 Igalia S.L." with open('OFL.txt', 'r') as OFLFile: lang = "English (US)" font.sfnt_names = ( (lang, 'Copyright', OFLFile.read()), (lang, 'License URL', 'http://scripts.sil.org/OFL'), (lang, 'Family', aName), (lang, 'SubFamily', 'Regular'), (lang, 'Fullname', aName), (lang, 'PostScriptName', aName) ) # Create a space character. g = font.createChar(ord(" "), "space") g.width = em return font
def generateTuringFont(myFont, cipher, newFontName): plain = "abcdefghijklmnopqrstuvwxyz" # Create a font to use as auxiliar variable temporal = fontforge.font() # Change the order of the letters plain = plain + plain.upper() cipher = cipher + cipher.upper() for i in range(len(plain)): myFont.selection.select( plain[i] ) myFont.copy() temporal.selection.select( cipher[i] ) temporal.paste() # Copy back the letters in the auxiliar font to the original font. temporal.selection.select(("ranges",None),"a","z") myFont.selection.select(("ranges",None),"a","z") temporal.copy() myFont.paste() temporal.selection.select(("ranges",None),"A","Z") myFont.selection.select(("ranges",None),"A","Z") temporal.copy() myFont.paste() # Save new font myFont.fontname = newFontName myFont.familyname = newFontName myFont.fullname = newFontName myFont.save(newFontName + ".sfd") temporal.close()
def generate_font_project_file(meta, outfile): font = fontforge.font() familyname = "STDevGen_1stMix" font.familyname = familyname font.fullname = familyname + "-Normal" font.fontname = familyname for em in meta: codepoint = em["loose"].get("codepoint",None) if codepoint is None: # Some of the glyphs are not intended as actual characters. continue basename = em["file_basename"] width = em["loose"].get("width",0) lines = em["loose"].get("lines",[]) glyph = font.createChar(codepoint) # Reportedly, importOutlines() doesn't like importing files without # any paths. If there are none, we can just skip it anyway. draw = False for line in lines: draw = bool(line.get("draw", True)) if draw: break if draw: glyph.importOutlines(tight_svg_filename(basename)) else: print >> sys.stderr, "Note: %s rendered as spacing-only" % codepoint glyph.width = width glyph.simplify() font.save(outfile)
def main(filename, fontname, fullname): if (not filename.endswith('.svg')): filename = filename + '.svg' font = fontforge.font() font.fontname = fontname font.fullname = fullname font.familyname = fullname # Create new glyph glyph = font.createChar(0) # Get SVG glyph.importOutlines(filename) # Make the glyph rest on the baseline ymin = glyph.boundingBox()[1] glyph.transform([1, 0, 0, 1, 0, -ymin]) # Set glyph side bearings, can be any value or even 0 glyph.left_side_bearing = glyph.right_side_bearing = 10 # font.generate("foobar.pfb", flags=["tfm", "afm"]) # Type1 with tfm/afm font.generate(split_filename(filename) + '.otf') # OpenType font.generate(split_filename(filename) + '.ttf') # TrueType
def main(): global newfont, oldfont, fontName newfont = fontforge.font() # newfont.em = 2048 oldfont = fontforge.open("Gregoria.otf") fontName = "gregoria" newfont.encoding="ISO10646-1" newfont.fontname="gregoriao" newfont.fullname="gregoriao" newfont.familyname="gregoriao" newfont.weight=oldfont.weight newfont.copyright=oldfont.copyright first_step() adjustAdditionalGlyphs() oldfont.close() oldfont = fontforge.open("Gregoria-Deminutae.otf") fontName="gregoria-deminutae" first_step() adjustAdditionalGlyphs() oldfont.close() oldfont = fontforge.open("Gregoria-Auctae.otf") fontName="gregoria-auctae" first_step() adjustAdditionalGlyphs() oldfont.close() newfont.em = 2048 newfont.generate("gregoriao.ttf") newfont.close()
def build_font(self, dir_name, familyname, fontname, fullname): '''Builds the font file.''' self.font = font = fontforge.font() # height = 32 font.descent = 4 * SQUARE_SIZE font.ascent = 8 * SQUARE_SIZE # font.em = 28 # font.design_size = 12 font.upos = -2 * SQUARE_SIZE font.uwidth = SQUARE_SIZE font.fontname = fontname font.familyname = familyname font.fullname = fullname font.encoding = 'unicode' if 'bold' in fontname.lower(): font.weight = 'Bold' if 'oblique' in fontname.lower(): font.italicangle = -10.0 if 'boldoblique' in fontname.lower(): font.appendSFNTName(0x0409, 'SubFamily', 'Bold Oblique') font.addLookup('Anchors', 'gpos_mark2base', (), ( ("mark", (("DFLT", ("dflt")),)), )) font.addLookupSubtable('Anchors', 'DiacriticTop') font.addAnchorClass('DiacriticTop', 'Top') font.addLookupSubtable('Anchors', 'DiacriticBottom') font.addAnchorClass('DiacriticBottom', 'Bottom') reader = Reader( *sorted(kitabyte.reader.get_font_def_filenames(dir_name))) deferred_glyph_defs = [] for glyph_def in kitabyte.reader.read_font_def(reader): if isinstance(glyph_def, Glyph): try: _logger.debug('Processing u+%x %s', glyph_def.char_code, fontforge.nameFromUnicode(glyph_def.char_code)) self._make_glyph(glyph_def) except (EnvironmentError, ValueError): _logger.debug('Deferring glyph u+%x %s', glyph_def.char_code, fontforge.nameFromUnicode(glyph_def.char_code)) deferred_glyph_defs.append(glyph_def) for glyph_def in deferred_glyph_defs: _logger.debug('Processing u+%x %s', glyph_def.char_code, fontforge.nameFromUnicode(glyph_def.char_code)) self._make_glyph(glyph_def) font.selection.all() font.removeOverlap() font.simplify() font.correctDirection() return font
def generate(filepath, name, mapFile, output): convertedPath = filepath + "/converted" isExists = os.path.exists(convertedPath) if not isExists: os.makedirs(convertedPath) convert2pbm(filepath) convert2svg(filepath) charMap = {} file = open(filepath + '/' + mapFile) list_of_all_the_lines = file.read().splitlines() # 文件名到字符的映射关系 for line in list_of_all_the_lines: chars = line.split(" ") charMap[chars[0]] = chars[1] # font = fontforge.font() family_name = "tesseracthand" style_name = name font.familyname = family_name font.fullname = family_name + "-" + style_name font.fontname = family_name + "-" + style_name for filename in os.listdir(filepath): if filename.endswith('.png'): fileRealName = filename.split('.')[0] char = charMap[fileRealName] glyph = font.createMappedChar(char) glyph.importOutlines("{0}/converted/{1}.svg".format(filepath, fileRealName)) font.generate(output + '/tesseracthand.ttf') return True
def __init__ (self, option): """ The `__init__` constructor function inits the font's option. """ if not option.input: self.font = fontforge.font(); else: self.font = fontforge.open(option.input); self.font.encoding = 'UnicodeBmp'; self.font.version = '2.000;PS 1;hotconv 1.0.49;makeotf.lib2.0.14853'; self.font.weight = 'Book' self.font.fontname = option.name; self.font.familyname = option.name; self.font.fullname = option.name; self.font.ascent = 1000; self.font.descent = 200; self.font.em = 1000; self.font.addLookup('liga', 'gsub_ligature', (), ( ( 'liga', ( ('latn', ('dflt')), ) ), )); self.font.addLookupSubtable('liga', 'liga'); self.output = option.output; self.index = option.index;
def convert_main(self, config_file, directory, outdir, metadata): try: self.font = fontforge.font() except: import fontforge with open(config_file) as f: self.config = json.load(f) self.metadata = json.loads(metadata) or {} self.font = fontforge.font() self.unicode_mapping = {} self.set_properties() self.add_glyphs(directory) # bearing table self.set_bearings(self.config["typography_parameters"].get( "bearing_table", {})) # kerning table self.set_kerning(self.config["typography_parameters"].get( "kerning_table", {})) # Generate font and save as a .ttf file filename = self.metadata.get( "filename", None) or self.config["props"].get("filename", None) self.generate_font_file(str(filename), outdir, config_file)
def main(): name = "Bhaataan-Gothic" font = fontforge.font() font.encoding = "UnicodeBmp" font.familyname = name font.fontname = name font.fullname = name font.ascent = 1000 font.descent = 0 add_anchorclasses(font) add_substitution(font) add_punctuations(font) add_basic_consonants(font) add_vowels(font) add_with_o_consonants(font) add_kerning(font) add_contextual_chaining(font) font.em = 1024 font.save(name) font.generate("%s.ttf" % name) font.generate("%s.woff" % name)
def __init__(self, source): self._new_font = fontforge.font() # Set up the new font shell self._new_font.encoding = 'UnicodeFull' self._new_font.fontname = source.font_name self._new_font.fullname = source.font_name self._new_font.familyname = source.font_name self._new_font.ascent = 850 self._new_font.em = 1792 self._new_font.descent = 256 self._new_font.gasp = ((65535, ( 'gridfit', 'antialias', 'symmetric-smoothing', 'gridfit+smoothing')),) self._new_font.gasp_version = 1 self._new_font.hhea_descent = -34 self._new_font.hhea_linegap = 0 self._new_font.os2_codepages = (1, 0) self._new_font.os2_fstype = 4 self._new_font.os2_panose = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) self._new_font.os2_strikeypos = 1075 self._new_font.os2_strikeysize = 90 self._new_font.os2_subyoff = 134 self._new_font.os2_subysize = 1075 self._new_font.os2_supyoff = 627 self._new_font.os2_supysize = 1075 self._new_font.os2_typolinegap = 0 self._new_font.weight = 'Book' # Fire up the reference font self._source_font = fontforge.open(source.tff_file) self._source_font.encoding = 'UnicodeFull'
def generate(fontname, files): filename = fontname + '.otb' newfont = fontforge.font() for file in files: if args.verbose: print(f'{filename}: {file}: importing bitmap strikes', file=sys.stderr) try: import_bitmap(newfont, file) except ValueError: print( f'opentype-bitmap: warning: {file}: file must end with ' '.pcf.gz, bdf.gz, .pcf, or .bdf', file=sys.stderr) except OSError: print(f'opentype-bitmap: warning: {file}: invalid bitmap font', file=sys.stderr) if newfont.changed: newfont.generate(filename, 'otb') print(f'{filename}')
def main(): font = fontforge.font() font.descent = 1 * SQUARE_SIZE font.ascent = 8 * SQUARE_SIZE font.upos = -1 * SQUARE_SIZE font.uwidth = SQUARE_SIZE font.fontname = 'pkmn_gb_en_tppocr-regular' font.familyname = 'pkmn_gb_en_tppocr' font.fullname = 'PkMn GB English TPPOCR Regular' font.encoding = 'unicode' char_pixel_data = get_pixel_data() red_char_pixel_data = get_pixel_data('red_font.png', rows=7) def draw_glyph(char, char_pixel_data): glyph = font.createChar(ord(char)) glyph.clear() pixel_data = char_pixel_data[char_row][char_col] pen = glyph.glyphPen() for tile_y, tile_x in itertools.product(range(8), range(8)): if pixel_data[tile_y * 8 + tile_x] != 0: continue x = tile_x * SQUARE_SIZE y = 7 * SQUARE_SIZE - tile_y * SQUARE_SIZE # Add +/-1 to slightly increase the block size so each block # will slightly overlap and ensure no points overlap. pen.moveTo((x - 1, y - 1)) pen.lineTo((x + SQUARE_SIZE + 1, y - 1)) pen.lineTo((x + SQUARE_SIZE + 1, y + SQUARE_SIZE + 1)) pen.lineTo((x - 1, y + SQUARE_SIZE + 1)) pen.closePath() glyph.width = SQUARE_SIZE * 8 for char_row, row in enumerate(CHARS): for char_col, char in enumerate(row): if char == ' ': continue draw_glyph(char, char_pixel_data) if char == 'c': draw_glyph(u'ċ', red_char_pixel_data) glyph = font.createChar(ord(' ')) glyph.width = SQUARE_SIZE * 8 font.selection.all() font.removeOverlap() font.simplify() font.correctDirection() font.version = VERSION font.copyright = COPYRIGHT font.generate(font.fontname + '.ttf', flags=('no-hints',))
def create_font(): """create a minimal FontForge font""" font = fontforge.font() # font.addLookup("belowbaseline","gpos_mark2base",0, # [["blwm",[["deva",["dflt"]]]]]) # font.addLookupSubtable("belowbaseline", "belowbasesub") # font.addAnchorClass("belowbasesub", "sub") return font
def __init__(self, kerning=15): #initialize the font self.font = fontforge.font() # starts in the character code for ! self.font_character_index = 33 #other fontforge options: self.kerning = kerning
def create_font(): """create a minimal FontForge font""" font = fontforge.font() #font.addLookup("belowbaseline","gpos_mark2base",0, # [["blwm",[["deva",["dflt"]]]]]) #font.addLookupSubtable("belowbaseline", "belowbasesub") #font.addAnchorClass("belowbasesub", "sub") return font
def generateFont(fontName: str, text: str, saveType: int = WOFF_TYPE, flags: int = 0) -> str: try: fontLocation = getFontLocation(fontName) if fontLocation is None: return None if saveType <= 0: return None if flags & ASCII_SUPPORT: charList = [chr(i) for i in range(32, 127)] else: charList = [] for i in text: if i not in charList: charList.append(i) fn = f"fonts/{md5(fontName)}_{sha256(''.join(charList))}" cont = False if saveType & TTF_TYPE and not exists(f"{fn}.ttf"): cont = True if saveType & WOFF_TYPE and not exists(f"{fn}.woff"): cont = True if saveType & WOFF2_TYPE and not exists(f"{fn}.woff2"): cont = True if saveType & EOT_TYPE and not exists(f"{fn}.eot"): cont = True if not cont: return fn print(fontLocation) ft: font = openfont(fontLocation) print(ft.encoding) nf = font() nf.encoding = 'UnicodeBMP' for char in charList: char = ord(char) ft.selection.select(("more", None), char) nf.selection.select(("more", None), char) ft.copy() nf.paste() if not exists('fonts/'): mkdir('fonts/') if saveType & TTF_TYPE: nf.generate(f"{fn}.ttf", flags="opentype") if saveType & WOFF_TYPE: nf.generate(f"{fn}.woff") if saveType & WOFF2_TYPE: nf.generate(f"{fn}.woff2") if saveType & EOT_TYPE: nf.generate(f"{fn}.eot") nf.close() return fn except Exception as e: s = settings() s.ReadSettings() if s.debug: raise e return None
def main(config_file): config = loadConfig(config_file) os.chdir(os.path.dirname(config_file) or '.') font = fontforge.font() setProperties(font, config) addGlyphs(font, config) for outfile in config['output']: sys.stderr.write('Generating %s...\n' % outfile) font.generate(outfile)
def __init__(self, code_base=1): f = fontforge.font() f.encoding = 'UnicodeFull' f.design_size = 16 f.em = 512 f.ascent = 448 # f.design_sizescent = 64 self.f = f self.char_code = code_base
def createFont(): font = fontforge.font() font.fontname = fontname font.fullname = fullname font.ascent = ascent font.descent = descent font.em = em font.encoding = encoding font.save(buildPath+fontname+".sfd") return font
def make_font(options: argparse.Namespace) -> None: font = fontforge.font() font.familyname = 'Duployan' font.fontname = font.familyname font.fullname = font.familyname font.encoding = 'UnicodeFull' builder = duployan.Builder(font, options.bold, options.noto) builder.augment() build_font(options, builder.font) patch_fonttools() tweak_font(options, builder)
def configFont(config_file, user): config = loadConfig(config_file) os.chdir(os.path.dirname(config_file) or '.') font = fontforge.font() setProperties(font, config) addGlyphs(font, config) i = 0 while os.path.exists('my_fonts/hand-spoken-' + user + '-' + str(i) + '.ttf'): i += 1 font.generate('my_fonts/hand-spoken-' + user + '-' + str(i) + '.ttf')
def main(): try: opts, args = getopt.getopt(sys.argv[1:], '', ['font=']) except getopt.GetoptError as err: print >> sys.stderr, str(err) sys.exit(1) font_file = None for o, a in opts: if o == '--font': font_file = a if font_file == None: print >> sys.stderr, "no font file" sys.exit(1) chars = set([]) for fi in args: f = codecs.open(fi, encoding='utf-8') for line in f: for c in line: chars.add(c) f.close() font = fontforge.open(font_file) ft_out = fontforge.font() ft_out.fontname = font.fontname ft_out.familyname = font.familyname ft_out.fullname = font.fullname ft_out.encoding = font.encoding for c in chars: try: uc = font[ord(c)] print ord(c), font.selection.select(uc) font.copy() ft_out.selection.select(uc) ft_out.paste() except TypeError: print "not found", pass print ft_out.generate("partial.ttf") print ft_out.fontname print ft_out.familyname print ft_out.fullname font.close() ft_out.close()
def init(options = {}, extensions = {}, **args): if 'svg' not in extensions: print 'font extension requires svg extension' exit(1) options['_font'] = font = fontforge.font() font.copyright = options['font-copyright'] font.familyname = options['font-family'] font.fondname = options['font-family'] font.fontname = options['font-family'] font.fullname = options['font-family'] font.weight = str(options['font-weight']) font.em = 1000
def __init__(self, paramsFile, svgdir, outname) : self.params = ConfigParser.SafeConfigParser() parameters = codecs.open(paramsFile, "r", "UTF-8") self.params.readfp(parameters) self.svgDir = svgdir self.font = fontforge.font() self.font.encoding = 'UnicodeBmp' # 1 USC-2 Unicode BMP self.font.fontname = self.params.get("Font", "enFamilyName") self.font.fullname = self.params.get("Font", "enFullName") self.font.familyname = self.params.get("Font", "enFamilyName") sfntNameList = list(self.font.sfnt_names[:]) subFamily = self.params.get("Font", "enSubFamily") self.font.sfnt_names = (('English (US)', 'Copyright', self.params.get("Font", 'copyright')), \ ('English (US)', 'Family', self.font.familyname), ('English (US)', 'SubFamily', subFamily), \ ('English (US)', 'UniqueID', u'FontForge 2.0 : ' + self.font.fullname + ": " + datetime.datetime.now().isoformat()),\ ('English (US)', 'Fullname', self.font.fullname),\ ('English (US)', 'Version', 'Version {0:09.3f}'.format(float(self.params.get("Font", 'version')))),\ # ('English (US)', 'PostScriptName', self.font.fontname),\ ('English (US)', 'License', "Open Font License"), ('English (US)', 'License URL', 'http://scripts.sil.org/OFL')) langCode = int(self.params.get("Font", "localizedLang")) self.font.appendSFNTName(langCode, 1, self.params.get("Font", "localizedFamilyName").encode('UTF-8')) self.font.appendSFNTName(langCode, 2, self.params.get("Font", "localizedSubFamily").encode('UTF-8')) self.font.appendSFNTName(langCode, 4, self.params.get("Font", "localizedFullName").encode('UTF-8')) self.font.appendSFNTName(0x409, 8, self.params.get("Font", "vendor")) self.font.appendSFNTName(0x409, 9, self.params.get("Font", "designer")) self.font.appendSFNTName(0x409, 11, self.params.get("Font", "vendorUrl")) print(self.font.sfnt_names) self.font.ascent = self.params.getint("Font", "fontAscent") self.font.descent = self.params.getint("Font", "fontDescent") self.font.os2_weight = self.params.getint("Font", "fontWeight") self.font.os2_winascent = self.params.getint("Font", "ascent") - self.font.ascent self.font.os2_windescent = self.params.getint("Font", "descent") - self.font.descent self.font.os2_family_class = self.params.getint("Font", "familyClass") self.fixedWidth = int(self.params.get("Font", "fixedWidth")) self.font.os2_panose = (2, 0, 6, 3, 0, 0, 0, 0, 0, 0) if self.fixedWidth > 0: self.font.os2_panose = (2, 0, 6, 9, 0, 0, 0, 0, 0, 0) self.font.em = int(self.params.get("Font", "emWidth")) logFile = codecs.open(outname +".log", "w", "UTF-8") logging.basicConfig(filemode="r", level=logging.DEBUG, stream=logFile) self.log = logging.getLogger(outname) # self.log = self.outName = outname self.sfdFile = outname + ".sfd" self.ttfFile = outname + ".ttf" self.glyphCount = 0 self.alternateTables = dict() # dict of tables, where each table is a list of tuples in the form # (precontext, orig_glyphs, postcontext, replace_glyphs) self.substitutions = [] self.subDict = dict() self.classes = dict()
def initialize_font(weight): """Create a new font, with constans initialized. """ font = fontforge.font() font.fontname = FONT_FAMILY_NAME + "-" + weight font.fullname = FONT_FAMILY_FULL_NAME + " " + weight font.familyname = FONT_FAMILY_FULL_NAME font.weight = weight font.encoding = "UnicodeFull" font.copyright = "" font.version = "" font.comment = None return font
def main(): font = fontforge.font() name = "liparxe-round" font.encoding = "UnicodeBmp" font.familyname = name font.fullname = name font.fontname = name create(font) font.save("%s.sfd" % name) font.generate("%s.ttf" % name)
def process(process_id, line_num_p_process): for i in range(process_id * line_num_p_process, (process_id + 1) * line_num_p_process): if i >= lines_num: break font_line = valid_fonts[i] font_id = font_line.strip().split(', ')[0] split = font_line.strip().split(', ')[1] font_name = font_line.strip().split(', ')[-1] font_file_path = os.path.join(fonts_file_path, split, font_name) try: cur_font = fontforge.open(font_file_path) except Exception as e: print('Cannot open', font_name) print(e) continue target_dir = os.path.join(sfd_path, split, "{}".format(font_id)) if not os.path.exists(target_dir): os.makedirs(target_dir) for char_id, char in enumerate(alphabet_chars): char_description = open( os.path.join(target_dir, '{}_{:02d}.txt'.format(font_id, char_id)), 'w') cur_font.selection.select(char) cur_font.copy() new_font_for_char = fontforge.font() new_font_for_char.selection.select(char) new_font_for_char.paste() new_font_for_char.fontname = "{}_".format(font_id) + font_name new_font_for_char.save( os.path.join(target_dir, '{}_{:02d}.sfd'.format(font_id, char_id))) char_description.write(str(ord(char)) + '\n') char_description.write( str(new_font_for_char[char].width) + '\n') char_description.write( str(new_font_for_char[char].vwidth) + '\n') char_description.write('{:02d}'.format(char_id) + '\n') char_description.write('{}'.format(font_id)) char_description.close() cur_font.close()
def post(self, request, *args, **kwargs): try: pk_list = json.loads(request.body) except: pk_list = [] if len(pk_list)<=0: return redirect("/") pk = [int(x) for x in pk_list] att = [] f = fontforge.font() gs = Glyph.objects.all() gs = Glyph.objects.filter(pk__in=pk_list) svgs = glob.glob("/Users/kirby/htdocs/testcol/font/don/svgs/*") count = 1 for g in gs: if g.license.attribution: att += [g] fn = os.path.join(settings.MEDIA_ROOT, str(g.svg)) if not os.path.exists(fn): continue c = f.createChar(0xf000 + count) c.importOutlines(fn) c.left_side_bearing = KERNING c.right_side_bearing = KERNING c.simplify() c.round() count += 1 random_name = "" while True: random_name = hex(int(1000000000000*random.random())) dir = os.path.join(tmp_root, random_name) if not os.path.exists(dir): break os.makedirs(dir) ttf_fn = os.path.join(dir, "font.ttf") eof_fn = os.path.join(dir, "font.eof") woff_fn = os.path.join(dir, "font.woff") license_fn = os.path.join(dir, "attribution.txt") f.generate(ttf_fn) f.generate(eof_fn) f.generate(woff_fn) f = open(license_fn, "w") for g in att: f.writelines("the icon '%s' is contributed by %s %s\n"%(g.name, g.author, "("+g.author_url+")" if g.author_url else "")) f.close() files = glob.glob(os.path.join(dir, "*")) #buf = StringIO.StringIO() zip_fn = os.path.join(tmp_root, random_name+".zip") z = zipfile.ZipFile(zip_fn, "w") #z = zipfile.ZipFile(buf, "w") for f in files: b = os.path.basename(f) print(b) z.write(f, b) z.close() return HttpResponse(json.dumps({"name": random_name}))
def generateTTF(filename): emsize = 1024 width = emsize height = emsize from xie.graphics.canvas import TrueTypeGlyphCanvasController canvas = TrueTypeGlyphCanvasController(width, height) from xie.graphics.drawing import DrawingSystem drawSystem = DrawingSystem(canvas) import fontforge f = fontforge.font() f.is_quadratic = True # f.strokedfont=True # f.strokewidth=50 f.em = emsize characters = sorted(rm.getCharacters()) print("總共有 %s 個字符" % len(characters)) for index, ch in enumerate(characters): if index % 100 == 0: print("正在描繪 %s 到 %s 個字符" % (index * 1, index + 100)) o = ord(ch) g = f.createChar(o) g.left_side_bearing = 100 g.right_side_bearing = 100 canvas.changeGlyph(g) character = rm.getCharacter(ch) from xie.graphics.shape import Boundary descriptionBoundary = Boundary(0, 0, 256, 256) drawSystem.save() drawSystem.setSourceBoundary(descriptionBoundary) drawSystem.draw(character) drawSystem.restore() # stroke(penType, strokeWidth, lineCap, lineJoin) # stroke(circular|calligraphic|polygon, strokeWidth, square|round|butt, miter|round|bevel) g.stroke("circular", 30, "round", "miter") g.correctDirection() g.removeOverlap() g.correctDirection() makeSureDirCreated(filename) f.generate(filename) print('結束')
def __init__(self, basename, isBold=False, isItalic=False): if isBold: self.weight = 'bold' else: self.weight = 'normal' if isItalic: self.style = 'italic' self.bitmaps = italicBitmaps else: self.style = 'normal' self.bitmaps = romanBitmaps self.glyphs = glyphs # That is, glyphs.glyphs s = [basename] if self.weight == 'bold': s.append(self.weight) if self.style == 'italic': s.append('italic') s = [cap(x) for x in s] self.human_name = ' '.join(s) self.fontname = ''.join(self.human_name.split()) self.familyname = ''.join(basename.split()) print("basename: {0}".format(basename)) print("fontname: {0}".format(self.fontname)) print("familyname: {0}".format(self.familyname)) print("human name: {0}".format(self.human_name)) print("") self.sfd_name = '{0}.sfd'.format(self.fontname) self.otf_name = '{0}.otf'.format(self.fontname) self.ttf_name = '{0}.ttf'.format(self.fontname) self.font = fontforge.font() self.font.ascent = ASCENT self.font.descent = DESCENT self.font.fontname = self.fontname self.font.familyname = self.familyname self.font.fullname = self.human_name if self.weight == 'bold': self.font.weight = cap(self.weight) # if self.style == 'italic': # self.font.isItalic = True g = self.font.createChar(0x0020, 'space') g.width = CHAR_WIDTH
def run(self): self.name = self.options.name self.path = self.options.path self.font = font = fontforge.font() font.fontname = self.name font.fullname = self.name font.familyname = self.name glyphs = self.options.glyphs.split(',,') for g in glyphs: self.grab(g) font.generate(self.path)
def createFont(strFontName): logFile= open(options.logfile,"w") if options.font_in: tt=fontforge.open(options.font_in) else: tt=fontforge.font(options.font_out) print "Adding Glyphs" AddGlyphs(tt, logFile) print "Setting font em size from", tt.em, "to", options.emsize tt.em = options.emsize logFile.write("Font em size set to {0}\n".format(tt.em)) print "Generating font" tt.generate(strFontName) print "Done" logFile.close()
def main(model_fd): data = json.load(model_fd) if not data: return validateModel(data) font = fontforge.font() font.familyname = data["font_name"] font.fontname = data["font_name"] font.design_size = 1024.0 font.hasvmetrics = True font.upos = 0 font.ascent = 1024 font.descent = 0 font.hhea_ascent = 1024 font.hhea_ascent_add = False font.hhea_descent = 0 font.hhea_descent_add = False font.hhea_linegap = 0 font.os2_use_typo_metrics = True font.os2_typoascent = 1024 font.os2_typoascent_add = False font.os2_typodescent = 0 font.os2_typodescent_add = False font.os2_typolinegap = 0 font.os2_winascent = 1024 font.os2_winascent_add = False font.os2_windescent = 0 font.os2_windescent_add = False for i, glyph in enumerate(data["glyphs"]): charcode = UTF8_AREA + i c = font.createChar(charcode) glyph["charcode"] = "\\u{:x}".format(charcode) c.importOutlines(glyph["path"]) #scale glyph to fit between 200 (base line) and 800 (x 0.6) #c.transform((0.6, 0.0, 0.0, 0.6, 200, 200.)) c.vwidth = 1024 c.width = 1024 font.generate(data["font_file"]) genQml(data)
def __init__(self, existing_font=None, preset=None): self._ff_messages = [] if existing_font: with self._captures_messages(): self._ff = fontforge.open(existing_font) else: self._ff = fontforge.font() self.name = DEFAULT_FONT_NAME self.family = DEFAULT_FAMILY_NAME self.postscript_name = DEFAULT_POSTSCRIPT_NAME self.apply_preset(preset or DefaultPreset) self.closed = False
def main(): font = fontforge.font(); name = "BhataanTransliteration" font.fullname = name; font.fontname = name; font.familyname = name; font.encoding = "UnicodeBmp"; create_characters(font); create(font); font.save("%s.sfd" % name); font.generate("%s.ttf" % name); font.generate("%s.woff" % name);
def initialize_font(glyph_database, font_type): font_name = FONT_NAME_PATTERN % font_type font = fontforge.font() font.familyname = font_name font.fullname = font_name for glyph_id, glyph_info in glyph_database['info'].iteritems(): print("Importing glyph [%s]: %s" % (font_type, glyph_id)) unicode_id = glyph_info['unicode_id'] unicode_name = 'uni' + hex(unicode_id).upper()[2:] char = font.createChar(unicode_id, unicode_name) char.importOutlines(GLYPH_PATH_PATTERN % (FONT_TYPES[font_type], glyph_id)) char.width = 1000 return font, font_name.replace(' ', '-')
def __init__(self, filename=None): self.filename = filename if filename != None and os.path.isfile(filename): self.sfdfile = fontforge.open(filename) else: self.sfdfile = fontforge.font() # set default self.setName('unnamed') self.sfdfile.weight = 'Medium' self.sfdfile.copyright = \ 'Created with python-fontforge, edit with FontForge' self.sfdfile.comment = 'Created %s' % time.ctime() self.sfdfile.ascent = 1000 self.sfdfile.descent = 0 self.sfdfile.upos = 0 self.sfdfile.encoding = 'UnicodeFull' self.glyphs = {}
def createFont(name): font = fontforge.font() font.familyname = fontName font.fontname = fontName font.fondname = fontName font.fullname = fontName font.copyright = ' ' font.comment = ' ' font.woffMetadata = ' ' font.version = '1.0.1' font.encoding = "utf-8" font.uwidth = 0 font.upos = 0 font.ascent = 960 font.descent = 64 font.em = 1024 return font
def icon(filepath): """Try to convert the contents of svg file to json representation of icon. :filepath: path to file :returns: dict """ iconfile = open(filepath) origincontents = iconfile.read() tempfont = fontforge.font() tempfont.ascent = BASE_ASCENT tempfont.descent = BASE_DESCENT tempfont.em = BASE_ASCENT + BASE_DESCENT glyph = tempfont.createChar(0xf000) try: tempiconfile = tempfile.NamedTemporaryFile(suffix='.svg') tempiconfile.write(origincontents) tempiconfile.flush() glyph.importOutlines(tempiconfile.name) bbox = glyph.boundingBox() if abs(bbox[2] - bbox[0]) < 1.0 or abs(bbox[3] - bbox[1]) < 1.0: return None glyph.transform((1, 0, 0, 1, -bbox[0], -bbox[1])) glyph.round() bbox = map(int, glyph.boundingBox()) tempiconfile.close() except: return None tmpf = tempfile.NamedTemporaryFile(suffix='.svg') tempfont.generate(tmpf.name) tempfont.close() output = tmpf.read() tmpf.close() output = re.sub(r'xmlns\s*=\s*["\'][^"\']+["\']', '', output) fontquery = pq(output) glyph = fontquery('glyph').eq(0) d = glyph.attr('d') return { 'viewBox': (0, 0, BASE_ASCENT, BASE_ASCENT), 'boundingBox': bbox, 'svg_d': d }
def icon(filepath): """Try to convert the contents of svg file to json representation of icon. :filepath: path to file :returns: dict """ iconfile = open(filepath) origincontents = iconfile.read() tempfont = fontforge.font() tempfont.ascent = BASE_ASCENT tempfont.descent = BASE_DESCENT tempfont.em = BASE_ASCENT + BASE_DESCENT glyph = tempfont.createChar(0xf000) try: tempiconfile = tempfile.NamedTemporaryFile(suffix='.svg') tempiconfile.write(origincontents) tempiconfile.flush() glyph.importOutlines(tempiconfile.name) bbox = glyph.boundingBox() if abs(bbox[2] - bbox[0]) < 1.0 or abs(bbox[3] - bbox[1]) < 1.0: return None glyph.transform((1, 0, 0, 1, -bbox[0], -bbox[1])) glyph.round() bbox = map(int, glyph.boundingBox()) tempiconfile.close() except: return None tmpf = tempfile.NamedTemporaryFile(suffix='.svg') tempfont.generate(tmpf.name) tempfont.close() output = tmpf.read() tmpf.close() output = re.sub(r'xmlns\s*=\s*["\'][^"\']+["\']', '', output) fontquery = pq(output) glyph = fontquery('glyph').eq(0) d = glyph.attr('d') return { 'viewBox': (0, 0,BASE_ASCENT, BASE_ASCENT), 'boundingBox': bbox, 'svg_d': d }
def create_font(conf): """ Create font with some default options """ font = fontforge.font() font.encoding = 'UnicodeFull' font.em = FONT_EM # TODO: Make ligatures optional # Forcing strings to stop TypeError: Bad type for argument due to # unicode_literals liga = str('liga') latn = str('latn') dflt = str('dflt') feature_script_lang = ((liga, ((latn, (dflt)),)),) # Set up ligatures font.addLookup('liga', 'gsub_ligature', (), feature_script_lang) font.addLookupSubtable('liga', 'liga') # Add all recommended font characters # Reference: https://www.microsoft.com/typography/otspec/recom.htm glyph = font.createChar(-1, '.notdef') glyph.width = 0 # TODO: Needs a default notdef glyph glyph = font.createChar(0x0, '.null') glyph.width = DEFAULT_GLYPH_WIDTH glyph = font.createChar(0xD, 'CR') glyph.width = DEFAULT_GLYPH_WIDTH glyph = font.createChar(0x20, 'space') try: glyph.width = conf['width_space'] except KeyError: glyph.width = DEFAULT_GLYPH_WIDTH logger.debug("Space character width: %d", glyph.width) glyph = font.createChar(ZWJ_INT) glyph.width = 0 glyph = font.createChar(VS16_INT) glyph.width = 0 return font
def makeFont(): boardWidth = (PARAMS['keyWidth']+PARAMS['horizontalSpacing'])*10 boardHeight = PARAMS['tallHeight']*1.8 font = fontforge.font() font.fontname = FONTNAME font.fullname = FONTNAME font.familyname = FONTNAME font.ascent = boardHeight font.descent = 0 def storeGlyph(char, svgFilename, width=0): glyph = font.createChar(ord(char)) glyph.width = width glyph.importOutlines(svgFilename) storeGlyph('/', 'board.svg', boardWidth) for key in KEYS.keys(): svgFilename = key+'.svg' if key=='star': storeGlyph('*', svgFilename) elif '2' in key: # this is a key that exists on the left # and the right, and this one is on the right. # So we store it as a lowercase letter storeGlyph(key[0].lower(), svgFilename) elif (key+'2') in KEYS: # this is a key that exists on the left # and the right, and this one is on the left # So we store it as an uppercase letter storeGlyph(key.upper(), svgFilename) else: # it appears on one side only; # be convenient and store it as both cases storeGlyph(key.upper(), svgFilename) storeGlyph(key.lower(), svgFilename) font.save('stenoboard.sfd') font.generate('stenoboard.ttf')
def font_generate(filename, dirpath): font = ff.font() font.fontname = "User" font.familyname = "UserFont1" for i in xrange(96): image_name = str(i + 32) + '.png' image_path = os.path.join(dirpath, image_name) glyph = font.createMappedChar(chr(i + 32)) glyph.importOutlines(image_path) font.selection.select(chr(i + 32)) font.autoTrace() if i != 0: font.autoWidth(10) # font.autoKern() filepath = os.path.join(dirpath, filename) font.generate(filepath)
def build_font(_f): modify_and_save_latin(_f, EN_TEMP) modify_and_save_jp(_f, JP_TEMP) deco_print('merge modified {} and modified {}'.format( _f.get('latin'), _f.get('japanese'))) target_font = fontforge.font() target_font = set_height(target_font) target_font.upos = 45 target_font.fontname = _f.get('family') target_font.familyname = _f.get('family') target_font.fullname = _f.get('name') target_font.weight = _f.get('weight_name') target_font = set_os2_values(target_font, _f) target_font = set_sfnt_names(target_font, _f) target_font = set_gasp_table(target_font) target_font.mergeFonts(EN_TEMP) if not DEBUG: os.remove(EN_TEMP) target_font.mergeFonts(JP_TEMP) if not DEBUG: os.remove(JP_TEMP) target_font = vertical_line_to_broken_bar(target_font) # target_font = emdash_to_broken_dash(target_font) # あまり必要性を感じないので削除 # 全角をいじるのはマージ前に行う target_font = post_process(target_font) fontpath = DIST + '/{}'.format(_f.get('filename')) if DEBUG: print_pdf(target_font, fontpath + '.pdf') target_font.generate(fontpath) target_font.close() fix_xAvgCharWidth(SOURCE + '/{}'.format(_f.get('japanese')), fontpath) deco_print('Generate {} completed.'.format(_f.get('name')))
def build_svg_only(): build = fontforge.font() build.encoding = "UnicodeBMP" build.ascent = ASCENT build.descent = DESCENT add_own_symbols(build) licf = open("src/COPYING") lic = licf.read() licf.close() build.appendSFNTName(0x409, 0, "No Copyright") build.appendSFNTName(0x409, 1, "Ocami PD") build.appendSFNTName(0x409, 2, "Regular") build.appendSFNTName(0x409, 4, "Ocami PD Regular") build.appendSFNTName(0x409, 6, "Ocami PD Regular") build.appendSFNTName(0x409, 13, lic) build.save("dist/ocami-symbols.sfd") build.close()
def newMathFont(aName): print("Generating %s.otf..." % aName, end="") mathFont = fontforge.font() mathFont.fontname = aName mathFont.familyname = aName mathFont.fullname = aName mathFont.copyright = "Copyright (c) 2014 Mozilla Corporation" mathFont.encoding = "UnicodeFull" # Create a space character. Also force the creation of some MATH subtables # so that OTS will not reject the MATH table. g = mathFont.createChar(ord(" "), "space") g.width = em g.italicCorrection = 0 g.topaccent = 0 g.mathKern.bottomLeft = tuple([(0, 0)]) g.mathKern.bottomRight = tuple([(0, 0)]) g.mathKern.topLeft = tuple([(0, 0)]) g.mathKern.topRight = tuple([(0, 0)]) mathFont[ord(" ")].horizontalVariants = "space" mathFont[ord(" ")].verticalVariants = "space" return mathFont
def __init__(self, em_size, basename): self.EM_SIZE = em_size SCALE_FACTOR = self.EM_SIZE/2048.0 if em_size == EM_SIZE_OTF: self.format = 'otf' elif em_size == EM_SIZE_TTF: self.format = 'ttf' self.human_name = basename self.fontname = ''.join(self.human_name.split()) self.familyname = ''.join(basename.split()) self.ASCENT = SCALE_FACTOR * 1700.0 self.DESCENT = SCALE_FACTOR * 324.0 self.CAP_HEIGHT = SCALE_FACTOR * 1790.0 self.CHAR_WIDTH = (self.EM_SIZE / ASPECT_RATIO) * 0.9 self.ROW_SIZE = self.EM_SIZE / DOT_ROWS self.COL_SIZE = self.CHAR_WIDTH / (DOT_COLUMNS - 1) self.DOT_SIZE = max(self.ROW_SIZE, self.COL_SIZE) / 2.0 self.DOT_H = self.DOT_SIZE * 2.1 self.DOT_V = self.DOT_SIZE * 2.1 self.font = fontforge.font() self.font.ascent = self.ASCENT self.font.descent = self.DESCENT self.font.fontname = self.fontname self.font.familyname = self.familyname self.font.fullname = self.human_name self.font.fontlog = open(FONTLOG_FILENAME, 'r').read() self.font.copyright = open(COPYRIGHT_FILENAME, 'r').read() g = self.font.createChar(0x0020, 'space') g.width = self.COL_SIZE * DOT_COLUMNS self.binary_filename = '{0}.{1}'.format(self.fontname, self.format) self.archive_filename = '{0}-{1}.sfd'.format(self.fontname, self.format)
def generate( font_path, texts, output ): font = fontforge.open(font_path) new_font = fontforge.font() new_font.encoding = 'UnicodeFull' texts = get_text_str(texts) for text in texts: hex_text = hex(ord(text)) val = hex_text.replace("0x","").upper() if len(val) < 4: for i in range(0, 4 - len(val)): val = "0" + val val = "uni" + val #print(text, val, texts, re.search("0x", hex_text), hex_text) try: font.selection.select(("ranges",None), val, val) font.copy() new_font.selection.select(("ranges",None), val, val) new_font.paste() except Exception as e: print(val, e) new_font.generate(output)
def generate(self): """Goes through all the registered glyphs inside the font and generates each one.""" # Create a new font. self.font = fontforge.font() # Go through the glyphs and generate each one. We display the # current status of the generation to the screen so we can see # something happening. total = len(self.glyphs) processed = 0 for gid, glyph in self.glyphs.iteritems(): processed += 1 self.log.debug(" [{0:4}/{1:4}] Unicode {3:04x}: {2}".format( processed, total, glyph.label, glyph.gid)) glyph.generate(self.font) # Finalize the font. self.font.fontname = self.name
def generate(): font = fontforge.font() # Some basic metadata. font.copyright = ('Copyright (c) 2014 Ryan Dorsey\n' 'Licensed under SIL Open Font License v1.1 ' '(http://scripts.sil.org/OFL)\n' 'Created with FontForge 2.0 (http://fontforge.sf.net)') font.encoding = config['specs']['encoding'] font.em = config['specs']['fontforge em'] font.descent = config['specs']['descent'] font.ascent = config['specs']['ascent'] font.familyname = config['specs']['family name'] font.fontname = config['specs']['font name'] font.fullname = config['specs']['full name'] font.version = config['specs']['version'] font.weight = config['specs']['weight'] make_basic_glyphs(font) make_private_use_glyphs(font) make_space_glyphs(font) font.mergeFeature('MazonHebrew-Regular.fea') font.save('MazonHebrew-Regular.gen.sfd') font.generate('MazonHebrew-Regular.gen.otf')
parser.add_argument('--debug', '-d', action='store_true', help='display debug messages') args = parser.parse_args() indir = args.dir[0] outdir = args.dir[1] except ImportError: # Older Pythons don't have argparse, so we use optparse instead import optparse parser = optparse.OptionParser(description='Convert a directory of svg and eps files into a unified font file.') parser.add_option('--name', metavar='fontname', type='string', nargs='?', default='fontrobot', help='reference name of the font (no spaces)') parser.add_option('--nohash', '-n', action='store_true', help='disable hash fingerprinting of font files') parser.add_argument('--debug', '-d', action='store_true', help='display debug messages') (args, posargs) = parser.parse_args() indir = posargs[0] outdir = posargs[1] f = fontforge.font() f.encoding = 'UnicodeFull' m = md5.new() cp = 0xf100 files = [] KERNING = 15 for dirname, dirnames, filenames in os.walk(indir): for filename in filenames: name, ext = os.path.splitext(filename) filePath = os.path.join(dirname, filename) size = os.path.getsize(filePath) if ext in ['.svg', '.eps']:
if len(src_codes) != len(set(src_codes)): stderr.write("Error in file %s: glyph codes aren't unique:\n" % args.config) for code in set(src_codes): if src_codes.count(code) > 1: stderr.write("Duplicate 'from:' 0x%04x\n" % code) sys.exit(1) try: font = fontforge.open(args.src_font) # set font encoding so we can select any unicode code point font.encoding = 'UnicodeFull' except: stderr.write("Error: Fontforge can't open source %s" % args.src_font) sys.exit(1) new_font = fontforge.font() new_font.encoding = 'UnicodeFull' # load font properties from config for key, value in config.get('font', {}).items(): setattr(new_font, key, value) for from_code, to_code in remap_config: try: font[from_code] except TypeError: stderr.write("Warning: no such glyph in the source font (code=0x%04x)\n" % from_code) continue
#!/usr/local/bin/fontforge #Needs: fonts/ayn+meem.init.svg # At one point splinestroke failed if the first spline on a contour had a length of 0 import fontforge; font=fontforge.font(); a = font.createChar(65); a.importOutlines("fonts/ayn+meem.init.svg");
def subset_font_raw(font_in, font_out, unicodes, opts): if '--namelist' in opts: # 2010-12-06 DC To allow setting namelist filenames, # change getopt.gnu_getopt from namelist to namelist= # and invert comments on following 2 lines # nam_fn = opts['--namelist'] nam_fn = font_out + '.nam' nam = file(nam_fn, 'w') else: nam = None if '--script' in opts: pe_fn = "/tmp/script.pe" pe = file(pe_fn, 'w') else: pe = None font = fontforge.open(font_in) if pe: print >> pe, 'Open("' + font_in + '")' extract_vert_to_script(font_in, pe) for i in unicodes: select_with_refs(font, i, font, pe, nam) addl_glyphs = [] if '--nmr' in opts: addl_glyphs.append('nonmarkingreturn') if '--null' in opts: addl_glyphs.append('.null') for glyph in addl_glyphs: font.selection.select(('more',), glyph) if nam: print >> nam, "0x%0.4X" % fontforge.unicodeFromName(glyph), glyph if pe: print >> pe, 'SelectMore("%s")' % glyph flags = () if '--simplify' in opts: font.simplify() font.round() flags = ('omit-instructions',) if '--strip_names' in opts: font.sfnt_names = () if '--new' in opts: font.copy() new = fontforge.font() new.encoding = font.encoding new.em = font.em new.layers['Fore'].is_quadratic = font.layers['Fore'].is_quadratic for i in unicodes: select_with_refs(font, i, new, pe, nam) new.paste() # This is a hack - it should have been taken care of above. font.selection.select('space') font.copy() new.selection.select('space') new.paste() new.sfnt_names = font.sfnt_names font = new else: font.selection.invert() print >> pe, "SelectInvert()" font.cut() print >> pe, "Clear()" if nam: print "Writing NameList", nam.close() if pe: print >> pe, 'Generate("' + font_out + '")' pe.close() os.system("fontforge -script " + pe_fn) else: font.generate(font_out, flags = flags) font.close() if '--roundtrip' in opts: # FontForge apparently contains a bug where it incorrectly calculates # the advanceWidthMax in the hhea table, and a workaround is to open # and re-generate font2 = fontforge.open(font_out) font2.generate(font_out, flags = flags)
fontforge.logWarning(" code point:" + str(f.CollabLastChangedCodePoint())) f.generate(fontFileOnDisk) js = json.dumps({ "seq": str(f.CollabLastSeq()), "glyph": str(f.CollabLastChangedName()), "codepoint": str(f.CollabLastChangedCodePoint()), "earl": str(fontFileURL), "end": "null" # this is simply so we dont have to manage keeping the last item with no terminating , }, sort_keys=True, indent=4, separators=(',', ': ')) print js fi = open(fontJsonOnDisk, 'w') fi.write(js) newfont=fontforge.font() f = newfont.CollabSessionJoin() fontforge.logWarning( "Joined session, font name: " + f.fullname ) openURLInBrowser( "http://localhost:8000" ) fontforge.logWarning("web-test-collab: starting up..."); f.CollabSessionSetUpdatedCallback( OnCollabUpdate ) while True: f.CollabSessionRunMainLoop() # if keyPressed(): # break; finalOutput = "/tmp/out-final.ttf" f.generate(finalOutput) fontforge.logWarning( "Left collab session, final file is at " + finalOutput )