Beispiel #1
0
def com_google_fonts_check_ttx_roundtrip(font):
    """Checking with fontTools.ttx"""
    from fontTools import ttx
    import sys
    ttFont = ttx.TTFont(font)
    failed = False

    class TTXLogger:
        msgs = []

        def __init__(self):
            self.original_stderr = sys.stderr
            self.original_stdout = sys.stdout
            sys.stderr = self
            sys.stdout = self

        def write(self, data):
            if data not in self.msgs:
                self.msgs.append(data)

        def restore(self):
            sys.stderr = self.original_stderr
            sys.stdout = self.original_stdout

    logger = TTXLogger()
    ttFont.saveXML(font + ".xml")
    export_error_msgs = logger.msgs

    if len(export_error_msgs):
        failed = True
        yield INFO, ("While converting TTF into an XML file,"
                     " ttx emited the messages listed below.")
        for msg in export_error_msgs:
            yield FAIL, msg.strip()

    f = ttx.TTFont()
    f.importXML(font + ".xml")
    import_error_msgs = [
        msg for msg in logger.msgs if msg not in export_error_msgs
    ]

    if len(import_error_msgs):
        failed = True
        yield INFO, (
            "While importing an XML file and converting it back to TTF,"
            " ttx emited the messages listed below.")
        for msg in import_error_msgs:
            yield FAIL, msg.strip()
    logger.restore()

    if not failed:
        yield PASS, "Hey! It all looks good!"
Beispiel #2
0
def update_ttx(in_file, out_file, image_dirs, prefix, ext, aliases_file):
    if ext != '.png':
        raise Exception('extension "%s" not supported' % ext)

    seq_to_file = collect_seq_to_file(image_dirs, prefix, ext)
    if not seq_to_file:
        raise ValueError(
            'no sequences with prefix "%s" and extension "%s" in %s' %
            (prefix, ext, ', '.join(image_dirs)))

    aliases = None
    if aliases_file:
        aliases = add_aliases.read_emoji_aliases(aliases_file)
        aliases = apply_aliases(seq_to_file, aliases)

    font = ttx.TTFont()
    font.importXML(in_file)

    lineheight = font['hhea'].ascent - font['hhea'].descent
    map_fn = get_png_file_to_advance_mapper(lineheight)
    seq_to_advance = remap_values(seq_to_file, map_fn)

    vadvance = font['vhea'].advanceHeightMax if 'vhea' in font else lineheight

    update_font_data(font, seq_to_advance, vadvance, aliases)

    font.saveXML(out_file)
Beispiel #3
0
def add_image_glyphs(in_file, out_file, pairs, verbosity=1):
    """Add images from pairs (glyphstr, filename) to .ttx file in_file and write
  to .ttx file out_file."""

    quiet = verbosity < 2
    font = ttx.TTFont(quiet=quiet)
    font.importXML(in_file, quiet=quiet)

    sort_glyphstr_tuples(pairs)

    font_builder = FontBuilder(font)
    # we've already sorted by length, so the longest glyphstrs are at the end. To see if
    # we have ligatures, we just need to check the last one.
    if len(pairs[-1][0]) > 1:
        font_builder.init_gsub()

    img_builder = svg_builder.SvgBuilder(font_builder)
    for glyphstr, filename in pairs:
        if verbosity > 1:
            print "Adding glyph for U+%s" % ",".join(
                ["%04X" % ord(char) for char in glyphstr])
        img_builder.add_from_filename(glyphstr, filename)

    font.saveXML(out_file, quiet=quiet)
    if verbosity:
        print "added %s images to %s" % (len(pairs), out_file)
