Django pdf question with pisa

心不动则不痛 提交于 2019-12-21 17:46:34

问题


I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so far what I have done.

EDIT: Here is my latest url, views & template.

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

In a template, I have this tag.

<a href="{% url c2duo.views.render_pdf invoices.pk %}">

回答1:


I dont know how much this will help, but this is the function i use to render the 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



回答2:


Just for fun, try this instead:

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)

If you still encounter an error, I'm guessing the error might be in pisa. Are you sure it's up to date?



来源:https://stackoverflow.com/questions/4678723/django-pdf-question-with-pisa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!