1

I generate PDF files in my django app by making something like:

context = Context({'data':data_object, 'MEDIA_ROOT':settings.MEDIA_ROOT})
html  = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('UTF-8')), result)
if not pdf.err:
    response = HttpResponse( result.getvalue() )
    response['Content-Type'] = 'application/pdf'
    response['Content-Disposition'] = 'attachment; filename="%s.pdf"'%(title)
    return response

And it works great, when users wants to download the PDF file. However, I am in need to attach this PDF in email message. Thats why I would need to get content of this PDF. I can't find anything in xhtml2pdf docs. Could you help me in resolving it?

dease
  • 2,975
  • 13
  • 39
  • 75

1 Answers1

1

You already do that here:

HttpResponse( result.getvalue() )
# result.getvalue() gives you the PDF file content as a string

...so you can take that and use it in your email sending code

For help with that see here https://stackoverflow.com/a/3363254/202168

example:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate


context = Context({'data':data_object, 'MEDIA_ROOT':settings.MEDIA_ROOT})
html  = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('UTF-8')), result)

if not pdf.err:
    msg = MIMEMultipart(
        From='from@example.com',
        To='to@example.com',
        Date=formatdate(localtime=True),
        Subject="Here's your PDF!"
    )
    msg.attach(MIMEText(result.getvalue()))

    smtp = smtplib.SMTP('smtp.googlemail.com')  # for example
    smtp.sendmail('from@example.com', ['to@example.com'], msg.as_string())
    smtp.close()
Community
  • 1
  • 1
Anentropic
  • 32,188
  • 12
  • 99
  • 147