Files
growth_report/utils/font_utils.py
2025-12-10 22:36:12 +08:00

76 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ==========================================
# 2. 字体工具函数 (Font Utilities)
# ==========================================
import os
import platform
import shutil
from pathlib import Path
def get_system_fonts():
"""获取系统中可用的字体列表"""
fonts = set()
if platform.system() == "Windows":
try:
system_fonts_dir = Path(os.environ['WINDIR']) / 'Fonts'
user_fonts_dir = Path.home() / 'AppData' / 'Local' / 'Microsoft' / 'Windows' / 'Fonts'
for folder in [system_fonts_dir, user_fonts_dir]:
if folder.exists():
for ext in ['*.ttf', '*.ttc', '*.otf']:
for font_file in folder.glob(ext):
fonts.add(font_file.stem)
except Exception as e:
print(f"读取系统字体时出错: {e}")
fonts = {"微软雅黑", "宋体", "黑体", "Arial", "Microsoft YaHei"}
return fonts
def is_font_available(font_name):
"""检查字体是否在系统中可用"""
system_fonts = get_system_fonts()
check_names = [font_name, font_name.replace(" ", ""), font_name.replace("-", ""),
font_name.lower(), font_name.upper()]
for name in check_names:
if name in system_fonts:
return True
return False
def install_fonts_from_directory(fonts_dir="fonts"):
"""从指定目录安装字体到系统"""
if platform.system() != "Windows":
print("字体安装功能目前仅支持Windows系统")
return False
target_font_dir = Path.home() / 'AppData' / 'Local' / 'Microsoft' / 'Windows' / 'Fonts'
target_font_dir.mkdir(parents=True, exist_ok=True)
if not os.path.exists(fonts_dir):
print(f"字体目录 {fonts_dir} 不存在,请创建该目录并将字体文件放入")
return False
font_files = []
for ext in ['.ttf', '.ttc', '.otf', '.fon']:
font_files.extend(Path(fonts_dir).glob(f'*{ext}'))
if not font_files:
print(f"{fonts_dir} 目录中未找到字体文件")
return False
installed_count = 0
for font_file in font_files:
try:
target_path = target_font_dir / font_file.name
if not target_path.exists():
shutil.copy2(font_file, target_path)
print(f"已安装字体: {font_file.name}")
installed_count += 1
except Exception as e:
print(f"安装字体 {font_file.name} 时出错: {str(e)}")
if installed_count > 0:
print(f"共安装了 {installed_count} 个新字体文件建议重启Python环境")
return True
return False