python - 如何在 Django 中将 PDFTemplateResponse 转换为类似字节的对象?

标签 python django wkhtmltopdf

我正在尝试使用 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,它表示预期的类似字节的对象,而不是PDFTemplateResponse

我假设我返回以查看 PDF 的 response 变量不是我应该在 attachments 属性中提供的类型。

我的问题是,如何在附件三元组中提供 PDFTemplateResponse 之前将其转换为类似字节的对象?

最佳答案

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)

Source

关于python - 如何在 Django 中将 PDFTemplateResponse 转换为类似字节的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49851702/

相关文章:

python - 在 python 中为一对分布生成 MLE

python - 如何让机器人休眠并停止响应命令(或 on_messages)

python - 在mac上使用python访问外部硬盘驱动器中的文件

python - Django - 'ContactForm' 对象没有属性 'get'

python - AppEngine 和 Django : including a template file

pdf-generation - pdfkit 在 OS X 和 Ubuntu 上呈现 PDF 文档时使用不同的字体

python - 为什么我的 scrapy 蜘蛛不抓取任何东西?

python - Django - 装饰器和错误信息

node.js - 在内存中使用 node-wkhtmltopdf 和 HTML

wkhtmltopdf - 相同的配置不同的输出