Beispiel #4
0
def do_generate_fonts(template_file,
                      font_basename,
                      pairs,
                      reuse=0,
                      verbosity=1):
    out_woff = font_basename + '.woff'
    if reuse > 1 and os.path.isfile(out_woff) and os.access(out_woff, os.R_OK):
        if verbosity:
            print 'Reusing ' + out_woff
        return

    out_ttx = font_basename + '.ttx'
    if reuse == 0:
        add_svg_glyphs.add_image_glyphs(template_file,
                                        out_ttx,
                                        pairs,
                                        verbosity=verbosity)
    elif verbosity:
        print 'Reusing ' + out_ttx

    quiet = verbosity < 2
    font = ttx.TTFont(flavor='woff', quiet=quiet)
    font.importXML(out_ttx, quiet=quiet)
    font.save(out_woff)
    if verbosity:
        print 'Wrote ' + out_woff
Beispiel #5
0
def getFont(charater, size, x_offset, y_offset):
    font_file = "open-sans/OpenSans-Light.ttf"
    font = ttx.TTFont(font_file)
    g = glyph.Glyph(glyphquery.glyphName(font, charater))
    contours = g.calculateContours(font)
    points = []
    for letter in contours:
        xy = (glyph.decomposeOutline(letter))
        for p in xy:
            points.append(
                stitchcode.Point(x_offset + (p[0] / size),
                                 y_offset + (p[1] / size), False))
    return points
Beispiel #6
0
 def write_words(self, words, unit_height, type, x, y):
     points = []
     height = 0
     if unit_height <= 2:
         if type == "in":
             points.extend(
                 straight_stitch.straight_stitch([
                     stitchcode.Point(x, y, False),
                     stitchcode.Point(x - len(words), y, False),
                     stitchcode.Point(x, y, False)
                 ], 30))
         else:
             points.extend(
                 straight_stitch.straight_stitch([
                     stitchcode.Point(x, y, False),
                     stitchcode.Point(x + len(words), y, False),
                     stitchcode.Point(x, y, False)
                 ], 30))
         i = 1
     else:
         font_file = "Consolas.ttf"
         my_font = ttx.TTFont(font_file)
         count, height, rows = self.how_many_lines(
             words, unit_height * self.SECTION_HEIGHT)
         if (unit_height * self.SECTION_HEIGHT / count <
                 self.SECTION_HEIGHT):
             print("ERROR")
         for i in range(0, len(rows)):
             m_y = y - ((height) * (i))
             points.append(stitchcode.Point(x, m_y, False))
             #print "height: {} row: {}".format(height,rows[i])
             letters, width = font.fill_stitch_string(
                 rows[i], 1462 / (height * 0.8), x, m_y, my_font, 1, 10,
                 100)
             #letters, width =font.satin_stitch_string(rows[i], 1462 / (height), x, m_y, my_font)
             if type == "in":
                 letters = [
                     stitchcode.Point(p.x - width, p.y) for p in letters
                 ]
             #(message, size, x_offset, y_offset, font, slope, density, p_distance):
             points.extend(letters)
     return height, points
Beispiel #7
0
def add_image_glyphs(in_file, out_file, pairs):
    """Add images from pairs (glyphstr, filename) to .ttx file in_file and write
  to .ttx file out_file."""

    font = ttx.TTFont()
    font.importXML(in_file)

    sort_glyphstr_tuples(pairs)

    font_builder = FontBuilder(font)
    # we've already sorted by length, so the longest glyphstrs are at the end. To
    # see if we have ligatures, we just need to check the last one.
    if len(pairs[-1][0]) > 1:
        font_builder.init_gsub()

    img_builder = svg_builder.SvgBuilder(font_builder)
    for glyphstr, filename in pairs:
        logging.debug("Adding glyph for U+%s",
                      ",".join(["%04X" % ord(char) for char in glyphstr]))
        img_builder.add_from_filename(glyphstr, filename)

    font.saveXML(out_file)
    logging.info("Added %s images to %s", len(pairs), out_file)
