Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

html - Django 3.0 - View a PDF in the browser

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Approach 1

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>

Approach

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...