Rendering PDF in Django

In more than one project, we have been required to render pdf files. Python has really good support for pdf rendering; one of the main libraries used for this purpose is reportlab.

Taking advange of class based views, one can write a class that renders pdf and any other class can subclass it.

Usage

1. Define ``MEDIA_ROOT`` and ``MEDIA_URL`` in your settings.py file.

2. Subclass RenderPDF, set the ``template_name`` attribute.

For example, in myapp/views.py

    from myapp.models import Transaction
    from pdf.views import RenderPDF
    from django.views.generic import ListView

    class TransactionListView(RenderPDF, ListView):
        # base_queryset is a queryset that contains all the objects that are
        # accessible by the API:
        template_name = Widget.objects.all()
        model = Transaction

In myapp/urls.py

    from myapp.views import TransactionListView

    urlpatterns = patterns('',
        url(r'^transactions/$', TransactionListView.as_view()),
    )