File size: 29,921 Bytes
b7ea422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced PDF Editor</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: #1e293b; }
        ::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: #64748b; }
        /* Custom styles for file inputs */
        input[type="file"]::file-selector-button {
            @apply bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 px-4 rounded-lg cursor-pointer transition-colors duration-200;
        }
        /* Custom select arrow */
        select {
            -webkit-appearance: none; -moz-appearance: none; appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke-width='2' stroke='%2394a3b8'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5' /%3E%3C/svg%3E");
            background-repeat: no-repeat; background-position: right 0.5rem center; background-size: 1.25em; padding-right: 2rem;
        }
        /* NEW: Styles for editable text layer */
        .text-layer {
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.2s;
        }
        .text-layer.active {
            opacity: 1;
            pointer-events: auto;
        }
        .text-layer > div {
            position: absolute;
            transform-origin: 0 0;
            color: transparent;
            caret-color: black;
            outline: 1px dashed rgba(67, 56, 202, 0);
            transition: outline 0.2s;
            white-space: pre;
            overflow: hidden;
            -webkit-user-select: text;
            -moz-user-select: text;
            -ms-user-select: text;
            user-select: text;
        }
        .text-layer.active > div:hover {
            outline: 1px dashed #c7d2fe;
        }
        .text-layer.active > div:focus {
             outline: 2px solid #4f46e5;
             background-color: rgba(199, 210, 254, 0.3);
        }
    </style>
