5

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 %}">
Shehzad009
  • 1,547
  • 6
  • 28
  • 42
  • next, you get the full error traceback or behavior you're having and add it to the question, so that everybody can see what happens when you try it this way. – nosklo Jan 13 '11 at 10:53
  • There's no `return` in `render_to_pdf(template_src, context_dict)`. Could you include more of the actual code you're actually using? – S.Lott Jan 13 '11 at 12:16

2 Answers2

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
zsquare
  • 9,916
  • 6
  • 53
  • 87
0

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?

Jordan Reiter
  • 20,467
  • 11
  • 95
  • 161
  • reiter, I get an invalid syntax error on the last line "except Exception('PDF error')" - so not sure why. Also, there was another syntax error on line has a syntax error where it says what pdf = ... There is an extra close bracket that should not be there. – Shehzad009 Jan 14 '11 at 09:54
  • Sorry, that's what I get for cut and pasting from a stranger's code. Should be fixed now. – Jordan Reiter Jan 18 '11 at 18:30