跳转到主要内容

基于fontTools的友好字体操作。

项目描述

python-fontbro

fontTools上友好字体操作。 :billed_cap

安装

pip install python-fontbro

使用

只需导入字体类

from fontbro import Font

font = Font("fonts/MyFont.ttf")

# or you can use any file-like object:
with open("fonts/MyFont.ttf") as fh:
    font = Font(fh)

方法

clone

"""
Creates a new Font instance reading the same binary file.
"""
font_clone = font.clone()

close

"""
Close the wrapped TTFont instance.
"""
font.close()

from_collection

"""
Gets a list of Font objects from a font collection file (.ttc / .otc)

:param filepath: The filepath
:type filepath: str or pathlib.Path

:returns: A list of Font objects.
:rtype: list
"""
fonts = Font.from_collection(filepath="my-font-collection.ttc")

获取字符

"""
Gets the font characters.

:param ignore_blank: If True, characters without contours will not be returned.
:type ignore_blank: bool

:returns: The characters.
:rtype: generator of dicts

:raises TypeError: If it's not possible to find the 'best' unicode cmap dict in the font.
"""
chars = font.get_characters(ignore_blank=False)

获取字符计数

"""
Gets the font characters count.

:param ignore_blank: If True, characters without contours will not be counted.
:type ignore_blank: bool

:returns: The characters count.
:rtype: int
"""
chars_count = font.get_characters_count(ignore_blank=False)

获取家族分类

"""
Gets the font family classification info reading
the sFamilyClass field from the OS/2 table.
If the OS/2 table is not available None is returned.

:returns: A dictionary containing the font family classification info, e.g.
    {
        "full_name": "Sans Serif / Neo-grotesque Gothic",
        "class_id": 8,
        "class_name": "Sans Serif",
        "subclass_id": 5,
        "subclass_name": "Neo-grotesque Gothic",
    }
:rtype: dict
"""
family_classification = font.get_family_classification()

获取家族名称

"""
Gets the family name reading the name records with priority order (16, 21, 1).

:returns: The font family name.
:rtype: str
"""
family_name = font.get_family_name()

获取特征

"""
Gets the font opentype features.

:returns: The features.
:rtype: list of dict
"""
features = font.get_features()

获取特征标签

"""
Gets the font opentype features tags.

:returns: The features tags list.
:rtype: list of str
"""
features_tags = font.get_features_tags()

获取文件名

"""
Gets the filename to use for saving the font to file-system.

:param variable_suffix: The variable suffix, default "Variable"
:type variable_suffix: str
:param variable_axes_tags: The variable axes tags flag,
    if True, the axes tags will be appended, eg '[wght,wdth]'
:type variable_axes_tags: bool
:param variable_axes_values: The variable axes values flag
    if True, each axis values will be appended, eg '[wght(100,100,900),wdth(75,100,125)]'
:type variable_axes_values: bool

:returns: The filename.
:rtype: str
"""
filename = font.get_filename(variable_suffix="Variable", variable_axes_tags=True, variable_axes_values=False)

获取指纹

"""
Gets the font fingerprint: an hash calculated from an image representation of the font.
Changing the text option affects the returned fingerprint.

:param text: The text used for generating the fingerprint, default value: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".
:type text: str
:returns: The fingerprint hash.
:rtype: imagehash.ImageHash
"""
hash = font.get_fingerprint()

获取指纹匹配

"""
Gets the fingerprint match between this font and another one.
by checking if their fingerprints are equal (difference <= tolerance).

:param other: The other font, can be either a filepath or a Font instance.
:type other: str or Font
:param tolerance: The diff tolerance, default 3.
:type tolerance: int
:param text: The text used for generating the fingerprint, default value: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".
:type text: str
:returns: A tuple containing the match info (match, diff, hash, other_hash).
:rtype: tuple
"""
match, diff, hash, other_hash = font.get_fingerprint_match(other="other_font.ttf", tolerance=10)

获取格式

"""
Gets the font format: otf, ttf, woff, woff2.

:param ignore_flavor: If True, the original format without compression will be returned.
:type ignore_flavor: bool

:returns: The format.
:rtype: str or None
"""
format = font.get_format(ignore_flavor=False)

获取字形

"""
Gets the font glyphs and their own composition.

:returns: The glyphs.
:rtype: generator of dicts
"""
glyphs = font.get_glyphs()

