python reportlab - 如何测试特定字体(核心或 TTF)是否可以编码/渲染 PDF 中给定的字形?

问题描述 投票:0回答:1

我见过如何确定一个Glyph是否可以显示?,这似乎不适用于核心字体。

https://docs.reportlab.com/reportlab/userguide/ch3_fonts/谈论

reportlab.rl_config.warnOnMissingFontGlyphs
,但这似乎只是打印一个警告,我不知道如何捕获。

如果有任何见解,我将不胜感激。

python reportlab
1个回答
1
投票

这似乎对我有用:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import unicodedata

# font_name = 'Times-Roman'
font_name = '/usr/share/fonts/truetype/noto/NotoSansMono-Thin.ttf'
# char_to_test = 'и'
char_to_test = 'A'

def font_can_render_glyph(font, glyph):
    name = unicodedata.name(glyph, "")
    if glyph in font.face.glyphWidths or name in font.face.glyphWidths:
        return True
    elif hasattr(font.face, 'charToGlyph') and ord(glyph) in font.face.charToGlyph:
        return True
    return False

if font_name[-4:] == ".ttf":
    font = TTFont(font_name, font_name)
else:
    font = pdfmetrics.getFont(font_name)

if font_can_render_glyph(font, char_to_test):
    print(f"The font '{font.fontName}' can render the glyph '{char_to_test}'.")
else:
    print(f"The font '{font.fontName}' cannot render the glyph '{char_to_test}'.")
© www.soinside.com 2019 - 2024. All rights reserved.