Reputation: 19
I simply want to click a link and view, in the browser, a PDF that I have uploaded to my Django project. To be sure in the Django docs (https://docs.djangoproject.com/en/3.1/howto/outputting-pdf/) about how to create reports is not at all what I'm looking to do. I don't need to generate a PDF, I already have the ones I need. (This comes up a LOT in other answers.)
No luck with: Render HTML to PDF in Django site (No surprise, it's 11 years)
Or: Django - JS : How to display the first PDF page as cover (somewhat surprised this is not the only time that a suggestion containing pdf.js occurs, I simply get an empty white square on me page with no further errors).
I have as well attempted embedding the PDF in a template with no luck.
(Recommended way to embed PDF in HTML?)
(Tried <embed>
and <iframe>
, and as you see in the link pdf.js once more. No go.)
How, generally, would one accomplish this specifically in Django 3.x?
Thanks.
Upvotes: 1
Views: 2139
Reputation: 6815
There are a few ways you can do this. I'm not sure if you're talking about user uploaded files, or files that are static-files.
Just link to the relevant file from a template. For user-uploaded files
{% load static %}
<a href="{% get_media_prefix %}name_of_pdf.pdf">Click Me</a>
For static files
{% load static %}
<a href="{% static 'name_of_pdf.pdf' %}">Click Me</a>
If you are trying to return the file from a view
from django.http import FileResponse
def load_file(request):
file = ... # get file somehow
return FileResponse(file)
See django docs for futher details. If the file is from your static folder, you could just use pythons open
to read it. It depends on how you are serving your static files.
If this pdf is a user-uploaded file, attached to a model, you can access it via the appropriate field.
Upvotes: 2