获取字形计数

"""
Gets the font glyphs count.

:returns: The glyphs count.
:rtype: int
"""
glyphs_count = font.get_glyphs_count()

获取图像

"""
Gets an image representation of the font rendering
some text using the given options.

:param text: The text rendered in the image
:type text: str
:param size: The font size
:type size: int
:param color: The text color
:type color: tuple
:param background_color: The background color
:type background_color: tuple
"""
img = font.get_image(text="Hello!", size=48, color=(0, 0, 0, 255), background_color=(255, 255, 255, 255))

获取斜体角度

"""
Gets the font italic angle.

:returns: The angle value including backslant, italic and roman flags.
:rtype: dict or None
"""
italic_angle = font.get_italic_angle()

获取名称

"""
Gets the name by its identifier from the font name table.

:param key: The name id or key (eg. "family_name")
:type key: int or str

:returns: The name.
:rtype: str or None

:raises KeyError: if the key is not a valid name key/id
"""
family_name = font.get_name(key=Font.NAME_FAMILY_NAME)

获取名称列表

"""
Gets the names records mapped by their property name.

:returns: The names.
:rtype: dict
"""
names = font.get_names()

获取样式标志

"""
Gets the style flag reading OS/2 and macStyle tables.

:param key: The key
:type key: string

:returns: The style flag.
:rtype: bool
"""
flag = font.get_style_flag(Font.STYLE_FLAG_BOLD)

获取样式标志列表

"""
Gets the style flags reading OS/2 and macStyle tables.

:returns: The dict representing the style flags.
:rtype: dict
"""
flags = font.get_style_flags()

获取样式名称

"""
Gets the style name reading the name records with priority order (17, 22, 2).

:returns: The font style name.
:rtype: str
"""
style_name = font.get_style_name()

获取SVG

"""
Gets an SVG representation of the font rendering
some text using the given options.

:param text: The text to be rendered as SVG paths.
:type text: str
:param size: The size of the font to be used for rendering the text, in points.
:type size: int

:returns: An SVG string that represents the rendered text.
:rtype: str
"""
svg_str = font.get_svg(text="Hello!", size=48)

获取TT字体

"""
Gets the wrapped TTFont instance.

:returns: The TTFont instance.
:rtype: TTFont
"""
ttfont = font.get_ttfont()

按名称获取Unicode区块

"""
Gets the unicode block by name (name is case-insensitive and ignores "-").

:param name: The name
:type name: str

:returns: The unicode block dict if the name is valid, None otherwise.
:rtype: dict or None
"""
block = font.get_unicode_block_by_name(name="Basic Latin")

获取Unicode区块列表

"""
Gets the unicode blocks and their coverage.
Only blocks with coverage >= coverage_threshold (0.0 <= coverage_threshold <= 1.0) will be returned.

:param coverage_threshold: The minumum required coverage for a block to be returned.
:type coverage_threshold: float

:returns: The list of unicode blocks.
:rtype: list of dicts
"""
blocks = font.get_unicode_blocks(coverage_threshold=0.00001)

按名称获取Unicode脚本

"""
Gets the unicode script by name/tag (name/tag is case-insensitive and ignores "-").

:param name: The name
:type name: str

:returns: The unicode script dict if the name/tag is valid, None otherwise.
:rtype: dict or None
"""
script = font.get_unicode_script_by_name(name="Latn")

获取Unicode脚本列表

"""
Gets the unicode scripts and their coverage.
Only scripts with coverage >= coverage_threshold (0.0 <= coverage_threshold <= 1.0) will be returned.

:param coverage_threshold: The minumum required coverage for a script to be returned.
:type coverage_threshold: float

:returns: The list of unicode scripts.
:rtype: list of dicts
"""
scripts = font.get_unicode_scripts(coverage_threshold=0.00001)

获取变量轴

"""
Gets the font variable axes.

:returns: The list of axes if the font is a variable font otherwise None.
:rtype: list of dict or None
"""
axes = font.get_variable_axes()

获取变量轴标签

"""
Gets the variable axes tags.

:returns: The variable axis tags.
:rtype: list or None
"""
axes_tags = font.get_variable_axes_tags()

按标签获取变量轴

