如何让xhtml2pdf-pisa支持西里尔字母?
解决Pisa生成PDF时西里尔字母显示黑方块的问题
你的核心问题是没有在Pisa配置中正确加载支持西里尔字母的字体,初始代码仅设置了编码,但未指定自定义字体的加载逻辑。以下是修改后的代码及错误说明:
错误分析
- 未配置Pisa的资源查找回调,导致程序无法识别你放入
static/fonts的西里尔字体文件 - 仅设置UTF-8编码不足以让PDF渲染非拉丁字符,必须明确指定支持西里尔的字体并关联到渲染流程
修改后的代码
import os from django.template.loader import get_template from django.http import HttpResponse from io import BytesIO import xhtml2pdf.pisa as pisa def fetch_resources(uri, rel): # 解析静态资源路径,适配项目目录结构 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) static_path = os.path.join(base_dir, 'static') # 处理URI中的/static/前缀,定位到实际字体文件 path = os.path.join(static_path, uri.replace('/static/', '')) return path def convert_to_pdf(template_name, **context): template = get_template(template_name) html = template.render(context) result = BytesIO() # 配置Pisa的核心参数,关联字体和资源回调 pdf = pisa.pisaDocument( BytesIO(html.encode("UTF-8")), result, encoding="UTF-8", fetch_resources=fetch_resources, # 指定支持西里尔的字体文件路径,替换为你实际的字体文件名 default_font=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/fonts/arialuni.ttf') ) result.seek(0) response = HttpResponse(result.getvalue(), content_type="application/pdf; charset=utf-8") response["Content-Disposition"] = 'inline; filename="output.pdf"' return response
额外注意事项
- 确保
static/fonts下的字体文件真实存在,比如示例中的arialuni.ttf可替换为你已准备的西里尔字体(如Roboto Cyrillic、Times New Roman Cyrillic等) - 在HTML模板中,需给文本元素指定对应字体样式,确保渲染时调用该字体:
.cyrillic-text { font-family: 'Arial Unicode MS', sans-serif; } - 检查字体文件路径是否正确,可通过
print(os.path.exists(default_font_path))验证路径有效性
内容的提问来源于stack exchange,提问作者Serega Derevnya
相关产品推荐
相关产品推荐

