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

  1. PDF generation directly using HTML by perenzo 7 years ago
  2. Custom 'save' method, automate creating pdf file from entry. by I159 3 years, 6 months ago
  3. View mixin and utils to generate PDF documents from html using xhtml2pdf by frankban 3 years, 6 months ago
  4. Something like list_detail generic view but returns PDF document instead by aurelije 6 years, 6 months ago
  5. Download images as png or pdf by gkelly 7 years, 12 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.