[Solved]-Django, ReportLab PDF Generation attached to an email

6👍

OK – I figured it out based on piecing a few things together –

First off – my requirements:
– I only wanted to create the PDFs in memory – I don’t want the files hanging around, as they take up space, and I don’t want what might be sensitive data hanging around unprotected on the server.

So – I picked ReportLab and Platypus functionality for generating my documents. I’ve invested enough time into it now, that’s it’s easy. So here’s my approach that lets me use the DocTempates in ReportLab, allows me to use Django’s email capabilities to send emails.

Here’s how I’m doing it:

 # Create the PDF object, using the buffer object as its "file."
  buffer = StringIO()
  doc = SimpleDocTemplate(buffer, pagesize=letter)
  Document = []

  # CRUFT PDF Data

  doc.build(Document)
  pdf = buffer.getvalue()
  buffer.close()

  email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
  email.attach('invoicex.pdf', pdf , 'application/pdf')
  email.send()

My issue from moving from web generation to email generation was getting the right object that could be “attached” to an email. Creating a buffer, then grabbing the data off the buffer did it for me…

10👍

Using ReportLab


try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.units import inch

def createPDF(request):
 x=100
 y=100
 buffer=StringIO()
 p=canvas.Canvas(buffer,pagesize=letter)
 p.drawString(x,y,"HELLOWORLD")
 p.showPage()
 p.save() 
 pdf=buffer.getvalue()
 buffer.close() 
 return pdf

def someView(request):
 EmailMsg=mail.EmailMessage(YourSubject,YourEmailBodyCopy,'email@email.com',["email@email.com"],headers={'Reply-To':'email@email.com'})
 pdf=createPDF(request)
 EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
 EmailMsg.send()

Works perfectly!!

3👍

I don’t see where your blob is rendered, so I can’t advise you on how to import it. I’ve gotten great results using Pisa and StringIO:

import ho.pisa as pisa
import StringIO
from django.template.loader import render_to_string
from django.core.mail import EmailMessage

render = render_to_string("books/agreement/agreement_base.html",
                              { "title": book.title,
                                "distribution": book.distribution_region })
out = StringIO.StringIO()
pdf = pisa.CreatePDF(StringIO.StringIO(render), out)
email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
email.attach('agreement.pdf', out.getvalue(), 'application/pdf')
email.send()

That said, if your PDF exists as an independent and persistent document on your filesystem, couldn’t you just:

email.attach('agreement.pdf', open('agreement.pdf', 'rb').read(), 'application/pdf')

Leave a comment