【发布时间】:2020-04-15 02:59:03
【问题描述】:
我有一个 pdfkit PDF,可以作为 Sendgrid 附件正常工作,由以下函数创建:
def wish_lists_pdf(user=current_user):
pdf_heading = "Thank you!"
pdf_subheading = "Please find the Wish Lists you signed up to sponsor listed below."
pdf_context = {
'heading': pdf_heading,
'subheading': pdf_subheading,
'user': user,
}
css = os.path.join(basedir, 'static/main.css')
pdf_content = render_template(
'partials/email_lists_pdf.html', **pdf_context)
path_wkhtmltopdf = app.config['WKHTMLTOPDF_EXE']
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
pdf_file = pdfkit.from_string(
pdf_content, False, configuration=config, css=css)
bytes_file = BytesIO(pdf_file)
return bytes_file
其实sendgrid需要这一行而不是字节编码:
encoded_file = base64.b64encode(pdf_attachment).decode()
按照不同教程的建议,我使用这种编码和 b64 编码进行了尝试。我不太了解编码的目的,所以这可能是我的错误的一些原因。无论如何,这是我想要提供 PDF 文件的路线:
@bp.route('download_lists_pdf/<int:user_id>', methods=['GET'])
def download_lists_pdf(user_id):
user = User.query.filter_by(id=user_id).first()
pdf_file = wish_lists_pdf(user=user)
return send_file(
pdf_file,
as_attachment=True,
attachment_filename="Wish List Reminder Page.pdf",
mimetype='application/pdf',
)
这会下载一个完全空白的 0kb PDF 文件。有人可以帮助我了解如何以允许我从 pdfkit 提供此 PDF 的方式使用 send_file() 吗?同样,作为 Sendgrid 附件,该文件可以正常工作。
如果有帮助,这里是 sendgrid 附件配置...
context = {
'heading': heading,
'subheading': subheading,
'user': user,
}
message = Mail(
from_email=app.config['ADMIN_EMAIL'],
to_emails=app.config['EMAIL_RECIPIENTS'],
subject=email_subject,
html_content=render_template('partials/email_lists.html', **context),
)
encoded_file = base64.b64encode(pdf_attachment).decode()
attached_file = Attachment(
FileContent(encoded_file),
FileName('Wish List Reminder Page.pdf'),
FileType('application/pdf'),
Disposition('attachment')
)
message.attachment = attached_file
sg = SendGridAPIClient(app.config['SENDGRID_API_KEY'])
response = sg.send(message)
提前感谢您的帮助。
编辑:在下面尝试但没有用
bytes_file = BytesIO(pdf_file)
return bytes(bytes_file), 200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline; filename="Wish List reminder sheet.pdf"'}
【问题讨论】:
标签: flask file-transfer pdfkit