【问题标题】:Django - Save to disk a pdf file generated using xhtml2pdfDjango - 将使用 xhtml2pdf 生成的 pdf 文件保存到磁盘
【发布时间】:2020-01-13 01:14:57
【问题描述】:

我一直在关注这个tutorial,它帮助我使用 xhtml2pdf 在 Django 中生成 pdf 文件。现在我想要将生成的文件保存到磁盘,而不必提示用户下载文件。

下面是我用来在utils.py文件和views.py文件中生成pdf文件的代码。

#utils.py file

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa

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 HttpResponse(result.getvalue(), content_type='application/pdf')
    return None 

#views.py snippet of code

html = template.render(context)
pdf = render_to_pdf('tdn.html', context)
if pdf: 
    response = HttpResponse(pdf, content_type='application/pdf')
    filename = "TDN_%s.pdf" %("12341231")
    content = "inline; filename='%s'" %(filename)
    download = request.GET.get("download")
    if download:
        content = "attachment; filename='%s'" %(filename)
        response['Content-Disposition'] = content
    TDN.objects.filter(id=tdn_no).update(printed=1)
    return response

return HttpResponse("Not found")

任何关于如何将生成的 pdf 写入磁盘的指针将不胜感激

【问题讨论】:

  • 是否要将文件保存在客户端计算机上?你不能强迫它:它取决于浏览器设置(我认为任何浏览器都不会允许)
  • @Dona 我想把它保存在服务器上,而不是客户端机器上。

标签: python django xhtml2pdf


【解决方案1】:

试过了吗?

with open('mypdf.pdf', 'wb+') as output:
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), output)

如果您想将其保存到 ImageField,请在 Django 中使用 ContentFile

【讨论】:

  • 感谢@KshitijSaxena 的建议。我在视图或 utils 文件中这样做?
  • 您可以在if not pdf.err 块内执行此操作!建议新建一个函数并将pdf作为参数传递。在 if 块中调用该函数!
  • 得到一个错误:需要一个类似字节的对象,而不是'pisaContext'
  • 这个错误你可以参考这个答案:stackoverflow.com/a/2900067/7697652
  • 非常感谢 Kshitij。使用您推荐给我的链接后,它现在运行良好。我真的很感激。
猜你喜欢
  • 1970-01-01
  • 2020-12-15
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多