import os from flask import Flask, request, render_template_string from PyPDF2 import PdfFileReader from werkzeug.utils import secure_filename # Initialize Flask app app = Flask(__name__) UPLOAD_FOLDER = 'uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # Ensure the upload folder exists if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) # HTML template for displaying the number of pages HTML_TEMPLATE = ''' PDF Page Count

Documentul incarcat are {{ page_count }} pagini.

''' @app.route('/', methods=['GET']) def index(): # Serve the HTML form return app.send_static_file('index.html') @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return "No file part", 400 file = request.files['file'] if file.filename == '': return "No selected file", 400 if file and file.filename.endswith('.pdf'): filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) # Count the number of pages in the PDF page_count = count_pdf_pages(filepath) # Render the page count return render_template_string(HTML_TEMPLATE, page_count=page_count) return "Invalid file format, please upload a PDF.", 400 def count_pdf_pages(pdf_path): try: with open(pdf_path, 'rb') as f: reader = PdfFileReader(f) if reader.isEncrypted: reader.decrypt('') return reader.numPages except Exception as e: print(f"Error reading PDF file: {e}") return "Cannot read PDF." if __name__ == '__main__': app.run(debug=True)