Beispiel #8
0
def main(argv):
    import glob
    from fontTools import ttx, ttLib

    options = []

    option_map = {
        "-V": "verbose",
        "-O": "keep_outlines",
        "-U": "uncompressed",
        "-S": "small_glyph_metrics",
        "-C": "keep_chunks",
    }

    for key, value in option_map.items():
        if key in argv:
            options.append(value)
            argv.remove(key)

    if len(argv) < 4:
        print("""
Usage:

emoji_builder.py [-V] [-O] [-U] [-S] [-A] font.ttf out-font.ttf strike-prefix...

This will search for files that have strike-prefix followed
by a hex number, and end in ".png".  For example, if strike-prefix
is "icons/uni", then files with names like "icons/uni1f4A9.png" will
be loaded.  All images for the same strike should have the same size
for best results.

If multiple strike-prefix parameters are provided, multiple
strikes will be embedded, in the order provided.

The script then embeds color bitmaps in the font, for characters
that the font already supports, and writes the new font out.

If -V is given, verbose mode is enabled.

If -U is given, uncompressed images are stored (imageFormat=1).

If -S is given, PNG images are stored with small glyph metrics (imageFormat=17).

By default, PNG images are stored with big glyph metrics (imageFormat=18).

If -O is given, the outline tables ('glyf', 'CFF ') and
related tables are NOT dropped from the font.
By default they are dropped.

If -C is given, unused chunks (color profile, etc) are NOT
dropped from the PNG images when embedding.
By default they are dropped.
""",
              file=sys.stderr)
        sys.exit(1)

    font_file = argv[1]
    out_file = argv[2]
    img_prefixes = argv[3:]
    del argv

    def add_font_table(font, tag, data):
        tab = ttLib.tables.DefaultTable.DefaultTable(tag)
        tab.data = str(data)
        font[tag] = tab

    def drop_outline_tables(font):
        for tag in ['cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG']:
            try:
                del font[tag]
            except KeyError:
                pass

    print()

    font = ttx.TTFont(font_file)
    print("Loaded font '%s'." % font_file)

    font_metrics = FontMetrics(font['head'].unitsPerEm, font['hhea'].ascent,
                               -font['hhea'].descent)
    print("Font metrics: upem=%d ascent=%d descent=%d." % \
          (font_metrics.upem, font_metrics.ascent, font_metrics.descent))
    glyph_metrics = font['hmtx'].metrics
    unicode_cmap = font['cmap'].getcmap(3, 10)
    if not unicode_cmap:
        unicode_cmap = font['cmap'].getcmap(3, 1)
    if not unicode_cmap:
        raise Exception("Failed to find a Unicode cmap.")

    image_format = 1 if 'uncompressed' in options else (
        17 if 'small_glyph_metrics' in options else 18)

    ebdt = CBDT(font_metrics, options)
    ebdt.write_header()
    eblc = CBLC(font_metrics, options)
    eblc.write_header()
    eblc.start_strikes(len(img_prefixes))

    def is_vs(cp):
        return cp >= 0xfe00 and cp <= 0xfe0f

    for img_prefix in img_prefixes:
        print()

        img_files = {}
        glb = "%s*.png" % img_prefix
        print("Looking for images matching '%s'." % glb)
        for img_file in glob.glob(glb):
            codes = img_file[len(img_prefix):-4]
            if "_" in codes:
                pieces = codes.split("_")
                cps = [int(code, 16) for code in pieces]
                uchars = "".join([unichr(cp) for cp in cps if not is_vs(cp)])
            else:
                cp = int(codes, 16)
                if is_vs(cp):
                    print("ignoring unexpected vs input %04x" % cp)
                    continue
                uchars = unichr(cp)
            img_files[uchars] = img_file
        if not img_files:
            raise Exception("No image files found in '%s'." % glb)
        print("Found images for %d characters in '%s'." %
              (len(img_files), glb))

        glyph_imgs = {}
        advance = width = height = 0
        for uchars, img_file in img_files.items():
            if len(uchars) == 1:
                try:
                    glyph_name = unicode_cmap.cmap[ord(uchars)]
                except:
                    print("no cmap entry for %x" % ord(uchars))
                    raise ValueError("%x" % ord(uchars))
            else:
                glyph_name = get_glyph_name_from_gsub(uchars, font,
                                                      unicode_cmap.cmap)
            glyph_id = font.getGlyphID(glyph_name)
            glyph_imgs[glyph_id] = img_file
            if "verbose" in options:
                uchars_name = ",".join(["%04X" % ord(char) for char in uchars])
                # print "Matched U+%s: id=%d name=%s image=%s" % (
                #    uchars_name, glyph_id, glyph_name, img_file)

            advance += glyph_metrics[glyph_name][0]
            w, h = PNG(img_file).get_size()
            width += w
            height += h

        glyphs = sorted(glyph_imgs.keys())
        if not glyphs:
            raise Exception(
                "No common characters found between font and '%s'." % glb)
        print("Embedding images for %d glyphs for this strike." % len(glyphs))

        advance, width, height = (div(x, len(glyphs))
                                  for x in (advance, width, height))
        strike_metrics = StrikeMetrics(font_metrics, advance, width, height)
        print("Strike ppem set to %d." % (strike_metrics.y_ppem))

        ebdt.start_strike(strike_metrics)
        ebdt.write_glyphs(glyphs, glyph_imgs, image_format)
        glyph_maps = ebdt.end_strike()

        eblc.write_strike(strike_metrics, glyph_maps)

    print()

    ebdt = ebdt.data()
    add_font_table(font, 'CBDT', ebdt)
    print("CBDT table synthesized: %d bytes." % len(ebdt))
    eblc.end_strikes()
    eblc = eblc.data()
    add_font_table(font, 'CBLC', eblc)
    print("CBLC table synthesized: %d bytes." % len(eblc))

    print()

    if 'keep_outlines' not in options:
        drop_outline_tables(font)
        print("Dropped outline ('glyf', 'CFF ') and related tables.")

