Example #1
0
def dotest(outputname, nostamp):
    ttf = TTFontFile()
    ttffile = os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf")
    ttf.getMetrics(ttffile)
    # test basic metrics:
    assert round(ttf.descent, 0) == -236, "Check descent"
    assert round(ttf.capHeight, 0) == 928, "Chech capHeight"
    assert ttf.flags == 4, "Check flags"
    assert [round(i, 0) for i in ttf.bbox] == [-918, -415, 1513,
                                               1167], "Check bbox"
    assert ttf.italicAngle == 0, "Check italicAngle==0"
    assert ttf.stemV == 87, "Check stemV"
    assert round(ttf.defaultWidth, 0) == 540, "Check defaultWidth"
    assert round(ttf.underlinePosition, 0) == -63, "Check underlinePosition"
    assert round(ttf.underlineThickness, 0) == 44, "Check underlineThickness"
    # test char widths (against binary file generated by tfpdf.php):
    # note: after fixing issue 82 this raw data started to be wrong
    #  1. total length - 65536, DejaVuSansCondensed.ttf maximal char is 65533, round to nearest 1024 size
    #  2. missing char width should be 540 instead of zero
    with open(os.path.join(common.basepath, "dejavusanscondensed.cw.dat"),\
            "rb") as file:
        data = file.read()
    char_widths = struct.unpack(">%dH" % (len(data) // 2), data)
    assert len(char_widths) == 65536, "Check cw.dat char_widths 65536"
    assert len(ttf.charWidths) == 65536, "Check ttf char_widths 65536"
    diff = []
    for i, (x, y) in enumerate(zip(char_widths, ttf.charWidths)):
        if x == 0 and y == ttf.defaultWidth: continue
        if x != y:  # compare each char width, but not 0
            diff.append(i)
    assert not diff, "Check char widths"
Example #2
0
def dotest(outputname, nostamp):
    ttf = TTFontFile()
    ttffile = os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf");
    ttf.getMetrics(ttffile)
    # test basic metrics:
    assert round(ttf.descent, 0) == -236, "Check descent"
    assert round(ttf.capHeight, 0) == 928, "Chech capHeight"
    assert ttf.flags == 4, "Check flags"
    assert [round(i, 0) for i in ttf.bbox] == [-918, -415, 1513, 1167], "Check bbox"
    assert ttf.italicAngle == 0, "Check italicAngle==0"
    assert ttf.stemV == 87, "Check stemV"
    assert round(ttf.defaultWidth, 0) == 540, "Check defaultWidth"
    assert round(ttf.underlinePosition, 0) == -63, "Check underlinePosition"
    assert round(ttf.underlineThickness, 0) == 44, "Check underlineThickness"
    # test char widths (against binary file generated by tfpdf.php):
    # note: after fixing issue 82 this raw data started to be wrong
    #  1. total length - 65536, DejaVuSansCondensed.ttf maximal char is 65533, round to nearest 1024 size
    #  2. missing char width should be 540 instead of zero
    with open(os.path.join(common.basepath, "dejavusanscondensed.cw.dat"),\
            "rb") as file:
        data = file.read()
    char_widths = struct.unpack(">%dH" % (len(data) // 2), data)
    assert len(char_widths) == 65536, "Check cw.dat char_widths 65536"
    assert len(ttf.charWidths) == 65536, "Check ttf char_widths 65536"
    diff = []
    for i, (x, y) in enumerate(zip(char_widths, ttf.charWidths)):
        if x == 0 and y == ttf.defaultWidth: continue
        if x != y:# compare each char width, but not 0
            diff.append(i)
    assert not diff, "Check char widths"
Example #3
0
def dotest(outputname, nostamp):
    ttf = TTFontFile()
    ttffile = os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf")
    ttf.getMetrics(ttffile)
    # test basic metrics:
    assert round(ttf.descent, 0) == -236
    assert round(ttf.capHeight, 0) == 928
    assert ttf.flags == 4
    assert [round(i, 0) for i in ttf.bbox] == [-918, -415, 1513, 1167]
    assert ttf.italicAngle == 0
    assert ttf.stemV == 87
    assert round(ttf.defaultWidth, 0) == 540
    assert round(ttf.underlinePosition, 0) == -63
    assert round(ttf.underlineThickness, 0) == 44
    # test char widths 8(against binary file generated by tfpdf.php):
    data = open(os.path.join(common.basepath, "dejavusanscondensed.cw.dat"),\
        "rb").read()
    char_widths = struct.unpack(">%dH" % int(len(data) / 2), data)
    assert len(ttf.charWidths) == len(char_widths)
    diff = []
    for i, (x, y) in enumerate(zip(char_widths, ttf.charWidths)):
        if x != y:  # compare each char width
            diff.append(i)
    assert not diff
    # for checking assertion works ttf.charWidths[1] = 600
    assert tuple(ttf.charWidths) == tuple(char_widths)
def get_fonts() -> list:
    """
    Returns a list of tuples (font, path) of all fonts installed on the system.
    """
    paths = []

    for path in QStandardPaths.standardLocations(QStandardPaths.FontsLocation):
        if os.path.isdir(path):
            paths.append(path)

    if platform.system() == "Linux":
        unix_paths = QStandardPaths.standardLocations(
            QStandardPaths.AppDataLocation)
        for path in unix_paths:
            possible_path = os.path.dirname(path) + os.sep + "fonts"
            if os.path.isdir(possible_path):
                paths.append(possible_path)

    fonts = dict()

    for i, path in enumerate(paths):
        for dir_path, dir_names, file_names in os.walk(path):
            for filename in file_names:
                if filename.endswith(".ttf"):
                    try:
                        absolute_file_path = dir_path + os.sep + filename

                        ttf = TTFontFile()
                        ttf.getMetrics(absolute_file_path)
                        font_name = ttf.fullName.replace("-", " ")
                        font_name = " ".join(
                            re.findall(r"[A-Z]?[^A-Z\s]+|[A-Z]+", font_name))

                        if font_name not in fonts:
                            fonts[font_name] = absolute_file_path

                    except RuntimeError:
                        pass

    fonts = sorted(fonts.items())
    return fonts
Example #5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"Basic test of TrueType Unicode font handling"

import struct
from fpdf.ttfonts import TTFontFile

if __name__ == '__main__':
    ttf = TTFontFile()
    ttffile = 'font/DejaVuSansCondensed.ttf'
    ttf.getMetrics(ttffile)
    # test basic metrics:
    assert round(ttf.descent, 0) == -236
    assert round(ttf.capHeight, 0) == 928
    assert ttf.flags == 4
    assert [round(i, 0) for i in ttf.bbox] == [-918, -415, 1513, 1167]
    assert ttf.italicAngle == 0
    assert ttf.stemV == 87
    assert round(ttf.defaultWidth, 0) == 540
    assert round(ttf.underlinePosition, 0) == -63
    assert round(ttf.underlineThickness, 0) == 44
    # test char widths 8(against binary file generated by tfpdf.php):
    data = open("dejavusanscondensed.cw.dat", "rb").read()
    char_widths = struct.unpack(">%dH" % int(len(data) / 2), data)
    assert len(ttf.charWidths) == len(char_widths)
    diff = []
    for i, (x, y) in enumerate(zip(char_widths, ttf.charWidths)):
        if x != y:  # compare each char width
            diff.append(i)
    assert not diff
Example #6
0
    def add_font(self, family, style='', fname=None, uni=True):
        """Add a TrueType or Type1 font"""
        family = family.lower()
        fontkey = family
        # Font already added!
        if family in self.fonts:
            return
        font_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '..', 'resources',
                         'fonts'))
        # noinspection PyAttributeOutsideInit
        self.FPDF_FONT_DIR = font_dir
        ttffilename = os.path.join(self.FPDF_FONT_DIR, fname)
        name = ''  # noqa: F841
        unifilename = None
        font_dict = None
        if font_dict is None:
            ttf = TTFontFile()
            ttf.getMetrics(ttffilename)
            desc = {
                'Ascent':
                int(round(ttf.ascent, 0)),
                'Descent':
                int(round(ttf.descent, 0)),
                'CapHeight':
                int(round(ttf.capHeight, 0)),
                'Flags':
                ttf.flags,
                'FontBBox':
                "[%s %s %s %s]" %
                (int(round(ttf.bbox[0], 0)), int(round(ttf.bbox[1], 0)),
                 int(round(ttf.bbox[2], 0)), int(round(ttf.bbox[3], 0))),
                'ItalicAngle':
                int(ttf.italicAngle),
                'StemV':
                int(round(ttf.stemV, 0)),
                'MissingWidth':
                int(round(ttf.defaultWidth, 0)),
            }

            # Generate metrics .pkl file
            font_dict = {
                'name': re.sub('[ ()]', '', ttf.fullName),
                'type': 'TTF',
                'desc': desc,
                'up': round(ttf.underlinePosition),
                'ut': round(ttf.underlineThickness),
                'ttffile': ttffilename,
                'fontkey': fontkey,
                'originalsize': os.stat(ttffilename).st_size,
                'cw': ttf.charWidths,
            }

        # include numbers in the subset! (if alias present)
        have_page_alias = lambda: hasattr(self, 'str_alias_nb_pages')
        sbarr = list(range(0, 57 if have_page_alias() else 32))

        self.fonts[fontkey] = {
            'i': len(self.fonts) + 1,
            'type': font_dict['type'],
            'name': font_dict['name'],
            'desc': font_dict['desc'],
            'up': font_dict['up'],
            'ut': font_dict['ut'],
            'cw': font_dict['cw'],
            'ttffile': font_dict['ttffile'],
            'fontkey': fontkey,
            'subset': sbarr,
            'unifilename': unifilename
        }
        self.font_files[fontkey] = {
            'length1': font_dict['originalsize'],
            'type': "TTF",
            'ttffile': ttffilename
        }
        self.font_files[fname] = {'type': "TTF"}
Example #7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"Basic test of TrueType Unicode font handling"

import struct
from fpdf.ttfonts import TTFontFile

    
if __name__ == '__main__':
    ttf = TTFontFile()
    ttffile = 'font/DejaVuSansCondensed.ttf';
    ttf.getMetrics(ttffile)
    # test basic metrics:
    assert round(ttf.descent, 0) == -236
    assert round(ttf.capHeight, 0) == 928
    assert ttf.flags == 4
    assert [round(i, 0) for i in ttf.bbox] == [-918, -415, 1513, 1167]
    assert ttf.italicAngle == 0
    assert ttf.stemV == 87
    assert round(ttf.defaultWidth, 0) == 540
    assert round(ttf.underlinePosition, 0) == -63
    assert round(ttf.underlineThickness, 0) == 44
    # test char widths 8(against binary file generated by tfpdf.php):
    data = open("dejavusanscondensed.cw.dat", "rb").read()
    char_widths = struct.unpack(">%dH" % int(len(data) / 2), data)
    assert len(ttf.charWidths) == len(char_widths)
    diff = []
    for i, (x, y) in enumerate(zip(char_widths, ttf.charWidths)):
        if x != y:              # compare each char width
            diff.append(i)