1

我通过以下方式在我的 django 应用程序中生成 PDF 文件:

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

当用户想要下载 PDF 文件时,它的效果很好。但是,我需要在电子邮件中附加此 PDF。这就是为什么我需要获取此 PDF 的内容。我在 xhtml2pdf 文档中找不到任何内容。你能帮我解决它吗?

4

1 回答 1

1

你已经在这里做到了:

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

...所以你可以把它用在你的电子邮件发送代码中

如需帮助,请参见此处https://stackoverflow.com/a/3363254/202168

例子:

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()
于 2015-01-22T18:36:37.470 回答