# hack removal of cmap pua entry for unknown flag glyph.  If we try to
# remove it earlier, getGlyphID dies.  Need to restructure all of this
# code.
    font_data.delete_from_cmap(font, [0xfe82b])

    font.save(out_file)
    print("Output font '%s' generated." % out_file)
Beispiel #9
0
def com_google_fonts_check_ttx_roundtrip(font):
    """Checking with fontTools.ttx"""
    from fontTools import ttx
    import sys
    ttFont = ttx.TTFont(font)
    failed = False

    class TTXLogger:
        msgs = []

        def __init__(self):
            self.original_stderr = sys.stderr
            self.original_stdout = sys.stdout
            sys.stderr = self
            sys.stdout = self

        def write(self, data):
            if data not in self.msgs:
                self.msgs.append(data)

        def restore(self):
            sys.stderr = self.original_stderr
            sys.stdout = self.original_stdout

    from xml.parsers.expat import ExpatError
    try:
        logger = TTXLogger()
        xml_file = font + ".xml"
        ttFont.saveXML(xml_file)
        export_error_msgs = logger.msgs

        if len(export_error_msgs):
            failed = True
            yield INFO, ("While converting TTF into an XML file,"
                         " ttx emited the messages listed below.")
            for msg in export_error_msgs:
                yield FAIL, msg.strip()

        f = ttx.TTFont()
        f.importXML(font + ".xml")
        import_error_msgs = [
            msg for msg in logger.msgs if msg not in export_error_msgs
        ]

        if len(import_error_msgs):
            failed = True
            yield INFO, ("While importing an XML file and converting"
                         " it back to TTF, ttx emited the messages"
                         " listed below.")
            for msg in import_error_msgs:
                yield FAIL, msg.strip()
        logger.restore()
    except ExpatError as e:
        failed = True
        yield FAIL, (
            "TTX had some problem parsing the generated XML file."
            " This most likely mean there's some problem in the font."
            " Please inspect the output of ttx in order to find more"
            " on what went wrong. A common problem is the presence of"
            " control characteres outside the accepted character range"
            " as defined in the XML spec. FontTools has got a bug which"
            " causes TTX to generate corrupt XML files in those cases."
            " So, check the entries of the name table and remove any"
            " control chars that you find there."
            " The full ttx error message was:\n"
            "======\n{}\n======".format(e))

    if not failed:
        yield PASS, "Hey! It all looks good!"

    # and then we need to cleanup our mess...
    if os.path.exists(xml_file):
        os.remove(xml_file)
