将django中的xhtml2pdf数据作为变量获取

时间:2015-01-22 18:14:35

标签: python django pdf xhtml2pdf

我通过制作类似的东西在我的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文档中找不到任何内容。 你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

你已经在这里做到了:

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