Python3+Django使用xhtml2pdf生成PDF时格鲁吉亚文字无法正常显示如何解决
问题原因
xhtml2pdf(pisa)对小语种字符集的支持依赖两个前提:一是配置的字体包含对应语言的字形,二是框架能正确加载到指定字体文件。你之前的配置存在三个核心问题:
- 引入的DejaVu系列字体默认不支持格鲁吉亚语字形
- CSS使用相对路径,xhtml2pdf解析时无法找到字体文件
- 视图函数没有配置静态资源解析回调,也没有指定默认字体,且存在模型查询的笔误
解决方案
1. 替换兼容字体
优先选用对格鲁吉亚语支持完整的开源字体,比如Noto Sans Georgian,下载后放到项目的static/font目录下。
2. 修正CSS配置
删除无效字体配置,全局指定字体优先级,字体路径写服务器绝对路径避免解析失败:
* { /* 把支持格鲁吉亚语的字体放在最前面 */ font-family: "Noto Sans Georgian", code2000, sans-serif; } @media print { @font-face { font-family: "Noto Sans Georgian"; /* 替换为你服务器上字体文件的真实绝对路径 */ src: url("/www/your_project/static/font/NotoSansGeorgian-Regular.ttf"); } @font-face { font-family: "Noto Sans Georgian"; src: url("/www/your_project/static/font/NotoSansGeorgian-Bold.ttf"); font-weight: bold; } /* 保留你原有需要的其他字体配置即可 */ }
3. 修正视图函数代码
添加静态资源解析回调,显式指定默认字体,修正模型查询笔误:
import os from django.conf import settings from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.template.loader import get_template from django.contrib.staticfiles import finders from xhtml2pdf import pisa # 静态资源解析回调,供xhtml2pdf加载字体、图片等资源 def link_callback(uri, rel): result = finders.find(uri) if result: if not isinstance(result, (list, tuple)): result = [result] path = list(os.path.realpath(p) for p in result)[0] else: path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) if not os.path.isfile(path): raise FileNotFoundError(f"资源不存在:{uri}") return path def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') # 这里把Customer替换为你实际的客户模型类名 customer = get_object_or_404(Customer, pk=pk) template_path = 'test.html' context = {'customer': customer} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, encoding='utf-8', link_callback=link_callback, default_font="Noto Sans Georgian" ) if pisa_status.err: return HttpResponse("PDF生成失败", status=500) return response
4. 异常排查
如果调整后仍有乱码,按以下顺序验证:
- 确认使用的字体文件确实包含格鲁吉亚语字符集,可在本地打开字体文件查看支持的字符列表
- 直接访问test.html页面,确认浏览器中格鲁吉亚语显示正常,字体资源无404错误
- 给包含格鲁吉亚语的HTML元素单独添加
style="font-family: 'Noto Sans Georgian'"属性,避免继承到不兼容的字体
内容的提问来源于stack exchange,提问作者Zura Begadze
相关产品推荐
相关产品推荐

