References
fontconfig package
High-Level Functions
|
Find the best matching font for a given pattern. |
|
Get a sorted list of fonts matching a pattern, ordered by quality. |
|
List all fonts matching a pattern. |
Utility Functions
Get fontconfig version. |
Deprecated Functions
|
High-level function to query fonts. |
Classes
A Blanks object holds a list of Unicode chars which are expected to be blank when drawn. |
|
A CharSet is a boolean array indicating a set of Unicode chars. |
|
A Config object holds the internal representation of a configuration. |
|
A FontSet simply holds a list of patterns; these are used to return the results of listing available fonts. |
|
An ObjectSet holds a list of pattern property names. |
|
A Pattern is an opaque type that holds both patterns to match against the available fonts, as well as the information about each font. |
High-Level Functions
These functions provide a convenient way to work with fonts, aligned with the core fontconfig library operations.
- fontconfig.match(str pattern: str = '', dict properties: Optional[Dict[str, Any]] = None, select: Iterable[str] = ('family', 'file', 'style'), Config config: Optional[Config] = None) Dict[str, Any] | None
Find the best matching font for a given pattern.
This wraps FcFontMatch and performs all necessary substitutions. Equivalent to the
fc-matchcommand-line tool.Example:
# Find best match for Arial Bold font = fontconfig.match(":family=Arial:weight=200") if font: print(font["file"]) # Using properties dict font = fontconfig.match(properties={"family": "Arial", "weight": 200}) # Custom properties to return font = fontconfig.match(":family=Arial", select=("family", "file", "weight"))
- Parameters:
pattern (str) – Pattern string like
":family=Arial:weight=200".properties (Optional[Dict[str, Any]]) – Dict of pattern properties (alternative to pattern string).
select (Iterable[str]) – Properties to include in result dict.
config (Optional[Config]) – Config instance (default: current config).
- Returns:
Dict with selected properties, or None if no match.
- fontconfig.sort(str pattern: str = '', dict properties: Optional[Dict[str, Any]] = None, select: Iterable[str] = ('family', 'file', 'style'), bool trim: bool = True, Config config: Optional[Config] = None) List[Dict[str, Any]]
Get a sorted list of fonts matching a pattern, ordered by quality.
This wraps FcFontSort and returns fonts in preference order. Equivalent to the
fc-match -scommand-line tool.Example:
# Get all Arial fonts, best matches first fonts = fontconfig.sort(":family=Arial") for font in fonts[:5]: # Top 5 matches print(font["family"], font["file"]) # Using properties dict fonts = fontconfig.sort(properties={"family": "Arial"}) # Without trimming (include all fonts even with no common charset) fonts = fontconfig.sort(":family=Arial", trim=False)
- Parameters:
pattern (str) – Pattern string like
":family=Arial".properties (Optional[Dict[str, Any]]) – Dict of pattern properties (alternative to pattern string).
select (Iterable[str]) – Properties to include in result dicts.
trim (bool) – Remove fonts with no common charset.
config (Optional[Config]) – Config instance (default: current config).
- Returns:
List of dicts with selected properties, sorted by match quality.
- fontconfig.list(str pattern: str = '', dict properties: Optional[Dict[str, Any]] = None, select: Iterable[str] = ('family'), Config config: Optional[Config] = None) List[Dict[str, Any]]
List all fonts matching a pattern.
This wraps FcFontList (same as query() but with better naming). Equivalent to the
fc-listcommand-line tool.Example:
# List all fonts with English support fonts = fontconfig.list(":lang=en", select=("family", "file")) # Using properties dict fonts = fontconfig.list(properties={"lang": ["en"]}) # List all fonts fonts = fontconfig.list()
- Parameters:
pattern (str) – Pattern string like
":lang=en:family=Arial".properties (Optional[Dict[str, Any]]) – Dict of pattern properties (alternative to pattern string).
select (Iterable[str]) – Properties to include in result dicts.
config (Optional[Config]) – Config instance (default: current config).
- Returns:
List of dicts with selected properties (no particular order).
Font Properties
The following font properties are supported in patterns and can be used in the
selectparameter. See alsomatch()andsort().Property
Type
Description
family
String
Font family names
familylang
String
Language corresponding to each family name
style
String
Font style. Overrides weight and slant
stylelang
String
Language corresponding to each style name
fullname
String
Font face full name where different from family and family + style
fullnamelang
String
Language corresponding to each fullname
slant
Int
Italic, oblique or roman
weight
Int
Light, medium, demibold, bold or black
width
Int
Condensed, normal or expanded
size
Double
Point size
aspect
Double
Stretches glyphs horizontally before hinting
pixelsize
Double
Pixel size
spacing
Int
Proportional, dual-width, monospace or charcell
foundry
String
Font foundry name
antialias
Bool
Whether glyphs can be antialiased
hintstyle
Int
Automatic hinting style
hinting
Bool
Whether the rasterizer should use hinting
verticallayout
Bool
Use vertical layout
autohint
Bool
Use autohinter instead of normal hinter
globaladvance
Bool
Use font global advance data (deprecated)
file
String
The filename holding the font relative to the config’s sysroot
index
Int
The index of the font within the file
ftface
FT_Face
Use the specified FreeType face object
rasterizer
String
Which rasterizer is in use (deprecated)
outline
Bool
Whether the glyphs are outlines
scalable
Bool
Whether glyphs can be scaled
dpi
Double
Target dots per inch
rgba
Int
unknown, rgb, bgr, vrgb, vbgr, none - subpixel geometry
scale
Double
Scale factor for point->pixel conversions (deprecated)
minspace
Bool
Eliminate leading from line spacing
charset
CharSet
Unicode chars encoded by the font
lang
LangSet
Set of RFC-3066-style languages this font supports
fontversion
Int
Version number of the font
capability
String
List of layout capabilities in the font
fontformat
String
String name of the font format
embolden
Bool
Rasterizer should synthetically embolden the font
embeddedbitmap
Bool
Use the embedded bitmap instead of the outline
decorative
Bool
Whether the style is a decorative variant
lcdfilter
Int
Type of LCD filter
namelang
String
Language name to be used for the default value of familylang, stylelang and fullnamelang
fontfeatures
String
List of extra feature tags in OpenType to be enabled
prgname
String
Name of the running program
hash
String
SHA256 hash value of the font data with “sha256:” prefix (deprecated)
postscriptname
String
Font name in PostScript
symbol
Bool
Whether font uses MS symbol-font encoding
color
Bool
Whether any glyphs have color
fontvariations
String
comma-separated string of axes in variable font
variable
Bool
Whether font is Variable Font
fonthashint
Bool
Whether font has hinting
order
Int
Order number of the font
Utility Functions
- fontconfig.get_version() str
Get fontconfig version.
Deprecated Functions
- fontconfig.query(str where: str = '', select: Iterable[str] = ('family')) List[Dict[str, Any]]
High-level function to query fonts.
Deprecated since version 0.3.0: Use
list(),match(), orsort()instead. This function is kept for backward compatibility.Example:
fonts = fontconfig.query(":lang=en", select=("family", "familylang")) for font in fonts: print(font["family"])
- Parameters:
where (str) – Query string like
":lang=en:family=Arial".select (Iterable[str]) – Set of font properties to include in the result. See
list()for a complete list of supported font properties.
- Returns:
List of font dict.
Classes
- class fontconfig.Blanks
A Blanks object holds a list of Unicode chars which are expected to be blank when drawn. When scanning new fonts, any glyphs which are empty and not in this list will be assumed to be broken and not placed in the FcCharSet associated with the font. This provides a significantly more accurate CharSet for applications.
Blanks is deprecated and should not be used in newly written code. It is still accepted by some functions for compatibility with older code but will be removed in the future.
- add(self, int ucs4: int) bool
Add a character to a Blanks
- is_member(self, int ucs4: int) bool
Query membership in a Blanks
- class fontconfig.CharSet
A CharSet is a boolean array indicating a set of Unicode chars.
Those associated with a font are marked constant and cannot be edited. FcCharSets may be reference counted internally to reduce memory consumption; this may be visible to applications as the result of FcCharSetCopy may return it’s argument, and that CharSet may remain unmodifiable.
Example:
# Create from string charset = fontconfig.CharSet.from_string("abc123") # Create from codepoints charset = fontconfig.CharSet.from_codepoints([0x41, 0x42, 0x43]) # Check membership if 'a' in charset: print("Contains 'a'") # Iterate over codepoints for codepoint in charset: print(f"U+{codepoint:04X}") # Get count print(f"Contains {len(charset)} characters")
- add(self, item: object) bool
Add a character to the charset.
- Args:
item: Single character string or integer codepoint
- Returns:
True on success
- Example::
charset.add(‘A’) charset.add(0x41) # Same as above
- copy(self) CharSet
Create a copy of this charset.
Note: Creates a true independent copy to avoid reference-counting issues.
- discard(self, item: object) bool
Remove a character from the charset if present.
- Args:
item: Single character string or integer codepoint
- Returns:
True if character was removed
- Example::
charset.discard(‘A’) charset.discard(0x41)
- class fontconfig.Config
A Config object holds the internal representation of a configuration.
There is a default configuration which applications may use by passing 0 to any function using the data within a Config.
Example:
# List config content config = fontconfig.Config.get_current() for name, desc, enabled in config: if enabled: print(name) print(desc) # Query fonts from the current config pattern = fontconfig.Pattern.parse(":lang=en") object_set = fontconfig.ObjectSet.create() object_set.add("family") fonts = config.font_list(pattern, object_set)
- app_font_add_dir(self, str dirname: str) bool
Add fonts from directory to font database
- app_font_add_file(self, str filename: str) bool
Add font file to font database
- app_font_clear(self) None
Remove all app fonts from font database
- build_fonts(self) bool
Build font database
- static enable_home(bool enable: bool) bool
Controls use of the home directory
- font_render_prepare(self, Pattern p: Pattern, Pattern font: Pattern) Pattern
Prepare pattern for loading font file
- get_cache_dirs(self) List[str]
Return the list of directories searched for cache files
- get_config_dirs(self) List[str]
Get config directories
- get_config_files(self) List[str]
Get config files
- get_font_dirs(self) List[str]
Get font directories
- get_rescan_interval(self) int
Get config rescan interval
- get_sysroot(self)
Obtain the system root directory
- static home()
Return the current home directory
- parse_and_load(self, str filename: str, bool complain: bool = True) bool
Load a configuration file
- parse_and_load_from_memory(self, bytes buffer: bytes, bool complain: bool = True) bool
Load a configuration from memory
- set_current(self) bool
Set configuration as default
- set_rescan_interval(self, int interval: int) bool
Set config rescan interval
- set_sysroot(self, str sysroot: str) None
Set the system root directory
- substitute(self, Pattern p: Pattern, str kind: str = 'pattern') bool
Execute substitutions
- substitute_with_pat(self, Pattern p: Pattern, Pattern p_pat: Pattern, str kind: str = 'pattern') bool
Execute substitutions
- upto_date(self) bool
Check timestamps on config files
- class fontconfig.FontSet
A FontSet simply holds a list of patterns; these are used to return the results of listing available fonts.
Example:
fonts = config.font_list(pattern, object_set) # Inspect elements for pattern in fonts: print(pattern)
- add(self, Pattern pattern: Pattern) bool
Add to a font set
- print(self) None
Print a set of patterns to stdout
- class fontconfig.ObjectSet
An ObjectSet holds a list of pattern property names.
It is used to indicate which properties are to be returned in the patterns from FontList.
Example:
# Create a new ObjectSet object_set = fontconfig.ObjectSet.create() object_set.build(["family", "familylang", "style", "stylelang"]) # Inspect elements for name in object_set: print(name)
- add(self, str value: str) bool
Add to an object set
- build(self, values: Iterable[str]) None
Build object set from iterable
- class fontconfig.Pattern
A Pattern is an opaque type that holds both patterns to match against the available fonts, as well as the information about each font.
Example:
# Create a new pattern. pattern = fontconfig.Pattern.create() pattern.add("family", "Arial") # Create a new pattern from str. pattern = fontconfig.Pattern.parse(":lang=en:family=Arial") # Pattern is iterable. Can convert to a Python dict. pattern_dict = dict(pattern)
- add(self, str key: str, value: object, bool append: bool = True) bool
Add a value to a pattern
- default_substitute(self) None
Perform default substitutions in a pattern.
Supplies default values for underspecified font patterns:
Patterns without a specified style or weight are set to Medium
Patterns without a specified style or slant are set to Roman
Patterns without a specified pixel size are given one computed from any specified point size (default 12), dpi (default 75) and scale (default 1).
- delete(self, str key: str) bool
Delete a property from a pattern
- equal_subset(self, Pattern pattern: Pattern, ObjectSet object_set: ObjectSet) bool
Compare portions of patterns
- format(self, str fmt: str) None
Format a pattern into a string according to a format specifier
- get(self, str key: str, int index: int = 0) Any
Return a value from a pattern
- print(self) None
Print a pattern for debugging
- remove(self, str key: str, int index: int = 0) bool
Remove one object of the specified type from the pattern
- unparse(self) str
Convert a pattern back into a string that can be parsed.