i need a python code to browse and select a pdf file, preview a pdf file into the…
- User
i need a python code to browse and select a pdf file, preview a pdf file into the browser , [not downloading it as attachment]
- Assistant
i need a python code to browse and select a pdf file, preview a pdf file into the browser , [not downloading it as attachment]
Certainly! You can create a web application using Python's Flask framework that allows users to browse and select a PDF file from their local machine and preview it directly in the browser without downloading it as an attachment. Below is a step-by-step guide along with the complete code to achieve this functionality.
<embed> or <iframe> tag.Python 3.x installed on your machine.
Flask library installed. You can install it using pip:
pip install Flask
pdf_preview_app/
│
├── app.py
├── templates/
│ ├── index.html
│ └── preview.html
└── uploads/
app.py)from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import os
from werkzeug.utils import secure_filename
import uuid
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'pdf'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Ensure the upload folder exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
# Check if the post request has the file part
if 'pdf_file' not in request.files:
return redirect(request.url)
file = request.files['pdf_file']
# If user does not select file, browser may submit an empty part
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
# Secure the filename and append a unique identifier to prevent overwriting
filename = secure_filename(file.filename)
unique_filename = f"{uuid.uuid4()}_{filename}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
file.save(file_path)
return redirect(url_for('preview_pdf', filename=unique_filename))
else:
return "Invalid file type. Please upload a PDF file."
@app.route('/preview/<filename>')
def preview_pdf(filename):
return render_template('preview.html', filename=filename)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
# Serve the uploaded PDF
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True)
templates/index.htmlThis is the main page where users can upload their PDF files.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Previewer</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.upload-container {
background-color: #fff;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="file"] {
margin-top: 10px;
}
input[type="submit"] {
margin-top: 15px;
padding: 10px 20px;
background-color: #007BFF;
border: none;
color: #fff;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0069d9;
}
</style>
</head>
<body>
<div class="upload-container">
<h2>Upload and Preview PDF</h2>
<form action="{{ url_for('upload_file') }}" method="post" enctype="multipart/form-data">
<input type="file" name="pdf_file" accept="application/pdf" required>
<br>
<input type="submit" value="Upload and Preview">
</form>
</div>
</body>
</html>
templates/preview.htmlThis page displays the uploaded PDF embedded in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Preview</title>
<style>
body {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
#pdf-viewer {
width: 100%;
height: 100%;
}
.back-button {
position: fixed;
top: 10px;
left: 10px;
background-color: #007BFF;
border: none;
color: #fff;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
z-index: 1000;
}
.back-button:hover {
background-color: #0069d9;
}
</style>
</head>
<body>
<button class="back-button" onclick="window.history.back()">← Back</button>
<embed src="{{ url_for('uploaded_file', filename=filename) }}" id="pdf-viewer" type="application/pdf">
<!-- Alternatively, you can use iframe:
<iframe src="{{ url_for('uploaded_file', filename=filename) }}" id="pdf-viewer"></iframe>
-->
</body>
</html>
Navigate to the Project Directory:
Open your terminal or command prompt and navigate to the pdf_preview_app directory.
Run the Flask App:
python app.py
Access the Application:
Open your web browser and navigate to http://127.0.0.1:5000/. You should see the upload form.
Upload and Preview PDF:
Delete Uploaded Files: To prevent the uploads directory from filling up, you might want to implement a cleanup mechanism to delete files after a certain period or after previewing.
Security Considerations: Ensure that the application is secure, especially if deploying it publicly. Validate and sanitize all inputs and consider using secure filenames and storage mechanisms.
Styling and User Experience: Enhance the UI/UX with better styling or by integrating PDF.js for more advanced PDF rendering and controls.
app.py
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import os
from werkzeug.utils import secure_filename
import uuid
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'pdf'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Ensure the upload folder exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'pdf_file' not in request.files:
return redirect(request.url)
file = request.files['pdf_file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
unique_filename = f"{uuid.uuid4()}_{filename}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
file.save(file_path)
return redirect(url_for('preview_pdf', filename=unique_filename))
else:
return "Invalid file type. Please upload a PDF file."
@app.route('/preview/<filename>')
def preview_pdf(filename):
return render_template('preview.html', filename=filename)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Previewer</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.upload-container {
background-color: #fff;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="file"] {
margin-top: 10px;
}
input[type="submit"] {
margin-top: 15px;
padding: 10px 20px;
background-color: #007BFF;
border: none;
color: #fff;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0069d9;
}
</style>
</head>
<body>
<div class="upload-container">
<h2>Upload and Preview PDF</h2>
<form action="{{ url_for('upload_file') }}" method="post" enctype="multipart/form-data">
<input type="file" name="pdf_file" accept="application/pdf" required>
<br>
<input type="submit" value="Upload and Preview">
</form>
</div>
</body>
</html>
templates/preview.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Preview</title>
<style>
body {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
#pdf-viewer {
width: 100%;
height: 100%;
}
.back-button {
position: fixed;
top: 10px;
left: 10px;
background-color: #007BFF;
border: none;
color: #fff;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
z-index: 1000;
}
.back-button:hover {
background-color: #0069d9;
}
</style>
</head>
<body>
<button class="back-button" onclick="window.history.back()">← Back</button>
<embed src="{{ url_for('uploaded_file', filename=filename) }}" id="pdf-viewer" type="application/pdf">
<!-- Alternatively, you can use iframe:
<iframe src="{{ url_for('uploaded_file', filename=filename) }}" id="pdf-viewer"></iframe>
-->
</body>
</html>
With this setup, you have a simple Flask web application that allows users to upload a PDF file and preview it directly in their browser without downloading it. This approach ensures a smooth user experience and leverages the browser's built-in PDF rendering capabilities. You can further enhance and customize this application based on your specific requirements.
Not yet included in a published release.