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
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
from fastapi import APIRouter, UploadFile, File, HTTPException, Form
from fastapi.responses import FileResponse, HTMLResponse
from pypdf import PdfReader, PdfWriter
import os
import shutil
import tempfile
from typing import List

# Define the APIRouter object
router = APIRouter(
    prefix="/pdf",
    tags=["PDF Manipulation"],
)

# ==========================
# 🧩 PDF Merge Endpoint
# ==========================
@router.post("/merge")
async def merge_pdfs(files: List[UploadFile] = File(..., description="List of PDFs to merge")):
    """
    Merges multiple uploaded PDF files into a single PDF.
    """
    if len(files) < 2:
        raise HTTPException(status_code=400, detail="Please upload at least two PDF files to merge.")

    pdf_writer = PdfWriter()
    
    # Create a temporary directory to store files
    # Note: We rely on the OS to clean up the temp dir eventually, 
    # or we return a FileResponse which keeps the file handle open briefly.
    # For a robust production app, consider BackgroundTasks for cleanup.
    temp_dir = tempfile.mkdtemp()
    output_path = os.path.join(temp_dir, "merged_output.pdf")
    
    try:
        for file in files:
            # Save the uploaded file temporarily
            temp_file_path = os.path.join(temp_dir, file.filename)
            with open(temp_file_path, "wb") as buffer:
                shutil.copyfileobj(file.file, buffer)
            
            # Read and append pages
            try:
                reader = PdfReader(temp_file_path)
                for page in reader.pages:
                    pdf_writer.add_page(page)
            except Exception as e:
                 raise HTTPException(status_code=500, detail=f"Error reading PDF file {file.filename}: {e}")
        
        # Write the merged PDF to the output path
        with open(output_path, "wb") as output_file:
            pdf_writer.write(output_file)
            
        return FileResponse(output_path, media_type="application/pdf", filename="merged_document.pdf")
        
    except Exception as e:
        shutil.rmtree(temp_dir) # Cleanup on error
        raise HTTPException(status_code=500, detail=str(e))

