def main(argvs): argc = len(argvs) if argc != 4: print "======> Usage: python %s step{1|3} font-file-name prefix" % argvs[ 0] print "======> eg. python %s step1 msgothic.ttc rbf-tmp-ttf" % argvs[ 0] quit() stepSeq = argvs[1] fontFSName = argvs[2] tmpPrefix = argvs[3] # Step 1 if stepSeq == "step1": # Get packed family names familyNames = fontforge.fontsInFile(fontFSName) # Breake TTC i = 0 for familyName in familyNames: # openName: "msgothic.ttc(MS UI Gothic)" openName = "%s(%s)" % (fontFSName, familyName) # tmp file name: rbf-tmp-ttf0a.ttf and rbf-tmp-ttf1a.ttf and so on. tmpTTF = "%s%da.ttf" % (tmpPrefix, i) # Open font font = fontforge.open(openName) for glyph in font.selection.byGlyphs.__iter__(): glyph.manualHints = True # glyph.manualHints() glyph.simplify() glyph.round() # for glyph in fontforge.activeFont().selection.byGlyphs.__iter__(): # glyph.manualHints = True # Edit font # font.encoding = 'UnicodeFull' # font.selection.all() # font.simplify() # font.round() # font.autoHint() # font.autoInstr() font.gasp = gasp() font.gasp_version = 1 # Generate font font.generate(tmpTTF, flags=flags) font.close() i += 1 print "======> Breake TTC." # Step 3 elif stepSeq == "step3": newTTCname = 'new_' + fontFSName files = glob.glob(tmpPrefix + '[0-9]a.ttf') fontX = [] for file in files: fontOpen = fontforge.open(file) fontX.append(fontOpen) # Generate TTC. if len(fontX) > 1: f = fontX[0] fontX.pop(0) f.generateTtc(newTTCname, (fontX), ttcflags=("merge", ), layer=1) else: print "======> Fonts not found. Or it is not enough fonts." quit() for openedFont in fontX: openedFont.close() f.close() print "======> Generate TTC." # Other else: pass
# Make sure the output directories exist. os.makedirs(todir, exist_ok=True) os.makedirs('css', exist_ok=True) # For each file in fromdir. for index, file in enumerate(files,1): # If a CSS file exists for this font file, skip it. file_exists = os.path.isfile(os.path.join(os.getcwd(), 'css', file + '.css')) if debugVideoManager or not file_exists: print(str(index).rjust(pad) + tstr + file, flush=True) if file_exists: continue # For each font in the file. for findex, fname in enumerate(fontforge.fontsInFile(os.path.join(fromdir,file))): print(col_space + fname, flush=True) # Get font info. stderr = OutputGrabber(sys.stderr) with stderr: try: font = fontforge.open(os.path.join(fromdir, f'${file}(${findex})'), 1) except EnvironmentError as e: if str(e) == 'Open failed': try: font = fontforge.open(os.path.join(fromdir,file),1) except: raise else: raise newfilename = font.cidfontname or font.fontname font.generate(os.path.join(todir, newfilename + '.woff')) font.generate(os.path.join(todir, newfilename + '.woff2')) names = {font.cidfamilyname, font.cidfontname, font.cidfullname, font.familyname, font.fontname, font.fullname, font.default_base_filename, font.fondname}
# via https://gist.github.com/tai271828/6f08b24d813355585f613c0c80bd774a """Convert TTC font to TTF using fontforge with python extension. **Warning** The scripts saves splitted fonts in the current working directory. Usage: python2 split_ttc_font_to_ttf.py Preinstallation: apt-get install python-fontforge """ import sys import fontforge fonts = fontforge.fontsInFile("Apple Color Emoji.ttc") for font_name in fonts: print(font_name) #font = fontforge.open('%s(%s)'%(sys.argv[1], font_name)) #font.generate('%s.ttf'%font_name) #font.close()
# fontforge.loadNamelist() # fontforge.loadNamelistDir() # fontforge.preloadCidmap() fontforge.printSetup("lpr") if (fontforge.unicodeFromName("A")!=65) or (fontforge.unicodeFromName("uni030D")!=0x30D): raise ValueError("Wrong return from unicodeFromName") foo = fontforge.version() ambrosia = sys.argv[1] fonts = fontforge.fonts() if ( len(fonts)!=0 ) : raise ValueError("Wrong return from fontforge.fonts") fontforge.activeFont() fontforge.activeGlyph() fontforge.activeLayer() fontnames= fontforge.fontsInFile(ambrosia) if len(fontnames)!=1 or fontnames[0]!='Ambrosia': raise ValueError("Wrong return from fontforge.fontsInFile") font = fontforge.open(ambrosia) morefonts = fontforge.fonts() if len(morefonts)!=1: raise ValueError("Wrong return from fontforge.fonts") instrs = fontforge.parseTTInstrs("SRP0\nMIRP[min,rnd,black]") print(fontforge.unParseTTInstrs(instrs))
errlog = [] files = os.listdir(fromdir) tstr = '/' + str(len(files)) + ' => ' pad = len(str(len(files))) # For each file in fromdir. for index, file in enumerate(files, 1): print(str(index).rjust(pad) + tstr + file) if os.path.isfile(os.path.join(os.getcwd(), 'css', file + '.css')): continue # For each font in the file. for fname in fontforge.fontsInFile(os.path.join(fromdir, file)): print(' ' * (pad * 2 + 5) + fname) # Get font info. stderr = OutputGrabber(sys.stderr) with stderr: try: font = fontforge.open( bytearray(os.path.join(fromdir, file + '(' + fname + ')')).decode('utf8'), 1) except EnvironmentError as e: if str(e) == 'Open failed': try: font = fontforge.open( bytearray(os.path.join(fromdir, file)).decode('utf8'), 1)
def main(argvs): # Set work and save director. Please apply these to your environment. workDir = argvs[1] saveDir = workDir + "/new" if not os.path.exists(saveDir): os.makedirs(saveDir) """ DO NOT CHANGE BELLOW. """ argc = len(argvs) if argc != 2: print "Usage: python %s /path/dir" % argvs[0] print " eg. python %s ~/Downloads/fonts" % argvs[0] quit() # TrueType 系統のファイルを探す。 fontFiles = fontsSearch(argvs[1], '*.ttc', '*.ttf') # 見つかった TrueType 系統のファイルを順次変換する。 for fontFile in fontFiles: # set variables. fontFSName = os.path.basename(fontFile) tmpPrefix = "breakttc" tempDir = tempfile.mkdtemp() print "Start breaking TTC." # Get packed family names familyNames = fontforge.fontsInFile(fontFile) i = 0 # Break a TTC to some TTFs. for familyName in familyNames: # openName format: "msgothic.ttc(MS UI Gothic)" print "%s" % familyName openName = "%s(%s)" % (fontFile, familyName) # tmp file name: breakttf0a.ttf and breakttf1a.ttf and so on. tmpTTF = "%s%da.ttf" % (tmpPrefix, i) # Open font font = fontforge.open(openName) # Edit font font.encoding = 'UnicodeFull' font.gasp = gasp() font.gasp_version = 1 font.os2_vendor = "maud" font.os2_version = 1 # Windows で幅広問題を回避する。 # ttf へ一時的に保存する。 font.generate(tempDir + "/" + tmpTTF, flags=flags) font.close() i += 1 print "Finish breaking TTC." print "Start generate TTC." # set variables. newTTCname = fontFSName newFontPath = tempDir + "/" + newTTCname saveFontPath = saveDir + "/" + newTTCname files = glob.glob(tempDir + "/" + tmpPrefix + '[0-9]a.ttf') f = fontforge.open(files[0]) files.pop(0) # TTC の場合 pop しても一つ以上残るはず。 if len(files) > 0: # 残りの ttf を最初の ttf に追加する。 for file in files: # Raspberry Pi 3 は複数開くとメモリが足りなくて落ちるので注意。 f2 = fontforge.open(file) f.generateTtc(newFontPath, f2, ttcflags=("merge", ), layer=1) f2.close() # TTF の場合 pop して一つ減ってるから 0 になるはず。 elif len(files) == 0: f.generate(newFontPath, flags=flags) # 新しく生成した分のフォントを閉じる。 f.close() print "Finish generate TTC." # temporary 内の ttc ファイルを保存先へ移動する。 if os.path.exists(newFontPath): shutil.move(newFontPath, saveFontPath) # temporary directory を掃除しておく。 shutil.rmtree(tempDir) print "Cleanup temporary directory." # Finish print "Finish all in dir."
def main(file): for font in fontforge.fontsInFile(file): f = fontforge.open(u'%s(%s)' % (file, font)) f.generate('%s.ttf' % font)
def main(): parser = argparse.ArgumentParser( description='Add ToUnicode tables to PDF files.') parser.add_argument('--outdir', default='tmp/sfd', type=str, help='Output .sfd files to this directory') parser.add_argument('pdfs', type=str, nargs='+', help='PDF files to process') args = parser.parse_args() fontnum = 0 for pdf in args.pdfs: print("Adding ToUnicode tables to PDF file {}".format(pdf)) with open(pdf, 'rb') as fobj: pdfdata = fobj.read() doc = PdfReader(fdata=pdfdata) doc.read_all() fonts = [ o for o in doc.indirect_objects.values() if hasattr(o, 'Type') and o.Type == '/Font' ] fonts = { font.FontDescriptor.FontName[1:]: font for font in fonts if font.FontDescriptor is not None } embedded_fonts = fontforge.fontsInFile(pdf) for fontname in embedded_fonts: if fontname not in fonts: print( "WARNING: font {} not found in pdf file".format(fontname)) continue print("Adding ToUnicode table to font {}".format(fontname)) font = fontforge.open('{}({})'.format(pdf, fontname)) fonts[fontname].ToUnicode = PdfDict() fonts[fontname].ToUnicode.stream = generate_tounicode( font, fonts[fontname]) # Need to save the modified font because fontforge won't read # ToUnicode when it converts to woff later. font.fontname = 'pretex{:06d}'.format(fontnum) font.save( os.path.join( args.outdir, '[{}]{}.sfd'.format(os.path.basename(pdf)[:-4], fontname))) fontnum += 1 PdfWriter(pdf, trailer=doc).write() # Measure extents for displayed equations pdfpath = os.path.realpath(os.path.dirname(pdf)) doc = poppler.document_new_from_file( 'file://{}'.format(os.path.realpath(pdf)), None) boxsize = os.path.join(pdfpath, 'boxsize.txt') with open(boxsize) as fobj: lines = fobj.readlines() with open(boxsize, 'w') as fobj: pageno = 0 for line in lines: if not (line.startswith('inline:') or line.startswith('display:')): fobj.write(line) continue pageno += 1 if not line.startswith('display:'): fobj.write(line) continue page = doc.get_page(pageno - 1) width, height = page.get_size() surf = cairo.RecordingSurface( cairo.Content.COLOR_ALPHA, cairo.Rectangle(0, 0, width, height)) ctx = cairo.Context(surf) page.render_for_printing(ctx) x, y, w, h = surf.ink_extents() fobj.write(line.strip() + '{},{},{},{}\n'.format(x, y, w, h))
def main(argvs): # Set work and save director. Please apply these to your environment. workDir = argvs[1] saveDir = workDir + "/new" if not os.path.exists(saveDir): os.makedirs(saveDir) """ DO NOT CHANGE BELLOW. """ argc = len(argvs) if argc != 2: print "Usage: python %s /path/dir" % argvs[0] print " eg. python %s ~/Downloads/fonts" % argvs[0] quit() # TrueType 系統のファイルを探す。 fontFiles = fontsSearch(argvs[1], '*.ttc', '*.ttf') # 見つかった TrueType 系統のファイルを順次変換する。 for fontFile in fontFiles: # set variables. fontFSName = os.path.basename(fontFile) tmpPrefix = "breakttc" tempDir = tempfile.mkdtemp() print "Start breaking TTC." # Get packed family names familyNames = fontforge.fontsInFile(fontFile) i = 0 # Break a TTC to some TTFs. for familyName in familyNames: # openName format: "msgothic.ttc(MS UI Gothic)" print "%s" % familyName openName = "%s(%s)" % (fontFile, familyName) # tmp file name: breakttf0a.ttf and breakttf1a.ttf and so on. tmpTTF = "%s%da.ttf" % (tmpPrefix, i) # Open font font = fontforge.open(openName) # Edit font font.encoding = 'UnicodeFull' font.gasp = gasp() font.gasp_version = 1 font.os2_vendor = "maud" font.os2_version = 1 # Windows で幅広問題を回避する。 # ttf へ一時的に保存する。 font.generate(tempDir + "/" + tmpTTF, flags=flags) font.close() i += 1 print "Finish breaking TTC." print "Start generate TTC." # set variables. newTTCname = fontFSName newFontPath = tempDir + "/" + newTTCname saveFontPath = saveDir + "/" + newTTCname files = glob.glob(tempDir + "/" + tmpPrefix + '[0-9]a.ttf') f = fontforge.open(files[0]) files.pop(0) # TTC の場合 pop しても一つ以上残るはず。 if len(files) > 0: # 残りの ttf を最初の ttf に追加する。 for file in files: # Raspberry Pi 3 は複数開くとメモリが足りなくて落ちるので注意。 f2 = fontforge.open(file) f.generateTtc(newFontPath, f2, ttcflags=("merge",), layer=1) f2.close() # TTF の場合 pop して一つ減ってるから 0 になるはず。 elif len(files) == 0: f.generate(newFontPath, flags=flags) # 新しく生成した分のフォントを閉じる。 f.close() print "Finish generate TTC." # temporary 内の ttc ファイルを保存先へ移動する。 if os.path.exists(newFontPath): shutil.move(newFontPath, saveFontPath) # temporary directory を掃除しておく。 shutil.rmtree(tempDir) print "Cleanup temporary directory." # Finish print "Finish all in dir."
def main(argvs): argc = len(argvs) if argc != 4: print "======> Usage: python %s step{1|3} font-file-name prefix" % argvs[0] print "======> eg. python %s step1 msgothic.ttc rbf-tmp-ttf" % argvs[0] quit() stepSeq = argvs[1] fontFSName = argvs[2] tmpPrefix = argvs[3] # Step 1 if stepSeq == "step1": # Get packed family names familyNames = fontforge.fontsInFile(fontFSName) # Breake TTC i = 0 for familyName in familyNames: # openName: "msgothic.ttc(MS UI Gothic)" openName = "%s(%s)" % (fontFSName, familyName) # tmp file name: rbf-tmp-ttf0a.ttf and rbf-tmp-ttf1a.ttf and so on. tmpTTF = "%s%da.ttf" % (tmpPrefix, i) # Open font font = fontforge.open(openName) for glyph in font.selection.byGlyphs.__iter__(): glyph.manualHints = True # glyph.manualHints() glyph.simplify() glyph.round() # for glyph in fontforge.activeFont().selection.byGlyphs.__iter__(): # glyph.manualHints = True # Edit font # font.encoding = 'UnicodeFull' # font.selection.all() # font.simplify() # font.round() # font.autoHint() # font.autoInstr() font.gasp = gasp() font.gasp_version = 1 # Generate font font.generate(tmpTTF, flags=flags) font.close() i += 1 print "======> Breake TTC." # Step 3 elif stepSeq == "step3": newTTCname = 'new_' + fontFSName files = glob.glob(tmpPrefix + '[0-9]a.ttf') fontX = [] for file in files: fontOpen = fontforge.open(file) fontX.append(fontOpen) # Generate TTC. if len(fontX) > 1: f = fontX[0] fontX.pop(0) f.generateTtc(newTTCname, (fontX), ttcflags=("merge",), layer=1) else: print "======> Fonts not found. Or it is not enough fonts." quit() for openedFont in fontX: openedFont.close() f.close() print "======> Generate TTC." # Other else: pass
# fontforge.loadNamelist() # fontforge.loadNamelistDir() # fontforge.loadPlugin() # fontforge.loadPluginDir() # fontforge.preloadCidmap() fontforge.printSetup("lpr") if ( (fontforge.unicodeFromName("A")!=65) | (fontforge.unicodeFromName("uni030D")!=0x30D) ) : raise ValueError, "Wrong return from unicodeFromName" foo = fontforge.version() fonts = fontforge.fonts() if ( len(fonts)!=0 ) : raise ValueError, "Wrong return from fontforge.fonts" fontforge.activeFont() fontforge.activeGlyph() fontforge.activeLayer() fontnames= fontforge.fontsInFile("fonts/Ambrosia.sfd") if ( len(fontnames)!=1 ) | (fontnames[0]!='Ambrosia' ): raise ValueError, "Wrong return from fontforge.fontsInFile" font = fontforge.open("fonts/Ambrosia.sfd") morefonts = fontforge.fonts() if ( len(morefonts)!=1 ) : raise ValueError, "Wrong return from fontforge.fonts" instrs = fontforge.parseTTInstrs("SRP0\nMIRP[min,rnd,black]") print fontforge.unParseTTInstrs(instrs)
errlog = [] files = os.listdir(fromdir) tstr = '/' + str(len(files)) + ' => ' pad = len(str(len(files))) # For each file in fromdir. for index, file in enumerate(files,1): print(str(index).rjust(pad) + tstr + file) if os.path.isfile(os.path.join(os.getcwd(), 'css', file + '.css')): continue # For each font in the file. for fname in fontforge.fontsInFile(os.path.join(fromdir,file)): print(' '*(pad*2+5) + fname) # Get font info. stderr = OutputGrabber(sys.stderr) with stderr: try: font = fontforge.open(bytearray(os.path.join(fromdir, file + '(' + fname + ')')).decode('utf8'), 1) except EnvironmentError as e: if str(e) == 'Open failed': try: font = fontforge.open(bytearray(os.path.join(fromdir, file)).decode('utf8'), 1) except: raise else: raise newfilename = font.cidfontname or font.fontname font.generate(os.path.join(todir, newfilename + '.woff')) names = {font.cidfamilyname, font.cidfontname, font.cidfullname, font.familyname, font.fontname, font.fullname, font.default_base_filename, font.fondname} names.update(string for language, strid, string in font.sfnt_names if strid in {'Family', 'Fullname', 'PostScriptName'})
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import glob import fontforge f1 = fontforge.fontsInFile('/tmp/msgothic.ttc'); for i in f1: print i f2 = fontforge.fontsInFile('/tmp/meiryo.ttc'); for i in f2: print i print "----- MS Gothic" f = fontforge.open('/tmp/msgothic.ttc') for x in f.sfnt_names: if x[1] == 'SubFamily': f.appendSFNTName(x[0], x[1], unicode('Bold', 'utf-8').encode('utf-16-be')) print f.fullname print f.familyname print f.temporary f.close print "----- Meiryo" f = fontforge.open('/tmp/meiryo.ttc(Meiryo)') f.simplify() f.round() f.autoHint() f.autoInstr() f.generate('/tmp/hoge.ttf') for x in f.sfnt_names: