How to Generate a PDF with PISA in Django

PostImage HowtoGenerateaPDFwithPISAinDjango DesktopTyping - How to Generate a PDF with PISA in Django

So, you need to generate a PDF in Django with PISA? No problem! Here at 20 Seven, we have had to do it many times and we came up with a simple easy-to-use guide anyone can use! Are you ready?

Let’s get started!

What you need before you get cracking

A copy of PISA
A copy of Reportlab

Download the files and install both on your device. Done? Cool, now we can move on to the next steps.

The inner workings

Now that you have PISA and Reportlab installed, you need to create a standard HTML template for your view. Here is a handy sample:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

<h2>{{ article.articletitle|upper }}</h2>
<div>{{ article.content }}</div>
<div id=”footerblock”>
{%block pager %}

Keep in mind that the pager block is going to paginate your pdf. Other users should use the instructions below (article functionality will grab the article from the database and send it to write_pdf in order to generate the pdf from the HTML created in the previous section).

import HTTP from Django
import get_template from django.template.loader
import Context from django.template
import ho.pisa as Pisa
import cStringIO as StringIO
import CGI

def write_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html  = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode(“UTF-8”)), result)
if not pdf.err:
return http.HttpResponse(result.getvalue(), \
return http.HttpResponse(‘Gremlin’s ate your pdf! %s’ % cgi.escape(html))

def article(request, id):
article = get_object_or_404(Article, pk=id)

return write_pdf(‘dtd/pdf/template.html’,{
‘pagesize’ : ‘A4’,
‘article’ : article})

We would suggest using UTF-8 as ISO-8859-1 may blow up on coding.

Note: Standard page size you will get when generating a pdf via PISA on Django is A4. If you want to change this, write_pdf can get a template that works with your specific context and encode it.

The Reportlab API will allow you to customize and prettify your pdf easily with awesome canvas capabilities.

PostImage HowtoGenerateaPDFwithPISAinDjango laptop white - How to Generate a PDF with PISA in Django

And that’s a wrap! We hope you have found this guide very helpful. If you love coding and building and learning new stuff, check out this article. Have fun playing around!

Related posts

Leave a Comment