请求协助:PDF转图片跨模板展示及Python脚本转Web服务
Solution: Display Converted PDF Image in Another Template & Turn Python Script into Web Service
Let’s use Flask (a lightweight, popular Python web framework) to solve this problem. I’ll break this into step-by-step, actionable parts:
1. Fix & Complete the Upload Form (index.html)
Your existing form was cut off—here’s a polished version that submits to a backend route for processing:
<!-- index.html (place in a `templates` folder) --> <!DOCTYPE html> <html> <body> {% block pagecontent %} <form action="/upload" id="file-upload-form" class="modal-content animate" enctype="multipart/form-data" method="post"> Select PDF File: <input type="file" name="myfile" accept=".pdf" required> </br> <span id="disp"></span> <button type="submit" class="btn">Upload & Convert</button> </form> {% endblock %} </body> </html>
- Added
accept=".pdf"to restrict uploads to PDF files only - Set the form action to
/upload, which we’ll define in the backend
2. Build the Flask Backend (app.py)
First, install required dependencies:
pip install flask pdf2image
(Note: pdf2image needs Poppler installed. On Linux, run sudo apt install poppler-utils; for Windows/macOS, download the Poppler binaries and add them to your PATH.)
Now the Flask app code:
from flask import Flask, render_template, request, redirect, url_for from pdf2image import convert_from_path import os import uuid app = Flask(__name__) # Configure storage for uploads and converted images UPLOAD_FOLDER = 'static/uploads' ALLOWED_EXTENSIONS = {'pdf'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # Create upload folder if it doesn't exist os.makedirs(UPLOAD_FOLDER, exist_ok=True) def allowed_file(filename): # Check if the file is a PDF return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/') def home(): # Serve the upload form return render_template('index.html') @app.route('/upload', methods=['POST']) def handle_upload(): # Validate the uploaded file if 'myfile' not in request.files: return "No file was selected." file = request.files['myfile'] if file.filename == '': return "No file chosen." if file and allowed_file(file.filename): # Generate a unique ID to avoid overwriting files unique_id = str(uuid.uuid4()) pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{unique_id}.pdf") file.save(pdf_path) # Convert PDF to image (save first page as PNG) images = convert_from_path(pdf_path) image_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{unique_id}.png") images[0].save(image_path, 'PNG') # Redirect to the display page with the image filename return redirect(url_for('show_image', image_filename=f"{unique_id}.png")) return "Invalid file type. Only PDFs are allowed." @app.route('/display/<image_filename>') def show_image(image_filename): # Pass the image URL to the display template image_url = url_for('static', filename=f'uploads/{image_filename}') return render_template('display.html', image_url=image_url) if __name__ == '__main__': app.run(debug=True)
3. Create the Image Display Template (display.html)
This template will show the converted PDF image:
<!-- display.html (place in the `templates` folder) --> <!DOCTYPE html> <html> <body> <h2>Converted PDF Page</h2> <img src="{{ image_url }}" alt="PDF to Image Conversion" style="max-width: 80%; height: auto;"> <br> <a href="/">Upload Another PDF</a> </body> </html>
Key Details & Improvements
- Unique Filenames: Using
uuidensures no conflicts when multiple users upload files. - Multi-Page Support: If you need to display all PDF pages, loop through the
imageslist in the backend to save each page, then pass a list of image URLs todisplay.htmland render them all with a loop. - Error Handling: Expand the basic error messages to use Flask’s flash system for user-friendly alerts.
- Static Files: Flask serves files from the
staticfolder, so we store uploads there for easy access.
How to Run
- Create a folder structure like this:
your-project/ ├── app.py ├── templates/ │ ├── index.html │ └── display.html └── static/ └── uploads/ - Run
python app.py - Visit
http://localhost:5000in your browser, upload a PDF, and you’ll see the converted image in the display template.
内容的提问来源于stack exchange,提问作者user9503597
相关产品推荐
相关产品推荐

