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

Django+xhtml2pdf自定义字体不生效及权限报错问题求助

解决Django+xhtml2pdf引入自定义字体失效及TTF权限错误的方案

一、正确配置自定义字体路径

xhtml2pdf无法直接解析Django的{% static %}标签,对相对路径支持也不佳,必须用本地绝对磁盘路径引入字体:

  1. 将YsabeauInfant-Regular.ttf(建议重命名去掉空格,避免路径解析问题)放到Django静态目录,比如static/fonts/下
  2. 在模板的CSS中用绝对路径声明字体:
@font-face {
    font-family: 'YsabeauInfant';
    src: url('C:/your-project-root/static/fonts/YsabeauInfant-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
body {
    font-family: 'YsabeauInfant', sans-serif;
}

注意替换C:/your-project-root为你实际的项目根目录绝对路径。

二、解决TTFError权限拒绝问题

1. 修复字体文件权限

右键字体文件→属性→安全页:

  • 确认当前登录用户(以及Python运行进程的用户)拥有读取和执行权限
  • 若权限不足,添加Everyone用户并授予读取权限

2. 自定义xhtml2pdf临时目录

系统临时目录权限限制可能导致报错,手动指定非系统盘的临时文件夹:

from xhtml2pdf import pisa
import tempfile
import os
from django.template.loader import get_template
from django.http import HttpResponse, BytesIO

def generate_pdf(request):
    # 创建自定义临时目录(确保路径存在)
    temp_dir = "D:/xhtml2pdf_temp"
    os.makedirs(temp_dir, exist_ok=True)
    # 强制xhtml2pdf使用该目录
    tempfile.tempdir = temp_dir

    # 生成PDF的核心逻辑
    template = get_template('pdf_template.html')
    html_content = template.render({'data': {}})
    output = BytesIO()
    pisa_status = pisa.CreatePDF(
        BytesIO(html_content.encode('utf-8')),
        dest=output
    )
    if not pisa_status.err:
        return HttpResponse(output.getvalue(), content_type='application/pdf')
    return HttpResponse("PDF生成失败", status=400)

3. 禁用字体缓存

缓存损坏也可能引发权限问题,在项目初始化代码(比如settings.py末尾)添加:

from xhtml2pdf.default import DEFAULT_FONT
DEFAULT_FONT['cache'] = False

4. 以管理员权限运行项目

右键启动项目的终端/IDE→选择"以管理员身份运行",避免进程权限不足。

三、验证字体生效

生成PDF后,用专业PDF阅读器(如Adobe Acrobat)查看:

  • 打开PDF→文件→属性→字体选项卡
  • 确认YsabeauInfant字体已被嵌入文档中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:32:20