Beispiel #10
0
For example, if strike-prefix is "icons/u", then files with names like
"icons/u1F4A9.png" or "icons/u1F1EF_1F1F5.png" will be loaded.  The script
then adds cmap, htmx, and potentially GSUB entries for the Unicode
characters found.  The advance width will be chosen based on image aspect
ratio.  If Unicode values outside the BMP are desired, the existing cmap
table should be of the appropriate (format 12) type.  Only the first cmap
table and the first GSUB lookup (if existing) are modified.
"""
    sys.exit(1)

in_file = sys.argv[1]
out_file = sys.argv[2]
img_prefix = sys.argv[3]
del sys.argv

font = ttx.TTFont()
font.importXML(in_file)

img_files = {}
glb = "%s*.png" % img_prefix
print "Looking for images matching '%s'." % glb
for img_file in glob.glob(glb):
    u = img_file[len(img_prefix):-4].upper()
    img_files[u] = img_file
if not img_files:
    raise Exception("No image files found in '%s'." % glb)

ascent = font['hhea'].ascent
descent = -font['hhea'].descent

g = font['GlyphOrder'].glyphOrder
Beispiel #11
0
#!/usr/bin/python

import sys

from fontTools import ttx

# 测试使用
sys.argv = ['ttf转换xml.py', '.\data\Funkster.ttf', '.\data\Funkster.xml']

if len(sys.argv) < 3:
    print("Usage : ttf转换xml.py in.ttx out.xml")
    sys.exit(1)

ttx_file = sys.argv[1]
xml_file = sys.argv[2]
del sys.argv

font = ttx.TTFont(ttx_file)
font.saveXML(xml_file)

font.close()
Beispiel #12
0
def main(argv):
    import glob
    from fontTools import ttx, ttLib

    options = []

    option_map = {
        "-V": "verbose",
        "-O": "keep_outlines",
        "-U": "uncompressed",
        "-C": "keep_chunks",
    }

    for key, value in option_map.items():
        if key in argv:
            options.append(value)
            argv.remove(key)

    if len(argv) < 4:
        print >> sys.stderr, """
Usage:

emoji_builder.py [-V] [-O] [-U] [-A] font.ttf out-font.ttf strike-prefix...

This will search for files that have strike-prefix followed
by a hex number, and end in ".png".  For example, if strike-prefix
is "icons/uni", then files with names like "icons/uni1f4A9.png" will
be loaded.  All images for the same strike should have the same size
for best results.

If multiple strike-prefix parameters are provided, multiple
strikes will be embedded, in the order provided.

The script then embeds color bitmaps in the font, for characters
that the font already supports, and writes the new font out.

If -V is given, verbose mode is enabled.

If -U is given, uncompressed images are stored (imageFormat=1).
By default, PNG images are stored (imageFormat=17).

If -O is given, the outline tables ('glyf', 'CFF ') and
related tables are NOT dropped from the font.
By default they are dropped.

