【问题标题】:How to send waysiprint pdf by mail如何通过邮件发送waysiprint pdf
【发布时间】:2020-08-21 16:39:29
【问题描述】:

我正在尝试使用 Wea​​syprint python 包从 HTML 模板生成一个 pdf 文件,我需要使用它通过电子邮件发送。

这是我尝试过的:

views.py:

       user_info = {
            "name": 'nadjib',
        }
        html_string = render_to_string('Proformas/command.html')

        html = HTML(string=html_string,base_url=request.build_absolute_uri())
        # html.write_pdf(target='/tmp/mypdf.pdf');

        fs = FileSystemStorage('/tmp')
        with fs.open('mypdf.pdf') as pdf:
          response = HttpResponse(pdf, content_type='application/pdf')
          response['Content-Disposition'] =  'filename="Commande.pdf"'
          pdf = weasyprint.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(
              stylesheets=[weasyprint.CSS(string='body { font-family: serif}')])
          to_emails = ['nadjzdz@gmail.com']
          subject = "SH INFOR FACTURE"
          email = EmailMessage(subject, body=pdf, from_email='attaazd@gmail.com', to=to_emails)
          email.attach("Commande".format(user_info['name']) + '.pdf', pdf, "application/pdf")
          email.content_subtype = "pdf"  # Main content is now text/html
          email.encoding = 'us-ascii'
          email.send()
        return response

pdf 渲染成功,但没有通过邮件发送?

【问题讨论】:

    标签: django weasyprint


    【解决方案1】:
    from weasyprint import HTML
    from django.template.loader import render_to_string
    from django.core.mail import send_mail, EmailMultiAlternatives
    
    
    mail = EmailMultiAlternatives(
        'title',
        'text',
        from_email,
        [to_email,],
    )
    mail.attach_alternative(html_content, "text/html")
        
    render_from_template = render_to_string('template.html', context={'context': 'context'})
    pdf_file = HTML(string=file)
    
    mail.attach(f'ticket.pdf', pdf_file.write_pdf(), 'application/pdf')
    
    mail.send()
    

    编辑: 你也可以使用 get_template()

    from django.template.loader import render_to_string, get_template
    
    def create_pdf(context):
    
    
        template_name = 'template.html'
        template = get_template(template_name)
        html = template.render(context)
        pdf_binary = HTML(string=html).write_pdf()
    
        return pdf_binary
    
    context = {'foo':'bar'}
    mail.attach(f'ticket.pdf', create_pdf(context), 'application/pdf')
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2023-03-06
      • 1970-01-01
      • 2015-06-21
      • 2023-03-10
      • 2013-01-06
      • 1970-01-01
      • 2021-12-18
      • 2018-03-31
      相关资源
      最近更新 更多