我正在尝试使用wkhtmltopdf
生成PDF并通过电子邮件将其作为附件发送。以下是我的观点:
class MYPDFView(View):
template = 'pdftemplate.html'
def get(self, request):
data = {}
response = PDFTemplateResponse(
request=request,
template=self.template,
filename="hello.pdf",
context= data,
show_content_in_browser=True,
cmd_options={'margin-top': 10,
"zoom":1,
"viewport-size" :"1366 x 513",
'javascript-delay':1000,
'footer-center' :'[page]/[topage]',
"no-stop-slow-scripts":True},
)
email = EmailMessage(
'Hello',
'Body goes here',
'from@example.com',
['to1@example.com', 'to2@example.com'],
['bcc@example.com'],
reply_to=['another@example.com'],
headers={'Message-ID': 'foo'},
attachments=[('demo.pdf', response, 'application/pdf')]
)
email.send()
return response
我得到的错误是TypeError
,它显示expected bytes-like object, not PDFTemplateResponse
。
我假设我的response
变量,我将返回查看我的PDF并不是我应该在attachments
属性中提供的类型。
我的问题是,如何在attachments
三联中提供PDFTemplateResponse之前将其转换为类字节对象?
答案 0 :(得分:1)
return_file = "tmp/hello.pdf"
temp_file = response.render_to_temporary_file("hello.html")
wkhtmltopdf(pages=[temp_file.name], output=return_file)
email.attach_file(return_file)