If -C is given, unused chunks (color profile, etc) are NOT
dropped from the PNG images when embedding.
By default they are dropped.
"""
        sys.exit(1)

    font_file = argv[1]
    out_file = argv[2]
    img_prefixes = argv[3:]
    del argv

    def add_font_table(font, tag, data):
        tab = ttLib.tables.DefaultTable.DefaultTable(tag)
        tab.data = str(data)
        font[tag] = tab

    def drop_outline_tables(font):
        for tag in ['cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG']:
            try:
                del font[tag]
            except KeyError:
                pass

    print

    font = ttx.TTFont(font_file)
    print "Loaded font '%s'." % font_file

    font_metrics = FontMetrics(font['head'].unitsPerEm,
                               font['hhea'].ascent,
                               -font['hhea'].descent)
    print "Font metrics: upem=%d ascent=%d descent=%d." % \
          (font_metrics.upem, font_metrics.ascent, font_metrics.descent)
    glyph_metrics = font['hmtx'].metrics
    unicode_cmap = font['cmap'].getcmap(3, 10)
    if not unicode_cmap:
        unicode_cmap = font['cmap'].getcmap(3, 1)
    if not unicode_cmap:
        raise Exception("Failed to find a Unicode cmap.")

    image_format = 1 if 'uncompressed' in options else 17

    ebdt = CBDT(font_metrics, options)
    ebdt.write_header()
    eblc = CBLC(font_metrics, options)
    eblc.write_header()
    eblc.start_strikes(len(img_prefixes))

    for img_prefix in img_prefixes:

        print

        img_files = {}
        glb = "%s*.png" % img_prefix
        print "Looking for images matching '%s'." % glb
        pattern = re.compile("^[A-Fa-f0-9]+$")
        for img_file in glob.glob(glb):
            if not pattern.match(img_file[len(img_prefix):-4]):
                continue
            uchar = int(img_file[len(img_prefix):-4], 16)
            img_files[uchar] = img_file
        if not img_files:
            raise Exception("No image files found in '%s'." % glb)
        print "Found images for %d characters in '%s'." % (len(img_files), glb)

        glyph_imgs = {}
        advance = width = height = 0
        for uchar, img_file in img_files.items():
            if uchar in unicode_cmap.cmap:
                glyph_name = unicode_cmap.cmap[uchar]
                glyph_id = font.getGlyphID(glyph_name)
                glyph_imgs[glyph_id] = img_file
                if "verbose" in options:
                    print "Matched U+%04X: id=%d name=%s image=%s" % (uchar, glyph_id, glyph_name, img_file)

                advance += glyph_metrics[glyph_name][0]
                w, h = PNG(img_file).get_size()
                width += w
                height += h

        glyphs = sorted(glyph_imgs.keys())
        if not glyphs:
            raise Exception("No common characteres found between font and '%s'." % glb)
        print "Embedding images for %d glyphs for this strike." % len(glyphs)

        advance, width, height = (div(x, len(glyphs)) for x in (advance, width, height))
        strike_metrics = StrikeMetrics(font_metrics, advance, width, height)
        print "Strike ppem set to %d." % (strike_metrics.y_ppem)

        ebdt.start_strike(strike_metrics)
        ebdt.write_glyphs(glyphs, glyph_imgs, image_format)
        glyph_maps = ebdt.end_strike()

        eblc.write_strike(strike_metrics, glyph_maps)

    print

    ebdt = ebdt.data()
    add_font_table(font, 'CBDT', ebdt)
    print "CBDT table synthesized: %d bytes." % len(ebdt)
    eblc.end_strikes()
    eblc = eblc.data()
    add_font_table(font, 'CBLC', eblc)
    print "CBLC table synthesized: %d bytes." % len(eblc)

    print

    if 'keep_outlines' not in options:
        drop_outline_tables(font)
        print "Dropped outline ('glyf', 'CFF ') and related tables."

    font.save(out_file)
    print "Output font '%s' generated." % out_file
Beispiel #13
0
            break
        elif char in Halant and state in [1, 6]:
            state = 5
            continue
        elif char in Nukta and state in [1]:
            state = 6
            continue
        break
    if current_i == count - 1:
        return True
    else:
        return False


#import GSUB info
font = ttx.TTFont("NotoSansDevanagari-Regular.ttf")
gsub_table = font["GSUB"].table
lookuplists = gsub_table.LookupList
scriptList = gsub_table.ScriptList
featureList = gsub_table.FeatureList

lookuplst = set()

syllable_list = []

for i in range(scriptList.ScriptCount):
    script = scriptList.ScriptRecord[i].Script
    langsyslist = [script.DefaultLangSys]
    for LangSysRecord in script.LangSysRecord:
        langsyslist.append(LangSysRecord.LangSys)
Beispiel #14
0
def main_codechart(args):
    path = os.path.dirname(args.fontpath)
    fontname, _ = os.path.splitext(os.path.basename(args.fontpath))
    output = os.path.join(path, fontname) + '.tex'
    
    fnt = ttx.TTFont(args.fontpath)
    
    ## this array keeps track of all combining marks that we will need to TEST!
    #marx = {}
    
    _TEMPL_HEAD = string.Template('''\
    \\documentclass{article}
    \\usepackage{fontspec}
    \\usepackage{xcolor}
    \\usepackage{tabu}
    \\usepackage{hyperref}
    \\usepackage{polyglossia}
    \\usepackage[top=0.5in, bottom=0.5in, left=0.5in, right=0.5in]{geometry}
    \\newfontfamily\\glyphfont[Path=./]{${fontname}.otf}
    \\setmainfont[Mapping=tex-text]{Times}
    \\setdefaultlanguage{english}
    \\setotherlanguage{russian} % don't have Church Slavic available yet :(
    
    \\begin{document}
    \\tabulinesep=1.2mm
    ''')
    
    _TEMPL_FONTDOC = string.Template('''\
    \\section{Font Documentation}
    
    \\textbf{Font name}: ${name} \\\\
    \\textbf{Font author}: ${author} \\\\
    \\textbf{Version}: ${version} \\\\
    \\textbf{Copyright information}: ${copyright} \\\\
    
    ''')
    
    _TEMPL_PHRASE = string.Template('''\
    \\section{Font Test} 
    
    {\\glyphfont{\\tiny The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    {\\glyphfont{\\scriptsize The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    {\\glyphfont{\\small The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    {\\glyphfont{The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    {\\glyphfont{\\large The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    {\\glyphfont{\\huge The quick brown fox jumps over the lazy dog. 1234567890}} \\\\
    \\begin{russian}
    {\\glyphfont{\\tiny ${phrase} }} \\\\
    {\\glyphfont{\\scriptsize ${phrase}}} \\\\
    {\\glyphfont{\\small ${phrase}}} \\\\
    {\\glyphfont{ ${phrase}}} \\\\
    {\\glyphfont{\\large ${phrase}}} \\\\
    {\\glyphfont{\\huge ${phrase}}} \\\\
    \\end{russian}
    
    ''')
    
    with codecs.open(output, 'w', 'utf-8') as f:
        f.write(_TEMPL_HEAD.substitute(fontname=fontname))
    
        font_copyright = fnt['name'].names[0].string.decode()
        font_name      = fnt['name'].names[1].string.decode()
        font_version   = fnt['name'].names[5].string.decode()
        font_author    = fnt['name'].names[9].string.decode()
        
        f.write(_TEMPL_FONTDOC.substitute(name=font_name, author=font_author, version=font_version, copyright=font_copyright))
    
        if 'Fedorovsk' in font_name:
            phrase = "Хрⷭ҇то́съ вᲂскре́се и҆з ме́ртвыхъ , сме́ртїю сме́рть пᲂпра́въ , и҆ сꙋ́щымъ во грᲂбѣ́хъ живо́тъ дарᲂва́въ ."
        elif 'Menaion' in font_name:
            phrase = "Хрⷭ҇то́съ вᲂскр҃се и҆з̾ ме́ртвыⷯ, сме́ртїю на́ смерть настꙋпѝ, и҆ гро́бымъ живо́тъ дарᲂва̀."
        else:
            phrase = "Хрⷭ҇то́съ воскре́се и҆з̾ ме́ртвыхъ, сме́ртїю сме́рть попра́въ, и҆ сꙋ́щымъ во гробѣ́хъ живо́тъ дарова́въ."
    
        phrase.encode('utf-8')
        b = _TEMPL_PHRASE.substitute(phrase=phrase).encode('utf-8')
        print(type(b))
        f.write(_TEMPL_PHRASE.substitute(phrase=phrase))
        
        f.write('\\clearpage\n')
        
        for range_name, range_ in _RANGES:
            # DOES FONT HAVE ANY GLYPHS IN THIS RANGE?
            HAS_GLYPHS = 0
            for x in range_:
                if x in fnt['cmap'].tables[1].cmap:
                    HAS_GLYPHS += 1
    
            if not HAS_GLYPHS:
                continue
    
            f.write("\\section{%s}\n\n" % range_name)
            numcols = int ( (len(range_) + 15) / 16 ) # number of columns
            tablestart = range_[0]
            width = max(1.05 * (numcols + 1), 4.0); 
        
            f.write("\\begin{tabu} to " + str(width) + "cm {X[r]|")
            for _ in range(numcols):
                f.write("X[c,b]|")
            f.write("}\n\n")
    
            colheaders = [tablestart + i * 16 for i in range(numcols)]
            f.write('&  ' + '  & '.join(("\\tiny{Ux%04x" % x)[:-1] + 'X}' for x in colheaders))
            f.write('\\\\\n\n')
    
            for rowidx in range(tablestart, tablestart + 16):
                line1 = []
                line2 = []
        
                for colidx in range(rowidx, rowidx + 16 * numcols, 16):
                    value = "%04x" % colidx
                    char  = "\\char\"" + ('%04x' % colidx).upper()  # chr($colidx);
                    char_name  = unicodedata.name(chr(colidx), '')
    
                    if colidx in fnt['cmap'].tables[1].cmap:
                        if "COMBINING" in char_name or colidx in _COMBINERS:
                            line1.append("\\vspace{1mm}\\glyphfont{\\Large{\u25CC" + char + "}}")
                            #if 'SIGN' not in name:
                            #    marx.append(char)
                        else:
                            line1.append("\\vspace{1mm}\\glyphfont{\\Large{" + char + "}}")
                    else:
                        line1.append("\\vspace{1mm}\\glyphfont{\\Large{\\ }}")
    
                    line2.append("\\tiny{" + value + "}")
            
                i = '%x' % (rowidx - tablestart)
                f.write("\\hline " + i.upper() + "  & " + ' & '.join(line1) + "\\\\\n")
                f.write(' & ' + " & ".join(line2) + "\\\\\n")
    
            f.write("\\hline\\end{tabu}\n\n")
    
        spec_info = os.path.join(path, fontname + '-specific-info.tex')
        if os.path.exists(spec_info):
            f.write("\\input{" + fontname + "-specific-info.tex}\n")
        
        f.write("\\end{document}\n")
    
    return 0
Beispiel #15
0
                    letters = [
                        stitchcode.Point(p.x - width, p.y) for p in letters
                    ]
                #(message, size, x_offset, y_offset, font, slope, density, p_distance):
                points.extend(letters)
        return height, points


def write_to_file(emb):
    emb.translate_to_origin()
    #emb.scale(1)
    emb.flatten()
    emb.save("Output/tags.exp")
    emb.save("Output/tags.png")


if __name__ == "__main__":
    font_file = "Consolas.ttf"
    my_font = ttx.TTFont(font_file)

    words = Words()
    points = words.write_words(
        "#Badminton #Cofee #Water #Tea Badeeee #Coffe #Wassr #Teeee", 2, "in",
        0, 0)
    #def write_words(self, words, unit_height, type, x, y):
    emb = stitchcode.Embroidery()
    for p in points:
        emb.addStitch(p)

    write_to_file(emb)