Warning, this article is technical… If you don’t care about python development, skip it 🙂

You want to create pdf reports, send letters or any other action needing pdf documents ?

If you are a python expert, you’ll have surely heard about ReportLab. Yeah, I know, to use it, you need to code it, and when you change your template you have to do everything again.

A solution to that, is to use RML, an xml language done by the company that created reportlab. RML permits to use stylesheets, and to have an xml document that generates the pdf (just like html).

There is a problem with RML. The reference handler, (Reportlab RML) isn’t free (neither as in beer nor as in speech)… But the fabulous guys at Z3C did an open source handler for RML, z3c.rml !

Just one problem : when you create big documents, the process will crawl, take all your ram and die badly. The solution to that aspect ? using PyPDF to join pdf files into one (one template per document part).

Now, here comes the real deal : we will template that xml, just like we would do for html, using an xml templating language : genshi.

To ease that task, I’ve made a little python lib that handles the templating, the merging of various documents into one and much more.

We passed various variables and a data list (testdata) containing the numbers 0 to 9, 100 times: [[0, …, 9], …, [0, …, 9]].
Please note that all keyword arguments passed to the function (beside template_file or template_string) are passed to the genshi template, and accessible as root variables there.

Needing to add another secion in the document with the same template ? No problem !

Eventually, we will create a single pdf files, with all the content, finalising the factory (cleaning it):

factory.render_document('test.pdf')
factory.cleanup()

And voilà! It’s as simple as that.

How to install it ?

To install pyjon.reports it’s very simple: just type easy_install pyjon.reports in your console (in a virtual env or globally), and you’ll be able to generate pdf documents in your applications in less than 5 minutes.

4 Comments

I have little knowledge in python, and trying to construct a simple template html file(a dynamic html file to send with mail, as a report from one tool). For this special purpose i dont need a entire framework to construct a single template rendering…..other documents regarding the python templates are seems framework centric. Here I want only template specific tutorials….

Your blog gave me some good points towards this, and the point of creating pdf reports …nice …:)
Thanks,
Haridas N.

My twin and I have been working on a game for the past year or so using cocos2D and we’re getting close to releasing it. I would love to get it ported over when it’s ready. What needs to be done to make that happen?