예제 #1
0
def vtt_compile(infile,
                outfile=None,
                ship=False,
                inplace=None,
                force_overwrite=False,
                **_):
    if not os.path.exists(infile):
        raise vttLib.VTTLibArgumentError("Input TTF '%s' not found." % infile)

    font = TTFont(infile)

    if outfile:
        pass
    elif inplace:
        # create (and overwrite exising) backup first
        import shutil

        shutil.copyfile(infile, infile + inplace)
        outfile = infile
    elif force_overwrite:
        # save to input file (no backup)
        outfile = infile
    else:
        # create new unique output file
        from fontTools.ttx import makeOutputFileName

        outfile = makeOutputFileName(infile, None, ".ttf")

    vttLib.compile_instructions(font, ship=ship)
    font.save(outfile)
예제 #2
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 2:
        print("usage: merge_woff_metadata.py METADATA.xml "
              "INPUT.woff [OUTPUT.woff]", file=sys.stderr)
        return 1

    metadata_file = args[0]
    with open(metadata_file, 'rb') as f:
        metadata = f.read()

    infile = args[1]
    if len(args) > 2:
        outfile = args[2]
    else:
        filename, ext = os.path.splitext(infile)
        outfile = makeOutputFileName(filename, None, ext)

    font = TTFont(infile)

    if font.flavor not in ("woff", "woff2"):
        print("Input file is not a WOFF or WOFF2 font", file=sys.stderr)
        return 1

    data = font.flavorData

    # this sets the new WOFF metadata
    data.metaData = metadata

    font.save(outfile)
예제 #3
0
def makeWOFF(files, destination):
    """
    Makes WOFF2 files from list of paths.

    *files* is a `list` of file paths as `string`
    *destination* is a `string` of the destination to save the WOFF files.
    """
    from fontTools.ttLib import woff2
    from fontTools.ttx import makeOutputFileName

    if not os.path.exists(destination):
        os.mkdir(destination)

    print("🏗  Making WOFF2")
    printProgressBar(0, len(files), prefix='  ', suffix='Complete', length=50)
    for i, file in enumerate(files):
        outfilename = makeOutputFileName(file,
                                         outputDir=destination,
                                         extension='.woff2')
        if os.path.exists(outfilename):
            os.remove(outfilename)

        woff2.compress(file, outfilename)
        printProgressBar(i + 1,
                         len(files),
                         prefix='  ',
                         suffix='Complete',
                         length=50)
예제 #4
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 2:
        print(
            "usage: merge_woff_metadata.py METADATA.xml "
            "INPUT.woff [OUTPUT.woff]",
            file=sys.stderr)
        return 1

    metadata_file = args[0]
    with open(metadata_file, 'rb') as f:
        metadata = f.read()

    infile = args[1]
    if len(args) > 2:
        outfile = args[2]
    else:
        filename, ext = os.path.splitext(infile)
        outfile = makeOutputFileName(filename, None, ext)

    font = TTFont(infile)

    if font.flavor not in ("woff", "woff2"):
        print("Input file is not a WOFF or WOFF2 font", file=sys.stderr)
        return 1

    data = font.flavorData

    # this sets the new WOFF metadata
    data.metaData = metadata

    font.save(outfile)
예제 #5
0
파일: webfonts.py 프로젝트: smc/Chilanka
def webfonts(infont, type):
    font = TTFont(infont, recalcBBoxes=0)
    woffFileName = makeOutputFileName(
        infont, outputDir=None, extension='.' + type)
    font.flavor = type
    font.save(woffFileName, reorderTables=False)
    font.close()
예제 #6
0
def webfonts(infont, type):
    font = TTFont(infont, recalcBBoxes=0)
    # Generate WOFF2
    woffFileName = makeOutputFileName(infont, outputDir=None, extension='.' + type)
    print("Processing %s => %s" % (infont, woffFileName))
    font.flavor = type
    font.save(woffFileName, reorderTables=False)
    font.close()
예제 #7
0
def make_output_name(filename):
    with open(filename, "rb") as f:
        f.seek(4)
        sfntVersion = f.read(4)
    assert len(sfntVersion) == 4, "not enough data"
    ext = '.ttf' if sfntVersion == b"\x00\x01\x00\x00" else ".otf"
    outfilename = makeOutputFileName(filename, outputDir=None, extension=ext)
    return outfilename
