Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
584 lines (552 loc) · 29 KB
/
Copy pathindex.html
File metadata and controls
584 lines (552 loc) · 29 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
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>توقيع المستندات</title>
<style>
:root{
--gold:#B68A35; --gold-d:#9c742a; --ink:#1b1b1b; --muted:#6b6b6b;
--bg:#f4f5f7; --card:#ffffff; --line:#e3e5ea; --ok:#2e7d4f; --danger:#c0392b;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;font-family:"Segoe UI",Tahoma,"Noto Naskh Arabic",Arial,sans-serif;background:var(--bg);color:var(--ink)}
header{background:var(--card);border-bottom:1px solid var(--line);padding:14px 18px;display:flex;align-items:center;gap:12px;position:sticky;top:0;z-index:50}
header .logo{width:34px;height:34px;border-radius:9px;background:linear-gradient(135deg,var(--gold),var(--gold-d));display:flex;align-items:center;justify-content:center;color:#fff;flex:0 0 auto}
.btn svg,.tab svg,.logo svg{flex:0 0 auto}
header h1{font-size:18px;margin:0;font-weight:700}
header .sub{font-size:12px;color:var(--muted)}
.langSwitch{margin-inline-start:auto;display:flex;gap:3px;border:1px solid var(--line);border-radius:10px;padding:3px;background:var(--bg);flex:0 0 auto}
.langSwitch button{appearance:none;border:0;background:transparent;padding:5px 11px;border-radius:8px;font-size:12px;font-weight:700;color:var(--muted);cursor:pointer;font-family:inherit;transition:.15s}
.langSwitch button:hover{color:var(--gold-d)}
.langSwitch button.on{background:var(--card);color:var(--gold-d);box-shadow:0 1px 3px rgba(0,0,0,.12)}
.wrap{max-width:1100px;margin:0 auto;padding:18px}
.toolbar{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:16px;align-items:center}
.btn{appearance:none;border:1px solid var(--line);background:var(--card);color:var(--ink);padding:10px 16px;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:7px;transition:.15s;font-family:inherit}
.btn:hover{border-color:var(--gold);color:var(--gold-d)}
.btn.primary{background:linear-gradient(135deg,var(--gold),var(--gold-d));color:#fff;border-color:transparent}
.btn.primary:hover{filter:brightness(1.05);color:#fff}
.btn.ok{background:var(--ok);color:#fff;border-color:transparent}
.btn:disabled{opacity:.45;cursor:not-allowed}
.hint{color:var(--muted);font-size:13px;margin:0 4px}
#pdfArea{display:flex;flex-direction:column;align-items:center;gap:18px}
.pageWrap{position:relative;background:#fff;box-shadow:0 2px 14px rgba(0,0,0,.10);line-height:0}
.pageWrap canvas{display:block}
.sig{position:absolute;cursor:move;touch-action:none;border:1.5px dashed transparent;user-select:none}
.sig:hover,.sig.active{border-color:var(--gold)}
.sig img{width:100%;height:100%;display:block;pointer-events:none}
.sig .handle{position:absolute;width:16px;height:16px;background:var(--gold);border:2px solid #fff;border-radius:50%;left:-8px;bottom:-8px;cursor:nwse-resize}
.sig .del{position:absolute;top:-12px;right:-12px;width:24px;height:24px;border-radius:50%;background:var(--danger);color:#fff;border:2px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer}
.empty{text-align:center;color:var(--muted);padding:70px 20px;border:2px dashed var(--line);border-radius:14px;background:var(--card)}
.empty b{display:block;font-size:17px;color:var(--ink);margin-bottom:6px}
/* modal */
.ov{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:100;padding:16px}
.ov.show{display:flex}
.modal{background:#fff;border-radius:16px;max-width:480px;width:100%;padding:22px}
.modal h3{margin:0 0 14px;font-size:17px}
.tabs{display:flex;gap:8px;margin-bottom:14px}
.tab{flex:1;padding:9px;border:1px solid var(--line);border-radius:9px;text-align:center;cursor:pointer;font-size:13px;font-weight:600;color:var(--muted);display:flex;align-items:center;justify-content:center;gap:6px}
.tab.on{border-color:var(--gold);color:var(--gold-d);background:#faf6ee}
.pane{display:none}.pane.on{display:block}
#drawCanvas{border:1px solid var(--line);border-radius:10px;width:100%;height:170px;touch-action:none;background:#fff;background-image:linear-gradient(#f0f0f0 1px,transparent 1px);background-size:100% 34px;background-position:0 33px}
.row{display:flex;gap:10px;align-items:center;margin-top:12px;flex-wrap:wrap}
.chk{display:flex;align-items:center;gap:7px;font-size:13px;color:var(--muted);cursor:pointer}
#imgPreview{max-width:100%;max-height:170px;border:1px solid var(--line);border-radius:10px;background:repeating-conic-gradient(#eee 0 25%,#fff 0 50%) 50%/18px 18px;display:none;margin-top:8px}
.modal .foot{display:flex;justify-content:flex-end;gap:10px;margin-top:18px}
.file{display:none}
.badge{font-size:12px;background:#faf6ee;color:var(--gold-d);padding:3px 9px;border-radius:20px;border:1px solid #ecdcb8}
.sel{flex:1;padding:8px 10px;border:1px solid var(--line);border-radius:9px;font-size:13px;background:#fff;color:var(--ink);font-family:inherit}
input[type=range]{accent-color:var(--gold)}
.spinner{width:40px;height:40px;border:4px solid var(--line);border-top-color:var(--gold);border-radius:50%;margin:0 auto 14px;animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
@media(max-width:560px){header h1{font-size:16px}.btn{padding:9px 12px;font-size:13px}}
</style>
</head>
<body>
<header>
<div class="logo"><svg width="18" height="18" viewBox="0 0 512 512" fill="currentColor"><path d="M362.7 19.3l-10.3 10.3 110 110 10.3-10.3c12.5-12.5 12.5-32.8 0-45.3l-64.7-64.7c-12.5-12.5-32.8-12.5-45.3 0zM329.4 52.7L52.7 329.4c-2.2 2.2-3.8 4.9-4.6 7.9L33 488c-1.1 4.6 .2 9.5 3.6 12.9s8.3 4.7 12.9 3.6l150.7-15.1c3-.8 5.7-2.4 7.9-4.6l276.7-276.7-110-110z"/></svg></div>
<div>
<h1 data-i18n="appTitle"></h1>
<div class="sub" data-i18n="appSub"></div>
</div>
<div class="langSwitch" id="langSwitch" role="group" aria-label="Language"></div>
</header>
<div class="wrap">
<div class="toolbar">
<button class="btn primary" id="btnOpen"><svg width="15" height="15" viewBox="0 0 384 512" fill="currentColor"><path d="M0 64C0 28.7 28.7 0 64 0H224V128c0 17.7 14.3 32 32 32H384V448c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V64zm384 64H256V0L384 128z"/></svg> <span data-i18n="btnOpen"></span></button>
<button class="btn" id="btnSig" disabled><svg width="15" height="15" viewBox="0 0 512 512" fill="currentColor"><path d="M362.7 19.3l-10.3 10.3 110 110 10.3-10.3c12.5-12.5 12.5-32.8 0-45.3l-64.7-64.7c-12.5-12.5-32.8-12.5-45.3 0zM329.4 52.7L52.7 329.4c-2.2 2.2-3.8 4.9-4.6 7.9L33 488c-1.1 4.6 .2 9.5 3.6 12.9s8.3 4.7 12.9 3.6l150.7-15.1c3-.8 5.7-2.4 7.9-4.6l276.7-276.7-110-110z"/></svg> <span data-i18n="btnSig"></span></button>
<button class="btn ok" id="btnSave" disabled><svg width="15" height="15" viewBox="0 0 512 512" fill="currentColor"><path d="M288 32c0-17.7-14.3-32-32-32s-32 14.3-32 32V274.7l-73.4-73.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l128 128c12.5 12.5 32.8 12.5 45.3 0l128-128c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L288 274.7V32zM64 352c-35.3 0-64 28.7-64 64v32c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V416c0-35.3-28.7-64-64-64H346.5l-45.3 45.3c-25 25-65.5 25-90.5 0L165.5 352H64z"/></svg> <span data-i18n="btnSave"></span></button>
<span class="badge" id="pageBadge" style="display:none"></span>
<span class="hint" id="hint"></span>
</div>
<div id="pdfArea">
<div class="empty" id="emptyState">
<b data-i18n="emptyTitle"></b>
<span data-i18n="emptyLine1"></span><br>
<span data-i18n="emptyLine2"></span>
</div>
</div>
</div>
<!-- signature modal -->
<div class="ov" id="ov">
<div class="modal">
<h3 data-i18n="modalTitle"></h3>
<div class="tabs">
<div class="tab on" data-tab="upload"><svg width="14" height="14" viewBox="0 0 512 512" fill="currentColor"><path d="M0 96C0 60.7 28.7 32 64 32H448c35.3 0 64 28.7 64 64V416c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V96zM323.8 202.5c-4.5-6.6-11.9-10.5-19.8-10.5s-15.4 3.9-19.8 10.5l-87 127.6L170.7 297c-4.6-5.7-11.5-9-18.7-9s-14.2 3.3-18.7 9l-64 80c-5.8 7.2-6.9 17.1-2.9 25.4s12.4 13.6 21.6 13.6h96 32H424c8.9 0 17.1-4.9 21.2-12.8s3.6-17.4-1.4-24.7l-120-176zM112 192a48 48 0 1 0 0-96 48 48 0 1 0 0 96z"/></svg> <span data-i18n="tabUpload"></span></div>
<div class="tab" data-tab="draw"><svg width="14" height="14" viewBox="0 0 512 512" fill="currentColor"><path d="M362.7 19.3l-10.3 10.3 110 110 10.3-10.3c12.5-12.5 12.5-32.8 0-45.3l-64.7-64.7c-12.5-12.5-32.8-12.5-45.3 0zM329.4 52.7L52.7 329.4c-2.2 2.2-3.8 4.9-4.6 7.9L33 488c-1.1 4.6 .2 9.5 3.6 12.9s8.3 4.7 12.9 3.6l150.7-15.1c3-.8 5.7-2.4 7.9-4.6l276.7-276.7-110-110z"/></svg> <span data-i18n="tabDraw"></span></div>
</div>
<div class="pane on" id="paneUpload">
<button class="btn" id="pickImg" data-i18n="pickImg"></button>
<div id="bgTools" style="display:none">
<label class="chk" style="margin-top:12px"><input type="checkbox" id="rmBg" checked> <span data-i18n="rmBg"></span></label>
<div class="row" id="sensRow">
<label style="font-size:13px;color:var(--muted);min-width:96px" data-i18n="sensLabel"></label>
<input type="range" id="sens" min="130" max="245" value="200" step="3" style="flex:1">
</div>
<div class="row" id="inkRow">
<label style="font-size:13px;color:var(--muted);min-width:96px" data-i18n="inkLabel"></label>
<select id="inkColor" class="sel">
<option value="orig" data-i18n="inkOrig"></option>
<option value="black" data-i18n="inkBlack"></option>
<option value="blue" data-i18n="inkBlue"></option>
</select>
</div>
</div>
<img id="imgPreview" alt="">
<p class="hint" style="margin-top:8px" data-i18n="uploadHint"></p>
</div>
<div class="pane" id="paneDraw">
<canvas id="drawCanvas"></canvas>
<div class="row">
<button class="btn" id="clearDraw"><svg width="14" height="14" viewBox="0 0 576 512" fill="currentColor"><path d="M290.7 57.4L57.4 290.7c-25 25-25 65.5 0 90.5l80 80c12 12 28.3 18.7 45.3 18.7H512c17.7 0 32-14.3 32-32s-14.3-32-32-32H387.9L518.6 285.3c25-25 25-65.5 0-90.5L381.3 57.4c-25-25-65.5-25-90.5 0zM297 387l-72 72H182.6l-80-80 124.7-124.7L297 387z"/></svg> <span data-i18n="clearDraw"></span></button>
<span class="hint" data-i18n="drawHint"></span>
</div>
</div>
<div class="foot">
<button class="btn" id="cancelSig" data-i18n="cancel"></button>
<button class="btn primary" id="addSig" data-i18n="addToDoc"></button>
</div>
</div>
</div>
<div class="ov" id="busy"><div class="modal" style="text-align:center;max-width:300px"><div class="spinner"></div><div id="busyText">…</div></div></div>
<input type="file" id="filePdf" class="file" accept="*/*">
<input type="file" id="fileImg" class="file" accept="image/*">
<script src="vendor/pdf.min.js"></script>
<script src="vendor/pdf-lib.min.js"></script>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = 'vendor/pdf.worker.min.js';
/* ================== i18n ==================
To add a language: add an entry to LANGS (name + dir)
and a matching dictionary to I18N. Nothing else needed. */
const LANGS = {
ar: { name:'عربي', dir:'rtl' },
en: { name:'EN', dir:'ltr' },
};
const I18N = {
ar: {
appTitle:'توقيع المستندات',
appSub:'ارفع أي ملف · أضف توقيعك · حرّكه للمكان · نزّل موقّعاً',
btnOpen:'افتح ملف',
btnSig:'أضف توقيع',
btnSave:'نزّل موقّعاً',
emptyTitle:'ابدأ برفع ملف',
emptyLine1:'أي نوع: PDF · Word · Excel · PowerPoint · صور · نصوص — يتحوّل تلقائياً ويصير قابلاً للتوقيع.',
emptyLine2:'اضغط «افتح ملف»، ثم «أضف توقيع» واسحبه على المكان المطلوب.',
modalTitle:'أضف توقيعاً',
tabUpload:'ارفع صورة',
tabDraw:'ارسم',
pickImg:'اختر صورة التوقيع',
rmBg:'شيل الخلفية وخلّ التوقيع فقط',
sensLabel:'ضبط الإزالة',
inkLabel:'لون التوقيع',
inkOrig:'كما هو',
inkBlack:'أسود',
inkBlue:'أزرق',
uploadHint:'حرّك «ضبط الإزالة» وراقب المعاينة لين يطلع التوقيع نظيف بدون خلفية. يشتغل مع أي خلفية فاتحة (ورق/صورة بالجوال).',
clearDraw:'امسح',
drawHint:'ارسم توقيعك بالماوس أو الإصبع.',
cancel:'إلغاء',
addToDoc:'أضِف للمستند',
busyImage:'جارٍ تجهيز الصورة…',
busyConvert:'جارٍ تحويل الملف إلى PDF…',
fileReady:'الملف جاهز — أضف توقيعك.',
openFailedHint:'فشل فتح الملف.',
openFailedAlert:'تعذّر فتح الملف: ',
imgUnsupported:'صيغة الصورة غير مدعومة في المتصفّح',
convertFailed:'فشل التحويل ({status})',
pageBadge: n => n + ' صفحة',
drawFirst:'ارسم توقيعك أولاً',
pickFirst:'اختر صورة التوقيع أولاً',
openFirst:'افتح ملفاً أولاً',
dragHint:'اسحب التوقيع للمكان، ومن الزاوية تكبّره/تصغّره.',
confirmNoSig:'ما فيه توقيع مضاف — تنزّل الملف كما هو؟',
generating:'جارٍ التوليد…',
generated:'تمّ — نُزّل الملف الموقّع.',
generateError:'صار خطأ أثناء التوليد: ',
generateFailedHint:'فشل التوليد.',
},
en: {
appTitle:'Document Signing',
appSub:'Upload any file · add your signature · drag it into place · download signed',
btnOpen:'Open File',
btnSig:'Add Signature',
btnSave:'Download Signed',
emptyTitle:'Start by uploading a file',
emptyLine1:'Any type: PDF · Word · Excel · PowerPoint · images · text — it converts automatically and becomes signable.',
emptyLine2:'Click "Open File", then "Add Signature" and drag it where you need it.',
modalTitle:'Add a Signature',
tabUpload:'Upload Image',
tabDraw:'Draw',
pickImg:'Choose signature image',
rmBg:'Remove the background, keep only the signature',
sensLabel:'Removal level',
inkLabel:'Signature color',
inkOrig:'As is',
inkBlack:'Black',
inkBlue:'Blue',
uploadHint:'Move "Removal level" and watch the preview until the signature comes out clean with no background. Works on any light background (paper / phone photo).',
clearDraw:'Clear',
drawHint:'Draw your signature with your mouse or finger.',
cancel:'Cancel',
addToDoc:'Add to Document',
busyImage:'Preparing the image…',
busyConvert:'Converting the file to PDF…',
fileReady:'File is ready — add your signature.',
openFailedHint:'Failed to open the file.',
openFailedAlert:'Could not open the file: ',
imgUnsupported:'This image format is not supported by the browser',
convertFailed:'Conversion failed ({status})',
pageBadge: n => n === 1 ? '1 page' : n + ' pages',
drawFirst:'Draw your signature first',
pickFirst:'Choose a signature image first',
openFirst:'Open a file first',
dragHint:'Drag the signature into place; use the corner handle to resize.',
confirmNoSig:'No signature added — download the file as is?',
generating:'Generating…',
generated:'Done — the signed file was downloaded.',
generateError:'An error occurred while generating: ',
generateFailedHint:'Generation failed.',
},
};
const LANG_KEY = 'signpdf.lang';
let lang = localStorage.getItem(LANG_KEY);
if(!LANGS[lang]) lang = 'ar';
function t(key, vars){
const dict = I18N[lang] || I18N.ar;
let v = (key in dict) ? dict[key] : I18N.ar[key];
if(v === undefined) return key;
if(typeof v === 'function') return v(vars);
if(vars && typeof vars === 'object'){
v = v.replace(/\{(\w+)\}/g, (m,k)=> (k in vars) ? vars[k] : m);
}
return v;
}
function applyLang(){
document.documentElement.lang = lang;
document.documentElement.dir = LANGS[lang].dir;
document.title = t('appTitle');
document.querySelectorAll('[data-i18n]').forEach(el=>{ el.textContent = t(el.dataset.i18n); });
document.querySelectorAll('#langSwitch button').forEach(b=> b.classList.toggle('on', b.dataset.lang===lang));
if(state.pageCount){
$('#pageBadge').textContent = t('pageBadge', state.pageCount);
}
}
function setLang(l){
if(!LANGS[l] || l===lang) return;
lang = l;
try{ localStorage.setItem(LANG_KEY, l); }catch(_){}
applyLang();
}
/* ================== app ================== */
const state = { pdfBytes:null, pageScales:[], sigs:[], pendingPng:null, pageCount:0 };
let sigId = 0;
const $ = s => document.querySelector(s);
const hint = k => { $('#hint').textContent = k ? t(k) : ''; };
// build the language switcher
(function(){
const sw = document.getElementById('langSwitch');
Object.keys(LANGS).forEach(code=>{
const b = document.createElement('button');
b.type = 'button'; b.dataset.lang = code; b.textContent = LANGS[code].name;
b.onclick = ()=> setLang(code);
sw.appendChild(b);
});
applyLang();
})();
/* ---------- open ANY file -> PDF -> render ---------- */
const busy = $('#busy');
const setBusy = k => { $('#busyText').textContent = t(k); busy.classList.add('show'); };
const clearBusy = () => busy.classList.remove('show');
$('#btnOpen').onclick = ()=> $('#filePdf').click();
$('#filePdf').onchange = async e =>{
const f = e.target.files[0]; if(!f) return;
e.target.value = ''; // allow re-picking same file
try{
const name = (f.name||'').toLowerCase();
const isPdf = f.type==='application/pdf' || name.endsWith('.pdf');
const isImg = (f.type||'').startsWith('image/') || /\.(png|jpe?g|gif|webp|bmp|tiff?|heic)$/.test(name);
let bytes;
if(isPdf){
bytes = new Uint8Array(await f.arrayBuffer());
} else if(isImg){
setBusy('busyImage');
bytes = await imageToPdfBytes(f);
} else {
setBusy('busyConvert');
bytes = await convertOnServer(f);
}
await loadPdfBytes(bytes);
hint('fileReady');
}catch(err){
alert(t('openFailedAlert') + (err.message||err));
hint('openFailedHint');
}finally{ clearBusy(); }
};
async function loadPdfBytes(bytes){
state.pdfBytes = bytes.slice(0); // keep a copy for pdf-lib export
state.sigs = []; state.pageScales = [];
await renderPdf(bytes.slice(0));
$('#btnSig').disabled = false; $('#btnSave').disabled = false;
}
/* any raster image -> single-page PDF, entirely in the browser */
async function imageToPdfBytes(f){
const {dataUrl, w, h} = await fileToPng(f);
const doc = await PDFLib.PDFDocument.create();
const png = await doc.embedPng(dataUrl);
const page = doc.addPage([w, h]);
page.drawImage(png, {x:0, y:0, width:w, height:h});
return await doc.save();
}
function fileToPng(f){
return new Promise((res,rej)=>{
const img = new Image();
img.onload = ()=>{
const c = document.createElement('canvas');
c.width = img.naturalWidth || 1; c.height = img.naturalHeight || 1;
c.getContext('2d').drawImage(img,0,0);
res({dataUrl:c.toDataURL('image/png'), w:c.width, h:c.height});
};
img.onerror = ()=> rej(new Error(t('imgUnsupported')));
img.src = URL.createObjectURL(f);
});
}
/* office / text / everything-else -> server (LibreOffice) -> PDF */
async function convertOnServer(f){
const fd = new FormData(); fd.append('file', f);
const r = await fetch('/convert', {method:'POST', body:fd});
if(!r.ok){
let msg = t('convertFailed', {status:r.status});
try{ const j = await r.json(); if(j.error) msg = j.error; }catch(_){}
throw new Error(msg);
}
return new Uint8Array(await r.arrayBuffer());
}
async function renderPdf(bytes){
const area = $('#pdfArea'); area.innerHTML = '';
const pdf = await pdfjsLib.getDocument({data:bytes}).promise;
const maxW = Math.min(900, document.querySelector('.wrap').clientWidth);
for(let i=1;i<=pdf.numPages;i++){
const page = await pdf.getPage(i);
const base = page.getViewport({scale:1});
const scale = maxW / base.width;
state.pageScales[i-1] = scale;
const vp = page.getViewport({scale});
const wrap = document.createElement('div');
wrap.className='pageWrap'; wrap.dataset.page=i-1;
wrap.style.width = vp.width+'px'; wrap.style.height = vp.height+'px';
const cv = document.createElement('canvas');
cv.width = vp.width; cv.height = vp.height;
cv.style.width = vp.width+'px'; cv.style.height = vp.height+'px';
wrap.appendChild(cv); area.appendChild(wrap);
await page.render({canvasContext:cv.getContext('2d'), viewport:vp}).promise;
}
state.pageCount = pdf.numPages;
$('#pageBadge').style.display='inline-block';
$('#pageBadge').textContent = t('pageBadge', pdf.numPages);
}
/* ---------- signature modal ---------- */
const ov = $('#ov');
document.querySelectorAll('.tab').forEach(tb=> tb.onclick = ()=>{
document.querySelectorAll('.tab').forEach(x=>x.classList.remove('on'));
document.querySelectorAll('.pane').forEach(x=>x.classList.remove('on'));
tb.classList.add('on');
$(tb.dataset.tab==='upload'?'#paneUpload':'#paneDraw').classList.add('on');
});
$('#btnSig').onclick = ()=>{
state.pendingPng=null; sigImg=null;
$('#imgPreview').style.display='none'; $('#bgTools').style.display='none';
clearDraw(); ov.classList.add('show');
};
$('#cancelSig').onclick = ()=> ov.classList.remove('show');
/* upload image -> background removal (luminance based) + live preview */
let sigImg = null; // the loaded source image, re-processed as controls change
$('#pickImg').onclick = ()=> $('#fileImg').click();
$('#fileImg').onchange = e =>{
const f = e.target.files[0]; if(!f) return;
const im = new Image();
im.onload = ()=>{ sigImg = im; $('#bgTools').style.display='block'; reprocessSig(); };
im.onerror = ()=> alert(t('imgUnsupported'));
im.src = URL.createObjectURL(f);
};
['rmBg','sens','inkColor'].forEach(id=>{ const el=$('#'+id); el.oninput=reprocessSig; el.onchange=reprocessSig; });
function reprocessSig(){
if(!sigImg) return;
const on = $('#rmBg').checked;
$('#sensRow').style.display = on ? 'flex' : 'none';
$('#inkRow').style.display = on ? 'flex' : 'none';
state.pendingPng = renderSignaturePng(sigImg, on, +$('#sens').value, $('#inkColor').value);
const pv = $('#imgPreview'); pv.src = state.pendingPng; pv.style.display='block';
}
/* Keep only the ink: pixels darker than the threshold stay (with a soft edge),
lighter pixels become transparent. Works on any LIGHT background, not just white. */
function renderSignaturePng(img, removeBg, threshold, ink){
const c = document.createElement('canvas');
c.width = img.naturalWidth; c.height = img.naturalHeight;
const ctx = c.getContext('2d');
ctx.drawImage(img,0,0);
if(removeBg){
const d = ctx.getImageData(0,0,c.width,c.height), p = d.data, soft = 28;
let ir=0,ig=0,ib=0, recolor = (ink!=='orig');
if(ink==='blue'){ ir=18; ig=42; ib=140; } // black is 0,0,0
for(let i=0;i<p.length;i+=4){
const L = 0.299*p[i] + 0.587*p[i+1] + 0.114*p[i+2]; // luminance
if(L >= threshold){ p[i+3]=0; continue; } // background -> transparent
let a = 255;
if(L > threshold-soft) a = Math.round((threshold-L)/soft*255); // feathered edge
if(recolor){ p[i]=ir; p[i+1]=ig; p[i+2]=ib; }
p[i+3] = a;
}
ctx.putImageData(d,0,0);
}
return c.toDataURL('image/png');
}
/* draw pad */
const dc = $('#drawCanvas'); let dctx, drawing=false, drew=false;
function initDraw(){
const r = dc.getBoundingClientRect();
dc.width = r.width; dc.height = r.height;
dctx = dc.getContext('2d');
dctx.lineWidth=2.5; dctx.lineCap='round'; dctx.lineJoin='round'; dctx.strokeStyle='#10243e';
}
function pos(e){ const r=dc.getBoundingClientRect(); const t=e.touches?e.touches[0]:e; return {x:t.clientX-r.left,y:t.clientY-r.top}; }
function dStart(e){ e.preventDefault(); drawing=true; drew=true; const p=pos(e); dctx.beginPath(); dctx.moveTo(p.x,p.y); }
function dMove(e){ if(!drawing)return; e.preventDefault(); const p=pos(e); dctx.lineTo(p.x,p.y); dctx.stroke(); }
function dEnd(){ drawing=false; }
['mousedown','touchstart'].forEach(ev=>dc.addEventListener(ev,dStart));
['mousemove','touchmove'].forEach(ev=>dc.addEventListener(ev,dMove,{passive:false}));
['mouseup','touchend','mouseleave'].forEach(ev=>dc.addEventListener(ev,dEnd));
function clearDraw(){ if(!dctx) initDraw(); dctx.clearRect(0,0,dc.width,dc.height); drew=false; }
$('#clearDraw').onclick = clearDraw;
/* confirm add */
$('#addSig').onclick = ()=>{
let png = null;
const drawingTab = $('#paneDraw').classList.contains('on');
if(drawingTab){
if(!drew){ alert(t('drawFirst')); return; }
png = dc.toDataURL('image/png');
} else {
if(!state.pendingPng){ alert(t('pickFirst')); return; }
png = state.pendingPng;
}
ov.classList.remove('show');
placeSignature(png);
};
/* ---------- place + drag + resize ---------- */
const DEL_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>';
function placeSignature(png){
const wraps = document.querySelectorAll('.pageWrap');
if(!wraps.length){ alert(t('openFirst')); return; }
// place on the page most centered in viewport
let target = wraps[0], best=Infinity;
wraps.forEach(w=>{ const r=w.getBoundingClientRect(); const d=Math.abs(r.top+r.height/2-window.innerHeight/2); if(d<best){best=d;target=w;} });
const img = new Image();
img.onload = ()=>{
const pageIdx = +target.dataset.page;
const w0 = Math.min(180, target.clientWidth*0.4);
const h0 = w0 * (img.naturalHeight/img.naturalWidth);
const el = document.createElement('div');
el.className='sig'; const id=++sigId; el.dataset.id=id;
el.style.width=w0+'px'; el.style.height=h0+'px';
el.style.left=(target.clientWidth/2 - w0/2)+'px';
el.style.top=(target.clientHeight/2 - h0/2)+'px';
el.innerHTML = `<img src="${png}"><div class="del">${DEL_ICON}</div><div class="handle"></div>`;
target.appendChild(el);
const rec = {id, pageIdx, png, el};
state.sigs.push(rec);
wireSig(el, rec, target);
hint('dragHint');
};
img.src = png;
}
function wireSig(el, rec, wrap){
el.querySelector('.del').onclick = (e)=>{ e.stopPropagation(); el.remove(); state.sigs = state.sigs.filter(s=>s.id!==rec.id); };
const handle = el.querySelector('.handle');
let mode=null, sx,sy, ox,oy, ow,oh;
const start = e=>{
e.preventDefault(); e.stopPropagation();
document.querySelectorAll('.sig').forEach(s=>s.classList.remove('active'));
el.classList.add('active');
const t = e.touches?e.touches[0]:e;
sx=t.clientX; sy=t.clientY;
ox=parseFloat(el.style.left); oy=parseFloat(el.style.top);
ow=el.offsetWidth; oh=el.offsetHeight;
mode = (e.target===handle || handle.contains(e.target))?'resize':'move';
document.addEventListener('mousemove',move); document.addEventListener('touchmove',move,{passive:false});
document.addEventListener('mouseup',end); document.addEventListener('touchend',end);
};
const move = e=>{
const t = e.touches?e.touches[0]:e; e.preventDefault();
const dx=t.clientX-sx, dy=t.clientY-sy;
if(mode==='move'){
let nx=ox+dx, ny=oy+dy;
nx=Math.max(0,Math.min(nx, wrap.clientWidth-el.offsetWidth));
ny=Math.max(0,Math.min(ny, wrap.clientHeight-el.offsetHeight));
el.style.left=nx+'px'; el.style.top=ny+'px';
} else {
const ratio = oh/ow;
let nw=Math.max(40, ow+dx);
nw=Math.min(nw, wrap.clientWidth-parseFloat(el.style.left));
el.style.width=nw+'px'; el.style.height=(nw*ratio)+'px';
}
};
const end = ()=>{ mode=null;
document.removeEventListener('mousemove',move); document.removeEventListener('touchmove',move);
document.removeEventListener('mouseup',end); document.removeEventListener('touchend',end);
};
el.addEventListener('mousedown',start); el.addEventListener('touchstart',start,{passive:false});
}
/* ---------- export with pdf-lib ---------- */
$('#btnSave').onclick = async ()=>{
if(!state.pdfBytes){ return; }
if(!state.sigs.length && !confirm(t('confirmNoSig'))) return;
$('#btnSave').disabled = true; hint('generating');
try{
const doc = await PDFLib.PDFDocument.load(state.pdfBytes);
const pages = doc.getPages();
for(const s of state.sigs){
const wrap = s.el.parentElement;
const scale = state.pageScales[s.pageIdx];
const page = pages[s.pageIdx];
const png = await doc.embedPng(s.png);
const left = parseFloat(s.el.style.left);
const top = parseFloat(s.el.style.top);
const w = s.el.offsetWidth, h = s.el.offsetHeight;
page.drawImage(png, {
x: left/scale,
y: page.getHeight() - (top/scale) - (h/scale),
width: w/scale,
height: h/scale,
});
}
const out = await doc.save();
const blob = new Blob([out], {type:'application/pdf'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'signed.pdf'; a.click();
hint('generated');
}catch(err){ alert(t('generateError')+err.message); hint('generateFailedHint'); }
$('#btnSave').disabled = false;
};
</script>
</body>
</html>