Django open pdf on certain page number

715 views Asked by At

I am trying to create a PDF analysis web app and I am stuck. I want to allow the user to open a certain page of the pdf that have over 300 pages in it. So, can anyone tell me how to use Django to open the pdf in a new tab on a specific page?


EDIT -- Actually the Django code is running on AWS server and I want the user to see and open a PDF on a specific page that is stored into my media folder after analysis.

3

There are 3 answers

1
Avi On

This depends on which library etc.

Not really a django question as @ps_ said.

From Adobe.com To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL.

For example, this HTML tag opens page 4 of a PDF file named myfile.pdf:

<A HREF="http://www.example.com/myfile.pdf#page=4">
1
ps_ On

The answer to this really isn't Django-specific and is going to depend on what viewer you are using to display the PDF. If you're relying on the browser to display it, according to Adobe, you can use an anchor link (#page=) in the url (e.g. http://www.example.com/myfile.pdf#page=XX) though I think support for this varies outside Firefox and Chrome.

If you're using PDF.JS, on the other hand, you'll be able to programatically select a page to render. You can see how to do that on the viewer's examples page, here.

0
Rashbir Kohli On

I was able to solve my question, it took a while and after every attempt to use different libraries and PDF.js failed. The solution is quite simple. so what I did is:

Step 1: Add MEDIA_ROOT and MEDIA_URL to settings.py.

# path to the MEDIA directory
MEDIA_ROOT = '/home/absolute/path/to/your/media/folder' 

# URL to use to open MEDIA 
MEDIA_URL = '/media/'

Step 2: Update the urls.py with the following code:

from . import settings
import django

urlpatterns = [
...
...
url(r'^(.*?)media/(?P<path>.*)$', django.views.static.serve,
             {'document_root': settings.MEDIA_ROOT}),
]

Step 3: Now I created an onclick in the HTML tag as:

My pdf files were in documents folder inside the media directory

onclick="window.open('media/documents/{{Your/Pdf/File/Path.pdf}}#page={{Page_number_to_open}}')"