예제 #8
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]
    if len(args) < 1:
        print("One argument, the input filename, must be provided.", file=sys.stderr)
        sys.exit(1)

    filename = args[0]
    outfilename = makeOutputFileName(filename, outputDir=None, extension='.woff2')

    print("Processing %s => %s" % (filename, outfilename))

    font = TTFont(filename, recalcBBoxes=False, recalcTimestamp=False)
    font.flavor = "woff2"
    font.save(outfilename, reorderTables=False)
예제 #9
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]
    if len(args) < 1:
        print("One argument, the input filename, must be provided.", file=sys.stderr)
        return 1

    filename = args[0]
    outfilename = makeOutputFileName(filename, outputDir=None, extension='.woff2')

    print("Processing %s => %s" % (filename, outfilename))

    font = TTFont(filename, recalcBBoxes=False, recalcTimestamp=False)
    font.flavor = "woff2"
    font.save(outfilename, reorderTables=False)
예제 #10
0
def main(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("input", metavar="INPUT")
    parser.add_argument("-o", "--output")
    parser.add_argument("-e", "--max-error", type=float, default=MAX_ERR)
    parser.add_argument("--post-format", type=float, default=POST_FORMAT)
    parser.add_argument("--keep-direction",
                        dest='reverse_direction',
                        action='store_false')
    options = parser.parse_args(args)

    output = options.output or makeOutputFileName(
        options.input, outputDir=None, extension='.ttf')
    font = TTFont(options.input)
    otf_to_ttf(font,
               post_format=options.post_format,
               max_err=options.max_error,
               reverse_direction=options.reverse_direction)
    font.save(output)
예제 #11
0
def main(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("input", metavar="INPUT")
    parser.add_argument("-o", "--output")
    parser.add_argument("-e", "--max-error", type=float, default=MAX_ERR)
    parser.add_argument("--post-format", type=float, default=POST_FORMAT)
    parser.add_argument(
        "--keep-direction", dest='reverse_direction', action='store_false')
    options = parser.parse_args(args)

    output = options.output or makeOutputFileName(options.input,
                                                  outputDir=None,
                                                  extension='.ttf')
    font = TTFont(options.input)
    otf_to_ttf(font,
               post_format=options.post_format,
               max_err=options.max_error,
               reverse_direction=options.reverse_direction)
    font.save(output)
예제 #12
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 1:
        print("usage: gzip.py " "INPUT.ttx [OUTPUT.ttf]", file=sys.stderr)
        return 1

    infile = args[0]
    if len(args) > 1:
        outfile = args[1]
    else:
        outfile = makeOutputFileName(infile, None, ".ttf")

    font = TTFont()
    font.importXML(infile)

    svg = font["SVG "]
    svg.compressed = True
    font.save(outfile)
예제 #13
0
def vtt_compile(
    infile, outfile=None, ship=False, inplace=None, force_overwrite=False, **kwargs
):
    font = TTFont(infile)

    if outfile:
        pass
    elif inplace:
        # create (and overwrite exising) backup first
        shutil.copyfile(infile, infile + inplace)
        outfile = infile
    elif force_overwrite:
        # save to input file (no backup)
        outfile = infile
    else:
        # create new unique output file
        from fontTools.ttx import makeOutputFileName

        outfile = makeOutputFileName(infile, None, ".ttf")

    compile_instructions(font, ship=ship)
    font.save(outfile)
예제 #14
0
def main(args):
    if not args.filepath:
        raise AttributeError('Please specify font filepath')
    if not os.path.exists(args.filepath):
        raise AttributeError('File: %s not found' % args.filepath)

    textfile_dir = '_posts'
    unichars = set()

    def walk_callback(args, dirname, fnames):
        for fname in fnames:
            unichars.update(get_unicodes(os.path.join(dirname, fname)))

    os.path.walk(textfile_dir, walk_callback, None)
    unicodes = [ord(c) for c in unichars]

    cjk_fontfile = args.filepath
    out_fontdir = 'assets/fonts'
    out_fontfile = makeOutputFileName(os.path.basename(args.filepath),
                                      outputDir=out_fontdir,
                                      extension='.woff',
                                      overWrite=True)

    options = subset.Options()
    dontLoadGlyphNames = not options.glyph_names
    font = subset.load_font(cjk_fontfile,
                            options,
                            dontLoadGlyphNames=dontLoadGlyphNames)
    subsetter = subset.Subsetter()
    subsetter.populate(glyphs=[], gids=[], unicodes=unicodes, text='')
    subsetter.subset(font)
    sfnt.USE_ZOPFLI = True
    font.flavor = 'woff'
    font.save(out_fontfile, reorderTables=False)

    print('Input font: % 7d bytes: %s' %
          (os.path.getsize(cjk_fontfile), cjk_fontfile))
    print('Subset font: % 7d bytes: %s' %
          (os.path.getsize(out_fontfile), out_fontfile))
예제 #15
0
def vtt_compile(
    infile,
    outfile=None,
    ship=False,
    inplace=None,
    force_overwrite=False,
    keep_cvar=False,
    **_,
):
    if not os.path.exists(infile):
        raise vttLib.VTTLibArgumentError("Input TTF '%s' not found." % infile)

    font = TTFont(infile)

    if keep_cvar and "cvar" not in font:
        raise vttLib.VTTLibArgumentError(
            "The --keep-cvar option was specified, but no cvar table exists in the font"
        )

    if outfile:
        pass
    elif inplace:
        # create (and overwrite exising) backup first
        import shutil

        shutil.copyfile(infile, infile + inplace)
        outfile = infile
    elif force_overwrite:
        # save to input file (no backup)
        outfile = infile
    else:
        # create new unique output file
        from fontTools.ttx import makeOutputFileName

        outfile = makeOutputFileName(infile, None, ".ttf")

    vttLib.compile_instructions(font, ship=ship, keep_cvar=keep_cvar)
    font.save(outfile)
예제 #16
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 1:
        print("usage: dump_woff_metadata.py "
              "INPUT.woff [OUTPUT.xml]", file=sys.stderr)
        return 1

    infile = args[0]
    if len(args) > 1:
        outfile = args[1]
    else:
        outfile = makeOutputFileName(infile, None, ".xml")

    font = TTFont(infile)

    if not font.flavorData or not font.flavorData.metaData:
        print("No WOFF metadata")
        return 1

    with open(outfile, "wb") as f:
        f.write(font.flavorData.metaData)
예제 #17
0
def main(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("input", metavar="INPUT")
    parser.add_argument("-o", "--output")
    parser.add_argument("-c",
                        "--cyrillic",
                        dest="cyr",
                        action="store_true",
                        default=False)
    parser.add_argument("-e", "--max-error", type=float, default=MAX_ERR)
    parser.add_argument("--post-format", type=float, default=POST_FORMAT)
    parser.add_argument("--keep-direction",
                        dest='reverse_direction',
                        action='store_false')
    options = parser.parse_args(args)

    output = options.output or makeOutputFileName(
        options.input, outputDir=None, extension='.ttf')
    font = TTFont(options.input)
    otf_to_ttf(font,
               post_format=options.post_format,
               max_err=options.max_error,
               reverse_direction=options.reverse_direction)

    if options.cyr:
        cmap = font['cmap']
        for table in cmap.tables:
            if table.format in [4, 12, 13, 14]:
                for key in table.cmap:
                    if (key >= 0x410 and key <= 0x44F):
                        table.cmap[key - 0x350] = table.cmap[key]
                    if key == 0x401:
                        table.cmap[0xA8] = table.cmap[key]
                    if key == 0x451:
                        table.cmap[0xB8] = table.cmap[key]

    font.save(output)
예제 #18
0
def vtt_compile(infile,
                outfile=None,
                ship=False,
                inplace=None,
                force_overwrite=False,
                **kwargs):
    font = TTFont(infile)

    if outfile:
        pass
    elif inplace:
        # create (and overwrite exising) backup first
        shutil.copyfile(infile, infile + inplace)
        outfile = infile
    elif force_overwrite:
        # save to input file (no backup)
        outfile = infile
    else:
        # create new unique output file
        from fontTools.ttx import makeOutputFileName
        outfile = makeOutputFileName(infile, None, ".ttf")

    compile_instructions(font, ship=ship)
    font.save(outfile)
예제 #19
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 1:
        print("usage: dump_woff_metadata.py "
              "INPUT.woff [OUTPUT.xml]",
              file=sys.stderr)
        return 1

    infile = args[0]
    if len(args) > 1:
        outfile = args[1]
    else:
        outfile = makeOutputFileName(infile, None, ".xml")

    font = TTFont(infile)

    if not font.flavorData or not font.flavorData.metaData:
        print("No WOFF metadata")
        return 1

    with open(outfile, "wb") as f:
        f.write(font.flavorData.metaData)
예제 #20
0
familyname = u"Georama"
weightname = filename.replace('Italic', '').replace('It', '').split("-")[1]
widthname = filename.replace(familyname, '').split("-")[0]
italicname = ""
if filename.endswith("Italic"):
    italicname = "Italic"
elif filename.endswith("It"):
    italicname = "It"

postscriptFullName = u"{0} {1} {2} {3}".format(
    familyname, widthname, weightname,
    italicname).replace('  ', ' ').replace('  ', ' ').rstrip()

# Set postscriptFullName
# print("\t{0}".format(postscriptFullName))
# setName(self, string, nameID, platformID, platEncID, langID):
font['name'].setName(postscriptFullName, 4, 3, 1, 1033)

# getName(self, nameID, platformID, platEncID, langID=None)
# print str(font['name'].getName(1,3,1)).replace(chr(0),"")

# for x in font['name'].names:
# 	print x.nameID, x.platformID, x.platEncID, str(x).replace(chr(0),"")

# Set usWeightClass
font['OS/2'].usWeightClass = wght[weightname]
# font['OS/2'].panose.bWeight = wght[weightname][1]

outputTTF = makeOutputFileName(inputTTF, '', extension)
font.save(outputTTF)
예제 #21
0
def main(args=None):
	"""Compress and decompress WOFF2 fonts"""
	import argparse
	from fontTools import configLogger
	from fontTools.ttx import makeOutputFileName

	class _HelpAction(argparse._HelpAction):

		def __call__(self, parser, namespace, values, option_string=None):
			subparsers_actions = [
					action for action in parser._actions
					if isinstance(action, argparse._SubParsersAction)]
			for subparsers_action in subparsers_actions:
					for choice, subparser in subparsers_action.choices.items():
							print(subparser.format_help())
			parser.exit()

	class _NoGlyfTransformAction(argparse.Action):
		def __call__(self, parser, namespace, values, option_string=None):
			namespace.transform_tables.difference_update({"glyf", "loca"})

	class _HmtxTransformAction(argparse.Action):
		def __call__(self, parser, namespace, values, option_string=None):
			namespace.transform_tables.add("hmtx")

	parser = argparse.ArgumentParser(
		prog="fonttools ttLib.woff2",
		description=main.__doc__,
		add_help = False
	)

	parser.add_argument('-h', '--help', action=_HelpAction,
		help='show this help message and exit')

	parser_group = parser.add_subparsers(title="sub-commands")
	parser_compress = parser_group.add_parser("compress",
		description = "Compress a TTF or OTF font to WOFF2")
	parser_decompress = parser_group.add_parser("decompress",
		description = "Decompress a WOFF2 font to OTF")

	for subparser in (parser_compress, parser_decompress):
		group = subparser.add_mutually_exclusive_group(required=False)
		group.add_argument(
			"-v",
			"--verbose",
			action="store_true",
			help="print more messages to console",
		)
		group.add_argument(
			"-q",
			"--quiet",
			action="store_true",
			help="do not print messages to console",
		)

	parser_compress.add_argument(
		"input_file",
		metavar="INPUT",
		help="the input OpenType font (.ttf or .otf)",
	)
	parser_decompress.add_argument(
		"input_file",
		metavar="INPUT",
		help="the input WOFF2 font",
	)

	parser_compress.add_argument(
		"-o",
		"--output-file",
		metavar="OUTPUT",
		help="the output WOFF2 font",
	)
	parser_decompress.add_argument(
		"-o",
		"--output-file",
		metavar="OUTPUT",
		help="the output OpenType font",
	)

	transform_group = parser_compress.add_argument_group()
	transform_group.add_argument(
		"--no-glyf-transform",
		dest="transform_tables",
		nargs=0,
		action=_NoGlyfTransformAction,
		help="Do not transform glyf (and loca) tables",
	)
	transform_group.add_argument(
		"--hmtx-transform",
		dest="transform_tables",
		nargs=0,
		action=_HmtxTransformAction,
		help="Enable optional transformation for 'hmtx' table",
	)

	parser_compress.set_defaults(
		subcommand=compress,
		transform_tables={"glyf", "loca"},
	)
	parser_decompress.set_defaults(subcommand=decompress)

	options = vars(parser.parse_args(args))

	subcommand = options.pop("subcommand", None)
	if not subcommand:
		parser.print_help()
		return

	quiet = options.pop("quiet")
	verbose = options.pop("verbose")
	configLogger(
		level=("ERROR" if quiet else "DEBUG" if verbose else "INFO"),
	)

	if not options["output_file"]:
		if subcommand is compress:
			extension = ".woff2"
		elif subcommand is decompress:
			# choose .ttf/.otf file extension depending on sfntVersion
			with open(options["input_file"], "rb") as f:
				f.seek(4)  # skip 'wOF2' signature
				sfntVersion = f.read(4)
			assert len(sfntVersion) == 4, "not enough data"
			extension = ".otf" if sfntVersion == b"OTTO" else ".ttf"
		else:
			raise AssertionError(subcommand)
		options["output_file"] = makeOutputFileName(
			options["input_file"], outputDir=None, extension=extension
		)

	try:
		subcommand(**options)
	except TTLibError as e:
		parser.error(e)
condSubst = [
    # A list of (Region, Substitution) tuples.
    ([{"wght": (0.158, 0.564)}], {"uniF8FF": "uniF8FF.001"}),
    # ([{"wght": (0.868, 1)}], {"uni20B5": "uni20B5.201_230"}),
    # ([{"wght": (0.868, 1)}], {"cent": "cent.201_230"}),
    # ([{"wght": (0.868, 1)}], {"colonmonetary": "colonmonetary.201_230"}),
    # ([{"wght": (0.868, 1)}], {"dollar": "dollar.201_230"}),
    # ([{"wght": (0.868, 1)}], {"uni20B2": "uni20B2.201_230"}),
    # ([{"wght": (0.868, 1)}], {"dollar.tf": "dollar.tf.201_230"}),
    # ([{"wght": (0.868, 1)}], {"cent.tf": "cent.tf.201_230"}),
    # ([{"wght": (0.71, 1)}], {"uni20A6": "uni20A6.169_230"}),
    # ([{"wght": (0.71, 1)}], {"peseta": "peseta.169_230"}),
    # ([{"wght": (0.71, 1)}], {"uni20A9": "uni20A9.169_230"}),
    # ([{"wght": (0.564, 1)}], {"uni20B1": "uni20B1.136_230"}),
    # ([{"wght": (0.424, 1)}], {"uni2761": "uni2761.79_230"}),
    # ([{"wght": (0.424, 1)}], {"paragraph": "paragraph.79_230"}),
]

# if style == "Upright":
# 	condSubst += [	    
# 		([{"wght": (0.564, 1)}], {"Adieresis.titl": "Adieresis.titl.136_230"}),
# 	    ([{"wght": (0.564, 1)}], {"Odieresis.titl": "Odieresis.titl.136_230"}),
# 	]

addFeatureVariations(f, condSubst)

# newFontPath = fontPath.split(".")[0] + "-italic.ttf" 
# f.save(fontPath)
extension = os.path.splitext(inputTTF)[1]
outputTTF = makeOutputFileName(inputTTF, '', extension)
f.save(outputTTF)
예제 #23
0
파일: build.py 프로젝트: smc/Meera-Tamil
                text = 'OFL v1.1'
            record.string = text
            names.append(record)
        # keep every thing else except Descriptor, Sample Text
        elif nameID not in (10, 19):
            names.append(record)

name.names = names

# FFTM is FontForge specific, remove it
del (font['FFTM'])
# force compiling GPOS/GSUB tables by fontTools, saves few tens of KBs
for tag in ('GPOS', 'GSUB'):
    font[tag].compile(font)

font.save(outfont)
# Generate WOFF
woffFileName = makeOutputFileName(infont, outputDir=None, extension='.woff')
print("Processing %s => %s" % (infont, woffFileName))
font.flavor = "woff"
font.save(woffFileName, reorderTables=False)
# Generate WOFF2
woff2FileName = makeOutputFileName(infont, outputDir=None, extension='.woff2')
print("Processing %s => %s" % (infont, woff2FileName))
font.flavor = "woff2"
font.save(woff2FileName, reorderTables=False)

font.close()

os.remove(tmpfont)
예제 #24
0
                text = 'OFL v1.1'
            record.string = text
            names.append(record)
        # keep every thing else except Descriptor, Sample Text
        elif nameID not in (10, 19):
            names.append(record)

name.names = names

# FFTM is FontForge specific, remove it
del(font['FFTM'])
# force compiling GPOS/GSUB tables by fontTools, saves few tens of KBs
for tag in ('GPOS', 'GSUB'):
    font[tag].compile(font)

font.save(outfont)
# Generate WOFF
woffFileName = makeOutputFileName(infont, outputDir=None, extension='.woff')
print("Processing %s => %s" % (infont, woffFileName))
font.flavor = "woff"
font.save(woffFileName, reorderTables=False)
# Generate WOFF2
woff2FileName = makeOutputFileName(infont, outputDir=None, extension='.woff2')
print("Processing %s => %s" % (infont, woff2FileName))
font.flavor = "woff2"
font.save(woff2FileName, reorderTables=False)

font.close()

os.remove(tmpfont)