使用 Django 作为附件输出 PDF 并重新加载

发布于 2024-09-28 21:16:15 字数 546 浏览 0 评论 0原文

我正在使用 django 生成 pdf 并将响应作为视图中的附件返回。

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

类似于文档 (http:// /docs.djangoproject.com/en/dev/howto/outputting-pdf/#write-your-view

重新加载页面的最佳方法是什么?

这没有成功(表单触发了 pdf 生成):

$('#the_form').submit(function(){
  location.reload();
});

非常感谢, 丹尼

I´m using django to generate a pdf and return the response as an attachment in the view.

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

Similar to the way described in the doc (http://docs.djangoproject.com/en/dev/howto/outputting-pdf/#write-your-view)

What is the best way to reload the page?

This didn´t work out (the form triggers the pdf generation):

$('#the_form').submit(function(){
  location.reload();
});

Thanks a lot,
Danny

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萧瑟寒风 2024-10-05 21:16:15

不要重新加载。相反,创建一个作为表单目标的视图。该视图在从真实 Web 服务器传送的目录中生成 PDF,然后将用户发送到适当的 URL,用户可以在其中下载文件(使用 HttpResponseRedirect)。

Don't reload. Instead create a view which is the target of the form. The view generates the PDF in a directory that is delivered from the real web server and then sends the user to the appropriated URL, where he can download the file (use HttpResponseRedirect).

遗忘曾经 2024-10-05 21:16:15

只需将表单目标设置为生成 pdf 的视图即可。下面我列出了这种方法与 Martin 建议的方法(将文件写入世界可以读取的目录)的一些优点和缺点

优点:

  • 您可以进行身份​​验证或特殊计费或其他任何操作
  • 每个请求都会生成一个新的 PDF(除非您明确缺点

  • 每个请求都会生成一个新的 PDF
  • 内存使用情况
  • 您必须从 Django 流式传输文件

-

另一个解决方案是使用网络服务器的 X-SendFile 标头。在谷歌上搜索您的特定服务器的说明。总体思路是,您的视图为网络服务器提供了一个文件路径,然后网络服务器将直接从磁盘读取该文件并将其返回给用户。您甚至可以“强制下载”这些文件,请查看您的网络服务器的文档以了解如何执行此操作。

Just set the forms target to the view that generates the pdf. Below I included some pros and cons for this approach vs the approach suggested by Martin (to write files to a directory the world can read)

Pros:

  • You can do authentication or special billing or whatever
  • Every request will generate a new PDF (unless you explicitly cache it)

Cons:

  • Every request will generate a new PDF
  • Memory usage
  • You have to stream a file from Django

--

Another solution would be to use the X-SendFile header of your webserver. Do a google search for instructions for your particular server. The general idea is that your view gives the webserver a path to a file which the webserver will then read directly from disk and return to the user. You can probably "force download" even these files, have a look at the documentation for your webserver on how to do it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文