我一直在关注这个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/