Django output pdf using reportlab

Today I implemented the pdf output of the CS outlines. I must say the reportlab was much easier to work with than the java based com.lowagie.text.pdf.PdfWriter. It only took me a few hours to completely reimplement the export to pdf’s in python/django. I will post the code below for those interested in exporting to pdf using django.

The one challenge I faced was to include html formatted textarea output into the pdf with its formatting preserved. So essentially use the XPreformatted class from reportlab but it doesn’t handle wrapping or removal of /r characters from the value. So had to parse it before inserting. Ofcourse I didn’t put the entire code in there as don’t want the world to know the inner workings. Just enough for another person to get a jist of how to export to pdf using django.

def exportPDF(request, course_slug):
''' provides a pdf view of the course '''

response = HttpResponse(mimetype='application/pdf')
filename = '-outline.pdf'
response['Content-Disposition'] = 'filename=' + filename
course = "Course"
_generate_pdf(course, response)
return response

def _generate_pdf(course,output):
#pdf stuff
from reportlab.lib.enums import TA_JUSTIFY, TA_RIGHT, TA_LEFT, TA_CENTER
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table , TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm, inch
from reportlab.lib import colors
from cStringIO import StringIO
from reportlab.platypus import XPreformatted
from django.conf import settings

doc = SimpleDocTemplate(output,pagesize=A4,

OutlinePDF.append(Spacer(1, 12))

def preformat_html_textarea(value,endwidth=135):
''' since reportlab doesn't provide a way to keep the

 of what ever
is entered in the html textarea. This is manual way to text wrap.
import textwrap
new_value = value.replace('
new_values = new_value.split('
result = ""
for line in new_values:
result += textwrap.fill(line,endwidth) + "

return result

Live Run of the code can be seen at: (haven't deployed yet but will be there in a few days after running through some unittests.)


Leave a Reply