Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 951f752

Browse files
authored
Merge pull request #21904 from ambi7/repr-html-fonts
Added _repr_html_ for fonts
2 parents aa5fdbb + 9b69954 commit 951f752

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

lib/matplotlib/font_manager.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,10 @@
2323
# - setWeights function needs improvement
2424
# - 'light' is an invalid weight value, remove it.
2525

26+
from base64 import b64encode
2627
import dataclasses
2728
from functools import lru_cache
29+
from io import BytesIO
2830
import json
2931
import logging
3032
from numbers import Number
@@ -380,6 +382,22 @@ def findSystemFonts(fontpaths=None, fontext='ttf'):
380382
return [fname for fname in fontfiles if os.path.exists(fname)]
381383

382384

385+
def fontentry_helper_repr_png_(fontent):
386+
from matplotlib.figure import Figure # Circular import.
387+
fig = Figure()
388+
font_path = Path(fontent.fname) if fontent.fname != '' else None
389+
fig.text(0, 0, fontent.name, font=font_path)
390+
with BytesIO() as buf:
391+
fig.savefig(buf, bbox_inches='tight', transparent=True)
392+
return buf.getvalue()
393+
394+
395+
def fontentry_helper_repr_html_(fontent):
396+
png_stream = fontentry_helper_repr_png_(fontent)
397+
png_b64 = b64encode(png_stream).decode()
398+
return f"<img src=\"data:image/png;base64, {png_b64}\" />"
399+
400+
383401
FontEntry = dataclasses.make_dataclass(
384402
'FontEntry', [
385403
('fname', str, dataclasses.field(default='')),
@@ -395,7 +413,11 @@ def findSystemFonts(fontpaths=None, fontext='ttf'):
395413
A class for storing Font properties.
396414
397415
It is used when populating the font lookup dictionary.
398-
"""})
416+
""",
417+
'_repr_html_': lambda self: fontentry_helper_repr_html_(self),
418+
'_repr_png_': lambda self: fontentry_helper_repr_png_(self),
419+
}
420+
)
399421

400422

401423
def ttfFontProperty(font):

lib/matplotlib/tests/test_font_manager.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import multiprocessing
33
import os
44
from pathlib import Path
5+
from PIL import Image
56
import shutil
67
import subprocess
78
import sys
@@ -11,9 +12,10 @@
1112
import pytest
1213

1314
from matplotlib.font_manager import (
14-
findfont, findSystemFonts, FontProperties, fontManager, json_dump,
15-
json_load, get_font, is_opentype_cff_font, MSUserFontDirectories,
16-
_get_fontconfig_fonts, ft2font, ttfFontProperty, cbook)
15+
findfont, findSystemFonts, FontEntry, FontProperties, fontManager,
16+
json_dump, json_load, get_font, is_opentype_cff_font,
17+
MSUserFontDirectories, _get_fontconfig_fonts, ft2font,
18+
ttfFontProperty, cbook)
1719
from matplotlib import pyplot as plt, rc_context
1820

1921
has_fclist = shutil.which('fc-list') is not None
@@ -268,6 +270,24 @@ def test_fontcache_thread_safe():
268270
f"{proc.returncode}.")
269271

270272

273+
def test_fontentry_dataclass():
274+
fontent = FontEntry(name='font-name')
275+
276+
png = fontent._repr_png_()
277+
img = Image.open(BytesIO(png))
278+
assert img.width > 0
279+
assert img.height > 0
280+
281+
html = fontent._repr_html_()
282+
assert html.startswith("<img src=\"data:image/png;base64")
283+
284+
285+
def test_fontentry_dataclass_invalid_path():
286+
with pytest.raises(FileNotFoundError):
287+
fontent = FontEntry(fname='/random', name='font-name')
288+
fontent._repr_html_()
289+
290+
271291
@pytest.mark.skipif(sys.platform == 'win32', reason='Linux or OS only')
272292
def test_get_font_names():
273293
paths_mpl = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf']]

0 commit comments

Comments
 (0)