我正在使用 xhtml2pdf 版本 0.2.4 我遇到了同样的问题,我能够使用这种编码来解决:
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
# PDF
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
然后在我看来,我定义如下:
def download_pdf(request, pk):
item = get_object_or_404(object, id=pk)
if item:
context ={
'item': item
}
template_name = 'template.html'
pdf = render_to_pdf(template_name, context)
return HttpResponse(pdf, content_type='application/pdf')
else:
messages.info(request, 'Item not found')
return redirect('home')
我的 HTML:
{% load static %}
{% load humanize %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/gif" href="{% static 'images/profile.png' %}" />
<title>{{ item.scientific_name}}</title>
<link rel="stylesheet" href="{% static 'style/Bootstrap/css/bootstrap.min.css' %}">
<style>
@page {
size: letter;
margin: 2cm;
@frame footer_frame {
/* Another static Frame */
-pdf-frame-content: footer_content;
left: 50pt;
width: 512pt;
top: 760pt;
height: 50px;
}
table {
-pdf-keep-with-next: true;
}
}
ul {
list-style-type: none;
}
ul li span {
font-weight: bold;
}
</style>