Django,ReportLab PDF生成附于电子邮件 [英] Django, ReportLab PDF Generation attached to an email

查看:176
本文介绍了Django,ReportLab PDF生成附于电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django和ReportLab生成PDF并将其附加到电子邮件中的最佳方法是什么?

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

我使用的是SimpleDocTemplate,可以附加生成的PDF对我的HttpResponse - 这是伟大的,但我无法找到如何准确地添加相同的附件到电子邮件:

I'm using a SimpleDocTemplate and can attach the generated PDF to my HttpResponse - which is great, but I'm having trouble finding out how to exactly add that same attachment to an email:

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
    doc = SimpleDocTemplate(response, pagesize=letter)
    Document = []

...通过将表格附加到文档...来制作我的pdf ...

... make my pdf by appending tables to the Document...

  doc.build(Document)
  email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
  email.attach('invoice.pdf', ???, 'application/pdf')
  email.send()

m只是不知道如何将我的pdf文档翻译成一个blob,以便email.attach可以接受它,并且email.send可以发送它。

I'm just not sure how to translate my pdfdocument as a blob so that email.attach can accept it and email.send can send it.

任何想法?

推荐答案

可以 - 我根据拼凑了几件事情来计算出来 -

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

首先 - 我的要求:
- 我只想在内存中创建PDF - 我不希望文件挂起来,因为占用空间,我不想要什么可能是敏感数据挂在在服务器上未受保护。

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.

所以 - 我选择了ReportLab和Platypus功能来生成我的文档。我现在投入了足够的时间,这很简单。所以这里是我的方法,让我在ReportLab中使用DocTempates,允许我使用Django的电子邮件功能来发送电子邮件。

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.

这是我如何做的:

 # 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()

我从Web生成到电子邮件生成的问题正在获得可以附加到电子邮件中的正确对象。创建缓冲区,然后从缓冲区中抓取数据为我...

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

这篇关于Django,ReportLab PDF生成附于电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