"""
Gets a variable axis by tag.

:param tag: The tag
:type tag: string

:returns: The variable axis by tag.
:rtype: dict or None
"""
axis = font.get_variable_axis_by_tag(tag="wght")

获取变量实例

"""
Gets the variable instances.

:returns: The list of instances if the font is a variable font otherwise None.
:rtype: list of dict or None
"""
instances = font.get_variable_instances()

按样式名称获取变量实例

"""
Gets the variable instance by style name, eg. style_name = 'Bold'

:param style_name: The style name
:type style_name: str

:returns: The variable instance matching the given style name.
:rtype: dict or None
"""
instance = font.get_variable_instance_by_style_name(style_name="Bold")

获取坐标最近的变量实例

"""
Gets the variable instance closest to coordinates.
eg. coordinates = {"wght": 1000, "slnt": 815, "wdth": 775}
If coordinates do not specify some axes, axes default value is used for lookup.

:param coordinates: The coordinates
:type coordinates: dict

:returns: The variable instance closest to coordinates.
:rtype: dict or None
"""
instance = font.get_variable_instance_closest_to_coordinates(coordinates={"wght": 1000, "slnt": 815, "wdth": 775})

获取版本

"""
Gets the font version.

:returns: The font version value.
:rtype: float
"""
version = font.get_version()

获取垂直度量

"""
Gets the font vertical metrics.

:returns: A dictionary containing the following vertical metrics:
    "units_per_em", "y_max", "y_min", "ascent", "descent", "line_gap",
    "typo_ascender", "typo_descender", "typo_line_gap", "cap_height", "x_height",
    "win_ascent", "win_descent"
:rtype: dict
"""
metrics = font.get_vertical_metrics()

获取粗细

"""
Gets the font weight value and name.

:returns: The weight name and value.
:rtype: dict or None
"""
weight = font.get_weight()

获取宽度

"""
Gets the font width value and name.

:returns: The width name and value.
:rtype: dict or None
"""
width = font.get_width()

是否为彩色

"""
Determines if the font is a color font.

:returns: True if color font, False otherwise.
:rtype: bool
"""
color = font.is_color()

是否为等宽字体

"""
Determines if the font is a monospace font.

:param threshold: The threshold (0.0 <= n <= 1.0) of glyphs with the same width to consider the font as monospace.
:type threshold: float

:returns: True if monospace font, False otherwise.
:rtype: bool
"""
mono = font.is_monospace()

是否为静态

"""
Determines if the font is a static font.

:returns: True if static font, False otherwise.
:rtype: bool
"""
static = font.is_static()

是否为变量

"""
Determines if the font is a variable font.

:returns: True if variable font, False otherwise.
:rtype: bool
"""
variable = font.is_variable()

重命名

"""
Renames the font names records (1, 2, 4, 6, 16, 17) according to
the given family_name and style_name (subfamily_name).

If family_name is not defined it will be auto-detected.
If style_name is not defined it will be auto-detected.

:param family_name: The family name
:type family_name: str
:param style_name: The style name
:type style_name: str
:param update_style_flags: if True the style flags will be updated by subfamily name
:type update_style_flags: bool

:raises ValueError: if the computed PostScript-name is longer than 63 characters.
"""
font.rename(family_name="My Font New", style_name="Bold Italic", update_style_flags=True)

清理

"""
Sanitize the font file using OpenType Sanitizer.
https://github.com/googlefonts/ots-python

:param strict: If True (default), raises an exception even on sanitizer warnings.
    If False, only raises an exception on sanitizer failure (non-zero exit code).
:type strict: bool

:raises Exception: If the OpenType Sanitizer reports an error during the sanitization process.
:return: None

:note: Uses OpenType Sanitizer (ots) to sanitize the font file.
    Saves the font to a temporary directory and invokes the sanitizer on the saved file.
    If `strict` is True (default), treats sanitizer warnings as errors.
    If `strict` is False, only checks for sanitizer errors.
"""
font.sanitize(strict=True)

保存

"""
Saves the font at filepath.

:param filepath: The filepath, if None the source filepath will be used
:type filepath: str or None
:param overwrite: The overwrite, if True the source font file can be overwritten
:type overwrite: bool

:returns: The filepath where the font has been saved to.
:rtype: str

:raises ValueError: If the filepath is the same of the source font and overwrite is not allowed.
"""
saved_font_path = font.save(filepath=None, overwrite=False)

