Login

Create PDF files using rml and django templates

Author:
mporrato
Posted:
June 29, 2007
Language:
Python
Version:
.96
Tags:
templates pdf rml
Score:
2 (after 2 ratings)

It allows you to create pdf much like normal html code taking advantage of django's template engine. It requires the trml2pdf module from OpenReport and can be used like render_to_response(). prompt specifies if a "save as" dialog should be shown to the user while filename is the name that the browser will suggest in the save dialog.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.http import HttpResponse
from django.template import loader, Context
from trml2pdf import trml2pdf

def pdf_render_to_response(template, context, filename=None, prompt=False):
    response = HttpResponse(mimetype='application/pdf')
    if not filename:
        filename = template+'.pdf'
    cd = []
    if prompt:
        cd.append('attachment')
    cd.append('filename=%s' % filename)
    response['Content-Disposition'] = '; '.join(cd)
    tpl = loader.get_template(template)
    tc = {'filename': filename}
    tc.update(context)
    ctx = Context(tc)
    pdf = trml2pdf.parseString(tpl.render(ctx))
    response.write(pdf)
    return response

More like this

Comments

prio (on July 17, 2007):
<p>Hi,</p> <p>You seem to be missing an import line:</p> <p>from django.template import loader, Context</p>

#

mporrato (on July 20, 2007):
<p>Oops! I stripped too many lines from my original code. I just updated the snippet.</p> <p>Thank you prio!</p>

#

Please login first before commenting.