我如何从html代码和pdf文件以及sendgrid API V3 uisng python django生成pdf

问题描述 投票:0回答:1

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

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': '[email protected]'
                }
            ],
            'subject': 'Sending with Twilio SendGrid is Fun'
        }
    ],
    'from': {
        'email': '[email protected]'
    },
    '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文件附加到电子邮件中

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

python django pdf sendgrid email-attachments
1个回答
0
投票
我想我正在做您希望通过pdfkit实现的类似操作

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

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

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!")

© www.soinside.com 2019 - 2024. All rights reserved.