rendering a ReportLab pdf built from SimpleDocTemplate

Ben Griffiths picture Ben Griffiths · Feb 21, 2011 · Viewed 9.6k times · Source

I've a got a django app that currently generates pdfs using a canvas that the user can download. I create a StringIO buffer, do some stuff and then send call response.write.

# Set up response
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=menu-%s.pdf' % str(menu_id)
# buffer
buff = StringIO()

# Create the pdf object
p = canvas.Canvas(buff)

# Add some elements... then

p.showPage()
p.save()

# Get the pdf from the buffer and return the response
pdf = buff.getvalue()
buff.close()
response.write(pdf)

I now want to build my pdf using platypus and SimpleDocTemplate and have written this

# Set up response
response = HttpResponse(mimetype='application/pdf')
pdf_name = "menu-%s.pdf" % str(menu_id)
response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name

menu_pdf = SimpleDocTemplate(pdf_name, rightMargin=72,
                            leftMargin=72, topMargin=72, bottomMargin=18)

# container for pdf elements
elements = []

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

# Add the content as before then...

menu_pdf.build(elements)
response.write(menu_pdf)
return response

But this doesn't work, it creates a bad pdf that cannot be opened. I presume the line

response.write(menu_pdf)

is incorrect.

How do I render the pdf?

Answer

G Gordon Worley III picture G Gordon Worley III · Feb 22, 2011

Your error is actually a pretty simple one. It's just a matter of trying to write the wrong thing. In your code, menu_pdf is not a PDF, but a SimpleDocTemplate, and the PDF has been stored in pdf_name, although here I suspect pdf_name is a path name rather than a file object. To fix it, change your code to use a memory file like you did in your original code:

# Set up response
response = HttpResponse(mimetype='application/pdf')
pdf_name = "menu-%s.pdf" % str(menu_id)
response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name

buff = StringIO()

menu_pdf = SimpleDocTemplate(buff, rightMargin=72,
                            leftMargin=72, topMargin=72, bottomMargin=18)

# container for pdf elements
elements = []

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

# Add the content as before then...

menu_pdf.build(elements)
response.write(buff.getvalue())
buff.close()
return response

I'm not sure if using file objects rather than paths with Platypus is mentioned in the documentation, but if you dig into the code you'll see that it is possible.