Skip to content

Commit 1a48184

Browse files
authored
Merge pull request #1960 from MarronEyes/img-font
Add support for loading TrueType font files.
2 parents d7b3732 + a8a875e commit 1a48184

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

pygments/formatters/img.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
88
:license: BSD, see LICENSE for details.
99
"""
10-
1110
import os
1211
import sys
1312

@@ -68,6 +67,15 @@ def __init__(self, font_name, font_size=14):
6867
self.font_size = font_size
6968
self.fonts = {}
7069
self.encoding = None
70+
self.variable = False
71+
if hasattr(font_name, 'read') or os.path.isfile(font_name):
72+
font = ImageFont.truetype(font_name, self.font_size)
73+
self.variable = True
74+
for style in STYLES:
75+
self.fonts[style] = font
76+
77+
return
78+
7179
if sys.platform.startswith('win'):
7280
if not font_name:
7381
self.font_name = DEFAULT_FONT_NAME_WIN
@@ -223,14 +231,42 @@ def get_font(self, bold, oblique):
223231
Get the font based on bold and italic flags.
224232
"""
225233
if bold and oblique:
234+
if self.variable:
235+
return self.get_style('BOLDITALIC')
236+
226237
return self.fonts['BOLDITALIC']
227238
elif bold:
239+
if self.variable:
240+
return self.get_style('BOLD')
241+
228242
return self.fonts['BOLD']
229243
elif oblique:
244+
if self.variable:
245+
return self.get_style('ITALIC')
246+
230247
return self.fonts['ITALIC']
231248
else:
249+
if self.variable:
250+
return self.get_style('NORMAL')
251+
232252
return self.fonts['NORMAL']
233253

254+
def get_style(self, style):
255+
"""
256+
Get the specified style of the font if it is a variable font.
257+
If not found, return the normal font.
258+
"""
259+
font = self.fonts[style]
260+
for style_name in STYLES[style]:
261+
try:
262+
font.set_variation_by_name(style_name)
263+
return font
264+
except ValueError:
265+
pass
266+
except OSError:
267+
return font
268+
269+
return font
234270

235271
class ImageFormatter(Formatter):
236272
"""
@@ -258,6 +294,8 @@ class ImageFormatter(Formatter):
258294
The font name to be used as the base font from which others, such as
259295
bold and italic fonts will be generated. This really should be a
260296
monospace font to look sane.
297+
If a filename or a file-like object is specified, the user must
298+
provide different styles of the font.
261299
262300
Default: "Courier New" on Windows, "Menlo" on Mac OS, and
263301
"DejaVu Sans Mono" on \\*nix

0 commit comments

Comments
 (0)