【问题标题】:Get xhtml2pdf data in django as variable在 django 中获取 xhtml2pdf 数据作为变量
【发布时间】:2015-01-22 18:14:34
【问题描述】:

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

【问题讨论】:

    标签: python django pdf xhtml2pdf


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2016-01-26
      • 1970-01-01
      • 2017-05-07
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多