How to Render and Open PDF file in Django?

Shape Image One

How to Render and Open PDF file in Django?

Interestingly to render PDF file in Django you don’t need to create HTML template.

In this tutorial, we are going to setting up the static PDF file and render and allow user to downlow PDF file.

There are two ways to access the static file in the Django Python script. One is using static() method. Another is using os.path.join() method.

Here is the twist. You can not use the static file path you get from static() method to open the file. If you use it, you will get an error saying…

Exception Value:
[Errno 2] No such file or directory: '/static/sample.pdf'

So, use later one.

Here is the sample code to set a view ( to render and open PDF file in Django.

from django.http import FileResponse
import os

def show_pdf(request):
	filepath = os.path.join('static', 'sample.pdf')
	return FileResponse(open(filepath, 'rb'), content_type='application/pdf')

Some of the points you should remember.

  • Django view function returns the FileResponse. You need to import it from django.http before using.
  • Open file in the ‘rb’ mode using Python open() method.
  • You have to provide the complete or relative path to your PDF file.
  • FileResponse content-type should be ‘application/pdf’.
  • Make sure, you have a PDF file present in your project static directory.

It is not good practice to hardcode the file path. File path of the static files can vary while deploying production build.

If you are getting FileNotFoundError, check this tutorial where I have described steps to debug this issue.

Note: If you have a download manager installed on your system, it will start downloading PDF file rather than showing it in the browser. If you want to prevent users from downloading or saving PDFs, this is not a recommended solution.

There are many use cases to open pdf file in Django. For example, if you are building an eCommerce website, with this technique you can allow users to download the invoices for purchased products and services. You can also allow users to download the specific documentation files.

There are different methods to open PDF file in Django based on the use case. Here we have discussed the simplest one. If you have any queries, let me know in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *