-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.js
More file actions
826 lines (730 loc) · 28 KB
/
Copy pathMain.js
File metadata and controls
826 lines (730 loc) · 28 KB
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";
/* =========================================================
STATE
========================================================= */
let pdfBytes = null; // pristine original file bytes, never mutated
let pdfjsDoc = null; // pdf.js document, used for preview + coordinate math
let pageOrder = []; // ordered list of ORIGINAL 1-based page numbers still in the document
let currentIndex = 0; // index into pageOrder (which page is currently shown)
let pageBaseRotation = {}; // { origPageNum: intrinsic /Rotate value from the source PDF }
let pageUserRotation = {}; // { origPageNum: extra rotation the user applied, degrees }
let pageScaleCache = {}; // { origPageNum: px-per-pt scale used to render/edit that page }
let annotations = []; // { id, page (ORIGINAL page number), type, x, y, w, h, ... }
let annotIdSeq = 1;
let selectedId = null;
let editingId = null; // id of the text box currently accepting keystrokes (vs. just selected)
let TARGET_WIDTH = null; // fixed once, on first load, so annotation coords stay valid
/* =========================================================
DOM
========================================================= */
const importBtn = document.getElementById('importBtn');
const pdfFileInput = document.getElementById('pdfFile');
const newPdfBtn = document.getElementById('newPdfBtn');
const exportBtn = document.getElementById('exportBtn');
const exportProgressBlock = document.getElementById('exportProgressBlock');
const clearBtn = document.getElementById('clearBtn');
const addTextBtn = document.getElementById('addTextBtn');
const fontFamilySelect = document.getElementById('fontFamily');
const fontSizeInput = document.getElementById('fontSize');
const fontColorInput = document.getElementById('fontColor');
const addImageBtn = document.getElementById('addImageBtn');
const imageFileInput = document.getElementById('imageFile');
// Maps our font-family option values to what pdf-lib needs (its 14 built-in
// standard fonts; no embedding/downloading required) and to a similar
// CSS stack so the preview looks right.
const STANDARD_FONT_MAP = {
'Helvetica': 'Helvetica',
'Helvetica-Bold': 'HelveticaBold',
'Times-Roman': 'TimesRoman',
'Times-Bold': 'TimesRomanBold',
'Courier': 'Courier',
'Courier-Bold': 'CourierBold'
};
const CSS_FONT_MAP = {
'Helvetica': { family: 'Helvetica, Arial, sans-serif', weight: 'normal' },
'Helvetica-Bold': { family: 'Helvetica, Arial, sans-serif', weight: 'bold' },
'Times-Roman': { family: '"Times New Roman", Times, serif', weight: 'normal' },
'Times-Bold': { family: '"Times New Roman", Times, serif', weight: 'bold' },
'Courier': { family: '"Courier New", Courier, monospace', weight: 'normal' },
'Courier-Bold': { family: '"Courier New", Courier, monospace', weight: 'bold' }
};
const rotateLeftBtn = document.getElementById('rotateLeftBtn');
const rotateRightBtn = document.getElementById('rotateRightBtn');
const deletePageBtn = document.getElementById('deletePageBtn');
const outputFilename = document.getElementById('outputFilename');
const outputSummary = document.getElementById('outputSummary');
const emptyState = document.getElementById('emptyState');
const stageWrap = document.getElementById('stageWrap');
const viewportArea = document.getElementById('viewportArea');
const stage = document.getElementById('stage');
const canvas = document.getElementById('pdf-canvas');
const overlay = document.getElementById('overlay');
const prevPageBtn = document.getElementById('prevPageBtn');
const nextPageBtn = document.getElementById('nextPageBtn');
const pageIndicator = document.getElementById('pageIndicator');
const contextMenu = document.getElementById('contextMenu');
/* =========================================================
LOADING A PDF
========================================================= */
importBtn.addEventListener('click', () => pdfFileInput.click());
pdfFileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (file) await handlePdfFile(file);
pdfFileInput.value = '';
});
async function handlePdfFile(file) {
if (file.type && file.type !== 'application/pdf' && !file.name.toLowerCase().endsWith('.pdf')) {
alert('That doesn\'t look like a PDF file.');
return;
}
const buf = await file.arrayBuffer();
pdfBytes = buf.slice(0);
await loadPdf(buf.slice(0));
}
newPdfBtn.addEventListener('click', async () => {
const { PDFDocument } = PDFLib;
const doc = await PDFDocument.create();
doc.addPage([612, 792]); // [595.28, 841.89] = A4.
const bytes = await doc.save();
pdfBytes = bytes;
await loadPdf(bytes.slice(0));
});
/* =========================================================
DRAG AND DROP
========================================================= */
let dragCounter = 0;
viewportArea.addEventListener('dragover', (e) => {
e.preventDefault();
});
viewportArea.addEventListener('dragenter', (e) => {
e.preventDefault();
dragCounter++;
viewportArea.classList.add('drag-active');
});
viewportArea.addEventListener('dragleave', (e) => {
e.preventDefault();
dragCounter = Math.max(0, dragCounter - 1);
if (dragCounter === 0) viewportArea.classList.remove('drag-active');
});
viewportArea.addEventListener('drop', async (e) => {
e.preventDefault();
dragCounter = 0;
viewportArea.classList.remove('drag-active');
const file = e.dataTransfer.files && e.dataTransfer.files[0];
if (file) await handlePdfFile(file);
});
async function loadPdf(bufferForJs) {
pdfjsDoc = await pdfjsLib.getDocument({ data: bufferForJs }).promise;
const pageCount = pdfjsDoc.numPages;
pageOrder = [];
pageBaseRotation = {};
pageUserRotation = {};
pageScaleCache = {};
annotations = [];
annotIdSeq = 1;
selectedId = null;
currentIndex = 0;
TARGET_WIDTH = null;
for (let i = 1; i <= pageCount; i++) {
pageOrder.push(i);
const page = await pdfjsDoc.getPage(i);
pageBaseRotation[i] = page.rotate || 0;
pageUserRotation[i] = 0;
}
emptyState.style.display = 'none';
stageWrap.style.display = 'block';
[exportBtn, clearBtn, addTextBtn, addImageBtn, rotateLeftBtn, rotateRightBtn,
deletePageBtn, prevPageBtn, nextPageBtn].forEach(el => el.disabled = false);
await renderCurrentPage();
updateOutputSummary();
}
/* =========================================================
RENDERING
========================================================= */
function combinedRotation(origPageNum) {
const total = (pageBaseRotation[origPageNum] || 0) + (pageUserRotation[origPageNum] || 0);
return ((total % 360) + 360) % 360;
}
async function renderCurrentPage() {
const pageNum = pageOrder[currentIndex];
const page = await pdfjsDoc.getPage(pageNum);
const rotation = combinedRotation(pageNum);
// Fix the on-screen render width once, based on the available viewport space,
// then reuse it for every page so previously-placed annotation coordinates stay valid.
if (TARGET_WIDTH === null) {
const available = viewportArea.clientWidth - 48; // minus padding
TARGET_WIDTH = Math.max(320, Math.min(available, 900));
}
const vpUnscaled = page.getViewport({ scale: 1, rotation });
const scale = TARGET_WIDTH / vpUnscaled.width;
pageScaleCache[pageNum] = scale;
const viewport = page.getViewport({ scale, rotation });
canvas.width = viewport.width;
canvas.height = viewport.height;
stage.style.width = viewport.width + 'px';
stage.style.height = viewport.height + 'px';
const ctx = canvas.getContext('2d');
await page.render({ canvasContext: ctx, viewport }).promise;
renderOverlay(pageNum);
updateFooter();
}
function renderOverlay(pageNum) {
overlay.innerHTML = '';
annotations.filter(a => a.page === pageNum).forEach(a => {
overlay.appendChild(buildAnnotEl(a));
});
}
function updateFooter() {
pageIndicator.textContent = `Page ${currentIndex + 1} of ${pageOrder.length}`;
prevPageBtn.disabled = currentIndex <= 0;
nextPageBtn.disabled = currentIndex >= pageOrder.length - 1;
}
prevPageBtn.addEventListener('click', async () => {
if (currentIndex > 0) { currentIndex--; await renderCurrentPage(); }
});
nextPageBtn.addEventListener('click', async () => {
if (currentIndex < pageOrder.length - 1) { currentIndex++; await renderCurrentPage(); }
});
/* =========================================================
ANNOTATION ELEMENTS (drag / edit / delete / resize)
========================================================= */
function buildAnnotEl(a) {
const el = document.createElement('div');
el.className = 'annot ' + (a.type === 'text' ? 'text-annot' : 'image-annot');
el.style.left = a.x + 'px';
el.style.top = a.y + 'px';
el.style.width = a.w + 'px';
el.dataset.id = a.id;
if (a.type === 'text') {
el.style.fontSize = a.fontSize + 'px';
el.style.color = a.color;
const fontCss = CSS_FONT_MAP[a.fontFamily] || CSS_FONT_MAP['Helvetica'];
el.style.fontFamily = fontCss.family;
el.style.fontWeight = fontCss.weight;
el.style.lineHeight = a.lineSpacing || 1.15;
el.textContent = a.text;
el.classList.toggle('is-empty', !a.text.trim());
// Only actively editable while it's the one box in "edit mode" (entered via
// double-click). Otherwise a single click can't tell "place cursor" apart
// from "start dragging", this keeps the two unambiguous.
el.contentEditable = (a.id === editingId) ? 'true' : 'false';
el.addEventListener('input', () => {
a.text = el.innerText;
el.classList.toggle('is-empty', !a.text.trim());
});
el.addEventListener('keydown', (ev) => {
// Force Enter to always insert a plain line break. Left to the browser's
// default, Chrome/Firefox/Safari each wrap new lines in different block
// elements (<div>, <p>, etc.), which makes reliably reading the text complete cancer.
if (ev.key === 'Enter') {
ev.preventDefault();
document.execCommand('insertLineBreak');
}
});
el.addEventListener('dblclick', (ev) => {
ev.preventDefault();
enterEditMode(a.id);
});
el.addEventListener('blur', () => {
if (editingId === a.id) editingId = null;
});
} else {
el.style.height = a.h + 'px';
const img = document.createElement('img');
img.src = a.imgDataUrl;
el.appendChild(img);
}
// Corner resize handles on all four corners, for both text (width + position
// only. Height stays auto-fit to content so wrapped text never gets clipped)
// and images (aspect-ratio-locked, from whichever corner you grab).
['tl', 'tr', 'bl', 'br'].forEach(corner => {
const handle = document.createElement('div');
handle.className = 'resize-handle ' + corner;
handle.contentEditable = 'false';
handle.addEventListener('mousedown', ev => {
ev.stopPropagation();
startResizeCorner(ev, a, el, corner);
});
el.appendChild(handle);
});
el.addEventListener('mousedown', ev => {
if (ev.target.classList.contains('resize-handle')) return;
selectAnnot(a.id);
if (a.id === editingId) {
// Currently typing into this box: a plain click should place the caret
// normally, but a click-and-drag should still move the box rather than
// fight with text selection.
startDragWithThreshold(ev, a, el);
return;
}
startDrag(ev, a, el);
});
// Backstop: never let the browser start a native HTML5 drag from inside an
// annotation (e.g. dragging selected text, or an <img>'s default drag-out
// behaviour), otherwise that's what was hijacks the page's "drop a PDF here" zone.
el.addEventListener('dragstart', ev => ev.preventDefault());
el.addEventListener('contextmenu', ev => {
ev.preventDefault();
selectAnnot(a.id);
openContextMenu(a, ev.clientX, ev.clientY);
});
if (a.id === selectedId) el.classList.add('selected');
return el;
}
function enterEditMode(id) {
// Only one box can be in edit mode at a time.
if (editingId != null && editingId !== id) {
const prevEl = overlay.querySelector(`[data-id="${editingId}"]`);
if (prevEl) prevEl.contentEditable = 'false';
}
editingId = id;
selectAnnot(id);
const el = overlay.querySelector(`[data-id="${id}"]`);
if (el) {
el.contentEditable = 'true';
el.focus();
}
}
function selectAnnot(id) {
selectedId = id;
[...overlay.children].forEach(c => c.classList.toggle('selected', c.dataset.id == id));
if (id != null) {
const a = annotations.find(x => x.id === id);
if (a && a.type === 'text') {
fontSizeInput.value = a.fontSize;
fontColorInput.value = a.color;
fontFamilySelect.value = a.fontFamily || 'Helvetica';
}
}
}
function startDrag(ev, a, el) {
ev.preventDefault();
const stageRect = stage.getBoundingClientRect();
const startX = ev.clientX, startY = ev.clientY;
const origX = a.x, origY = a.y;
function move(e) {
let nx = origX + (e.clientX - startX);
let ny = origY + (e.clientY - startY);
nx = Math.max(0, Math.min(nx, stageRect.width - a.w));
ny = Math.max(0, Math.min(ny, stageRect.height - (a.h || 20)));
a.x = nx; a.y = ny;
el.style.left = nx + 'px';
el.style.top = ny + 'px';
}
function up() {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', up);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', up);
}
// Same as startDrag, but doesn't commit to dragging until the mouse has actually
// moved a few pixels, so a plain click (no movement) leaves native contentEditable
// caret placement / text selection completely alone, and only a real drag takes over.
function startDragWithThreshold(ev, a, el) {
const THRESHOLD = 6;
const stageRect = stage.getBoundingClientRect();
const startX = ev.clientX, startY = ev.clientY;
const origX = a.x, origY = a.y;
let dragging = false;
function move(e) {
const dx = e.clientX - startX, dy = e.clientY - startY;
if (!dragging) {
if (Math.abs(dx) < THRESHOLD && Math.abs(dy) < THRESHOLD) return;
dragging = true;
// A drag just started: clear any in-progress text selection so it
// doesn't visually fight with the box moving.
const sel = window.getSelection();
if (sel) sel.removeAllRanges();
}
let nx = origX + dx, ny = origY + dy;
nx = Math.max(0, Math.min(nx, stageRect.width - a.w));
ny = Math.max(0, Math.min(ny, stageRect.height - (a.h || 20)));
a.x = nx; a.y = ny;
el.style.left = nx + 'px';
el.style.top = ny + 'px';
}
function up() {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', up);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', up);
}
// corner is one of 'tl' | 'tr' | 'bl' | 'br'.
// Text: only width (and x, when dragging a left-hand corner) changes — height
// stays auto-fit to content so wrapped text is never clipped by a fixed box.
// Image: aspect ratio stays locked, resizing from whichever corner you grab.
function startResizeCorner(ev, a, el, corner) {
ev.preventDefault();
const startX = ev.clientX, startY = ev.clientY;
const origX = a.x, origY = a.y, origW = a.w, origH = a.h;
const isImage = a.type === 'image';
const ratio = isImage && origH ? origW / origH : 1;
const isLeft = corner === 'tl' || corner === 'bl';
const isTop = corner === 'tl' || corner === 'tr';
const MIN = 16;
function move(e) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
let nw = Math.max(MIN, isLeft ? origW - dx : origW + dx);
let nh = origH;
if (isImage) {
nh = Math.max(MIN, isTop ? origH - dy : origH + dy);
// Lock to whichever dimension the user is dragging more. Feels natural
// whether the gesture is mostly horizontal or mostly vertical.
if (Math.abs(dx) >= Math.abs(dy)) nh = nw / ratio;
else nw = nh * ratio;
}
a.w = nw;
a.x = isLeft ? origX + (origW - nw) : origX;
el.style.width = nw + 'px';
el.style.left = a.x + 'px';
if (isImage) {
a.h = nh;
a.y = isTop ? origY + (origH - nh) : origY;
el.style.height = nh + 'px';
el.style.top = a.y + 'px';
}
}
function up() {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', up);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', up);
}
/* =========================================================
RIGHT-CLICK CONTEXT MENU
========================================================= */
function openContextMenu(a, clientX, clientY) {
contextMenu.innerHTML = '';
if (a.type === 'text') {
const fontRow = document.createElement('div');
fontRow.className = 'cm-row';
const fontLabel = document.createElement('label');
fontLabel.textContent = 'Font';
const fontSel = document.createElement('select');
Object.keys(CSS_FONT_MAP).forEach(key => {
const opt = document.createElement('option');
opt.value = key;
opt.textContent = fontFamilySelect.querySelector(`option[value="${key}"]`).textContent;
if (key === a.fontFamily) opt.selected = true;
fontSel.appendChild(opt);
});
fontSel.addEventListener('change', () => {
a.fontFamily = fontSel.value;
renderOverlay(a.page);
});
fontRow.appendChild(fontLabel);
fontRow.appendChild(fontSel);
contextMenu.appendChild(fontRow);
const sizeRow = document.createElement('div');
sizeRow.className = 'cm-row';
const sizeLabel = document.createElement('label');
sizeLabel.textContent = 'Size';
const sizeInput = document.createElement('input');
sizeInput.type = 'number';
sizeInput.min = '6'; sizeInput.max = '96';
sizeInput.value = a.fontSize;
sizeInput.addEventListener('change', () => {
a.fontSize = parseInt(sizeInput.value, 10) || 16;
renderOverlay(a.page);
});
sizeRow.appendChild(sizeLabel);
sizeRow.appendChild(sizeInput);
contextMenu.appendChild(sizeRow);
const spacingRow = document.createElement('div');
spacingRow.className = 'cm-row';
const spacingLabel = document.createElement('label');
spacingLabel.textContent = 'Line spacing';
const spacingInput = document.createElement('input');
spacingInput.type = 'number';
spacingInput.min = '0.8'; spacingInput.max = '3'; spacingInput.step = '0.05';
spacingInput.value = a.lineSpacing || 1.15;
spacingInput.addEventListener('change', () => {
a.lineSpacing = parseFloat(spacingInput.value) || 1.15;
renderOverlay(a.page);
});
spacingRow.appendChild(spacingLabel);
spacingRow.appendChild(spacingInput);
contextMenu.appendChild(spacingRow);
const colorRow = document.createElement('div');
colorRow.className = 'cm-row';
const colorLabel = document.createElement('label');
colorLabel.textContent = 'Colour';
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.value = a.color;
colorInput.addEventListener('input', () => {
a.color = colorInput.value;
renderOverlay(a.page);
});
colorRow.appendChild(colorLabel);
colorRow.appendChild(colorInput);
contextMenu.appendChild(colorRow);
}
const delRow = document.createElement('button');
delRow.className = 'button cm-delete';
delRow.textContent = a.type === 'text' ? 'Delete text box' : 'Delete image';
delRow.style.width = '100%';
delRow.addEventListener('click', () => {
annotations = annotations.filter(x => x.id !== a.id);
renderOverlay(a.page);
closeContextMenu();
});
contextMenu.appendChild(delRow);
contextMenu.style.display = 'flex';
// Position after showing so we can measure it, then clamp to the viewport.
const menuRect = contextMenu.getBoundingClientRect();
let left = clientX, top = clientY;
if (left + menuRect.width > window.innerWidth) left = window.innerWidth - menuRect.width - 8;
if (top + menuRect.height > window.innerHeight) top = window.innerHeight - menuRect.height - 8;
contextMenu.style.left = Math.max(8, left) + 'px';
contextMenu.style.top = Math.max(8, top) + 'px';
}
function closeContextMenu() {
contextMenu.style.display = 'none';
contextMenu.innerHTML = '';
}
document.addEventListener('mousedown', (e) => {
if (contextMenu.style.display === 'none') return;
if (!e.target.closest('#contextMenu')) closeContextMenu();
});
window.addEventListener('scroll', closeContextMenu, true);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeContextMenu();
});
/* =========================================================
ADDING ANNOTATIONS
========================================================= */
addTextBtn.addEventListener('click', () => {
const pageNum = pageOrder[currentIndex];
const a = {
id: annotIdSeq++,
page: pageNum,
type: 'text',
x: 60, y: 60, w: 220, h: 24,
text: '',
fontSize: parseInt(fontSizeInput.value, 10) || 16,
fontFamily: fontFamilySelect.value,
color: fontColorInput.value,
lineSpacing: 1.15
};
annotations.push(a);
renderOverlay(pageNum);
enterEditMode(a.id);
updateOutputSummary();
});
fontFamilySelect.addEventListener('change', () => {
if (selectedId == null) return;
const a = annotations.find(x => x.id === selectedId);
if (a && a.type === 'text') {
a.fontFamily = fontFamilySelect.value;
renderOverlay(a.page);
}
});
fontSizeInput.addEventListener('change', () => {
if (selectedId == null) return;
const a = annotations.find(x => x.id === selectedId);
if (a && a.type === 'text') {
a.fontSize = parseInt(fontSizeInput.value, 10) || 16;
renderOverlay(a.page);
}
});
fontColorInput.addEventListener('change', () => {
if (selectedId == null) return;
const a = annotations.find(x => x.id === selectedId);
if (a && a.type === 'text') {
a.color = fontColorInput.value;
renderOverlay(a.page);
}
});
addImageBtn.addEventListener('click', () => imageFileInput.click());
imageFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
const dataUrl = ev.target.result;
const img = new Image();
img.onload = () => {
const pageNum = pageOrder[currentIndex];
const maxW = 220;
const w = Math.min(maxW, img.width);
const h = w * (img.height / img.width);
const a = {
id: annotIdSeq++,
page: pageNum,
type: 'image',
x: 60, y: 100, w, h,
imgDataUrl: dataUrl
};
annotations.push(a);
renderOverlay(pageNum);
selectAnnot(a.id);
updateOutputSummary();
};
img.src = dataUrl;
};
reader.readAsDataURL(file);
imageFileInput.value = '';
});
document.addEventListener('mousedown', (e) => {
if (e.target.closest('.annot')) return; // its own handlers take care of this
if (e.target.closest('#editToolbar')) return; // don't deselect when using the toolbar
if (e.target.closest('#contextMenu')) return; // don't deselect when using the context menu
selectAnnot(null);
});
/* =========================================================
PAGES TAB (rotate/delete)
========================================================= */
rotateLeftBtn.addEventListener('click', async () => {
const pageNum = pageOrder[currentIndex];
pageUserRotation[pageNum] = ((pageUserRotation[pageNum] || 0) - 90 + 360) % 360;
await renderCurrentPage();
});
rotateRightBtn.addEventListener('click', async () => {
const pageNum = pageOrder[currentIndex];
pageUserRotation[pageNum] = ((pageUserRotation[pageNum] || 0) + 90) % 360;
await renderCurrentPage();
});
deletePageBtn.addEventListener('click', async () => {
if (pageOrder.length <= 1) {
alert("Can't delete the only remaining page.");
return;
}
if (!confirm('Delete this page from the export? This cannot be undone within the session.')) return;
pageOrder.splice(currentIndex, 1);
currentIndex = Math.min(currentIndex, pageOrder.length - 1);
await renderCurrentPage();
updateOutputSummary();
});
/* =========================================================
CLEAR SESSION
========================================================= */
clearBtn.addEventListener('click', () => {
if (!confirm('Clear the current document and all edits?')) return;
pdfBytes = null;
pdfjsDoc = null;
pageOrder = [];
annotations = [];
selectedId = null;
currentIndex = 0;
TARGET_WIDTH = null;
emptyState.style.display = 'block';
stageWrap.style.display = 'none';
overlay.innerHTML = '';
[exportBtn, clearBtn, addTextBtn, addImageBtn, rotateLeftBtn, rotateRightBtn,
deletePageBtn, prevPageBtn, nextPageBtn].forEach(el => el.disabled = true);
pageIndicator.textContent = 'No document loaded';
updateOutputSummary();
});
/* =========================================================
STATUS SUMMARY (shown in the footer)
========================================================= */
function updateOutputSummary() {
if (!pdfjsDoc) {
outputSummary.textContent = 'Open a PDF to get started.';
return;
}
const textCount = annotations.filter(a => a.type === 'text').length;
const imgCount = annotations.filter(a => a.type === 'image').length;
outputSummary.textContent =
`${pageOrder.length} page${pageOrder.length === 1 ? '' : 's'} · ` +
`${textCount} text box${textCount === 1 ? '' : 'es'} · ` +
`${imgCount} image${imgCount === 1 ? '' : 's'}`;
}
exportBtn.addEventListener('click', downloadPdf);
/* =========================================================
EXPORT
========================================================= */
async function downloadPdf() {
exportBtn.disabled = true;
exportProgressBlock.style.display = 'flex';
try {
const { PDFDocument, degrees, rgb, StandardFonts } = PDFLib;
const srcDoc = await PDFDocument.load(pdfBytes.slice(0));
const outDoc = await PDFDocument.create();
const fontCache = {};
async function getFont(fontFamilyKey) {
const stdName = STANDARD_FONT_MAP[fontFamilyKey] || StandardFonts.Helvetica;
if (!fontCache[stdName]) {
fontCache[stdName] = await outDoc.embedFont(StandardFonts[stdName] || StandardFonts.Helvetica);
}
return fontCache[stdName];
}
const zeroBasedIndices = pageOrder.map(n => n - 1);
const copiedPages = await outDoc.copyPages(srcDoc, zeroBasedIndices);
copiedPages.forEach((page, i) => {
outDoc.addPage(page);
const origPageNum = pageOrder[i];
page.setRotation(degrees(combinedRotation(origPageNum)));
});
const imgCache = {};
for (const a of annotations) {
const displayIdx = pageOrder.indexOf(a.page);
if (displayIdx === -1) continue; // its page was deleted
const outPage = outDoc.getPages()[displayIdx];
const pdfjsPage = await pdfjsDoc.getPage(a.page);
const rotation = combinedRotation(a.page);
const scale = pageScaleCache[a.page] ||
(TARGET_WIDTH / pdfjsPage.getViewport({ scale: 1, rotation }).width);
const viewport = pdfjsPage.getViewport({ scale, rotation });
if (a.type === 'text') {
const sizePt = a.fontSize / scale;
const maxWidthPt = a.w / scale;
// approximate baseline offset from the top of the box
const anchorX = a.x;
const anchorY = a.y + a.fontSize * 0.85;
const [px, py] = viewport.convertToPdfPoint(anchorX, anchorY);
const c = hexToRgb01(a.color);
const font = await getFont(a.fontFamily);
outPage.drawText(a.text || '', {
x: px, y: py, size: sizePt, font,
color: rgb(c.r, c.g, c.b),
lineHeight: sizePt * (a.lineSpacing || 1.15),
maxWidth: maxWidthPt
});
} else {
const [x1, y1] = viewport.convertToPdfPoint(a.x, a.y);
const [x2, y2] = viewport.convertToPdfPoint(a.x + a.w, a.y + a.h);
const xPt = Math.min(x1, x2), yPt = Math.min(y1, y2);
const wPt = Math.abs(x2 - x1), hPt = Math.abs(y2 - y1);
let embedded = imgCache[a.imgDataUrl];
if (!embedded) {
const isPng = a.imgDataUrl.startsWith('data:image/png');
const base64 = a.imgDataUrl.split(',')[1];
const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
embedded = isPng ? await outDoc.embedPng(bytes) : await outDoc.embedJpg(bytes);
imgCache[a.imgDataUrl] = embedded;
}
outPage.drawImage(embedded, { x: xPt, y: yPt, width: wPt, height: hPt });
}
}
const outBytes = await outDoc.save();
const blob = new Blob([outBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = (outputFilename.value || 'signed.pdf').trim() || 'signed.pdf';
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
} catch (err) {
console.error(err);
alert('Something went wrong generating the PDF: ' + err.message);
} finally {
exportBtn.disabled = false;
exportProgressBlock.style.display = 'none';
}
}
function hexToRgb01(hex) {
const h = hex.replace('#', '');
return {
r: parseInt(h.substring(0, 2), 16) / 255,
g: parseInt(h.substring(2, 4), 16) / 255,
b: parseInt(h.substring(4, 6), 16) / 255
};
}