【发布时间】: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 我想把它保存在服务器上,而不是客户端机器上。