我正在使用 xthml2pdf 生成阿拉伯语发票。我进行了很多搜索来解决问题并遵循了所有步骤,但我不知道为什么它不起作用。
实用程序代码:
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=result, encoding='UTF-8')
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
查看代码:
pdf = render_to_pdf('pdf/invoice.html'), context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "invoice-%s.pdf" % invoice_number
content = "inline; filename= %s" % filename
response['Content-Disposition'] = content
return response
最后是 HTML 代码:
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="UTF-8">
<style>
@font-face{font-family:samim; src: url('/assets/fonts/Shabnam-FD.ttf') }
body{
background: #fff;
font-family: samim !important;
direction: rtl !important;
}
</style>
</head>
<body>
<div>
<pdf:language name="arabic"/>
<p>سلام</p>
</div>
</body>
</html>
在 Django 中使用 xhtml2pdf 时,允许使用 Django 的
STATIC_URL
和 MEDIA_URL
设置解析 URL 引用。这样,在任何环境中,您的代码都可以工作,因为 Django 承担了繁重的工作。
xhtml2pdf 允许用户指定
link_callback
参数来指向将相对 URL 转换为绝对系统路径的函数。请参阅此处的一个示例 。 [xhtml2pdf-文档]
使用此函数(例如
url_converter
),您的代码应该是:
def render_to_pdf(template_src, context_dict={}):
#•••Rest of your code•••
result = BytesIO()
result.seek(0)
status = pisa.CreatePDF(html, dest=result, link_callback=url_converter)
if not status.err:
result.seek(0)
return FileResponse(result, content_type='application/pdf')
记住
collectstatic
文件,以便 Django 可以正确找到您的文件。