Django, ReportLab PDF Generation attached to an email

后端 未结 3 1809
生来不讨喜
生来不讨喜 2021-02-08 23:43

What\'s the best way to use Django and ReportLab to generate PDFs and attach them to an email message?

I\'m using a SimpleDocTemplate and can attach the generated PDF to

3条回答
  •  清歌不尽
    2021-02-09 00:13

    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...

提交回复
热议问题