在Windows中使用python安装字体

ncecgwcz  于 2023-02-09  发布在  Windows
关注(0)|答案(2)|浏览(402)

我正在开发一个python脚本来在Windows中安装一个字体列表。我有一个这样的列表,

fonts_list = ["/path/to/file/myFont1.ttf", "/path/to/file/myFont1.ttf", "/path/to/file/myFont1.ttf"]

我只是尝试,使用shutil和操作系统复制字体文件,之后我尝试将其添加到Windows注册表,即使有管理员权限,它也不起作用。从脚本输出没有显示任何错误,但在列表中提到的Windows字体目录中没有任何字体。

os.system(reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" /v "FontName (TrueType)")

所以我开始从网上寻找更多的种子,然后我发现了这个,Installing TTF fonts on windows with python.但它不工作太.接下来我试着调用Windows fontview.exe,但对于一个字体列表,这是一个灾难.

os.system("fontview " + fontsList[0])

有没有办法在Windows中以编程方式安装字体?或者Windows中有没有任何用户级目录可以简单地复制字体文件,就像Linux系统有~/.fonts,Mac有~/Library/Fonts?请帮助。

7eumitmz

7eumitmz1#

这里有一个install_font函数,它将字体复制到系统的Fonts文件夹,在当前会话中加载它,通知正在运行的程序,并更新注册表,它只依赖于Python的标准库,应该在Python 2和Python 3中都能工作。

c类型定义

import os
import shutil
import ctypes
from ctypes import wintypes

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

if not hasattr(wintypes, 'LPDWORD'):
    wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)

user32.SendMessageTimeoutW.restype = wintypes.LPVOID
user32.SendMessageTimeoutW.argtypes = (
    wintypes.HWND,   # hWnd
    wintypes.UINT,   # Msg
    wintypes.LPVOID, # wParam
    wintypes.LPVOID, # lParam
    wintypes.UINT,   # fuFlags
    wintypes.UINT,   # uTimeout
    wintypes.LPVOID) # lpdwResult

gdi32.AddFontResourceW.argtypes = (
    wintypes.LPCWSTR,) # lpszFilename

# http://www.undocprint.org/winspool/getfontresourceinfo
gdi32.GetFontResourceInfoW.argtypes = (
    wintypes.LPCWSTR, # lpszFilename
    wintypes.LPDWORD, # cbBuffer
    wintypes.LPVOID,  # lpBuffer
    wintypes.DWORD)   # dwQueryType

函数定义

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)
ctrmrzij

ctrmrzij2#

当我在Windows中安装字体时,我主要使用这两种方法。

    • 方法1**
import os
import winreg

def install_font(font_file_path):
    # Open the registry key where the font information is stored
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", 0,
                         winreg.KEY_ALL_ACCESS)

    # Get the name of the font file
    font_file_name = os.path.basename(font_file_path)

    # Set the font information in the registry
    winreg.SetValueEx(key, font_file_name, 0, winreg.REG_SZ, font_file_path)

    # Close the registry key
    winreg.CloseKey(key)

# Example usage
font_file_path = "C:\Windows\Fonts\myfont.ttf"
install_font(font_file_path)
    • 方法二**
import ctypes

def install_font(font_path):
    # Load the AddFontResourceA function from the gdi32 library
    addfont = ctypes.windll.gdi32.AddFontResourceA

    # Call the AddFontResourceA function with the font path as the argument
    result = addfont(font_path)

    # Return True if the font was installed successfully, False otherwise
    return result != 0

# Example usage
font_path = r"C:\Windows\Fonts\myfont.ttf"
result = install_font(font_path)

if result:
    print("Font installed successfully")
else:
    print("Font installation failed")

我希望这会有所帮助。

相关问题