python - Django - 将使用 xhtml2pdf 生成的 pdf 文件保存到磁盘

标签 python django xhtml2pdf

我一直在关注这个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 写入磁盘的指示将不胜感激

最佳答案

尝试过这个吗?

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

如果你想将其保存到 ImageField,请使用 Django 中的 ContentFile!

关于python - Django - 将使用 xhtml2pdf 生成的 pdf 文件保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885037/

相关文章:

javascript - 如何正确划分前端和后端的任务?

python - Ubuntu、virtualenv、flask/bottle 和 mod_wsgi 不工作,500 内部服务器错误

python - 从 numpy 数组中删除选择索引处的行

django - 如何使用 borb 库和 Django 从静态文件将图像添加到 Pdf 文件

python - 如何创建用于 pisa (xhtml2pdf) 的布局?

python - Django - 使用 xhtml2pdf 将生成的 PDF 保存在模型中

python - 在 python 中,有什么方法可以获取作为对象传递给函数的参数?

python - 如何将参数传递给信号

django - 如何由用户查询 Django 中的模型

python - 密码保护使用 pisa 创建的 pdf 文件