-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.html
More file actions
394 lines (339 loc) · 17.3 KB
/
crop.html
File metadata and controls
394 lines (339 loc) · 17.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crop PDF</title>
<script src="static/js/app.js"></script>
<script src="static/js/pdf.min.js"></script>
<link rel="stylesheet" href="static/css/all.min.css">
<style>
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
.thumbnail.active { border: 2px solid #10b981; background: #ecfdf5; }
#crop-canvas { cursor: crosshair; }
.toggle-btn.active { background: white; box-shadow: 0 1px 3px rgba(0,0,0,0.1); color: #059669; }
</style>
</head>
<body class="bg-slate-50 h-screen flex flex-col overflow-hidden font-sans">
<header class="h-16 bg-white border-b flex items-center justify-between px-6 z-50 shrink-0">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-emerald-600 rounded-xl flex items-center justify-center text-white shadow-lg">
<i class="fa-solid fa-crop-simple"></i>
</div>
<h1 class="text-lg font-bold text-slate-800 tracking-tight">PDF<span class="text-emerald-600">Crop</span></h1>
<button onclick="pywebview.api.home_page()" class="ml-2 p-2 text-slate-400 hover:text-emerald-600 transition-colors" title="Home">
<i class="fa-solid fa-house text-lg"></i> Go to Home Page
</button>
</div>
<div id="controls" class="hidden flex items-center gap-6">
<div class="flex items-center gap-1 bg-slate-100 p-1 rounded-xl border border-slate-200">
<button id="mode-current" onclick="setApplyMode('current')" class="toggle-btn active px-4 py-1.5 rounded-lg text-xs font-bold transition-all">
Apply Crop to Current Page
</button>
<button id="mode-all" onclick="setApplyMode('all')" class="toggle-btn px-4 py-1.5 rounded-lg text-xs font-bold transition-all text-slate-500">
Apply Crop to All Pages
</button>
</div>
<button onclick="openFile()" class="bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 px-5 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2">
<i class="fa-solid fa-plus"></i> Upload New File
</button>
<button onclick="saveAndProcess()" class="bg-slate-900 hover:bg-emerald-600 text-white px-5 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2">
<i class="fa-solid fa-file-export"></i> Save Cropped PDF
</button>
</div>
</header>
<main class="flex-1 flex overflow-hidden">
<aside id="sidebar" class="hidden w-64 bg-white border-r flex flex-col">
<div class="p-4 border-b">
<p class="text-[10px] font-bold uppercase text-slate-400">Pages</p>
</div>
<div id="thumbnail-container" class="flex-1 overflow-y-auto p-4 space-y-4"></div>
</aside>
<section class="flex-1 relative overflow-auto bg-slate-200 flex justify-center p-8">
<div id="upload-zone" class="m-auto text-center bg-white p-12 rounded-3xl shadow-xl border-2 border-dashed border-slate-300 hover:border-emerald-500 cursor-pointer transition-all w-full max-w-md" onclick="openFile()">
<i class="fa-solid fa-cloud-arrow-up text-5xl text-emerald-500 mb-4"></i>
<h3 class="text-xl font-bold text-slate-800">Select PDF</h3>
<p class="text-slate-500 text-sm mt-2">Open a multipage PDF to start cropping</p>
</div>
<div id="pdf-container" class="hidden relative shadow-2xl bg-white">
<canvas id="main-canvas"></canvas>
<canvas id="crop-canvas" class="absolute top-0 left-0"></canvas>
</div>
</section>
</main>
<div id="pagination" class="hidden fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/90 backdrop-blur shadow-2xl border px-4 py-2 rounded-2xl flex items-center gap-4">
<button onclick="changePage(-1)" class="p-2 hover:text-emerald-600"><i class="fa-solid fa-chevron-left"></i></button>
<div class="flex items-center gap-2 font-bold text-sm">
<input type="number" id="page-num" class="w-12 text-center border rounded p-1" min="1">
<span class="text-slate-400">/</span>
<span id="page-count">0</span>
</div>
<button onclick="changePage(1)" class="p-2 hover:text-emerald-600"><i class="fa-solid fa-chevron-right"></i></button>
</div>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = './static/js/pdf.worker.min.js'
let pdfDoc = null,
pageNum = 1,
currentPath = '',
scale = 1.5,
crops = {},
applyMode = 'current';
const mainCanvas = document.getElementById('main-canvas');
const cropCanvas = document.getElementById('crop-canvas');
const ctx = mainCanvas.getContext('2d');
const cCtx = cropCanvas.getContext('2d');
let isDrawing = false, isMoving = false, isResizing = false;
let startX, startY, dragHandle = null;
const handleSize = 8;
const deleteSize = 20;
function setApplyMode(mode) {
applyMode = mode;
document.getElementById('mode-current').classList.toggle('active', mode === 'current');
document.getElementById('mode-all').classList.toggle('active', mode === 'all');
document.getElementById('mode-current').classList.toggle('text-slate-500', mode !== 'current');
document.getElementById('mode-all').classList.toggle('text-slate-500', mode !== 'all');
}
async function openFile() {
const path = await pywebview.api.get_file_path();
if (!path) return;
currentPath = path;
const base64 = await pywebview.api.load_pdf_as_base64(path);
const loadingTask = pdfjsLib.getDocument({data: atob(base64)});
pdfDoc = await loadingTask.promise;
document.getElementById('upload-zone').classList.add('hidden');
document.getElementById('sidebar').classList.remove('hidden');
document.getElementById('pdf-container').classList.remove('hidden');
document.getElementById('pagination').classList.remove('hidden');
document.getElementById('controls').classList.remove('hidden');
document.getElementById('page-count').textContent = pdfDoc.numPages;
renderThumbnails();
renderPage(1);
}
async function renderPage(num) {
pageNum = num;
const page = await pdfDoc.getPage(num);
const viewport = page.getViewport({scale});
mainCanvas.height = viewport.height;
mainCanvas.width = viewport.width;
cropCanvas.height = viewport.height;
cropCanvas.width = viewport.width;
await page.render({canvasContext: ctx, viewport}).promise;
document.getElementById('page-num').value = num;
document.querySelectorAll('.thumbnail').forEach(el => el.classList.remove('active'));
const activeThumb = document.getElementById(`thumb-${num}`);
if (activeThumb) {
activeThumb.classList.add('active');
activeThumb.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
}
drawExistingCrop();
}
async function renderThumbnails() {
const container = document.getElementById('thumbnail-container');
container.innerHTML = '';
for (let i = 1; i <= pdfDoc.numPages; i++) {
const page = await pdfDoc.getPage(i);
const viewport = page.getViewport({scale: 0.2});
const canvas = document.createElement('canvas');
canvas.id = `thumb-${i}`;
canvas.className = 'thumbnail w-full rounded shadow-sm cursor-pointer hover:ring-2 ring-emerald-400 transition-all';
canvas.onclick = () => renderPage(i);
container.appendChild(canvas);
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({canvasContext: context, viewport}).promise;
}
}
function changePage(delta) {
let newPage = pageNum + delta;
if (newPage >= 1 && newPage <= pdfDoc.numPages) renderPage(newPage);
}
document.getElementById('page-num').addEventListener('change', (e) => {
let val = parseInt(e.target.value);
if (val >= 1 && val <= pdfDoc.numPages) renderPage(val);
});
function getHandle(x, y, crop) {
if (!crop) return null;
const c = { x: crop.x * scale, y: crop.y * scale, w: crop.width * scale, h: crop.height * scale };
const handles = {
nw: { x: c.x, y: c.y },
ne: { x: c.x + c.w, y: c.y },
sw: { x: c.x, y: c.y + c.h },
se: { x: c.x + c.w, y: c.y + c.h }
};
for (let h in handles) {
if (Math.abs(x - handles[h].x) <= handleSize && Math.abs(y - handles[h].y) <= handleSize) return h;
}
return null;
}
function isOverDeleteIcon(x, y, crop) {
if (!crop) return false;
const cx = crop.x * scale, cy = crop.y * scale, cw = crop.width * scale;
const iconX = cx + cw - 25; // 25px from right
const iconY = cy + 10; // 10px from top
return x >= iconX && x <= iconX + deleteSize && y >= iconY && y <= iconY + deleteSize;
}
function isInside(x, y, crop) {
if (!crop) return false;
const cx = crop.x * scale, cy = crop.y * scale, cw = crop.width * scale, ch = crop.height * scale;
return x >= cx && x <= cx + cw && y >= cy && y <= cy + ch;
}
cropCanvas.onmousedown = (e) => {
const rect = cropCanvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const crop = crops[pageNum - 1];
// 1. Check Delete Icon first
if (isOverDeleteIcon(x, y, crop)) {
crops[pageNum - 1] = null;
drawExistingCrop();
return;
}
// 2. Check Resize handles
const handle = getHandle(x, y, crop);
if (handle) {
isResizing = true;
dragHandle = handle;
}
// 3. Check Move
else if (isInside(x, y, crop)) {
isMoving = true;
startX = x - (crop.x * scale);
startY = y - (crop.y * scale);
}
// 4. Start Drawing New
else {
isDrawing = true;
startX = x;
startY = y;
crops[pageNum - 1] = null;
}
};
cropCanvas.onmousemove = (e) => {
const rect = cropCanvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const crop = crops[pageNum - 1];
if (!isDrawing && !isMoving && !isResizing) {
const handle = getHandle(x, y, crop);
if (isOverDeleteIcon(x, y, crop)) {
cropCanvas.style.cursor = 'pointer';
} else if (handle) {
cropCanvas.style.cursor = (handle === 'nw' || handle === 'se') ? 'nwse-resize' : 'nesw-resize';
} else if (isInside(x, y, crop)) {
cropCanvas.style.cursor = 'move';
} else {
cropCanvas.style.cursor = 'crosshair';
}
}
if (isDrawing) {
const w = (x - startX) / scale;
const h = (y - startY) / scale;
crops[pageNum - 1] = { pageIndex: pageNum-1, x: startX/scale, y: startY/scale, width: w, height: h };
} else if (isMoving) {
crop.x = (x - startX) / scale;
crop.y = (y - startY) / scale;
} else if (isResizing) {
const cx = crop.x * scale, cy = crop.y * scale, cw = crop.width * scale, ch = crop.height * scale;
if (dragHandle === 'nw') {
crop.x = x / scale; crop.y = y / scale;
crop.width = (cx + cw - x) / scale; crop.height = (cy + ch - y) / scale;
} else if (dragHandle === 'ne') {
crop.y = y / scale;
crop.width = (x - cx) / scale; crop.height = (cy + ch - y) / scale;
} else if (dragHandle === 'sw') {
crop.x = x / scale;
crop.width = (cx + cw - x) / scale; crop.height = (y - cy) / scale;
} else if (dragHandle === 'se') {
crop.width = (x - cx) / scale; crop.height = (y - cy) / scale;
}
}
if (isDrawing || isMoving || isResizing) drawExistingCrop();
};
cropCanvas.onmouseup = () => {
const crop = crops[pageNum - 1];
if (crop && (isDrawing || isResizing)) {
if (crop.width < 0) { crop.x += crop.width; crop.width = Math.abs(crop.width); }
if (crop.height < 0) { crop.y += crop.height; crop.height = Math.abs(crop.height); }
}
isDrawing = isMoving = isResizing = false;
dragHandle = null;
drawExistingCrop();
};
function drawExistingCrop() {
cCtx.clearRect(0, 0, cropCanvas.width, cropCanvas.height);
const crop = crops[pageNum - 1];
if (!crop) return;
const cx = crop.x * scale, cy = crop.y * scale, cw = crop.width * scale, ch = crop.height * scale;
// Draw Main Box
cCtx.strokeStyle = '#10b981';
cCtx.lineWidth = 2;
cCtx.strokeRect(cx, cy, cw, ch);
cCtx.fillStyle = 'rgba(16, 185, 129, 0.15)';
cCtx.fillRect(cx, cy, cw, ch);
// Draw Resize Handles
cCtx.fillStyle = '#10b981';
[[cx, cy], [cx + cw, cy], [cx, cy + ch], [cx + cw, cy + ch]].forEach(([hx, hy]) => {
cCtx.fillRect(hx - 4, hy - 4, 8, 8);
});
// Draw Delete Icon (Red Circle with X)
const iconX = cx + cw - 25;
const iconY = cy + 10;
cCtx.fillStyle = '#ef4444'; // Tailwind red-500
cCtx.beginPath();
cCtx.arc(iconX + 10, iconY + 10, 10, 0, Math.PI * 2);
cCtx.fill();
cCtx.strokeStyle = 'white';
cCtx.lineWidth = 2;
cCtx.beginPath();
cCtx.moveTo(iconX + 6, iconY + 6);
cCtx.lineTo(iconX + 14, iconY + 14);
cCtx.moveTo(iconX + 14, iconY + 6);
cCtx.lineTo(iconX + 6, iconY + 14);
cCtx.stroke();
}
async function saveAndProcess() {
const currentIdx = pageNum - 1;
const sourceCrop = crops[currentIdx];
if (!sourceCrop) {
alert("Please draw a crop box on the current page first.");
return;
}
let finalCrops = {};
if (applyMode === 'all') {
let conflictingPages = [];
for (let i = 0; i < pdfDoc.numPages; i++) {
if (i !== currentIdx && crops[i]) {
conflictingPages.push(i + 1);
}
}
if (conflictingPages.length > 0) {
const msg = `Pages ${conflictingPages.join(', ')} already have crop boxes. These will be replaced by the current page's crop box. Proceed?`;
if (!confirm(msg)) return;
}
for (let i = 0; i < pdfDoc.numPages; i++) {
finalCrops[i] = { ...sourceCrop, pageIndex: i };
}
} else {
finalCrops = crops;
}
const payload_save = {
filePath: currentPath,
};
const savePath = await pywebview.api.save_file_path(JSON.stringify(payload_save));
if (!savePath) return;
const payload = {
filePath: currentPath,
savePath: savePath,
crops: Object.values(finalCrops).filter(c => c !== null)
};
const success = await pywebview.api.process_crop(JSON.stringify(payload));
if (success) alert("PDF cropped and saved successfully!");
}
</script>
</body>
</html>