Skip to content

Commit 4aed557

Browse files
committed
pdf/ps: Support any font in a collection
1 parent b76787e commit 4aed557

File tree

7 files changed

+100
-26
lines changed

7 files changed

+100
-26
lines changed

lib/matplotlib/backends/_backend_pdf_ps.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def get_glyphs_subset(fontfile: str, glyphs: set[GlyphIndexType]) -> TTFont:
4242
4343
Parameters
4444
----------
45-
fontfile : str
45+
fontfile : FontPath
4646
Path to the font file
4747
glyphs : set[GlyphIndexType]
4848
Set of glyph indices to include in subset.
@@ -80,8 +80,7 @@ def get_glyphs_subset(fontfile: str, glyphs: set[GlyphIndexType]) -> TTFont:
8080
'xref', # The cross-reference table (some Apple font tooling information).
8181
]
8282
# if fontfile is a ttc, specify font number
83-
if fontfile.endswith(".ttc"):
84-
options.font_number = 0
83+
options.font_number = fontfile.face_index
8584

8685
font = subset.load_font(fontfile, options)
8786
subsetter = subset.Subsetter(options=options)
@@ -255,11 +254,12 @@ def track_glyph(self, font: FT2Font, chars: str | CharacterCodeType,
255254
charcode = chars
256255
chars = chr(chars)
257256

258-
glyph_map = self.glyph_maps.setdefault(font.fname, GlyphMap())
257+
font_path = font_manager.FontPath(font.fname, font.face_index)
258+
glyph_map = self.glyph_maps.setdefault(font_path, GlyphMap())
259259
if result := glyph_map.get(chars, glyph):
260260
return result
261261

262-
subset_maps = self.used.setdefault(font.fname, [{}])
262+
subset_maps = self.used.setdefault(font_path, [{}])
263263
use_next_charmap = (
264264
# Multi-character glyphs always go in the non-0 subset.
265265
len(chars) > 1 or

lib/matplotlib/backends/backend_pdf.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
RendererBase)
3333
from matplotlib.backends.backend_mixed import MixedModeRenderer
3434
from matplotlib.figure import Figure
35-
from matplotlib.font_manager import get_font, fontManager as _fontManager
35+
from matplotlib.font_manager import FontPath, get_font, fontManager as _fontManager
3636
from matplotlib._afm import AFM
3737
from matplotlib.ft2font import FT2Font, FaceFlags, Kerning, LoadFlags, StyleFlags
3838
from matplotlib.transforms import Affine2D, BboxBase
@@ -893,8 +893,10 @@ def fontName(self, fontprop, subset=0):
893893
as the filename of the font.
894894
"""
895895

896-
if isinstance(fontprop, str):
896+
if isinstance(fontprop, FontPath):
897897
filenames = [fontprop]
898+
elif isinstance(fontprop, str):
899+
filenames = [FontPath(fontprop, 0)]
898900
elif mpl.rcParams['pdf.use14corefonts']:
899901
filenames = _fontManager._find_fonts_by_props(
900902
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir
@@ -934,7 +936,7 @@ def writeFonts(self):
934936
_log.debug('Embedding Type-1 font %s from dvi.', dvifont.texname)
935937
fonts[pdfname] = self._embedTeXFont(dvifont)
936938
for (filename, subset), Fx in sorted(self._fontNames.items()):
937-
_log.debug('Embedding font %s:%d.', filename, subset)
939+
_log.debug('Embedding font %r:%d.', filename, subset)
938940
if filename.endswith('.afm'):
939941
# from pdf.use14corefonts
940942
_log.debug('Writing AFM font.')
@@ -985,7 +987,8 @@ def _embedTeXFont(self, dvifont):
985987

986988
# Reduce the font to only the glyphs used in the document, get the encoding
987989
# for that subset, and compute various properties based on the encoding.
988-
charmap = self._character_tracker.used[dvifont.fname][0]
990+
font_path = FontPath(dvifont.fname, dvifont.face_index)
991+
charmap = self._character_tracker.used[font_path][0]
989992
chars = {
990993
# DVI type 1 fonts always map single glyph to single character.
991994
ord(self._character_tracker.subset_to_unicode(dvifont.fname, 0, ccode))
@@ -1240,12 +1243,12 @@ def embedTTFType42(font, subset_index, charmap, descriptor):
12401243
wObject = self.reserveObject('Type 0 widths')
12411244
toUnicodeMapObject = self.reserveObject('ToUnicode map')
12421245

1243-
_log.debug("SUBSET %s:%d characters: %s", filename, subset_index, charmap)
1246+
_log.debug("SUBSET %r:%d characters: %s", filename, subset_index, charmap)
12441247
with _backend_pdf_ps.get_glyphs_subset(filename,
12451248
charmap.values()) as subset:
12461249
fontdata = _backend_pdf_ps.font_as_file(subset)
12471250
_log.debug(
1248-
"SUBSET %s:%d %d -> %d", filename, subset_index,
1251+
"SUBSET %r:%d %d -> %d", filename, subset_index,
12491252
os.stat(filename).st_size, fontdata.getbuffer().nbytes
12501253
)
12511254

@@ -2136,13 +2139,13 @@ def draw_mathtext(self, gc, x, y, s, prop, angle):
21362139
for font, fontsize, ccode, glyph_index, ox, oy in glyphs:
21372140
subset_index, subset_charcode = self.file._character_tracker.track_glyph(
21382141
font, ccode, glyph_index)
2139-
fontname = font.fname
2142+
font_path = FontPath(font.fname, font.face_index)
21402143
self._setup_textpos(ox, oy, 0, oldx, oldy)
21412144
oldx, oldy = ox, oy
2142-
if (fontname, subset_index, fontsize) != prev_font:
2143-
self.file.output(self.file.fontName(fontname, subset_index), fontsize,
2145+
if (font_path, subset_index, fontsize) != prev_font:
2146+
self.file.output(self.file.fontName(font_path, subset_index), fontsize,
21442147
Op.selectfont)
2145-
prev_font = fontname, subset_index, fontsize
2148+
prev_font = font_path, subset_index, fontsize
21462149
self.file.output(self._encode_glyphs([subset_charcode], fonttype),
21472150
Op.show)
21482151
self.file.output(Op.end_text)
@@ -2333,7 +2336,9 @@ def output_singlebyte_chunk(kerns_or_chars):
23332336
if (item.ft_object, subset) != prev_font:
23342337
if singlebyte_chunk:
23352338
output_singlebyte_chunk(singlebyte_chunk)
2336-
ft_name = self.file.fontName(item.ft_object.fname, subset)
2339+
font_path = FontPath(item.ft_object.fname,
2340+
item.ft_object.face_index)
2341+
ft_name = self.file.fontName(font_path, subset)
23372342
self.file.output(ft_name, fontsize, Op.selectfont)
23382343
self._setup_textpos(item.x, 0, 0, prev_start_x, 0, 0)
23392344
singlebyte_chunk = []

lib/matplotlib/backends/backend_ps.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def _font_to_ps_type3(font_path, subset_index, glyph_indices):
9494
9595
Parameters
9696
----------
97-
font_path : path-like
97+
font_path : FontPath
9898
Path to the font to be subsetted.
9999
subset_index : int
100100
The subset of the above font being created.
@@ -176,7 +176,7 @@ def _font_to_ps_type42(font_path, subset_index, glyph_indices, fh):
176176
177177
Parameters
178178
----------
179-
font_path : path-like
179+
font_path : FontPath
180180
Path to the font to be subsetted.
181181
subset_index : int
182182
The subset of the above font being created.
@@ -187,12 +187,8 @@ def _font_to_ps_type42(font_path, subset_index, glyph_indices, fh):
187187
"""
188188
_log.debug("SUBSET %s:%d characters: %s", font_path, subset_index, glyph_indices)
189189
try:
190-
kw = {}
191-
# fix this once we support loading more fonts from a collection
192-
# https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541
193-
if font_path.endswith('.ttc'):
194-
kw['fontNumber'] = 0
195-
with (fontTools.ttLib.TTFont(font_path, **kw) as font,
190+
with (fontTools.ttLib.TTFont(font_path.path,
191+
fontNumber=font_path.face_index) as font,
196192
_backend_pdf_ps.get_glyphs_subset(font_path, glyph_indices) as subset):
197193
fontdata = _backend_pdf_ps.font_as_file(subset).getvalue()
198194
_log.debug(

lib/matplotlib/dviread.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,10 @@ def fname(self):
719719
"""A fake filename"""
720720
return self.texname.decode('latin-1')
721721

722+
@property
723+
def face_index(self): # For compatibility with FT2Font.
724+
return 0
725+
722726
def _get_fontmap(self, string):
723727
"""Get the mapping from characters to the font that includes them.
724728

lib/matplotlib/dviread.pyi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ class DviFont:
7878
def widths(self) -> list[int]: ...
7979
@property
8080
def fname(self) -> str: ...
81+
@property
82+
def face_index(self) -> int: ...
8183
def resolve_path(self) -> Path: ...
8284
@property
8385
def subfont(self) -> int: ...

lib/matplotlib/tests/test_backend_pdf.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io
44
import os
55
from pathlib import Path
6+
import string
67

78
import numpy as np
89
import pytest
@@ -365,7 +366,7 @@ def test_glyphs_subset():
365366

366367
# subsetted FT2Font
367368
glyph_indices = {nosubcmap[ord(c)] for c in chars}
368-
with get_glyphs_subset(fpath, glyph_indices) as subset:
369+
with get_glyphs_subset(fm.FontPath(fpath, 0), glyph_indices) as subset:
369370
subfont = FT2Font(font_as_file(subset))
370371
subfont.set_text(chars)
371372
subcmap = subfont.get_charmap()
@@ -402,6 +403,38 @@ def test_multi_font_type42():
402403
horizontalalignment='center', verticalalignment='center')
403404

404405

406+
@image_comparison(['ttc_type3.pdf'], style='mpl20')
407+
def test_ttc_type3():
408+
fp = fm.FontProperties(family=['WenQuanYi Zen Hei'])
409+
if Path(fm.findfont(fp)).name != 'wqy-zenhei.ttc':
410+
pytest.skip('Font wqy-zenhei.ttc may be missing')
411+
412+
fonts = ['WenQuanYi Zen Hei', 'WenQuanYi Zen Hei Mono']
413+
plt.rc('font', size=16)
414+
plt.rc('pdf', fonttype=3)
415+
416+
figs = plt.figure(figsize=(7, len(fonts) / 2)).subfigures(len(fonts))
417+
for font, fig in zip(fonts, figs):
418+
fig.text(0.5, 0.5, f'{font}: {string.ascii_uppercase}', font=font,
419+
horizontalalignment='center', verticalalignment='center')
420+
421+
422+
@image_comparison(['ttc_type42.pdf'], style='mpl20')
423+
def test_ttc_type42():
424+
fp = fm.FontProperties(family=['WenQuanYi Zen Hei'])
425+
if Path(fm.findfont(fp)).name != 'wqy-zenhei.ttc':
426+
pytest.skip('Font wqy-zenhei.ttc may be missing')
427+
428+
fonts = ['WenQuanYi Zen Hei', 'WenQuanYi Zen Hei Mono']
429+
plt.rc('font', size=16)
430+
plt.rc('pdf', fonttype=42)
431+
432+
figs = plt.figure(figsize=(7, len(fonts) / 2)).subfigures(len(fonts))
433+
for font, fig in zip(fonts, figs):
434+
fig.text(0.5, 0.5, f'{font}: {string.ascii_uppercase}', font=font,
435+
horizontalalignment='center', verticalalignment='center')
436+
437+
405438
@pytest.mark.parametrize('family_name, file_name',
406439
[("Noto Sans", "NotoSans-Regular.otf"),
407440
("FreeMono", "FreeMono.otf")])

lib/matplotlib/tests/test_backend_ps.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
from collections import Counter
22
import io
3+
from pathlib import Path
34
import re
5+
import string
46
import tempfile
57

68
import numpy as np
79
import pytest
810

9-
from matplotlib import cbook, path, patheffects
11+
from matplotlib import cbook, font_manager, path, patheffects
1012
from matplotlib.figure import Figure
1113
from matplotlib.patches import Ellipse
1214
from matplotlib.testing import _gen_multi_font_text
@@ -340,6 +342,38 @@ def test_multi_font_type42():
340342
horizontalalignment='center', verticalalignment='center')
341343

342344

345+
@image_comparison(['ttc_type3.eps'], style='mpl20')
346+
def test_ttc_type3():
347+
fp = font_manager.FontProperties(family=['WenQuanYi Zen Hei'])
348+
if Path(font_manager.findfont(fp)).name != 'wqy-zenhei.ttc':
349+
pytest.skip('Font wqy-zenhei.ttc may be missing')
350+
351+
fonts = ['WenQuanYi Zen Hei', 'WenQuanYi Zen Hei Mono']
352+
plt.rc('font', size=16)
353+
plt.rc('pdf', fonttype=3)
354+
355+
figs = plt.figure(figsize=(7, len(fonts) / 2)).subfigures(len(fonts))
356+
for font, fig in zip(fonts, figs):
357+
fig.text(0.5, 0.5, f'{font}: {string.ascii_uppercase}', font=font,
358+
horizontalalignment='center', verticalalignment='center')
359+
360+
361+
@image_comparison(['ttc_type42.eps'], style='mpl20')
362+
def test_ttc_type42():
363+
fp = font_manager.FontProperties(family=['WenQuanYi Zen Hei'])
364+
if Path(font_manager.findfont(fp)).name != 'wqy-zenhei.ttc':
365+
pytest.skip('Font wqy-zenhei.ttc may be missing')
366+
367+
fonts = ['WenQuanYi Zen Hei', 'WenQuanYi Zen Hei Mono']
368+
plt.rc('font', size=16)
369+
plt.rc('pdf', fonttype=42)
370+
371+
figs = plt.figure(figsize=(7, len(fonts) / 2)).subfigures(len(fonts))
372+
for font, fig in zip(fonts, figs):
373+
fig.text(0.5, 0.5, f'{font}: {string.ascii_uppercase}', font=font,
374+
horizontalalignment='center', verticalalignment='center')
375+
376+
343377
@image_comparison(["scatter.eps"])
344378
def test_path_collection():
345379
rng = np.random.default_rng(19680801)

0 commit comments

Comments
 (0)