使用tkinter中的tkFont来识别字体(Helvetica-Light)是否可用/已安装

时间:2015-07-21 22:58:19

标签: python django tkinter

我们有一个Django应用程序,我们使用HTMLpdf生成工具来构建pdf文档。我们遇到了将HTML转换为pdf的服务器上不存在的字体问题,我想添加一个单元测试,可以验证托管服务器上是否存在字体。

据我所知,我应该使用Tkinter的tkFont模块获取可用的字体列表,并确认我们使用的字体在此列表中找到。

class VerifyFontsExistOnServer(BaseTransactionTestCase):
    def test_if_font_exists(self):
        import Tkinter
        import tkFont
        Tkinter.Tk()
        installed_font_families =[i for i in tkFont.families()
                                  if 'Helvetica' in i
                                  or 'Courier' in i
                                  or 'DejaVuSerif' in i
                                  or 'OCRA' in i]

        for font in installed_font_families:
            log.info('{0}'.format(font))

但是当我列出项目时,我得到Helvetica字体,但不是Helvetica-Light。我相信这是这个家族的一部分,但是有没有办法确定这个家族的这种特殊字体是否存在?

1 个答案:

答案 0 :(得分:1)

我最终编写了一个基于shell的方法来调用fc-list terminal命令:

def verify_fonts_are_installed_for_statements():
    import subprocess
    from os import path
    potential_locations = [
        '/usr/bin/fc-list',
        '/usr/sbin/fc-list',
        '/usr/local/sbin/fc-list',
        '/usr/local/bin/fc-list',
    ]
    valid_path = None
    for file_path in potential_locations:
        if path.exists(file_path):
            valid_path = file_path
            break
    if valid_path is None:
        raise IOError('could not find fc-list to verify fonts exist.')

    cmd = [valid_path]
    output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]

    if 'Helvetica Neue' not in output:
        raise FontNotInstalledException('Helvetica Neue')
    if 'Courier' not in output:
        raise FontNotInstalledException('Courier')

    log.debug('Courier and Helvetica Neue were found to be installed.')
相关问题