【问题标题】:expected str, bytes or os.PathLike object, not pisaContext预期的 str、bytes 或 os.PathLike 对象,而不是 pisaContext
【发布时间】:2018-05-22 19:30:09
【问题描述】:

我正在尝试通过电子邮件发送 PDF:

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return pdf
    return None

在我的观点中:

pdf = render_to_pdf('expenses/pdf_report.html', data)
mail.attach_file(pdf)
mail.send()

我收到此错误:

预期的 str、字节或 os.PathLike 对象,而不是 pisaContext

如何获取 str 或 bytes 而不是 pisaContext

【问题讨论】:

  • 您必须在您的 render_to_pdf() 中返回结果:return HttpResponse(result.getvalue(), content_type='application/pdf')
  • @Borut 预期 str、字节或 os.PathLike 对象,而不是 HttpResponse
  • 基于 Django 文档:link,您应该使用 attach() 而不是 attach_file()。那么它应该与 return result.getvalue() 一起使用。

标签: python django


【解决方案1】:

试试下面的代码。未经测试,但应该可以工作

from django.template.loader import render_to_string

def render_to_pdf(template_src, context_dict={}):
    html = render_to_string(template_src, context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return result.getvalue()
    return None

参考:https://github.com/codingforentrepreneurs/Guides/blob/master/all/Render_to_PDF_in_Django.md

【讨论】:

    猜你喜欢
    • 2018-11-08
    • 2018-11-11
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多