保存为WOFF

"""
Saves font as woff.

:param filepath: The filepath
:type filepath: str
:param overwrite: The overwrite, if True the source font file can be overwritten
:type overwrite: bool

:returns: The filepath where the font has been saved to.
:rtype: str
"""
saved_font_path = font.save_as_woff(filepath=None, overwrite=True)

保存为WOFF2

"""
Saves font as woff2.

:param filepath: The filepath
:type filepath: str
:param overwrite: The overwrite, if True the source font file can be overwritten
:type overwrite: bool

:returns: The filepath where the font has been saved to.
:rtype: str
"""
saved_font_path = font.save_as_woff2(filepath=None, overwrite=True)

保存到文件对象

"""
Writes the font to a file-like object. If no file-object is passed, an
instance of `BytesIO` is created for the user.
:param fileobject: A file-like object to write to.

:returns: The file object that was originally pass, or a new BytesIO
instance.
:rtype: typing.io.IO
"""

fileobject = font.save_to_fileobject(fileobject=None)

保存变量实例

"""
Save all instances of a variable font to specified directory in one or more format(s).

:param dirpath: The dirpath
:type dirpath: The directory path where the instances will be saved.
:param woff2: Whether to save instances also in WOFF2 format. Default is True.
:type woff2: bool
:param woff: Whether to save instances also in WOFF format. Default is True.
:type woff: bool
:param overwrite: Whether to overwrite existing files in the directory. Default is True.
:type overwrite: bool
:param options: Additional options to be passed to the instancer when generating static instances.
:type options: dictionary

:returns: A list containing dictionaries for each saved instance. Each dictionary
    includes 'instance' (containing instance metadata) and 'files' (a dictionary
    with file formats as keys and file-paths as values).

:raises TypeError: If the font is not a variable font.
"""

saved_fonts = font.save_variable_instances(dirpath, woff2=True, woff=True, overwrite=True, **options)

设置家族分类

"""
Sets font family classification (sFamilyClass in the OS/2 table)
based on provided class_id and subclass_id.

:param class_id: Numeric identifier of the font family class.
:param subclass_id: Optional numeric identifier of the font family subclass (default is 0).
:raises OperationError: If the OS/2 table is not available in the font.
:raises ArgumentError: If class_id is invalid or subclass_id is specified but invalid.
"""
font.set_family_classification(**font.FAMILY_CLASSIFICATION_SCRIPTS_CALLIGRAPHIC)
# alternatively:
font.set_family_classification(class_id=10, subclass_id=5)

设置家族名称

"""
Sets the family name updating the related font names records.

:param name: The name
:type name: The new family name.
"""
font.set_family_name(name="My Font New")

设置名称

"""
Sets the name by its identifier in the font name table.

:param key: The name id or key (eg. "family_name")
:type key: int or str
:param value: The value
:type value: str
"""
font.set_name(Font.NAME_FAMILY_NAME, "Family Name Renamed")

设置名称列表

"""
Sets the names by their identifier in the name table.

:param names: The names
:type names: dict
"""
font.set_names(names={
    Font.NAME_FAMILY_NAME: "Family Name Renamed",
    Font.NAME_SUBFAMILY_NAME: "Regular Renamed",
})

设置样式标志

"""
Sets the style flag.

:param key: The flag key
:type key: str
:param value: The value
:type value: bool
"""
font.set_style_flag(Font.STYLE_FLAG_BOLD, True)

设置样式标志列表

"""
Sets the style flags, flags set to None will be ignored.

:param bold: The bold flag value.
:type bold: bool or None
:param italic: The italic flag value.
:type italic: bool or None
:param underline: The underline flag value.
:type underline: bool or None
:param outline: The outline flag value.
:type outline: bool or None
"""
font.set_style_flags(regular=None, bold=None, italic=None, outline=None, underline=None)

按子家族名称设置样式标志

"""
Sets the style flags by the subfamily name value.
The subfamily values should be "regular", "italic", "bold" or "bold italic"
to allow this method to work properly.
"""
font.set_style_flags_by_subfamily_name()

设置样式名称

"""
Sets the style name updating the related font names records.

:param name: The name
:type name: The new style name.
"""
font.set_style_name(name="Bold Italic")

设置垂直度量

