<p>为了生成PDF,您可以使用xhtml2pdf库。
<br/><br/>函数返回response object,只需传递模板名称、上下文数据和pdfname。在</p>
<pre><code>def fetch_resources(uri, rel):
"""
Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link element.
`rel` gives a relative path, but it's not used here.
"""
if uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT,
uri.replace(settings.MEDIA_URL, ""))
elif uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
else:
path = os.path.join(settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
if not os.path.isfile(path):
path = os.path.join(settings.MEDIA_ROOT,
uri.replace(settings.MEDIA_URL, ""))
if not os.path.isfile(path):
raise UnsupportedMediaPathException(
'media urls must start with %s or %s' % (
settings.MEDIA_ROOT, settings.STATIC_ROOT))
return path
def render_to_pdf_response(template_name, context=None, pdfname='test.pdf'):
file_object = HttpResponse(mimetype='application/pdf')
file_object['Content-Disposition'] = 'attachment; filename=%s' % pdfname
template = get_template(template_name)
html = template.render(Context(context))
pisa.CreatePDF(html.encode("UTF-8"), file_object , encoding='UTF-8',
link_callback=fetch_resources)
return file_object
</code></pre>
<p>以下是安装说明:<a href="https://pypi.python.org/pypi/xhtml2pdf/" rel="nofollow">https://pypi.python.org/pypi/xhtml2pdf/</a></p>