-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf.js
More file actions
464 lines (418 loc) · 13.8 KB
/
pdf.js
File metadata and controls
464 lines (418 loc) · 13.8 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
import { jsPDF } from "jspdf";
import { getSlots } from "./layout.js";
async function fileToImage(file) {
const url = URL.createObjectURL(file);
try {
const img = await new Promise((res, rej) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = rej;
i.src = url;
});
return img;
} finally {
URL.revokeObjectURL(url);
}
}
async function blobToImage(blob) {
const url = URL.createObjectURL(blob);
try {
const img = await new Promise((res, rej) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = rej;
i.src = url;
});
return img;
} finally {
URL.revokeObjectURL(url);
}
}
function fitWithin(imgW, imgH, slotW, slotH, padding = 2, mode = "max") {
const maxW = Math.max(0, slotW - padding * 2);
const maxH = Math.max(0, slotH - padding * 2);
let w, h;
if (mode === "height") {
const r = maxH / imgH;
w = imgW * r;
h = maxH;
if (w > maxW) {
const r2 = maxW / imgW;
w = maxW;
h = imgH * r2;
}
} else if (mode === "width") {
const r = maxW / imgW;
w = maxW;
h = imgH * r;
if (h > maxH) {
const r2 = maxH / imgH;
h = maxH;
w = imgW * r2;
}
} else {
const r = Math.min(maxW / imgW, maxH / imgH);
w = imgW * r;
h = imgH * r;
}
const x = (slotW - w) / 2 + padding;
const y = (slotH - h) / 2 + padding;
return { x, y, w, h };
}
function layoutFitMode(layoutKey) {
// Row -> equal height; Column -> equal width; Grids -> equal width; Hero/Mosaic -> max
if (/_row$/.test(layoutKey)) return "height";
if (/_col$/.test(layoutKey)) return "width";
if (layoutKey === "hero" || layoutKey === "mosaic") return "max";
if (/^\d+x\d+$/.test(layoutKey) || /grid/.test(layoutKey)) return "width";
return "max";
}
// Simple enhancement with auto-adjust based on brightness/contrast
function analyzeLuma(ctx, w, h) {
const img = ctx.getImageData(0, 0, w, h);
const d = img.data;
let sum = 0, sumSq = 0, n = w * h;
for (let i = 0; i < d.length; i += 4) {
const y = 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2];
sum += y;
sumSq += y * y;
}
const mean = sum / n;
const variance = Math.max(0, sumSq / n - mean * mean);
const std = Math.sqrt(variance);
return { mean, std };
}
function enhanceCanvas(ctx, w, h) {
const { mean, std } = analyzeLuma(ctx, w, h);
// Determine adjustments
let contrast = 1.0;
let brightness = 1.0;
if (mean < 105) brightness = 1.08; // dark -> brighten
if (mean > 170) brightness = 0.94; // washed -> darken
if (std < 45) contrast = 1.15; // low contrast -> boost
if (std > 80) contrast = 0.98; // very high -> soften slightly
const imgData = ctx.getImageData(0, 0, w, h);
const d = imgData.data;
const c = contrast;
const b = (brightness - 1) * 255;
for (let i = 0; i < d.length; i += 4) {
d[i] = Math.min(255, Math.max(0, (d[i] - 128) * c + 128 + b));
d[i + 1] = Math.min(255, Math.max(0, (d[i + 1] - 128) * c + 128 + b));
d[i + 2] = Math.min(255, Math.max(0, (d[i + 2] - 128) * c + 128 + b));
}
ctx.putImageData(imgData, 0, 0);
// Gentle sharpen
const wImg = w, hImg = h;
const src = ctx.getImageData(0, 0, wImg, hImg);
const out = ctx.createImageData(wImg, hImg);
const s = src.data, o = out.data;
const k = [0, -1, 0, -1, 5, -1, 0, -1, 0];
for (let y = 1; y < hImg - 1; y++) {
for (let x = 1; x < wImg - 1; x++) {
for (let ch = 0; ch < 3; ch++) {
let sum = 0, idx = 0;
for (let ky = -1; ky <= 1; ky++) {
for (let kx = -1; kx <= 1; kx++) {
const px = (y + ky) * wImg + (x + kx);
sum += s[px * 4 + ch] * k[idx++];
}
}
const p = (y * wImg + x) * 4 + ch;
o[p] = Math.min(255, Math.max(0, sum));
}
o[(y * wImg + x) * 4 + 3] = s[(y * wImg + x) * 4 + 3];
}
}
ctx.putImageData(out, 0, 0);
}
// Naive background removal: estimate bg color from edges and mask similar colors
function removeBackground(ctx, w, h) {
const samplePoints = [
[0, 0], [w - 1, 0], [0, h - 1], [w - 1, h - 1],
[Math.floor(w / 2), 0], [Math.floor(w / 2), h - 1], [0, Math.floor(h / 2)], [w - 1, Math.floor(h / 2)]
];
const data = ctx.getImageData(0, 0, w, h);
const d = data.data;
function rgbAt(x, y) {
const i = (y * w + x) * 4;
return [d[i], d[i + 1], d[i + 2]];
}
let r = 0, g = 0, b = 0;
for (const [sx, sy] of samplePoints) {
const [rr, gg, bb] = rgbAt(sx, sy);
r += rr; g += gg; b += bb;
}
r /= samplePoints.length; g /= samplePoints.length; b /= samplePoints.length;
const thr = 40; // color distance threshold
const soft = 15; // feather range
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const dr = d[i] - r, dg = d[i + 1] - g, db = d[i + 2] - b;
const dist = Math.sqrt(dr * dr + dg * dg + db * db);
if (dist < thr) {
const t = Math.max(0, Math.min(1, (thr - dist) / soft));
d[i + 3] = Math.round(255 * (1 - t)); // more transparent near bg
}
}
}
data.data.set(d);
ctx.putImageData(data, 0, 0);
}
// Feather alpha edges to look natural
function featherAlpha(ctx, w, h, radius = 1.5) {
const img = ctx.getImageData(0, 0, w, h);
const d = img.data;
const copy = new Uint8ClampedArray(d);
const r = Math.max(1, Math.round(radius));
for (let y = r; y < h - r; y++) {
for (let x = r; x < w - r; x++) {
let sum = 0, cnt = 0;
for (let ky = -r; ky <= r; ky++) {
for (let kx = -r; kx <= r; kx++) {
const i = ((y + ky) * w + (x + kx)) * 4 + 3;
sum += copy[i];
cnt++;
}
}
const iCenter = (y * w + x) * 4 + 3;
d[iCenter] = Math.round(sum / cnt);
}
}
ctx.putImageData(img, 0, 0);
}
// Compute bounding box of non-transparent or high-contrast content
function getContentBBox(ctx, w, h) {
const img = ctx.getImageData(0, 0, w, h);
const d = img.data;
let minX = w, minY = h, maxX = -1, maxY = -1;
// compute border color average to detect content without alpha
let br = 0, bg = 0, bb = 0, bc = 0;
for (let x = 0; x < w; x++) {
const i1 = (x * 4);
const i2 = ((h - 1) * w + x) * 4;
br += d[i1] + d[i2]; bg += d[i1 + 1] + d[i2 + 1]; bb += d[i1 + 2] + d[i2 + 2]; bc += 2;
}
for (let y = 0; y < h; y++) {
const i1 = (y * w) * 4;
const i2 = (y * w + (w - 1)) * 4;
br += d[i1] + d[i2]; bg += d[i1 + 1] + d[i2 + 1]; bb += d[i1 + 2] + d[i2 + 2]; bc += 2;
}
br /= bc; bg /= bc; bb /= bc;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const a = d[i + 3];
const dr = d[i] - br, dg = d[i + 1] - bg, db = d[i + 2] - bb;
const dist = Math.sqrt(dr * dr + dg * dg + db * db);
const isContent = a > 12 || dist > 24;
if (isContent) {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
}
if (maxX < 0) return { x: 0, y: 0, w, h };
// add small padding
const pad = Math.round(Math.min(w, h) * 0.02);
const bx = Math.max(0, minX - pad);
const by = Math.max(0, minY - pad);
const bw = Math.min(w - bx, (maxX - minX + 1) + pad * 2);
const bh = Math.min(h - by, (maxY - minY + 1) + pad * 2);
return { x: bx, y: by, w: bw, h: bh };
}
async function callRemoveBgAPI(file, apiKey) {
const formData = new FormData();
formData.append("image_file", file);
formData.append("size", "auto");
formData.append("format", "png");
const resp = await fetch("https://api.remove.bg/v1.0/removebg", {
method: "POST",
headers: { "X-Api-Key": apiKey },
body: formData
});
if (!resp.ok) throw new Error("Remove.bg API error");
const blob = await resp.blob();
return blob;
}
async function prepareImage(item, { removeBg, enhance, useRemoveBgApi, removeBgApiKey }) {
// Load file to image then draw onto canvas as PNG with alpha for PDF
let sourceImg;
try {
if (removeBg && useRemoveBgApi && removeBgApiKey) {
const cutBlob = await callRemoveBgAPI(item.file, removeBgApiKey);
sourceImg = await blobToImage(cutBlob);
} else {
sourceImg = await fileToImage(item.file);
}
} catch {
sourceImg = await fileToImage(item.file);
}
const maxDim = 2000; // cap processing resolution for performance
const scale = Math.min(1, maxDim / Math.max(sourceImg.naturalWidth || sourceImg.width, sourceImg.naturalHeight || sourceImg.height));
const w0 = Math.max(1, Math.round((sourceImg.naturalWidth || sourceImg.width) * scale));
const h0 = Math.max(1, Math.round((sourceImg.naturalHeight || sourceImg.height) * scale));
const canvas = document.createElement("canvas");
canvas.width = w0;
canvas.height = h0;
const ctx = canvas.getContext("2d");
ctx.drawImage(sourceImg, 0, 0, w0, h0);
// Remove background (fallback heuristic if not using API)
if (removeBg && !(useRemoveBgApi && removeBgApiKey)) {
removeBackground(ctx, w0, h0);
}
// Feather edges if any transparency present
if (removeBg) {
featherAlpha(ctx, w0, h0, 2);
}
// Smart crop to content bbox
const bbox = getContentBBox(ctx, w0, h0);
let cropCanvas = canvas;
if (bbox.w > 0 && bbox.h > 0 && (bbox.w < w0 || bbox.h < h0)) {
cropCanvas = document.createElement("canvas");
cropCanvas.width = bbox.w;
cropCanvas.height = bbox.h;
const cctx = cropCanvas.getContext("2d");
cctx.drawImage(canvas, bbox.x, bbox.y, bbox.w, bbox.h, 0, 0, bbox.w, bbox.h);
}
// Adaptive enhancement
if (enhance) {
const ec = cropCanvas.getContext("2d");
enhanceCanvas(ec, cropCanvas.width, cropCanvas.height);
}
const dataUrl = cropCanvas.toDataURL("image/png"); // keep transparency
return { dataUrl, w: cropCanvas.width, h: cropCanvas.height };
}
function drawWrappedText(doc, text, x, y, maxWidthMm, lineHeightMm, fontSize = 10) {
if (!text) return 0;
doc.setFont("helvetica", "normal");
doc.setFontSize(fontSize);
const words = text.split(/\s+/);
let line = "";
let usedH = 0;
const lh = lineHeightMm || 4.2;
for (let i = 0; i < words.length; i++) {
const test = line ? line + " " + words[i] : words[i];
const w = doc.getTextWidth(test);
const wMm = (w / doc.internal.scaleFactor);
if (wMm > maxWidthMm && line) {
doc.text(line, x, y + usedH);
usedH += lh;
line = words[i];
} else {
line = test;
}
}
if (line) {
doc.text(line, x, y + usedH);
usedH += lh;
}
return usedH;
}
export async function generatePDFBlob(items, options) {
const {
pageSizeKey,
pageWmm,
pageHmm,
orientation,
layoutKey,
marginMm,
title,
captionMode,
removeBg,
enhance,
useRemoveBgApi,
removeBgApiKey
} = options;
const doc = new jsPDF({
orientation,
unit: "mm",
format: pageSizeKey
});
if (title) {
const centerX = pageWmm / 2;
const centerY = pageHmm / 2;
doc.setFillColor(255, 255, 255);
doc.rect(0, 0, pageWmm, pageHmm, "F");
doc.setTextColor(20, 20, 20);
doc.setFont("helvetica", "bold");
doc.setFontSize(28);
doc.text(title, centerX, centerY, { align: "center", baseline: "middle", maxWidth: pageWmm - marginMm * 2 });
}
// Prepare all images with optional processing
const prepared = await Promise.all(items.map(async (it) => {
const processed = await prepareImage(it, { removeBg, enhance, useRemoveBgApi, removeBgApiKey });
return {
id: it.id,
name: it.name,
dataUrl: processed.dataUrl,
w: processed.w,
h: processed.h,
description: it.description || ""
};
}));
const slots = getSlots(layoutKey, pageWmm, pageHmm, marginMm);
const perPage = slots.length;
for (let i = 0; i < prepared.length; i += perPage) {
if (i !== 0 || title) {
doc.addPage(pageSizeKey, orientation);
}
const pageItems = prepared.slice(i, i + perPage);
pageItems.forEach((imgData, idx) => {
const s = slots[idx];
if (!s) return;
// If caption side mode, reserve right strip for caption
let imgSlot = { ...s };
let captionRect = null;
if (captionMode === "side") {
const sideW = Math.max(20, s.w * 0.28);
imgSlot.w = s.w - sideW - 2;
captionRect = { x: s.x + imgSlot.w + 2, y: s.y + 2, w: sideW - 2, h: s.h - 4 };
}
const mode = layoutFitMode(layoutKey);
const fit = fitWithin(imgData.w, imgData.h, imgSlot.w, imgSlot.h, 2, mode);
const imgX = imgSlot.x + fit.x;
const imgY = imgSlot.y + fit.y;
// Draw image
doc.addImage(
imgData.dataUrl,
"PNG",
imgX,
imgY,
fit.w,
fit.h,
undefined,
"FAST"
);
// Caption rendering
const text = imgData.description?.trim();
if (!text || captionMode === "none") return;
doc.setTextColor(20, 20, 20);
if (captionMode === "below") {
const pad = 2;
const captionY = imgY + fit.h + pad + 4; // baseline adjust
const maxW = s.w - 4;
drawWrappedText(doc, text, s.x + 2, captionY, maxW, 5, 10);
} else if (captionMode === "side" && captionRect) {
doc.setDrawColor(230, 230, 230);
doc.rect(captionRect.x, captionRect.y, captionRect.w, captionRect.h);
doc.setTextColor(30, 30, 30);
drawWrappedText(doc, text, captionRect.x + 2, captionRect.y + 6, captionRect.w - 4, 5, 10);
} else if (captionMode === "overlay") {
const barH = Math.min(14, Math.max(10, fit.h * 0.18));
const barY = imgY + fit.h - barH;
doc.setFillColor(0, 0, 0);
doc.setGState(new doc.GState({ opacity: 0.6 }));
doc.rect(imgX, barY, fit.w, barH, "F");
doc.setGState(new doc.GState({ opacity: 1 }));
doc.setTextColor(255, 255, 255);
const padX = 3;
drawWrappedText(doc, text, imgX + padX, barY + 6, fit.w - padX * 2, 5, 10);
}
});
}
const blob = doc.output("blob");
return blob;
}