4

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

这是我尝试过的:

def send_pdf(request):
minutes = int(request.user.tagging.count()) * 5
testhours = minutes / 60
hours = str(round(testhours, 3))
user_info = {
    "name": str(request.user.first_name + ' ' + request.user.last_name),
    "hours": str(hours),
    "taggedArticles": str(request.user.tagging.count())
}
html = render_to_string('users/certificate_template.html',
                        {'user': user_info})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name'] + '.pdf')
pdf = weasyprint.HTML(string=html).write_pdf(response, )
from_email = 'our_business_email_address'
to_emails = ['Reciever1', 'Reciever2']
subject = "Certificate from INC."
message = 'Enjoy your certificate.'
email = EmailMessage(subject, message, from_email, to_emails)
email.attach("certificate.pdf", pdf, "application/pdf")
email.send()
return HttpResponse(response, content_type='application/pdf')

但它返回一个错误TypeError: expected bytes-like object, not HttpResponse

如何从 HTML 模板生成 pdf 文件并将其发送到电子邮件?

更新:现在有了这个更新的代码,它正在生成 pdf 并发送一封电子邮件,但是当我从收到的电子邮件中打开附加的 pdf 文件时,它说unsupported file formate data

这是更新的代码:

def send_pdf(request):
minutes = int(request.user.tagging.count()) * 5
testhours = minutes / 60
hours = str(round(testhours, 3))
user_info = {
    "name": str(request.user.first_name + ' ' + request.user.last_name),
    "hours": str(hours),
    "taggedArticles": str(request.user.tagging.count())
}
html = render_to_string('users/certificate_template.html',
                        {'user': user_info})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name']) + '.pdf'
pdf = weasyprint.HTML(string=html).write_pdf()
from_email = 'arycloud7@icloud.com'
to_emails = ['abdul12391@gmail.com', 'arycloud7@gmail.com']
subject = "Certificate from Nami Montana"
message = 'Enjoy your certificate.'
email = EmailMessage(subject, body=pdf, from_email=settings.EMAIL_HOST_USER, to=to_emails)
# email.attach("certificate.pdf", pdf, "application/pdf")
email.content_subtype = "pdf"  # Main content is now text/html
email.encoding = 'ISO-8859-1'
email.send()
return HttpResponse(pdf, content_type='application/pdf')

请帮帮我!

提前致谢!

4

4 回答 4

5

这是上述代码的完整工作版本:

    user_infor = ast.literal_eval(ipn_obj.custom)
    if int(user_infor['taggedArticles']) > 11:
        # generate and send an email with pdf certificate file to the user's email
        user_info = {
            "name": user_infor['name'],
            "hours": user_infor['hours'],
            "taggedArticles": user_infor['taggedArticles'],
            "email": user_infor['email'],
        }
        html = render_to_string('users/certificate_template.html',
                                {'user': user_info})
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name']) + '.pdf'
        pdf = weasyprint.HTML(string=html, base_url='http://8d8093d5.ngrok.io/users/process/').write_pdf(
            stylesheets=[weasyprint.CSS(string='body { font-family: serif}')])
        to_emails = [str(user_infor['email'])]
        subject = "Certificate from Nami Montana"
        email = EmailMessage(subject, body=pdf, from_email=settings.EMAIL_HOST_USER, to=to_emails)
        email.attach("certificate_{}".format(user_infor['name']) + '.pdf', pdf, "application/pdf")
        email.content_subtype = "pdf"  # Main content is now text/html
        email.encoding = 'us-ascii'
        email.send()
于 2018-03-12T08:05:58.520 回答
3

从 Weasysprint 文档中可以看出,调用方法write_pdf()会将文档呈现为单个File.

http://weasyprint.readthedocs.io/en/stable/tutorial.html

一旦你有了一个 HTML 对象,调用它的 write_pdf() 或 write_png() 方法来获取单个 PDF 或 PNG 文件中呈现的文档。

此外,他们提到

如果没有参数,这些方法会在内存中返回一个字节字符串。

因此,您可以获取其 PDF 字节字符串并将其用于附件或传递文件名以将 PDF 写入其中。

有一点,您还可以将可写的类似文件的对象发送到write_pdf().

如果您传递文件名或可写的类似文件的对象,它们将直接在那里写入。

您可以像这样生成并附加 PDF 文件:

pdf = weasyprint.HTML(string=html).write_pdf()
...
email.attach("certificate.pdf", pdf, "application/pdf")

如果成功,您也可以发送 200 响应,如果失败,您也可以发送 500。

说明 关于 SMTP 服务器

通常,您需要一个 SMTP 邮件服务器来将您的邮件中继到您的目的地。

正如您从 Django文档 send_mail中看到的,需要一些配置

使用 EMAIL_HOST 和 EMAIL_PORT 设置中指定的 SMTP 主机和端口发送邮件。EMAIL_HOST_USER 和 EMAIL_HOST_PASSWORD 设置(如果设置)用于对 SMTP 服务器进行身份验证,EMAIL_USE_TLS 和 EMAIL_USE_SSL 设置控制是否使用安全连接。

然后,您可以使用send_mail()以下参数将您的消息中继到本地 SMTP 服务器。

send_mail(主题,消息,from_email,receiver_list,fail_silently=False,auth_user=None,auth_password=None,connection=None,html_message=None)

注意:不要错过认证参数。

于 2018-03-11T05:17:39.373 回答
1

这段代码对我有用

    template = get_template('admin/invoice.html')
    context = {
        "billno": bill_num,
        "billdate": bill_date,
        "patientname": patient_name,
        "totalbill": total_bill,
        "billprocedure": invoice_cal,

    }

    html  = template.render(context)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)#, link_callback=fetch_resources)
    pdf = result.getvalue()
    filename = 'Invoice.pdf'
    to_emails = ['receiver@gmail.com']
    subject = "From CliMan"
    email = EmailMessage(subject, "helloji", from_email=settings.EMAIL_HOST_USER, to=to_emails)
    email.attach(filename, pdf, "application/pdf")
    email.send(fail_silently=False)
于 2021-06-06T15:58:56.507 回答
0

基于@Rishabh gupta 答案:

import io

from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from weasyprint import HTML

context = { "name": 'Hello', }
html_string = render_to_string('myapp/report.html', context)
html = HTML(string=html_string)
buffer = io.BytesIO()
html.write_pdf(target=buffer)
pdf = buffer.getvalue()

email_message = EmailMultiAlternatives(
    to=("youremailadress@gmail.com",),
    subject="subject test print",
    body="heres is the body",
)
filename = 'test.pdf'
mimetype_pdf = 'application/pdf'
email_message.attach(filename, pdf, mimetype_pdf)
email_message.send(fail_silently=False)  # TODO zzz mabye change this to True

于 2021-09-14T17:15:37.393 回答