我正在使用 wkhtmltopdf 包装器在 Django 1.6 中将模板生成为 PDF。当我想在之后显示 PDF 或使用 HttpResponse 发送 PDF 文件以供下载时,它工作正常,但我想做的是在我的 tmp 文件夹中创建文件并将其附加到电子邮件中。
我不确定如何实现这一目标。
# views.py
context = {
'products_dict': products_dict,
'main_categories': main_categories,
'user_category': user_category
}
response = PDFTemplateResponse(request=request,
context=context,
template="my_template.html",
filename="filename.pdf",
show_content_in_browser=True,
cmd_options={'encoding': 'utf8',
'quiet': True,
'orientation': 'landscape',
}
)
return response
上面的代码完全按照我想要的方式生成 PDF。问题是我不想在浏览器中显示 PDF 或开始下载(我不想返回响应)。我只想创建它,然后将文件附加到这样的电子邮件中:
email = EmailMessage()
email.subject = "subject"
email.body = "Your PDF"
email.from_email = "sender@gmail.com"
email.to = [ "receiver@gmail.com", ]
# Attach PDF file to the email
email.attach_file(my_pdf_file_here)
# Send email
email.send()
我尝试使用子流程,但似乎无法在生成 PDF 之前将上下文发送到我的模板以呈现它。
编辑(解决方案):感谢 Daniel Roseman 帮助实现我想要的目标。我确实在这里使用了 wkhtmltopdf 的测试文件:http://pydoc.net/Python/django-wkhtmltopdf/1.1/wkhtmltopdf.tests.tests/
在我看来,这是我所做的:
order = Order.objects.get(id=order_id)
return_file = "tmp/" + 'order' + str(order_id) + '.pdf'
context = {
'order' : order,
'items' : order.ordered_products.all()
}
response = PDFTemplateResponse(request=request,
context=context,
template="'products/order_pdf.html'",
cmd_options={ 'encoding': 'utf8',
'quiet': True
}
)
temp_file = response.render_to_temporary_file("products/order_pdf.html")
wkhtmltopdf(pages=[temp_file.name], output=return_file)
然后您可以像这样在 email.attach() 方法中使用 return_file:
email.attach_file(return_file)
您也可以在 wkhtmltopdf 方法中省略输出参数。然后该方法将返回输出并在 attach_file() 方法中使用此输出。
最佳答案
您的问题不在于 wkhtmltopdf,而在于 django-wkhtmltopdf,它提供了一些使用 wkhtmltopdf 呈现的基于类的 View 。如果您不需要 View ,则不需要使用它们:您可以自己呈现模板并将结果字符串传递给命令行 wkhtmltopdf 工具。
看起来 django-wkhtmltopdf 库确实提供了一些实用函数(在 utils 目录中),这可能会使最后一个阶段更容易一些。
关于python - 在不返回 HttpResponse 或使用 URL 的情况下使用 wkhtmltopdf 创建 PDF 文件的任何方法?我只想将 PDF 文件附加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24289477/