开发者

Django pdf question with pisa

开发者 https://www.devze.com 2023-02-04 23:51 出处:网络
I want togenerate 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

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开发者_C百科.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 %}">


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消