Django生成PDF时阿拉伯语显示异常问题求助
解决Django+xhtml2pdf生成PDF时阿拉伯语显示异常的问题
问题核心
你的代码存在两个关键问题导致阿拉伯语渲染失效:
- 模板中
@font-face定义的字体名称与body的font-family引用不匹配 - 字体文件的相对路径无法被xhtml2pdf正确解析
修复步骤
1. 修正模板字体配置
先将NotoKufiArabic-VariableFont_wght.ttf放到项目的静态文件目录(比如static/fonts/),然后修改模板代码:
{% load static %} <html lang="ar" dir="rtl"> <head> <meta charset="UTF-8"> <title>تقرير المورد - {{ supplier.supplier_name }}</title> <style> @font-face { font-family: 'NotoKufiArabic'; src: url('{% static "fonts/NotoKufiArabic-VariableFont_wght.ttf" %}') format('truetype'); font-weight: normal; font-style: normal; } body { font-family: 'NotoKufiArabic', sans-serif; direction: rtl; text-align: right; } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; text-align: right; } th { background-color: #f2f2f2; } </style> </head> <!-- 原body内容保持不变 --> </html>
2. 优化视图函数的PDF生成逻辑
在调用pisaDocument时添加字体路径配置,确保xhtml2pdf能正确定位字体文件:
from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO from django.shortcuts import get_object_or_404 from django.conf import settings from ..models import Supplier, TransactionModel from django.db.models import Sum def generate_pdf_report(request, supplier_name): supplier = get_object_or_404(Supplier, supplier_name=supplier_name) transactions = TransactionModel.objects.filter(supplier_name=supplier).order_by('payment_date') total_paid = transactions.aggregate(Sum('payment_amount'))['payment_amount__sum'] or 0 remaining_amount = supplier.total_amount - total_paid context = { 'supplier': supplier, 'transactions': transactions, 'total_paid': total_paid, 'remaining_amount': remaining_amount, } template = get_template('supplier_report.html') html = template.render(context) result = BytesIO() # 配置字体搜索路径为静态文件的fonts目录 font_path = settings.STATIC_ROOT / 'fonts' pdf = pisa.pisaDocument( BytesIO(html.encode("UTF-8")), result, encoding='UTF-8', options={'font_path': str(font_path)} ) if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{supplier_name}_report.pdf"' return response return HttpResponse('Error generating PDF', status=400)
3. 补充配置检查
确保settings.py中静态文件路径配置正确:
STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [BASE_DIR / 'static']
执行python manage.py collectstatic将静态文件收集到STATIC_ROOT目录,保证xhtml2pdf能访问到字体文件。
内容的提问来源于stack exchange,提问作者basel nabil
相关产品推荐
相关产品推荐