"""
Sets the vertical metrics.

:param metrics: Keyword arguments representing the vertical metrics that can be set:
    "units_per_em", "y_max", "y_min", "ascent", "descent", "line_gap",
    "typo_ascender", "typo_descender", "typo_line_gap", "cap_height", "x_height",
    "win_ascent", "win_descent"
"""
font.set_vertical_metrics(units_per_em=2000, y_max=2102, y_min=-533, ascent=1800, descent=-400, line_gap=0, typo_ascender=1800, typo_descender=-400, typo_line_gap=0, cap_height=1400, x_height=1080, win_ascent=2160, win_descent=540)

子集

"""
Subsets the font using the given options (unicodes or glyphs or text),
it is possible to pass also subsetter options, more info here:
https://github.com/fonttools/fonttools/blob/main/Lib/fontTools/subset/__init__.py

:param unicodes: The unicodes
:type unicodes: str or list
:param glyphs: The glyphs
:type glyphs: list
:param text: The text
:type text: str
:param options: The subsetter options
:type options: dict
"""
font.subset(unicodes="", glyphs=[], text="", **options)

转换为切片变量

"""
Converts the variable font to a partial one slicing the variable axes at the given coordinates.
If an axis value is not specified, the axis will be left untouched.
If an axis min and max values are equal, the axis will be pinned.

:param coordinates: The coordinates dictionary, each item value must be tuple/list/dict
    (with 'min', 'default' and 'max' keys) for slicing or float/int for pinning, eg.
    {'wdth':100, 'wght':(100,600), 'ital':(30,65,70)} or
    {'wdth':100, 'wght':[100,600], 'ital':[30,65,70]} or
    {'wdth':100, 'wght':{'min':100,'max':600}, 'ital':{'min':30,'default':65,'max':70}}
:type coordinates: dict
:param options: The options for the fontTools.varLib.instancer
:type options: dictionary

:raises TypeError: If the font is not a variable font
:raises ValueError: If the coordinates are not defined (empty)
:raises ValueError: If the coordinates axes are all pinned
"""
font.to_sliced_variable(coordinates, **options)

转换为静态

"""
Converts the variable font to a static one pinning
the variable axes at the given coordinates.
If an axis value is not specified, the axis will be pinned at its default value.
If coordinates are not specified each axis will be pinned at its default value.

:param coordinates: The coordinates, eg. {'wght':500, 'ital':50}
:type coordinates: dict or None
:param style_name: The existing instance style name, eg. 'Black'
:type style_name: str or None
:param update_names: if True the name records will be updated based on closest instance
:type update_names: bool
:param update_style_flags: if True the style flags will be updated based on closest instance
:type update_style_flags: bool

:param options: The options for the fontTools.varLib.instancer
:type options: dictionary

:raises TypeError: If the font is not a variable font
:raises ValueError: If the coordinates axes are not all pinned
"""
font.to_static(coordinates=None, style_name=None, update_names=True, update_style_flags=True, **options)

测试

# clone repository
git clone https://github.com/fabiocaccamo/python-fontbro.git && cd python-fontbro

# create virtualenv and activate it
python -m venv venv && . venv/bin/activate

# upgrade pip
python -m pip install --upgrade pip

# install requirements
python -m pip install -r requirements.txt -r requirements-test.txt

# install pre-commit to run formatters and linters
pre-commit install --install-hooks

# run tests using tox
tox

# or run tests using unittest
python -m unittest

许可证

MIT许可证下发布。

致谢

特别感谢Jérémie HornusJust Van Rossum

支持

  • :star: 在GitHub上星标此项目
  • :octocat: 在GitHub上关注我
  • :blue_heart: 在Twitter上关注我
  • :moneybag: 在Github上赞助我

另请参阅

  • python-benedict - 支持键列表/键路径支持的字典子类,I/O快捷方式(base64、csv、json、pickle、plist、查询字符串、toml、xml、yaml)以及许多实用工具。 📘
  • python-fsutil - 懒惰开发者的文件系统实用工具。 🧟‍♂️

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

python_fontbro-0.24.0.tar.gz (58.9 kB 查看哈希值)

上传于 来源

构建的发行版

python_fontbro-0.24.0-py3-none-any.whl (40.4 kB 查看哈希值)

上传于 Python 3

由以下支持