You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Cloud Function中fpdf2加载字体出现扩展名不支持错误的问询

解决Google Cloud Function中fpdf2加载GitHub字体的扩展名检查问题

核心问题

fpdf2的add_font方法会校验传入的文件路径扩展名,而通过repo.get_contents获取的字节流或BytesIO对象没有真实文件路径,导致触发"Unsupported font file extension"错误。

可行解决方案

最稳妥的方式是将GitHub获取的字体内容写入云函数的临时目录(/tmp),生成带正确扩展名的文件后再调用add_font。

代码实现示例

from github import Github
from fpdf import FPDF
import os
import uuid

def cloud_function_entry(request):
    # 从环境变量读取GitHub认证令牌
    github_token = os.environ.get("GITHUB_TOKEN")
    g = Github(github_token)
    repo = g.get_repo("your-username/your-font-repo")
    
    # 获取仓库中的TTF字体文件内容
    font_file = repo.get_contents("fonts/custom-font.ttf")
    font_bytes = font_file.decoded_content
    
    # 生成唯一临时文件名,避免并发冲突
    temp_font_filename = f"{uuid.uuid4()}.ttf"
    temp_font_path = os.path.join("/tmp", temp_font_filename)
    
    # 将字体字节写入临时文件
    with open(temp_font_path, "wb") as f:
        f.write(font_bytes)
    
    # 初始化PDF并加载字体
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font("CustomFont", "", temp_font_path)
    pdf.set_font("CustomFont", "", 14)
    pdf.cell(0, 10, "这是用自定义字体生成的内容", ln=True)
    
    # 输出PDF(根据云函数需求调整返回格式)
    pdf_output = pdf.output(dest="S").encode("latin-1")
    return pdf_output

关键说明

  1. 临时目录权限:Google Cloud Function的/tmp目录是可读写的,函数执行完毕后会自动清理文件,无需手动删除。
  2. 文件名唯一性:使用uuid生成唯一文件名,避免多实例并发执行时的文件覆盖问题。
  3. GitHub权限:确保配置的GITHUB_TOKEN拥有目标仓库的读取权限,且已在云函数环境变量中正确设置。

替代方案(不推荐,仅应急)

如果无法使用临时文件,可通过修改fpdf2的add_font方法逻辑绕过扩展名检查,但此方法依赖fpdf2的内部实现,版本更新后可能失效。例如直接调用字体加载的内部方法:

from fpdf import FPDF
from fpdf.fonts import FontFace

# 假设font_bytes是从GitHub获取的字体字节流
pdf = FPDF()
font_face = FontFace(family="CustomFont")
pdf.core_fonts["CustomFont"] = font_face
pdf._load_font("CustomFont", "", font_bytes)

内容的提问来源于stack exchange,提问作者Jason Vuka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:33:24