-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
60 lines (49 loc) · 2.22 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import uuid
from flask import Flask, request, render_template, send_from_directory
from PyPDF2 import PdfReader, PdfWriter
app = Flask(__name__)
# Define base directories for uploads and split PDFs
UPLOAD_FOLDER = 'static/uploads'
PAGES_FOLDER = 'static/pages'
# Ensure the directories exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(PAGES_FOLDER, exist_ok=True)
# Set the app's configuration
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['PAGES_FOLDER'] = PAGES_FOLDER
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Generate a unique folder name based on UUID
unique_id = str(uuid.uuid4())
upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], unique_id)
os.makedirs(upload_folder, exist_ok=True)
# Get the uploaded file
pdf_file = request.files['pdf_file']
if pdf_file and pdf_file.filename.endswith('.pdf'):
# Save the uploaded PDF in the unique folder
upload_path = os.path.join(upload_folder, pdf_file.filename)
pdf_file.save(upload_path)
# Split PDF into individual pages
reader = PdfReader(upload_path)
page_files = []
output_folder = os.path.join(app.config['PAGES_FOLDER'], unique_id)
os.makedirs(output_folder, exist_ok=True)
for i, page in enumerate(reader.pages):
writer = PdfWriter()
writer.add_page(page)
output_filename = f'page_{i+1}.pdf'
output_path = os.path.join(output_folder, output_filename)
with open(output_path, 'wb') as output_pdf:
writer.write(output_pdf)
page_files.append(output_filename)
# Pass unique_id and page_files to the template
return render_template('index.html', page_files=page_files, unique_id=unique_id)
return render_template('index.html', page_files=None)
@app.route('/download/<folder>/<filename>')
def download_file(folder, filename):
folder_path = os.path.join(app.config['PAGES_FOLDER'], folder)
return send_from_directory(folder_path, filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)