</head>
<body class="bg-slate-900 text-slate-300">

    <div id="loading-overlay" class="fixed inset-0 bg-black bg-opacity-70 z-50 flex-col items-center justify-center hidden">
        <div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-indigo-500"></div>
        <p id="loading-text" class="text-white text-xl mt-4">Loading...</p>
    </div>

    <div class="flex flex-col md:flex-row h-screen">
        <aside id="sidebar" class="w-full md:w-80 lg:w-96 bg-slate-800 p-6 shadow-2xl overflow-y-auto transition-all duration-300">
            <h1 class="text-2xl font-bold text-white mb-6">Advanced PDF Editor</h1>

            <div class="mb-6">
                <label for="pdf-upload" class="block text-sm font-medium text-slate-400 mb-2">1. Upload PDF</label>
                <input type="file" id="pdf-upload" accept=".pdf" class="block w-full text-sm text-slate-400 file:mr-4 file:border-0">
            </div>

            <div id="controls-panel" class="space-y-6 hidden">
                <div class="p-4 bg-slate-700/50 rounded-lg">
                    <h3 class="font-semibold text-white mb-3">Document Settings</h3>
                     <div>
                        <label for="document-name" class="block text-sm font-medium text-slate-400 mb-1">Document Name</label>
                        <input type="text" id="document-name" placeholder="edited-document" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                    </div>
                </div>

                <div class="p-4 bg-slate-700/50 rounded-lg">
                    <h3 class="font-semibold text-white mb-3">Text Editing</h3>
                    <div class="space-y-4">
                       <p class="text-sm text-slate-400">Enable to edit text content directly on the pages.</p>
                       <button id="toggle-text-edit-btn" class="w-full bg-indigo-500 hover:bg-indigo-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200">Enable Text Editing</button>
                    </div>
                </div>

                <div class="p-4 bg-slate-700/50 rounded-lg">
                    <h3 class="font-semibold text-white mb-3">Image Watermark</h3>
                    <div class="space-y-4">
                        <div>
                            <label for="watermark-upload" class="block text-sm font-medium text-slate-400 mb-2">Upload Image</label>
                            <input type="file" id="watermark-upload" accept="image/png, image/jpeg" class="block w-full text-sm text-slate-400 file:mr-4 file:border-0">
                        </div>
                        <div>
                            <label for="watermark-opacity" class="block text-sm font-medium text-slate-400">Opacity: <span id="watermark-opacity-value">0.3</span></label>
                            <input type="range" id="watermark-opacity" min="0" max="1" step="0.05" value="0.3" class="w-full h-2 bg-slate-600 rounded-lg appearance-none cursor-pointer">
                        </div>
                    </div>
                </div>

                <div class="p-4 bg-slate-700/50 rounded-lg">
                    <h3 class="font-semibold text-white mb-3">Page Border</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="border-color" class="block text-sm font-medium text-slate-400 mb-1">Color</label>
                            <input type="color" id="border-color" value="#000000" class="w-full h-10 p-1 bg-slate-600 rounded-md cursor-pointer">
                        </div>
                        <div>
                            <label for="border-width" class="block text-sm font-medium text-slate-400 mb-1">Width (px)</label>
                            <input type="number" id="border-width" min="0" value="0" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <div class="col-span-2">
                            <label for="border-position" class="block text-sm font-medium text-slate-400 mb-1">Position</label>
                            <select id="border-position" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                                <option value="center">Center</option>
                                <option value="inside">Inside</option>
                                <option value="outside">Outside</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="p-4 bg-slate-700/50 rounded-lg">
                    <h3 class="font-semibold text-white mb-3">Header & Footer</h3>
                    <div class="space-y-4">
                        <div>
                            <label for="header-text" class="block text-sm font-medium text-slate-400 mb-1">Header Text</label>
                            <input type="text" id="header-text" placeholder="e.g., Confidential" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <div>
                            <label for="footer-text" class="block text-sm font-medium text-slate-400 mb-1">Footer Text</label>
                            <input type="text" id="footer-text" placeholder="e.g., Company Name" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <div>
                            <label for="font-family" class="block text-sm font-medium text-slate-400 mb-1">Font</label>
                            <select id="font-family" class="w-full bg-slate-600 text-white rounded-md border-slate-500 focus:ring-indigo-500 focus:border-indigo-500">
                                <option>Arial</option>
                                <option>Helvetica</option>
                                <option>Times New Roman</option>
                                <option>Courier New</option>
                                <option>Verdana</option>
                                <option>Georgia</option>
                            </select>
                        </div>
                        <div class="flex items-center">
                            <input id="page-numbers" type="checkbox" checked class="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-600">
                            <label for="page-numbers" class="ml-3 block text-sm font-medium text-slate-400">Add Page Numbers (updates automatically)</label>
                        </div>
                    </div>
                </div>
                
                <div class="pt-4 space-y-3">
                    <button id="download-btn" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center">
                        <svg class="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" /></svg>
                        Download Edited PDF
                    </button>
                    <button id="reset-btn" class="w-full bg-rose-600 hover:bg-rose-700 text-white font-bold py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center">
                       <svg class="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0011.664 0l3.181-3.183m-4.991-2.695v4.992h-4.992m0 0l-3.181-3.183a8.25 8.25 0 0111.664 0l3.181 3.183" /></svg>
                        Reset All Edits
                    </button>
                </div>
            </div>
        </aside>

        <main id="pdf-viewer-container" class="flex-1 p-4 lg:p-8 overflow-y-auto">
            <div id="pdf-viewer" class="flex flex-col items-center space-y-6">
                <div id="placeholder" class="w-full h-full flex flex-col items-center justify-center text-slate-500">
                    <svg class="w-24 h-24 mb-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>
                    <h2 class="text-2xl font-semibold">Your PDF will appear here</h2>
                    <p class="mt-2">Upload a file using the panel on the left to get started.</p>
                </div>
            </div>
        </main>
    </div>

    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js`;

        // DOM Elements
        const pdfUpload = document.getElementById('pdf-upload');
        const pdfViewer = document.getElementById('pdf-viewer');
        const placeholder = document.getElementById('placeholder');
        const controlsPanel = document.getElementById('controls-panel');
        const loadingOverlay = document.getElementById('loading-overlay');
        const loadingText = document.getElementById('loading-text');

        // Control Elements
        const documentNameInput = document.getElementById('document-name');
        const watermarkUpload = document.getElementById('watermark-upload');
        const watermarkOpacitySlider = document.getElementById('watermark-opacity');
        const watermarkOpacityValue = document.getElementById('watermark-opacity-value');
        const borderColorPicker = document.getElementById('border-color');
        const borderWidthInput = document.getElementById('border-width');
        const borderPositionSelect = document.getElementById('border-position');
        const headerTextInput = document.getElementById('header-text');
        const footerTextInput = document.getElementById('footer-text');
        const fontFamilySelect = document.getElementById('font-family');
        const pageNumbersCheckbox = document.getElementById('page-numbers');
        const downloadBtn = document.getElementById('download-btn');
        const resetBtn = document.getElementById('reset-btn');
        const toggleTextEditBtn = document.getElementById('toggle-text-edit-btn'); // NEW

        // App State
        let pdfDoc = null;
        let originalCanvases = [];
        let watermarkImage = null;
        let deletedPageIndexes = new Set();
        let textEditModeEnabled = false; // NEW

        // --- PDF Loading and Rendering ---

        pdfUpload.addEventListener('change', handlePdfUpload);

        async function handlePdfUpload(event) {
            const file = event.target.files[0];
            if (!file || file.type !== 'application/pdf') {
                alert('Please select a valid PDF file.');
                return;
            }
            resetAll(false);
            const fileReader = new FileReader();
            fileReader.onload = async (e) => {
                showLoading('Loading PDF...');
                try {
                    const typedarray = new Uint8Array(e.target.result);
                    pdfDoc = await pdfjsLib.getDocument({ data: typedarray }).promise;
                    await renderAllPages();
                    controlsPanel.classList.remove('hidden');
                    placeholder.classList.add('hidden');
                } catch (error) {
                    console.error('Error loading PDF:', error);
                    alert('Could not load the PDF. It might be corrupted or protected.');
                } finally {
                    hideLoading();
                }
            };
            fileReader.readAsArrayBuffer(file);
        }

        async function renderAllPages() {
            pdfViewer.innerHTML = '';
            originalCanvases = [];
            deletedPageIndexes.clear();
            const numPages = pdfDoc.numPages;
            const scale = 1.5;

            for (let i = 0; i < numPages; i++) {
                showLoading(`Rendering page ${i + 1} of ${numPages}...`);
                const page = await pdfDoc.getPage(i + 1);
                const viewport = page.getViewport({ scale });

                const pageContainer = document.createElement('div');
                pageContainer.className = 'page-container relative bg-white rounded-lg shadow-lg overflow-hidden';
                pageContainer.dataset.pageIndex = i;
                
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                const deleteButton = document.createElement('button');
                deleteButton.innerHTML = '&times;';
                deleteButton.className = 'absolute top-2 right-2 w-8 h-8 bg-red-600 text-white text-xl font-bold rounded-full flex items-center justify-center hover:bg-red-700 transition-all z-20';
                deleteButton.title = 'Delete Page';
                deleteButton.onclick = () => deletePage(i);
                
                const renderContext = { canvasContext: context, viewport: viewport };
                await page.render(renderContext).promise;
                
                originalCanvases.push(canvas.toDataURL());
                
                // NEW: Create and render the text layer
                const textLayerDiv = document.createElement('div');
                textLayerDiv.className = 'text-layer';
                await renderTextLayer(page, scale, textLayerDiv);

                pageContainer.appendChild(deleteButton);
                pageContainer.appendChild(canvas);
                pageContainer.appendChild(textLayerDiv); // Add text layer on top
                pdfViewer.appendChild(pageContainer);
            }
        }
        
        // NEW: Function to render the editable text layer
        async function renderTextLayer(page, scale, container) {
            const textContent = await page.getTextContent();
            const viewport = page.getViewport({ scale });
            textContent.items.forEach(item => {
                const textDiv = document.createElement('div');
                textDiv.textContent = item.str;
                textDiv.setAttribute('contenteditable', 'true');
                
                const style = textDiv.style;
                style.height = `${item.height}px`;
                style.fontFamily = item.fontName;

                // pdf.js gives a transform matrix [scaleX, skewY, skewX, scaleY, x, y]
                // We need to convert it to a CSS matrix for proper positioning and rotation
                const cssTransform = `matrix(${item.transform[0]}, ${item.transform[1]}, ${item.transform[2]}, ${item.transform[3]}, ${item.transform[4]}, ${viewport.height - item.transform[5]})`;
                style.transform = cssTransform;
                
                // Adjust font size based on the scaling in the transform matrix
                const fontHeight = Math.sqrt((item.transform[2] * item.transform[2]) + (item.transform[3] * item.transform[3]));
                style.fontSize = `${fontHeight}px`;

                container.appendChild(textDiv);
            });
        }
        
        // --- Event Listeners for Controls ---
        const controls = [watermarkOpacitySlider, borderColorPicker, borderWidthInput, borderPositionSelect, headerTextInput, footerTextInput, pageNumbersCheckbox, fontFamilySelect];
        controls.forEach(control => {
            control.addEventListener('input', () => {
                if (control.id === 'watermark-opacity') watermarkOpacityValue.textContent = control.value;
                applyAllEdits();
            });
        });
        
        watermarkUpload.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = (e) => {
                watermarkImage = new Image();
                watermarkImage.onload = applyAllEdits;
                watermarkImage.src = e.target.result;
            };
            reader.readAsDataURL(file);
        });
        
        resetBtn.addEventListener('click', () => resetAll(true));
        
        // NEW: Listener for text edit toggle
        toggleTextEditBtn.addEventListener('click', () => {
            textEditModeEnabled = !textEditModeEnabled;
            document.querySelectorAll('.text-layer').forEach(layer => {
                layer.classList.toggle('active', textEditModeEnabled);
            });
            if (textEditModeEnabled) {
                toggleTextEditBtn.textContent = 'Disable Text Editing';
                toggleTextEditBtn.classList.replace('bg-indigo-500', 'bg-amber-600');
                toggleTextEditBtn.classList.replace('hover:bg-indigo-600', 'hover:bg-amber-700');
            } else {
                toggleTextEditBtn.textContent = 'Enable Text Editing';
                toggleTextEditBtn.classList.replace('bg-amber-600', 'bg-indigo-500');
                toggleTextEditBtn.classList.replace('hover:bg-amber-700', 'hover:bg-indigo-600');
            }
        });

        // --- Core Editing Logic ---
        
        function deletePage(index) {
            if (deletedPageIndexes.has(index)) return;
            const visiblePages = pdfDoc.numPages - deletedPageIndexes.size;
            if (visiblePages <= 1) {
                alert("You cannot delete the last page.");
                return;
            }
            deletedPageIndexes.add(index);
            const pageContainer = document.querySelector(`.page-container[data-page-index='${index}']`);
            if (pageContainer) pageContainer.style.display = 'none';
            applyAllEdits();
        }

        function applyAllEdits() {
            if (!pdfDoc) return;
            const visiblePageContainers = Array.from(document.querySelectorAll('.page-container')).filter(c => c.style.display !== 'none');
            const newTotalPages = visiblePageContainers.length;

            visiblePageContainers.forEach((container, newPageIndex) => {
                const originalIndex = parseInt(container.dataset.pageIndex);
                const canvas = container.querySelector('canvas');
                const context = canvas.getContext('2d');
                const originalImage = new Image();
                originalImage.onload = () => {
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.drawImage(originalImage, 0, 0);
                    drawWatermark(context, canvas.width, canvas.height);
                    drawBorder(context, canvas.width, canvas.height);
                    drawHeaderText(context, canvas.width);
                    drawFooterText(context, canvas.width, canvas.height, newPageIndex + 1, newTotalPages);
                };
                originalImage.src = originalCanvases[originalIndex];
            });
        }
        
        const getTextFont = () => `${'16px'} ${fontFamilySelect.value}`;

        function drawHeaderText(ctx, width) {
            const text = headerTextInput.value;
            if (!text) return;
            ctx.fillStyle = '#000000';
            ctx.font = getTextFont();
            ctx.textAlign = 'center';
            ctx.fillText(text, width / 2, 30);
        }

        function drawFooterText(ctx, width, height, pageNum, totalPages) {
            const userText = footerTextInput.value;
            let fullText = userText;
            if (pageNumbersCheckbox.checked) {
                const pageNumText = `Page ${pageNum} of ${totalPages}`;
                fullText = userText ? `${userText} | ${pageNumText}` : pageNumText;
            }
            if (!fullText) return;
            ctx.fillStyle = '#000000';
            ctx.font = getTextFont();
            ctx.textAlign = 'center';
            ctx.fillText(fullText, width / 2, height - 20);
        }

        function drawWatermark(ctx, width, height) {
            if (!watermarkImage) return;
            ctx.globalAlpha = parseFloat(watermarkOpacitySlider.value);
            const canvasAspect = width / height;
            const imgAspect = watermarkImage.width / watermarkImage.height;
            let drawWidth, drawHeight;
            if (canvasAspect > imgAspect) {
                drawHeight = height * 0.6;
                drawWidth = drawHeight * imgAspect;
            } else {
                drawWidth = width * 0.6;
                drawHeight = drawWidth / imgAspect;
            }
            ctx.drawImage(watermarkImage, (width - drawWidth) / 2, (height - drawHeight) / 2, drawWidth, drawHeight);
            ctx.globalAlpha = 1.0;
        }

        function drawBorder(ctx, width, height) {
            const borderWidth = parseInt(borderWidthInput.value);
            if (borderWidth <= 0) return;
            ctx.strokeStyle = borderColorPicker.value;
            ctx.lineWidth = borderWidth;
            const position = borderPositionSelect.value;
            ctx.beginPath();
            if (position === 'inside') ctx.rect(borderWidth, borderWidth, width - borderWidth * 2, height - borderWidth * 2);
            else if (position === 'outside') ctx.rect(0, 0, width, height);
            else ctx.rect(borderWidth / 2, borderWidth / 2, width - borderWidth, height - borderWidth);
            ctx.stroke();
        }

        // --- PDF Generation & Utility ---

        downloadBtn.addEventListener('click', generatePdf);
        
        // NEW: Function to burn text edits onto the canvas before download
        async function burnTextEdits() {
            showLoading('Applying text edits...');
            const visibleContainers = Array.from(document.querySelectorAll('.page-container')).filter(c => c.style.display !== 'none');
            for (const container of visibleContainers) {
                const textLayer = container.querySelector('.text-layer');
                const canvas = container.querySelector('canvas');
                const ctx = canvas.getContext('2d');

                // Use html2canvas to render the HTML text layer to a temporary canvas
                const textCanvas = await html2canvas(textLayer, {
                    backgroundColor: null, // Transparent background
                    scale: 1, // Already scaled
                    width: canvas.width,
                    height: canvas.height,
                    logging: false
                });

                // Draw the rendered text on top of the main canvas
                ctx.drawImage(textCanvas, 0, 0);
            }
        }

        async function generatePdf() {
            if (!pdfDoc) return;
            showLoading('Generating PDF...');
            
            // Turn off text edit mode visually to prevent outlines in the final PDF
            const wasEditing = textEditModeEnabled;
            if (wasEditing) toggleTextEditBtn.click();
            
            applyAllEdits();

            try {
                // NEW: Wait for text edits to be burned onto the canvas
                await burnTextEdits();

                const { jsPDF } = window.jspdf;
                const visibleCanvases = Array.from(document.querySelectorAll('.page-container')).filter(c => c.style.display !== 'none').map(c => c.querySelector('canvas'));
                if (visibleCanvases.length === 0) {
                    alert("No pages to generate.");
                    hideLoading();
                    return;
                }

                const firstCanvas = visibleCanvases[0];
                const orientation = firstCanvas.width > firstCanvas.height ? 'l' : 'p';
                const pdf = new jsPDF(orientation, 'px', [firstCanvas.width, firstCanvas.height]);
                
                visibleCanvases.forEach((canvas, index) => {
                    const imgData = canvas.toDataURL('image/jpeg', 0.9);
                    if (index > 0) pdf.addPage([canvas.width, canvas.height], orientation);
                    pdf.addImage(imgData, 'JPEG', 0, 0, canvas.width, canvas.height);
                });

                const docName = documentNameInput.value.trim() || 'edited-document';
                pdf.save(`${docName}.pdf`);
            } catch(error) {
                console.error("Error generating PDF:", error);
                alert("An error occurred while generating the PDF.");
            } finally {
                // Restore text edit mode if it was on
                if (wasEditing) toggleTextEditBtn.click();
                hideLoading();
            }
        }

        function resetAll(redraw) {
            // Reset text edit mode if enabled
            if (textEditModeEnabled) {
                toggleTextEditBtn.click();
            }
            // Remove text layers before resetting other things
            document.querySelectorAll('.text-layer').forEach(layer => layer.remove());

            document.querySelectorAll('.page-container').forEach(c => c.style.display = 'block');
            deletedPageIndexes.clear();
            
            documentNameInput.value = '';
            watermarkUpload.value = '';
            watermarkImage = null;
            watermarkOpacitySlider.value = 0.3;
            watermarkOpacityValue.textContent = '0.3';
            borderColorPicker.value = '#000000';
            borderWidthInput.value = 0;
            borderPositionSelect.value = 'center';
            headerTextInput.value = '';
            footerTextInput.value = '';
            fontFamilySelect.value = 'Arial';
            pageNumbersCheckbox.checked = true;

            if (redraw && pdfDoc) {
                // If redrawing, re-render text layers as well.
                renderAllPages(); 
            } else if (redraw) {
                applyAllEdits();
            }
        }

        function showLoading(message) {
            loadingText.textContent = message;
            loadingOverlay.classList.remove('hidden');
            loadingOverlay.classList.add('flex');
        }

        function hideLoading() {
            loadingOverlay.classList.add('hidden');
            loadingOverlay.classList.remove('flex');
        }

    </script>
</body>
</html>