Django、ReportLab PDF 生成附加在电子邮件中

发布于 2024-10-06 04:06:16 字数 992 浏览 1 评论 0原文

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

我正在使用 SimpleDocTemplate,并且可以将生成的 PDF 附加到我的 HttpResponse - 这很棒,但我无法找到如何将相同的附件准确添加到电子邮件中:

    # 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 = []

...通过将表格附加到文档...

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

我只是不确定如何将我的 pdfdocument 翻译为 blob,以便 email.attach 可以接受它并且 email.send 可以发送它。

有什么想法吗?

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 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 = []

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

  doc.build(Document)
  email = EmailMessage('Hello', 'Body', '[email protected]', ['[email protected]'])
  email.attach('invoice.pdf', ???, 'application/pdf')
  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.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋意浓 2024-10-13 04:06:16

使用 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 protected]',["[email protected]"],headers={'Reply-To':'[email protected]'})
 pdf=createPDF(request)
 EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
 EmailMsg.send()

效果非常好!

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 protected]',["[email protected]"],headers={'Reply-To':'[email protected]'})
 pdf=createPDF(request)
 EmailMsg.attach('yourChoosenFileName.pdf',pdf,'application/pdf')
 EmailMsg.send()

Works perfectly!!

仙气飘飘 2024-10-13 04:06:16

好的 - 我根据将一些事情拼凑在一起找到了它 -

首先 - 我的要求:
- 我只想在内存中创建 PDF - 我不希望文件闲置,因为它们占用空间,而且我不希望敏感数据在服务器上不受保护地闲置。

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

我是这样做的:

 # 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', '[email protected]', ['[email protected]'])
  email.attach('invoicex.pdf', pdf , 'application/pdf')
  email.send()

从网络生成转向电子邮件生成,我的问题是获取可以“附加”到电子邮件的正确对象。创建一个缓冲区,然后从缓冲区中获取数据对我来说是这样......

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', '[email protected]', ['[email protected]'])
  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...

獨角戲 2024-10-13 04:06:16

我看不到你的 blob 在哪里渲染,所以我无法建议你如何导入它。我使用 Pisa 和 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', '[email protected]', ['[email protected]'])
email.attach('agreement.pdf', out.getvalue(), 'application/pdf')
email.send()

也就是说,如果您的 PDF 作为独立且持久的文档存在于您的文件系统上,您难道不能:

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

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', '[email protected]', ['[email protected]'])
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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文