首页 > 解决方案 > 如何从 html 代码和 pdf 文件以及 sendgrid API V3 uisng python django 生成 pdf

问题描述

我有一个包含模板代码的变量

template = '''
<html>
<div>
Hello world
</div>
</html>
'''

我想生成一个pdf并使用下面的sendgrid代码附加文件

import os
from sendgrid import SendGridAPIClient


template = '''
<html>
<div>
Hello world
</div>
</html>

message = {
    'personalizations': [
        {
            'to': [
                {
                    'email': 'test@example.com'
                }
            ],
            'subject': 'Sending with Twilio SendGrid is Fun'
        }
    ],
    'from': {
        'email': 'test@example.com'
    },
    'content': [
        {
            'type': 'text/plain',
            'value': template
        }
    ]
}
try:
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(str(e))

目前我已经创建了发票模板,现在我想知道如何使用该模板生成 pdf 并将该 pdf 文件附在电子邮件中

我的模板代码太长,所以我不在这里包括它

标签: pythondjangopdfsendgridemail-attachments

解决方案


我使用 PDKFIT 来完成您想要实现的类似操作

我将 HTML 文件创建为模板,然后遍历它们并转换为 PDF

pdfkit 是“离线”的(它不使用在线转换 API),从数据安全 POV 来看,这对我来说非常重要

import pdfkit
import os

files = os.listdir('generated/')

options = {'disable-javascript': None}

for file in files:

       convert = str('generated/' + file)
       converted = str('upload/' + file + ".pdf")
       pdfkit.from_file(convert, converted, options=options)

       os.remove('generated/' + file)
       print(file + " deleted!")

推荐阅读