Django 使用 pisa 生成 PDF 的问题
我想用pisa把一个html模板生成一个pdf文件。我觉得我已经安装了所有需要的包,但似乎遇到了一些问题。下面是我到目前为止所做的视图。
编辑:这是我最新的url、视图和模板。
url.py
(r'^index/render_pdf/(?P<id>\d+)/$', render_pdf),
views.py
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html, id):
invoice_items_list = Invoice_Items.objects.filter(pk=id)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
在一个模板中,我有这个标签。
<a href="{% url c2duo.views.render_pdf invoices.pk %}">
2 个回答
0
为了好玩,试试这个:
def render_to_pdf(template_src, context_dict):
html = "<html><head><title>Title</title></head><body><h1>Hello</h1></body></html>"
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html), result)
if not pdf.err:
return http.HttpResponse("" % (repr(result.getvalue())))
else:
raise Exception("The error was %s" % pdf.err)
如果你还是遇到错误,我猜问题可能出在pisa上。你确定它是最新的吗?
1
我不知道这能帮上多少忙,但这是我用来生成PDF的函数:
def fetch_resources(uri, rel):
"""
Callback to allow pisa/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.
"""
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html):
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result