# ==========================
# πŸ”„ PDF Rotate Endpoint
# ==========================
@router.post("/rotate")
async def rotate_pdf(
    file: UploadFile = File(..., description="PDF file to rotate"),
    degrees: int = 90 
):
    """
    Rotates all pages of a single PDF by a specified degree (90, 180, or 270).
    """
    if degrees not in [90, 180, 270]:
        raise HTTPException(status_code=400, detail="Rotation must be 90, 180, or 270 degrees.")
        
    pdf_writer = PdfWriter()

    temp_dir = tempfile.mkdtemp()
    input_path = os.path.join(temp_dir, file.filename)
    output_path = os.path.join(temp_dir, f"rotated_{degrees}.pdf")
        
    try:
        # Save the uploaded file temporarily
        with open(input_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Read, rotate, and write
        try:
            reader = PdfReader(input_path)
            for page in reader.pages:
                page.rotate(degrees)
                pdf_writer.add_page(page)
        except Exception as e:
             raise HTTPException(status_code=500, detail=f"Error processing PDF: {e}")

        # Write the rotated PDF
        with open(output_path, "wb") as output_file:
            pdf_writer.write(output_file)

        return FileResponse(output_path, media_type="application/pdf", filename=f"rotated_{degrees}.pdf")

    except Exception as e:
        shutil.rmtree(temp_dir)
        raise HTTPException(status_code=500, detail=str(e))


# ==========================
# 🎨 Modern UI Endpoint
# ==========================
@router.get("/ui", response_class=HTMLResponse)
async def pdf_tools_ui():
    html_content = """
    <!DOCTYPE html>
    <html lang="en" data-theme="light">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>PDF Tools | by Sam</title>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
        
        <style>
            /* --- Shared Theme Config --- */
            :root {
                --primary: #ef4444; /* PDF Red */
                --primary-hover: #dc2626;
                --bg-body: #f8fafc;
                --bg-card: #ffffff;
                --text-main: #0f172a;
                --text-sub: #64748b;
                --border: #e2e8f0;
                --drop-bg: #fef2f2;
                --drop-hover: #fee2e2;
                --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            }

            [data-theme="dark"] {
                --primary: #f87171;
                --primary-hover: #ef4444;
                --bg-body: #0f172a;
                --bg-card: #1e293b;
                --text-main: #f8fafc;
                --text-sub: #94a3b8;
                --border: #334155;
                --drop-bg: #1e293b;
                --drop-hover: #450a0a;
                --shadow: 0 10px 15px -3px rgb(0 0 0 / 0.5);
            }

            * { box-sizing: border-box; margin: 0; padding: 0; transition: background-color 0.3s ease, color 0.3s ease; }
            
            body {
                font-family: 'Plus Jakarta Sans', sans-serif;
                background-color: var(--bg-body);
                color: var(--text-main);
                min-height: 100vh;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 1rem;
            }

            /* --- Navbar --- */
            .navbar {
                width: 100%; max-width: 1000px; display: flex;
                justify-content: space-between; align-items: center; margin-bottom: 2rem;
                animation: fadeIn 0.8s ease-out;
            }
            .brand { font-size: 1.5rem; font-weight: 800; display: flex; align-items: center; gap: 0.5rem; }
            .brand span { color: var(--primary); }
            .theme-toggle { background: none; border: none; cursor: pointer; font-size: 1.2rem; padding: 8px; border-radius: 50%; background-color: var(--bg-card); border: 1px solid var(--border); }

            /* --- Container & Tabs --- */
            .container {
                background: var(--bg-card); width: 100%; max-width: 800px;
                border-radius: 24px; box-shadow: var(--shadow);
                border: 1px solid var(--border); overflow: hidden;
                animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
            }
            .tabs { display: flex; border-bottom: 1px solid var(--border); }
            .tab-btn {
                flex: 1; padding: 1rem; border: none; background: transparent;
                font-family: inherit; font-weight: 600; color: var(--text-sub);
                cursor: pointer; transition: all 0.2s; border-bottom: 3px solid transparent;
            }
            .tab-btn:hover { background-color: var(--drop-bg); }
            .tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); }

            .tab-content { padding: 2.5rem; display: none; animation: fadeIn 0.4s ease; }
            .tab-content.active { display: block; }

            /* --- Controls --- */
            .drop-area {
                border: 2px dashed var(--border); border-radius: 16px; padding: 3rem 1rem;
                text-align: center; cursor: pointer; background-color: var(--drop-bg);
                transition: all 0.3s; margin-bottom: 1.5rem;
            }
            .drop-area:hover, .drop-area.dragover { border-color: var(--primary); background-color: var(--drop-hover); transform: scale(1.01); }
            .drop-icon { font-size: 3rem; margin-bottom: 1rem; display: block; }

            .file-list { margin-bottom: 1rem; text-align: left; background: var(--bg-body); padding: 1rem; border-radius: 8px; display: none; }
            .file-item { font-size: 0.9rem; color: var(--text-sub); padding: 4px 0; border-bottom: 1px solid var(--border); }

            .rotate-options { display: flex; gap: 1rem; justify-content: center; margin-bottom: 1.5rem; }
            .rotate-btn {
                padding: 0.5rem 1rem; border: 1px solid var(--border); border-radius: 8px;
                background: var(--bg-body); color: var(--text-sub); cursor: pointer;
            }
            .rotate-btn.selected { background: var(--primary); color: white; border-color: var(--primary); }

            .btn {
                padding: 0.8rem 2rem; border-radius: 12px; font-weight: 600; width: 100%;
                cursor: pointer; border: none; font-size: 1rem; background-color: var(--primary); color: white;
                display: flex; justify-content: center; align-items: center; gap: 10px;
            }
            .btn:disabled { opacity: 0.6; cursor: not-allowed; }

            /* --- Footer --- */
            .dev-footer {
                margin-top: 3rem; text-align: center; font-size: 0.9rem; color: var(--text-sub);
                padding: 1rem; border-top: 1px solid var(--border); width: 100%; max-width: 600px;
            }
            .dev-badge {
                display: inline-block; background: var(--bg-card); padding: 5px 15px;
                border-radius: 20px; border: 1px solid var(--border); font-weight: 500; margin-top: 5px;
            }
            .dev-name { color: var(--primary); font-weight: 700; }

            .spinner { width: 20px; height: 20px; border: 2px solid #ffffff; border-top-color: transparent; border-radius: 50%; animation: spin 0.8s linear infinite; display: none; }
            @keyframes spin { to { transform: rotate(360deg); } }
            @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
            @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

        </style>
    </head>
    <body>

        <nav class="navbar">
            <div class="brand">πŸ“„ PDF Tools <span>Suite</span></div>
            <button class="theme-toggle" onclick="toggleTheme()" id="themeBtn">πŸŒ™</button>
        </nav>

        <div class="container">
            <div class="tabs">
                <button class="tab-btn active" onclick="switchTab('merge')">Merge PDFs</button>
                <button class="tab-btn" onclick="switchTab('rotate')">Rotate PDF</button>
            </div>

            <div id="tab-merge" class="tab-content active">
                <p style="text-align: center; color: var(--text-sub); margin-bottom: 1rem;">Combine multiple PDF files into one.</p>
                
                <div class="drop-area" id="mergeDrop">
                    <input type="file" id="mergeInput" accept="application/pdf" multiple hidden>
                    <span class="drop-icon">πŸ“‘</span>
                    <h3 style="font-weight: 600;">Drag & Drop PDFs here</h3>
                    <p style="color: var(--text-sub); font-size: 0.9rem;">or click to browse</p>
                </div>

                <div class="file-list" id="mergeFileList"></div>

                <button class="btn" id="mergeBtn" onclick="processMerge()" disabled>
                    <div class="spinner" id="mergeSpinner"></div>
                    <span id="mergeBtnText">Merge Files</span>
                </button>
                <p id="mergeError" style="color: #ef4444; text-align: center; margin-top: 10px; display: none;"></p>
            </div>

            <div id="tab-rotate" class="tab-content">
                <p style="text-align: center; color: var(--text-sub); margin-bottom: 1rem;">Rotate all pages in a PDF document.</p>
                
                <div class="drop-area" id="rotateDrop">
                    <input type="file" id="rotateInput" accept="application/pdf" hidden>
                    <span class="drop-icon">πŸ”„</span>
                    <h3 id="rotateText" style="font-weight: 600;">Upload PDF to Rotate</h3>
                </div>

                <div class="rotate-options">
                    <button class="rotate-btn selected" onclick="setRotation(90)">90Β° CW</button>
                    <button class="rotate-btn" onclick="setRotation(180)">180Β°</button>
                    <button class="rotate-btn" onclick="setRotation(270)">270Β° CW</button>
                </div>

                <button class="btn" id="rotateBtn" onclick="processRotate()" disabled>
                    <div class="spinner" id="rotateSpinner"></div>
                    <span id="rotateBtnText">Rotate PDF</span>
                </button>
                <p id="rotateError" style="color: #ef4444; text-align: center; margin-top: 10px; display: none;"></p>
            </div>
        </div>

        <footer class="dev-footer">
            <div>Designed & Developed by</div>
            <div class="dev-badge">
                <span class="dev-name">Sameer Banchhor</span> | Data Scientist
            </div>
        </footer>

        <script>
            // --- Theme & Tab Logic ---
            const html = document.documentElement;
            const themeBtn = document.getElementById('themeBtn');
            function toggleTheme() {
                const current = html.getAttribute('data-theme');
                const next = current === 'light' ? 'dark' : 'light';
                html.setAttribute('data-theme', next);
                themeBtn.textContent = next === 'light' ? 'πŸŒ™' : 'β˜€οΈ';
                localStorage.setItem('theme', next);
            }
            const savedTheme = localStorage.getItem('theme') || 'light';
            html.setAttribute('data-theme', savedTheme);
            themeBtn.textContent = savedTheme === 'light' ? 'πŸŒ™' : 'β˜€οΈ';

            function switchTab(tab) {
                document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
                document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
                document.getElementById('tab-' + tab).classList.add('active');
                // Simple active class toggle for buttons
                const btns = document.querySelectorAll('.tab-btn');
                if(tab === 'merge') btns[0].classList.add('active');
                else btns[1].classList.add('active');
            }

            // --- Merge Logic ---
            const mergeDrop = document.getElementById('mergeDrop');
            const mergeInput = document.getElementById('mergeInput');
            const mergeFileList = document.getElementById('mergeFileList');
            const mergeBtn = document.getElementById('mergeBtn');
            let mergeFiles = [];

            mergeDrop.addEventListener('click', () => mergeInput.click());
            
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => {
                mergeDrop.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); });
            });
            mergeDrop.addEventListener('drop', (e) => {
                if(e.dataTransfer.files.length) handleMergeFiles(e.dataTransfer.files);
            });
            mergeInput.addEventListener('change', () => handleMergeFiles(mergeInput.files));

            function handleMergeFiles(files) {
                mergeFiles = Array.from(files); // Convert FileList to Array
                if(mergeFiles.length < 2) {
                    alert("Please select at least 2 PDF files.");
                    return;
                }
                updateFileList();
                mergeBtn.disabled = false;
            }

            function updateFileList() {
                mergeFileList.style.display = 'block';
                mergeFileList.innerHTML = mergeFiles.map((f, i) => 
                    `<div class="file-item">${i+1}. ${f.name} (${(f.size/1024/1024).toFixed(2)} MB)</div>`
                ).join('');
            }

            async function processMerge() {
                if(mergeFiles.length < 2) return;
                setLoading('merge', true);
                
                const formData = new FormData();
                mergeFiles.forEach(file => formData.append('files', file));

                try {
                    const res = await fetch('/pdf/merge', { method: 'POST', body: formData });
                    if(!res.ok) throw new Error("Merge failed");
                    
                    const blob = await res.blob();
                    downloadBlob(blob, 'merged_document.pdf');
                } catch(e) {
                    showError('merge', e.message);
                } finally {
                    setLoading('merge', false);
                }
            }

            // --- Rotate Logic ---
            const rotateDrop = document.getElementById('rotateDrop');
            const rotateInput = document.getElementById('rotateInput');
            const rotateText = document.getElementById('rotateText');
            const rotateBtn = document.getElementById('rotateBtn');
            let rotateFile = null;
            let currentRotation = 90;

            rotateDrop.addEventListener('click', () => rotateInput.click());
            
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => {
                rotateDrop.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); });
            });
            rotateDrop.addEventListener('drop', (e) => {
                if(e.dataTransfer.files.length) handleRotateFile(e.dataTransfer.files[0]);
            });
            rotateInput.addEventListener('change', () => handleRotateFile(rotateInput.files[0]));

            function handleRotateFile(file) {
                if(!file || file.type !== 'application/pdf') {
                    alert("Please select a valid PDF."); return;
                }
                rotateFile = file;
                rotateText.textContent = "Selected: " + file.name;
                rotateBtn.disabled = false;
            }

            function setRotation(deg) {
                currentRotation = deg;
                document.querySelectorAll('.rotate-btn').forEach(b => b.classList.remove('selected'));
                // Identify button by onclick text content or order. 
                // Hardcoding logic for simplicity:
                const btns = document.querySelectorAll('.rotate-btn');
                if(deg === 90) btns[0].classList.add('selected');
                if(deg === 180) btns[1].classList.add('selected');
                if(deg === 270) btns[2].classList.add('selected');
            }

            async function processRotate() {
                if(!rotateFile) return;
                setLoading('rotate', true);

                const formData = new FormData();
                formData.append('file', rotateFile);

                try {
                    const res = await fetch(`/pdf/rotate?degrees=${currentRotation}`, { 
                        method: 'POST', 
                        body: formData 
                    });
                    if(!res.ok) throw new Error("Rotation failed");

                    const blob = await res.blob();
                    downloadBlob(blob, `rotated_${currentRotation}_${rotateFile.name}`);
                } catch(e) {
                    showError('rotate', e.message);
                } finally {
                    setLoading('rotate', false);
                }
            }

            // --- Helpers ---
            function downloadBlob(blob, filename) {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
            }

            function setLoading(type, isLoading) {
                const btn = document.getElementById(`${type}Btn`);
                const spinner = document.getElementById(`${type}Spinner`);
                const text = document.getElementById(`${type}BtnText`);
                const error = document.getElementById(`${type}Error`);
                
                error.style.display = 'none';
                if(isLoading) {
                    btn.disabled = true;
                    spinner.style.display = 'block';
                    text.textContent = 'Processing...';
                } else {
                    btn.disabled = false;
                    spinner.style.display = 'none';
                    text.textContent = type === 'merge' ? 'Merge Files' : 'Rotate PDF';
                }
            }

            function showError(type, msg) {
                const el = document.getElementById(`${type}Error`);
                el.textContent = "Error: " + msg;
                el.style.display = 'block';
            }
        </script>
    </body>
    </html>
    """
    return html_content