How to show a PDF file in a Django view?

2019-01-08 07:22发布

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

10条回答
乱世女痞
2楼-- · 2019-01-08 07:50

Here is a typical use-case for displaying a PDF using class-based views:

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

class DisplayPDFView(View):

    def get_context_data(self, **kwargs):  # Exec 1st
        context = {}
        # context logic here
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data()
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'inline; filename="worksheet_pdf.pdf"'  # Can use attachment or inline

        # pdf generation logic here
        # open an existing pdf or generate one using i.e. reportlab

        return response

# Remove login_required if view open to public
display_pdf_view = login_required(DisplayPDFView.as_view())

For generating your own pdf with reportlab see the Django project Docs on PDF Generation.

Chris Pratt's response shows a good example of opening existing PDFs.

查看更多
ら.Afraid
3楼-- · 2019-01-08 07:51

Browsers aren't PDF readers (unless they have the proper plugin/addon).

You may want to render the PDF as HTML instead, which can be done from the backend or the frontend.

查看更多
SAY GOODBYE
4楼-- · 2019-01-08 07:51

I am just throwing this out there.

You can simply add your PDF resume to your static files.

If you are using White Noise to serve your static files, then you don't even need to make the view. Just then access your resume at the static location.

I added mine, here it is: https://www.jefferythewind.com/static/main/resume/TIm-D_Nice.pdf

Warning: This doesn't solve the login_required requirement in the question

查看更多
Viruses.
5楼-- · 2019-01-08 08:02

If you are working on a Windows machine pdf must be opened as rb not r.

def pdf_view(request):
    with open('/path / to /name.pdf', 'rb') as pdf:
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
查看更多
登录 后发表回答