我在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文档中找不到任何内容。
您能帮我解决吗?

最佳答案

您已经在这里完成了:

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

关于python - 在Django中获取xhtml2pdf数据作为变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28095880/

10-11 22:15
查看更多