python - 如何从 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 文件附在电子邮件中
我的模板代码太长,所以我不在这里包括它
解决方案
我使用 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!")
推荐阅读
- java - 使用任何文件附加程序的 Log4j 每日轮换和每月保留
- git - 使用 git hooks 将 vue-cli 项目的 dist 目录推送到 nginx 服务器的子文件夹
- c# - soapAction 中的空间获得 HTML 编码并破坏 WCF 服务客户端
- python - 每次加载表单时如何在Flask中运行路由功能
- python - 如何在 Python 项目中使用其他类的属性
- javascript - 如何在单个 json 文件中个性化 mysql 行?
- css - 按钮下方和右侧的线
- java - 在数据库表中使用编码字符串
- python - 什么是python中等效的php编码方法
- java - 为什么递归中的值没有改变?