如何在Django视图中显示PDF文件? [英] How to show a PDF file in a Django view?

查看:140
本文介绍了如何在Django视图中显示PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Django视图中显示 PDF文件,而不是使用户必须下载它才能看到它?

Is it possible to show a PDF file in the Django view, rather than making the user have to download it to see it?

如果可能的话,怎么办?

And if it is possible, how would it be done?

这是我到目前为止所拥有的-

This is what I have so far -

@login_required
def resume(request, applicant_id):

    #Get the applicant's resume
    resume = File.objects.get(applicant=applicant_id)
    fsock = open(resume.location, 'r')
    response = HttpResponse(fsock, mimetype='application/pdf')

    return response

推荐答案

简而言之,如果您有PDF文件,并且希望通过Django视图输出,则只需将文件内容转储到响应中,然后并以适当的mimetype进行发送.

Simplistically, if you have a PDF file and you want to output it through a Django view, all you need to do is dump the file contents into the response and send it with the appropriate mimetype.

def pdf_view(request):
    with open('/path/to/my/file.pdf', 'r') as pdf:
        response = HttpResponse(pdf.read(), mimetype='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response
    pdf.closed

您也许可以直接返回响应而无需指定Content-Disposition,但这可以更好地表明您的意图,并且还可以指定文件名,以防用户决定保存它.

You can probably just return the response directly without specifying Content-Disposition, but that better indicates your intention and also allows you specify the filename just in case the user decides to save it.

此外,请注意,上面的视图无法处理由于某种原因而无法打开或读取文件的情况.由于它是用with完成的,因此不会引发任何异常,但是您仍然必须返回某种响应.您可以简单地举一个Http404之类的东西.

Also, note that the view above doesn't handle the scenario where the file cannot be opened or read for whatever reason. Since it's done with with, it won't raise any exceptions, but you still must return some sort of response. You could simply raise an Http404 or something, though.

这篇关于如何在Django视图中显示PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