Cookie notice
Ok This website uses cookies to manage logged in users and to gather statistics on how people use the site.
We also use them to implement this annoying cookie notice, otherwise you'd have to read it on every page. ;)

RML2PDF with Django

You should download the ZIP archive of the entire project to get the full code listing and to try it out.

(5.9 KB, 01 Dec 2010, md5 checksum=0279b9699042e868079b168e1362d7cc)


Report Markup Language™ is an XML-style language created by ReportLab that describes the precise look of a printed page. This sample application shows how you can use the RML2PDF conversion library from within the Django web framework.

RML is commercial software which is part of the ReportLab PLUS package. You will need to create a user account to download a trial version of ReportLab PLUS.

It's simple to integrate Report Markup Language into your Django project, and add great looking dynamic PDF output to your website. RML lets you add complex and great looking PDF document output to your site, with the minimum of development time.

This is a simple demonstration of how to merge an RML 'template' with user-submitted, variable content - in this case the user's name - and convert the output into a PDF which is returned to the browser.

This project simply reads the template file 'hello.rml' into memory, and then substitutes a particular string using the Django templating engine. It then uses the rml2pdf python module's 'go' method to create a PDF from the RML. The resulting PDF is turned into a byte stream and returned to the browser.

Code overview

Here's a walkthrough of the most interesting parts of the sample application. The downloadable archive also contains a README file and commented code.

The code generates a PDF file with a single page containing the text "Welcome <name> to the world of RML", where <name> is a variable that you submit through a Django form. The form is really simple with one field to submit:

<p>Enter your name:</p>
<form action="/getPDF/" method="get">
    <input type="text" name="q">
    <input type="submit" value="Make a PDF">

A function in loads the RML template into a Template object and substitutes the variable.

t = Template(open('hello.rml').read())
c = Context({"name": name})
rml = t.render(c)

The resulting RML is passed into the rml2pdf.go() to generate the PDF.

buf = cStringIO.StringIO()
rml2pdf.go(rml, outputFileName=buf)
pdfData =

Set the relevant properties for the response object and return the PDF to the browser.

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=output.pdf'
return response