Sure! Below is a simple Python script using the Flask web framework to display a PDF file directly within a webpage without prompting the user to download it.
First, make sure you have Flask installed. You can install it using pip:
pip install flask
Directory Structure:
your_project/
├── app.py # The Python script provided below
└── static/
└── sample.pdf # The PDF file you want to display
Python Code (app.py):
from flask import Flask, render_template_string, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''
<!doctype html>
<html>
<head>
<title>Display PDF</title>
</head>
<body>
<h1>Embedded PDF Viewer</h1>
<iframe src="{{ url_for('static', filename='sample.pdf') }}" width="100%" height="600px" style="border:none;">
This browser does not support PDFs. Please download the PDF to view it: <a href="{{ url_for('static', filename='sample.pdf') }}">Download PDF</a>
</iframe>
</body>
</html>
''')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
-
Import Statements:
Flask to create the web application.
render_template_string to render HTML directly from a string.
url_for to generate the URL for the PDF file in the static directory.
-
Application Setup:
- Initializes the Flask app.
- Defines a route for the home page (
'/').
-
Route Function (index):
- Returns an HTML page that includes an
<iframe> to embed the PDF.
- Uses
url_for('static', filename='sample.pdf') to point to the PDF file.
-
HTML Template:
- Uses an
<iframe> to display the PDF inline.
- Sets
width="100%" and height="600px" to control the size of the viewer.
- Includes a fallback message and link if the browser doesn't support embedded PDFs.
Steps to Run the Application:
-
Place Your PDF File:
- Ensure your PDF file is named
sample.pdf.
- Place it inside a folder named
static within your project directory.
-
Run the Flask App:
-
View in Browser:
- Open a web browser and go to
http://localhost:5000/.
- You should see the PDF displayed within the webpage.
Notes:
-
Browser Support:
- Most modern browsers can display PDFs inline.
- If the PDF doesn't display, ensure that your browser's PDF viewer is enabled.
-
Customization:
- You can adjust the
width and height attributes of the <iframe> to change the size.
- To use a different PDF file, place it in the
static folder and update the filename in the code.
Security Considerations:
- Ensure that you trust the content of the PDF file, as embedding arbitrary PDFs can pose security risks.
- For production use, properly configure Flask and consider serving static files through a web server like Nginx.
Let me know if you need further assistance or have any questions!