Login

Create PDF files using rml and django templates

Author:
mporrato
Posted:
June 29, 2007
Language:
Python
Version:
.96
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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

prio (on July 17, 2007):

Hi,

You seem to be missing an import line:

from django.template import loader, Context

#

mporrato (on July 20, 2007):

Oops! I stripped too many lines from my original code. I just updated the snippet.

Thank you prio!

#

Please login first before commenting.