Python3如何安装.ttf字体文件?

5
我想在Windows 10上使用Python3(更准确地说是Python 3.6)代码安装.ttf字体文件,我进行了谷歌搜索,但我找到的唯一一件事是这个Install TTF fonts on windows with python,我测试了它,但它什么也没做。有没有办法使用Python3代码安装.ttf文件?提前感谢。

你的系统中有.ttf文件吗? - Rafael
我只有一个文件夹里的.ttf字体文件,已经准备好安装,但我想用Python代码来安装。 - Senhor Sardinhas
2个回答

7

这个库看起来很有前途(我自己还没有尝试过)。

安装

pip install --user fonttools

或者

pip3 install --user fonttools

代码

from fontTools.ttLib import TTFont
font = TTFont('/path/to/font.ttf')

然后使用font.save方法:

定义:font.save(self, file, reorderTables=True)

文档字符串:将字体保存到磁盘。与构造函数类似,'file'参数可以是路径名或可写文件对象。


我在Windows上运行Visual Code时遇到了一个错误:_ImportError: No module named fontTools.ttLib_。 - Senhor Sardinhas
1
你在你的环境中安装了这个库吗? - Rafael
现在导入部分和font = TTFont('/path/to/font.ttf')已经起作用,但现在又出现了另一个问题,就是当我尝试执行font.save时,它会给我一个错误_NameError: name 'self' is not defined_。 - Senhor Sardinhas
1
.save is a method. You need to call it like that: font.save("path/to/save/") - Rafael
2
我正在阅读文档时遇到了一些困难。有没有更简单的替代方案的相关信息? - greendino
1
哈哈,尝试将字体安装到“Fonts”文件夹,但是出现了“PermissionError:[Errno 13] Permission denied:'C:\ Windows \ Fonts'”错误。 - user14023416

1

这可能会对您有所帮助,它尝试安装文件夹中的所有字体,但您可以使用install_font函数将其修改为仅安装1个字体:https://gist.github.com/tushortz/598bf0324e37033ed870c4e46461fb1e

import os
import shutil
import ctypes
from ctypes import wintypes
import sys
import ntpath
try:
    import winreg
except ImportError:
    import _winreg as winreg

user32 = ctypes.WinDLL('user32', use_last_error=True)
gdi32 = ctypes.WinDLL('gdi32', use_last_error=True)

FONTS_REG_PATH = r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'

HWND_BROADCAST = 0xFFFF
SMTO_ABORTIFHUNG = 0x0002
WM_FONTCHANGE = 0x001D
GFRI_DESCRIPTION = 1
GFRI_ISTRUETYPE = 3

def install_font(src_path):
    # copy the font to the Windows Fonts folder
    dst_path = os.path.join(os.environ['SystemRoot'], 'Fonts',
                            os.path.basename(src_path))
    shutil.copy(src_path, dst_path)
    # load the font in the current session
    if not gdi32.AddFontResourceW(dst_path):
        os.remove(dst_path)
        raise WindowsError('AddFontResource failed to load "%s"' % src_path)
    # notify running programs
    user32.SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0,
                               SMTO_ABORTIFHUNG, 1000, None)
    # store the fontname/filename in the registry
    filename = os.path.basename(dst_path)
    fontname = os.path.splitext(filename)[0]
    # try to get the font's real name
    cb = wintypes.DWORD()
    if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), None,
                                  GFRI_DESCRIPTION):
        buf = (ctypes.c_wchar * cb.value)()
        if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), buf,
                                      GFRI_DESCRIPTION):
            fontname = buf.value
    is_truetype = wintypes.BOOL()
    cb.value = ctypes.sizeof(is_truetype)
    gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb),
                               ctypes.byref(is_truetype), GFRI_ISTRUETYPE)
    if is_truetype:
        fontname += ' (TrueType)'
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, FONTS_REG_PATH, 0,
                        winreg.KEY_SET_VALUE) as key:
        winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename)

基本上,使用 Windows 的 gdi32 API 中的 AddFontResourceW 加载字体,并使用 SendMessage API 通知正在运行的程序 - 这将使字体在运行的程序中可见。

要永久安装字体到 Windows 中,您需要将字体文件复制到 Fonts 文件夹中(C:\Windows\Fonts,或 %userprofile%\AppData\Local\Microsoft\Windows\Fonts 用于每个用户的文件夹),然后在注册表中添加一个键 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts (或 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts 用于每个用户的安装)。


虽然这可能回答了问题,但最好在此处包含答案的基本部分,并提供参考链接。 - Sergey Shubin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接