dom-to-pptx 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1007 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('pptxgenjs')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'pptxgenjs'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.domToPptx = {}, global.PptxGenJS));
5
+ })(this, (function (exports, PptxGenJS) { 'use strict';
6
+
7
+ // src/utils.js
8
+
9
+ // Helper to save gradient text
10
+ function getGradientFallbackColor(bgImage) {
11
+ if (!bgImage) return null;
12
+ // Extract first hex or rgb color
13
+ // linear-gradient(to right, #4f46e5, ...) -> #4f46e5
14
+ const hexMatch = bgImage.match(/#(?:[0-9a-fA-F]{3}){1,2}/);
15
+ if (hexMatch) return hexMatch[0];
16
+
17
+ const rgbMatch = bgImage.match(/rgba?\(.*?\)/);
18
+ if (rgbMatch) return rgbMatch[0];
19
+
20
+ return null;
21
+ }
22
+
23
+ function mapDashType(style) {
24
+ if (style === 'dashed') return 'dash';
25
+ if (style === 'dotted') return 'dot';
26
+ // PPTX also supports 'lgDash', 'dashDot', 'lgDashDot', 'lgDashDotDot'
27
+ // but we'll stick to basics for now.
28
+ return 'solid';
29
+ }
30
+
31
+ /**
32
+ * Analyzes computed border styles and determines the rendering strategy.
33
+ * @returns {{type: 'uniform' | 'composite' | 'none', ...}}
34
+ */
35
+ function getBorderInfo(style, scale) {
36
+ const top = {
37
+ width: parseFloat(style.borderTopWidth) || 0,
38
+ style: style.borderTopStyle,
39
+ color: parseColor(style.borderTopColor).hex,
40
+ };
41
+ const right = {
42
+ width: parseFloat(style.borderRightWidth) || 0,
43
+ style: style.borderRightStyle,
44
+ color: parseColor(style.borderRightColor).hex,
45
+ };
46
+ const bottom = {
47
+ width: parseFloat(style.borderBottomWidth) || 0,
48
+ style: style.borderBottomStyle,
49
+ color: parseColor(style.borderBottomColor).hex,
50
+ };
51
+ const left = {
52
+ width: parseFloat(style.borderLeftWidth) || 0,
53
+ style: style.borderLeftStyle,
54
+ color: parseColor(style.borderLeftColor).hex,
55
+ };
56
+
57
+ const hasAnyBorder = top.width > 0 || right.width > 0 || bottom.width > 0 || left.width > 0;
58
+ if (!hasAnyBorder) return { type: 'none' };
59
+
60
+ // Check if all sides are uniform
61
+ const isUniform =
62
+ top.width === right.width &&
63
+ top.width === bottom.width &&
64
+ top.width === left.width &&
65
+ top.style === right.style &&
66
+ top.style === bottom.style &&
67
+ top.style === left.style &&
68
+ top.color === right.color &&
69
+ top.color === bottom.color &&
70
+ top.color === left.color;
71
+
72
+ if (isUniform) {
73
+ return {
74
+ type: 'uniform',
75
+ options: {
76
+ width: top.width * 0.75 * scale, // Convert to points and scale
77
+ color: top.color,
78
+ dashType: mapDashType(top.style),
79
+ },
80
+ };
81
+ } else {
82
+ // Borders are different, must render as separate shapes
83
+ return {
84
+ type: 'composite',
85
+ sides: {
86
+ top,
87
+ right,
88
+ bottom,
89
+ left,
90
+ },
91
+ };
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Generates an SVG image for composite borders that respects border-radius.
97
+ */
98
+ function generateCompositeBorderSVG(w, h, radius, sides) {
99
+ radius = radius / 2; // Adjust for SVG rendering
100
+
101
+ const clipId = 'clip_' + Math.random().toString(36).substr(2, 9);
102
+
103
+ let borderRects = '';
104
+
105
+ // TOP
106
+ if (sides.top.width > 0 && sides.top.color) {
107
+ borderRects += `<rect x="0" y="0" width="${w}" height="${sides.top.width}" fill="#${sides.top.color}" />`;
108
+ }
109
+ // RIGHT
110
+ if (sides.right.width > 0 && sides.right.color) {
111
+ borderRects += `<rect x="${w - sides.right.width}" y="0" width="${sides.right.width}" height="${h}" fill="#${sides.right.color}" />`;
112
+ }
113
+ // BOTTOM
114
+ if (sides.bottom.width > 0 && sides.bottom.color) {
115
+ borderRects += `<rect x="0" y="${h - sides.bottom.width}" width="${w}" height="${sides.bottom.width}" fill="#${sides.bottom.color}" />`;
116
+ }
117
+ // LEFT
118
+ if (sides.left.width > 0 && sides.left.color) {
119
+ borderRects += `<rect x="0" y="0" width="${sides.left.width}" height="${h}" fill="#${sides.left.color}" />`;
120
+ }
121
+
122
+ const svg = `
123
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
124
+ <defs>
125
+ <clipPath id="${clipId}">
126
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" />
127
+ </clipPath>
128
+ </defs>
129
+ <g clip-path="url(#${clipId})">
130
+ ${borderRects}
131
+ </g>
132
+ </svg>`;
133
+
134
+ return 'data:image/svg+xml;base64,' + btoa(svg);
135
+ }
136
+
137
+ /**
138
+ * Parses a CSS color string (hex, rgb, rgba) into a hex code and opacity.
139
+ * @param {string} str - The CSS color string.
140
+ * @returns {{hex: string | null, opacity: number}} - Object with hex color (without #) and opacity (0-1).
141
+ */
142
+ function parseColor(str) {
143
+ if (!str || str === 'transparent' || str.startsWith('rgba(0, 0, 0, 0)')) {
144
+ return { hex: null, opacity: 0 };
145
+ }
146
+ if (str.startsWith('#')) {
147
+ let hex = str.slice(1);
148
+ if (hex.length === 3)
149
+ hex = hex
150
+ .split('')
151
+ .map((c) => c + c)
152
+ .join('');
153
+ return { hex: hex.toUpperCase(), opacity: 1 };
154
+ }
155
+ const match = str.match(/[\d.]+/g);
156
+ if (match && match.length >= 3) {
157
+ const r = parseInt(match[0]);
158
+ const g = parseInt(match[1]);
159
+ const b = parseInt(match[2]);
160
+ const a = match.length > 3 ? parseFloat(match[3]) : 1;
161
+ const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
162
+ return { hex, opacity: a };
163
+ }
164
+ return { hex: null, opacity: 0 };
165
+ }
166
+
167
+ /**
168
+ * Calculates padding values from computed CSS styles, scaled to inches.
169
+ * @param {CSSStyleDeclaration} style - The computed CSS style of the element.
170
+ * @param {number} scale - The scaling factor for converting pixels to inches.
171
+ * @returns {number[]} - An array of padding values [top, right, bottom, left] in inches.
172
+ */
173
+ function getPadding(style, scale) {
174
+ const pxToInch = 1 / 96;
175
+ return [
176
+ (parseFloat(style.paddingTop) || 0) * pxToInch * scale,
177
+ (parseFloat(style.paddingRight) || 0) * pxToInch * scale,
178
+ (parseFloat(style.paddingBottom) || 0) * pxToInch * scale,
179
+ (parseFloat(style.paddingLeft) || 0) * pxToInch * scale,
180
+ ];
181
+ }
182
+
183
+ /**
184
+ * Extracts the blur radius for soft edges from a CSS filter string.
185
+ * @param {string} filterStr - The CSS filter string.
186
+ * @param {number} scale - The scaling factor.
187
+ * @returns {number | null} - The blur radius in points, or null if no blur is found.
188
+ */
189
+ function getSoftEdges(filterStr, scale) {
190
+ if (!filterStr || filterStr === 'none') return null;
191
+ const match = filterStr.match(/blur\(([\d.]+)px\)/);
192
+ if (match) return parseFloat(match[1]) * 0.75 * scale;
193
+ return null;
194
+ }
195
+
196
+ /**
197
+ * Generates text style options for PPTX from computed CSS styles.
198
+ * Handles font properties, color, and text transformations.
199
+ * @param {CSSStyleDeclaration} style - The computed CSS style of the element.
200
+ * @param {number} scale - The scaling factor for converting pixels to inches.
201
+ * @returns {PptxGenJS.TextOptions} - PPTX text style object.
202
+ */
203
+ function getTextStyle(style, scale) {
204
+ let colorObj = parseColor(style.color);
205
+
206
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
207
+ if (colorObj.opacity === 0 && bgClip === 'text') {
208
+ const fallback = getGradientFallbackColor(style.backgroundImage);
209
+ if (fallback) colorObj = parseColor(fallback);
210
+ }
211
+
212
+ return {
213
+ color: colorObj.hex || '000000',
214
+ fontFace: style.fontFamily.split(',')[0].replace(/['"]/g, ''),
215
+ fontSize: parseFloat(style.fontSize) * 0.75 * scale,
216
+ bold: parseInt(style.fontWeight) >= 600,
217
+ italic: style.fontStyle === 'italic',
218
+ underline: style.textDecoration.includes('underline'),
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Determines if a given DOM node is primarily a text container.
224
+ * Checks if the node has text content and if its children are all inline elements.
225
+ * @param {HTMLElement} node - The DOM node to check.
226
+ * @returns {boolean} - True if the node is considered a text container, false otherwise.
227
+ */
228
+ function isTextContainer(node) {
229
+ const hasText = node.textContent.trim().length > 0;
230
+ if (!hasText) return false;
231
+ const children = Array.from(node.children);
232
+ if (children.length === 0) return true;
233
+ const isInline = (el) =>
234
+ window.getComputedStyle(el).display.includes('inline') ||
235
+ ['SPAN', 'B', 'STRONG', 'EM', 'I', 'A', 'SMALL'].includes(el.tagName);
236
+ return children.every(isInline);
237
+ }
238
+
239
+ /**
240
+ * Extracts the rotation angle in degrees from a CSS transform string.
241
+ * @param {string} transformStr - The CSS transform string.
242
+ * @returns {number} - The rotation angle in degrees.
243
+ */
244
+ function getRotation(transformStr) {
245
+ if (!transformStr || transformStr === 'none') return 0;
246
+ const values = transformStr.split('(')[1].split(')')[0].split(',');
247
+ if (values.length < 4) return 0;
248
+ const a = parseFloat(values[0]);
249
+ const b = parseFloat(values[1]);
250
+ return Math.round(Math.atan2(b, a) * (180 / Math.PI));
251
+ }
252
+
253
+ /**
254
+ * Converts an SVG DOM node to a PNG data URL.
255
+ * Inlines styles to ensure accurate rendering in the PNG.
256
+ * @param {SVGElement} node - The SVG DOM node to convert.
257
+ * @returns {Promise<string | null>} - A Promise that resolves with the PNG data URL or null on error.
258
+ */
259
+ function svgToPng(node) {
260
+ return new Promise((resolve) => {
261
+ const clone = node.cloneNode(true);
262
+ const rect = node.getBoundingClientRect();
263
+ const width = rect.width || 300;
264
+ const height = rect.height || 150;
265
+
266
+ function inlineStyles(source, target) {
267
+ const computed = window.getComputedStyle(source);
268
+ const properties = [
269
+ 'fill',
270
+ 'stroke',
271
+ 'stroke-width',
272
+ 'stroke-linecap',
273
+ 'stroke-linejoin',
274
+ 'opacity',
275
+ 'font-family',
276
+ 'font-size',
277
+ 'font-weight',
278
+ ];
279
+
280
+ if (computed.fill === 'none') target.setAttribute('fill', 'none');
281
+ else if (computed.fill) target.style.fill = computed.fill;
282
+
283
+ if (computed.stroke === 'none') target.setAttribute('stroke', 'none');
284
+ else if (computed.stroke) target.style.stroke = computed.stroke;
285
+
286
+ properties.forEach((prop) => {
287
+ if (prop !== 'fill' && prop !== 'stroke') {
288
+ const val = computed[prop];
289
+ if (val && val !== 'auto') target.style[prop] = val;
290
+ }
291
+ });
292
+
293
+ for (let i = 0; i < source.children.length; i++) {
294
+ if (target.children[i]) inlineStyles(source.children[i], target.children[i]);
295
+ }
296
+ }
297
+
298
+ inlineStyles(node, clone);
299
+
300
+ clone.setAttribute('width', width);
301
+ clone.setAttribute('height', height);
302
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
303
+
304
+ const xml = new XMLSerializer().serializeToString(clone);
305
+ const svgUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xml)}`;
306
+
307
+ const img = new Image();
308
+ img.crossOrigin = 'Anonymous';
309
+ img.onload = () => {
310
+ const canvas = document.createElement('canvas');
311
+ const scale = 3;
312
+ canvas.width = width * scale;
313
+ canvas.height = height * scale;
314
+ const ctx = canvas.getContext('2d');
315
+ ctx.scale(scale, scale);
316
+ ctx.drawImage(img, 0, 0, width, height);
317
+ resolve(canvas.toDataURL('image/png'));
318
+ };
319
+ img.onerror = () => resolve(null);
320
+ img.src = svgUrl;
321
+ });
322
+ }
323
+
324
+ /**
325
+ * Parses CSS box-shadow properties and converts them into PPTX-compatible shadow options.
326
+ * Supports multiple shadows, prioritizing the first visible (non-transparent) outer shadow.
327
+ * @param {string} shadowStr - The CSS `box-shadow` string.
328
+ * @param {number} scale - The scaling factor.
329
+ * @returns {PptxGenJS.ShapeShadow | null} - PPTX shadow options, or null if no visible outer shadow.
330
+ */
331
+ function getVisibleShadow(shadowStr, scale) {
332
+ if (!shadowStr || shadowStr === 'none') return null;
333
+ const shadows = shadowStr.split(/,(?![^()]*\))/);
334
+ for (let s of shadows) {
335
+ s = s.trim();
336
+ if (s.startsWith('rgba(0, 0, 0, 0)')) continue;
337
+ const match = s.match(
338
+ /(rgba?\([^)]+\)|#[0-9a-fA-F]+)\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px/
339
+ );
340
+ if (match) {
341
+ const colorStr = match[1];
342
+ const x = parseFloat(match[2]);
343
+ const y = parseFloat(match[3]);
344
+ const blur = parseFloat(match[4]);
345
+ const distance = Math.sqrt(x * x + y * y);
346
+ let angle = Math.atan2(y, x) * (180 / Math.PI);
347
+ if (angle < 0) angle += 360;
348
+ const colorObj = parseColor(colorStr);
349
+ return {
350
+ type: 'outer',
351
+ angle: angle,
352
+ blur: blur * 0.75 * scale,
353
+ offset: distance * 0.75 * scale,
354
+ color: colorObj.hex || '000000',
355
+ opacity: colorObj.opacity,
356
+ };
357
+ }
358
+ }
359
+ return null;
360
+ }
361
+
362
+ /**
363
+ * Generates an SVG data URL for a linear gradient background with optional border-radius and border.
364
+ * Parses CSS linear-gradient string to create SVG <linearGradient> and <rect> elements.
365
+ * @param {number} w - Width of the SVG.
366
+ * @param {number} h - Height of the SVG.
367
+ * @param {string} bgString - The CSS `background-image` string (e.g., `linear-gradient(...)`).
368
+ * @param {number} radius - Border radius for the rectangle.
369
+ * @param {{color: string, width: number} | null} border - Optional border object with color (hex) and width.
370
+ * @returns {string | null} - SVG data URL or null if parsing fails.
371
+ */
372
+ function generateGradientSVG(w, h, bgString, radius, border) {
373
+ try {
374
+ const match = bgString.match(/linear-gradient\((.*)\)/);
375
+ if (!match) return null;
376
+ const content = match[1];
377
+ const parts = content.split(/,(?![^()]*\))/).map((p) => p.trim());
378
+
379
+ let x1 = '0%',
380
+ y1 = '0%',
381
+ x2 = '0%',
382
+ y2 = '100%';
383
+ let stopsStartIdx = 0;
384
+ if (parts[0].includes('to right')) {
385
+ x1 = '0%';
386
+ x2 = '100%';
387
+ y2 = '0%';
388
+ stopsStartIdx = 1;
389
+ } else if (parts[0].includes('to left')) {
390
+ x1 = '100%';
391
+ x2 = '0%';
392
+ y2 = '0%';
393
+ stopsStartIdx = 1;
394
+ } else if (parts[0].includes('to top')) {
395
+ y1 = '100%';
396
+ y2 = '0%';
397
+ stopsStartIdx = 1;
398
+ } else if (parts[0].includes('to bottom')) {
399
+ y1 = '0%';
400
+ y2 = '100%';
401
+ stopsStartIdx = 1;
402
+ }
403
+
404
+ let stopsXML = '';
405
+ const stopParts = parts.slice(stopsStartIdx);
406
+ stopParts.forEach((part, idx) => {
407
+ let color = part;
408
+ let offset = Math.round((idx / (stopParts.length - 1)) * 100) + '%';
409
+ const posMatch = part.match(/(.*?)\s+(\d+(\.\d+)?%?)$/);
410
+ if (posMatch) {
411
+ color = posMatch[1];
412
+ offset = posMatch[2];
413
+ }
414
+ let opacity = 1;
415
+ if (color.includes('rgba')) {
416
+ const rgba = color.match(/[\d.]+/g);
417
+ if (rgba && rgba.length > 3) {
418
+ opacity = rgba[3];
419
+ color = `rgb(${rgba[0]},${rgba[1]},${rgba[2]})`;
420
+ }
421
+ }
422
+ stopsXML += `<stop offset="${offset}" stop-color="${color}" stop-opacity="${opacity}"/>`;
423
+ });
424
+
425
+ let strokeAttr = '';
426
+ if (border) {
427
+ strokeAttr = `stroke="#${border.color}" stroke-width="${border.width}"`;
428
+ }
429
+
430
+ const svg = `
431
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
432
+ <defs><linearGradient id="grad" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}">${stopsXML}</linearGradient></defs>
433
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="url(#grad)" ${strokeAttr} />
434
+ </svg>`;
435
+ return 'data:image/svg+xml;base64,' + btoa(svg);
436
+ } catch {
437
+ return null;
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Generates an SVG data URL for a blurred rectangle or ellipse, used for soft-edge effects.
443
+ * @param {number} w - Original width of the element.
444
+ * @param {number} h - Original height of the element.
445
+ * @param {string} color - Hex color of the shape (without #).
446
+ * @param {number} radius - Border radius of the shape.
447
+ * @param {number} blurPx - Blur radius in pixels for the SVG filter.
448
+ * @returns {{data: string, padding: number}} - Object containing SVG data URL and calculated padding.
449
+ */
450
+ function generateBlurredSVG(w, h, color, radius, blurPx) {
451
+ const padding = blurPx * 3;
452
+ const fullW = w + padding * 2;
453
+ const fullH = h + padding * 2;
454
+ const x = padding;
455
+ const y = padding;
456
+ let shapeTag = '';
457
+ const isCircle = radius >= Math.min(w, h) / 2 - 1 && Math.abs(w - h) < 2;
458
+
459
+ if (isCircle) {
460
+ const cx = x + w / 2;
461
+ const cy = y + h / 2;
462
+ const rx = w / 2;
463
+ const ry = h / 2;
464
+ shapeTag = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="#${color}" filter="url(#f1)" />`;
465
+ } else {
466
+ shapeTag = `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="#${color}" filter="url(#f1)" />`;
467
+ }
468
+
469
+ const svg = `
470
+ <svg xmlns="http://www.w3.org/2000/svg" width="${fullW}" height="${fullH}" viewBox="0 0 ${fullW} ${fullH}">
471
+ <defs>
472
+ <filter id="f1" x="-50%" y="-50%" width="200%" height="200%">
473
+ <feGaussianBlur in="SourceGraphic" stdDeviation="${blurPx}" />
474
+ </filter>
475
+ </defs>
476
+ ${shapeTag}
477
+ </svg>`;
478
+
479
+ return {
480
+ data: 'data:image/svg+xml;base64,' + btoa(svg),
481
+ padding: padding,
482
+ };
483
+ }
484
+
485
+ // src/image-processor.js
486
+
487
+ async function getProcessedImage(src, targetW, targetH, radius) {
488
+ return new Promise((resolve) => {
489
+ const img = new Image();
490
+ img.crossOrigin = 'Anonymous'; // Critical for canvas manipulation
491
+
492
+ img.onload = () => {
493
+ const canvas = document.createElement('canvas');
494
+ // Double resolution for better quality
495
+ const scale = 2;
496
+ canvas.width = targetW * scale;
497
+ canvas.height = targetH * scale;
498
+ const ctx = canvas.getContext('2d');
499
+ ctx.scale(scale, scale);
500
+
501
+ // 1. Draw the Mask (Rounded Rect)
502
+ ctx.beginPath();
503
+ if (ctx.roundRect) {
504
+ ctx.roundRect(0, 0, targetW, targetH, radius);
505
+ } else {
506
+ // Fallback for older browsers if needed
507
+ ctx.rect(0, 0, targetW, targetH);
508
+ }
509
+ ctx.fillStyle = '#000';
510
+ ctx.fill();
511
+
512
+ // 2. Composite Source-In
513
+ ctx.globalCompositeOperation = 'source-in';
514
+
515
+ // 3. Draw Image (Object Cover Logic)
516
+ const wRatio = targetW / img.width;
517
+ const hRatio = targetH / img.height;
518
+ const maxRatio = Math.max(wRatio, hRatio);
519
+ const renderW = img.width * maxRatio;
520
+ const renderH = img.height * maxRatio;
521
+ const renderX = (targetW - renderW) / 2;
522
+ const renderY = (targetH - renderH) / 2;
523
+
524
+ ctx.drawImage(img, renderX, renderY, renderW, renderH);
525
+
526
+ resolve(canvas.toDataURL('image/png'));
527
+ };
528
+
529
+ img.onerror = () => resolve(null);
530
+ img.src = src;
531
+ });
532
+ }
533
+
534
+ // src/index.js
535
+
536
+ const PPI = 96;
537
+ const PX_TO_INCH = 1 / PPI;
538
+
539
+ /**
540
+ * Main export function. Accepts single element or an array.
541
+ * @param {HTMLElement | string | Array<HTMLElement | string>} target - The root element(s) to convert.
542
+ * @param {Object} options - { fileName: string }
543
+ */
544
+ async function exportToPptx(target, options = {}) {
545
+ const pptx = new PptxGenJS();
546
+ pptx.layout = 'LAYOUT_16x9';
547
+
548
+ // Standardize input to an array, ensuring single or multiple elements are handled consistently
549
+ const elements = Array.isArray(target) ? target : [target];
550
+
551
+ for (const el of elements) {
552
+ const root = typeof el === 'string' ? document.querySelector(el) : el;
553
+ if (!root) {
554
+ console.warn('Element not found, skipping slide:', el);
555
+ continue;
556
+ }
557
+
558
+ const slide = pptx.addSlide();
559
+ await processSlide(root, slide, pptx);
560
+ }
561
+
562
+ const fileName = options.fileName || 'export.pptx';
563
+ pptx.writeFile({ fileName });
564
+ }
565
+
566
+ /**
567
+ * Worker function to process a single DOM element into a single PPTX slide.
568
+ * @param {HTMLElement} root - The root element for this slide.
569
+ * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
570
+ * @param {PptxGenJS} pptx - The main PPTX instance.
571
+ */
572
+ async function processSlide(root, slide, pptx) {
573
+ const rootRect = root.getBoundingClientRect();
574
+ const PPTX_WIDTH_IN = 10;
575
+ const PPTX_HEIGHT_IN = 5.625;
576
+
577
+ const contentWidthIn = rootRect.width * PX_TO_INCH;
578
+ const contentHeightIn = rootRect.height * PX_TO_INCH;
579
+ const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
580
+
581
+ const layoutConfig = {
582
+ rootX: rootRect.x,
583
+ rootY: rootRect.y,
584
+ scale: scale,
585
+ offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
586
+ offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
587
+ };
588
+
589
+ const renderQueue = [];
590
+ let domOrderCounter = 0;
591
+
592
+ async function collect(node) {
593
+ const order = domOrderCounter++; // Assign a DOM order for z-index tie-breaking
594
+ const result = await createRenderItem(node, layoutConfig, order, pptx);
595
+ if (result) {
596
+ if (result.items) renderQueue.push(...result.items); // Add any generated render items to the queue
597
+ if (result.stopRecursion) return; // Stop processing children if the item fully consumed the node
598
+ }
599
+ for (const child of node.children) await collect(child);
600
+ }
601
+
602
+ await collect(root);
603
+
604
+ renderQueue.sort((a, b) => {
605
+ if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
606
+ return a.domOrder - b.domOrder;
607
+ });
608
+
609
+ for (const item of renderQueue) {
610
+ if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
611
+ if (item.type === 'image') slide.addImage(item.options);
612
+ if (item.type === 'text') slide.addText(item.textParts, item.options);
613
+ }
614
+ }
615
+
616
+ async function createRenderItem(node, config, domOrder, pptx) {
617
+ if (node.nodeType !== 1) return null;
618
+ const style = window.getComputedStyle(node);
619
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')
620
+ return null;
621
+
622
+ const rect = node.getBoundingClientRect();
623
+ if (rect.width === 0 || rect.height === 0) return null;
624
+
625
+ const zIndex = style.zIndex !== 'auto' ? parseInt(style.zIndex) : 0;
626
+ const rotation = getRotation(style.transform);
627
+ const elementOpacity = parseFloat(style.opacity);
628
+
629
+ const widthPx = node.offsetWidth || rect.width;
630
+ const heightPx = node.offsetHeight || rect.height;
631
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
632
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
633
+ const centerX = rect.left + rect.width / 2;
634
+ const centerY = rect.top + rect.height / 2;
635
+
636
+ let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
637
+ let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
638
+ let w = unrotatedW;
639
+ let h = unrotatedH;
640
+
641
+ const items = [];
642
+
643
+ // Image handling for SVG nodes directly
644
+ if (node.nodeName.toUpperCase() === 'SVG') {
645
+ const pngData = await svgToPng(node);
646
+ if (pngData)
647
+ items.push({
648
+ type: 'image',
649
+ zIndex,
650
+ domOrder,
651
+ options: { data: pngData, x, y, w, h, rotate: rotation },
652
+ });
653
+ return { items, stopRecursion: true };
654
+ }
655
+ // Image handling for <img> tags, including rounded corners
656
+ if (node.tagName === 'IMG') {
657
+ let borderRadius = parseFloat(style.borderRadius) || 0;
658
+ if (borderRadius === 0) {
659
+ const parentStyle = window.getComputedStyle(node.parentElement);
660
+ if (parentStyle.overflow !== 'visible')
661
+ borderRadius = parseFloat(parentStyle.borderRadius) || 0;
662
+ }
663
+ const processed = await getProcessedImage(node.src, widthPx, heightPx, borderRadius);
664
+ if (processed)
665
+ items.push({
666
+ type: 'image',
667
+ zIndex,
668
+ domOrder,
669
+ options: { data: processed, x, y, w, h, rotate: rotation },
670
+ });
671
+ return { items, stopRecursion: true };
672
+ }
673
+
674
+ const bgColorObj = parseColor(style.backgroundColor);
675
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
676
+ const isBgClipText = bgClip === 'text';
677
+ const hasGradient =
678
+ !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
679
+
680
+ const borderColorObj = parseColor(style.borderColor);
681
+ const borderWidth = parseFloat(style.borderWidth);
682
+ const hasBorder = borderWidth > 0 && borderColorObj.hex;
683
+
684
+ const borderInfo = getBorderInfo(style, config.scale);
685
+ const hasUniformBorder = borderInfo.type === 'uniform';
686
+ const hasCompositeBorder = borderInfo.type === 'composite';
687
+
688
+ const shadowStr = style.boxShadow;
689
+ const hasShadow = shadowStr && shadowStr !== 'none';
690
+ const borderRadius = parseFloat(style.borderRadius) || 0;
691
+ const softEdge = getSoftEdges(style.filter, config.scale);
692
+
693
+ let isImageWrapper = false;
694
+ const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
695
+ if (imgChild) {
696
+ const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
697
+ const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
698
+ if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
699
+ }
700
+
701
+ let textPayload = null;
702
+ const isText = isTextContainer(node);
703
+
704
+ if (isText) {
705
+ const textParts = [];
706
+ const isList = style.display === 'list-item';
707
+ if (isList) {
708
+ const fontSizePt = parseFloat(style.fontSize) * 0.75 * config.scale;
709
+ const bulletShift = (parseFloat(style.fontSize) || 16) * PX_TO_INCH * config.scale * 1.5;
710
+ x -= bulletShift;
711
+ w += bulletShift;
712
+ textParts.push({
713
+ text: '• ',
714
+ options: {
715
+ // Default bullet point styling
716
+ color: parseColor(style.color).hex || '000000',
717
+ fontSize: fontSizePt,
718
+ },
719
+ });
720
+ }
721
+
722
+ node.childNodes.forEach((child, index) => {
723
+ // Process text content, sanitizing whitespace and applying text transformations
724
+ let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
725
+ let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
726
+ textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
727
+ if (index === 0 && !isList) textVal = textVal.trimStart();
728
+ else if (index === 0) textVal = textVal.trimStart();
729
+ if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
730
+ if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
731
+ if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
732
+
733
+ if (textVal.length > 0) {
734
+ textParts.push({
735
+ text: textVal,
736
+ options: getTextStyle(nodeStyle, config.scale),
737
+ });
738
+ }
739
+ });
740
+
741
+ if (textParts.length > 0) {
742
+ let align = style.textAlign || 'left';
743
+ if (align === 'start') align = 'left';
744
+ if (align === 'end') align = 'right';
745
+ let valign = 'top';
746
+ if (style.alignItems === 'center') valign = 'middle';
747
+ if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
748
+
749
+ const pt = parseFloat(style.paddingTop) || 0;
750
+ const pb = parseFloat(style.paddingBottom) || 0;
751
+ if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
752
+
753
+ let padding = getPadding(style, config.scale);
754
+ if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
755
+
756
+ textPayload = { text: textParts, align, valign, inset: padding };
757
+ }
758
+ }
759
+
760
+ if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
761
+ let bgData = null;
762
+ let padIn = 0;
763
+ if (softEdge) {
764
+ const svgInfo = generateBlurredSVG(widthPx, heightPx, bgColorObj.hex, borderRadius, softEdge);
765
+ bgData = svgInfo.data;
766
+ padIn = svgInfo.padding * PX_TO_INCH * config.scale;
767
+ } else {
768
+ bgData = generateGradientSVG(
769
+ widthPx,
770
+ heightPx,
771
+ style.backgroundImage,
772
+ borderRadius,
773
+ hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
774
+ );
775
+ }
776
+
777
+ if (bgData) {
778
+ items.push({
779
+ type: 'image',
780
+ zIndex,
781
+ domOrder,
782
+ options: {
783
+ data: bgData,
784
+ x: x - padIn,
785
+ y: y - padIn,
786
+ w: w + padIn * 2,
787
+ h: h + padIn * 2,
788
+ rotate: rotation,
789
+ },
790
+ });
791
+ }
792
+
793
+ if (textPayload) {
794
+ items.push({
795
+ type: 'text',
796
+ zIndex: zIndex + 1,
797
+ domOrder,
798
+ textParts: textPayload.text,
799
+ options: {
800
+ x,
801
+ y,
802
+ w,
803
+ h,
804
+ align: textPayload.align,
805
+ valign: textPayload.valign,
806
+ inset: textPayload.inset,
807
+ rotate: rotation,
808
+ margin: 0,
809
+ wrap: true,
810
+ autoFit: false,
811
+ },
812
+ });
813
+ }
814
+ if (hasCompositeBorder) {
815
+ // Add border shapes after the main background
816
+ const borderItems = createCompositeBorderItems(
817
+ borderInfo.sides,
818
+ x,
819
+ y,
820
+ w,
821
+ h,
822
+ config.scale,
823
+ zIndex,
824
+ domOrder
825
+ );
826
+ items.push(...borderItems);
827
+ }
828
+ } else if (
829
+ (bgColorObj.hex && !isImageWrapper) ||
830
+ hasUniformBorder ||
831
+ hasCompositeBorder ||
832
+ hasShadow ||
833
+ textPayload
834
+ ) {
835
+ const finalAlpha = elementOpacity * bgColorObj.opacity;
836
+ const transparency = (1 - finalAlpha) * 100;
837
+
838
+ const shapeOpts = {
839
+ x,
840
+ y,
841
+ w,
842
+ h,
843
+ rotate: rotation,
844
+ fill:
845
+ bgColorObj.hex && !isImageWrapper
846
+ ? { color: bgColorObj.hex, transparency: transparency }
847
+ : { type: 'none' },
848
+ // Only apply line if the border is uniform
849
+ line: hasUniformBorder ? borderInfo.options : null,
850
+ };
851
+
852
+ if (hasShadow) {
853
+ shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
854
+ }
855
+
856
+ const borderRadius = parseFloat(style.borderRadius) || 0;
857
+ const widthPx = node.offsetWidth || rect.width;
858
+ const heightPx = node.offsetHeight || rect.height;
859
+ const isCircle =
860
+ borderRadius >= Math.min(widthPx, heightPx) / 2 - 1 && Math.abs(widthPx - heightPx) < 2;
861
+
862
+ let shapeType = pptx.ShapeType.rect;
863
+ if (isCircle) shapeType = pptx.ShapeType.ellipse;
864
+ else if (borderRadius > 0) {
865
+ shapeType = pptx.ShapeType.roundRect;
866
+ shapeOpts.rectRadius = Math.min(1, borderRadius / (Math.min(widthPx, heightPx) / 2));
867
+ }
868
+
869
+ // MERGE TEXT INTO SHAPE (if text exists)
870
+ if (textPayload) {
871
+ const textOptions = {
872
+ shape: shapeType,
873
+ ...shapeOpts,
874
+ align: textPayload.align,
875
+ valign: textPayload.valign,
876
+ inset: textPayload.inset,
877
+ margin: 0,
878
+ wrap: true,
879
+ autoFit: false,
880
+ };
881
+ items.push({
882
+ type: 'text',
883
+ zIndex,
884
+ domOrder,
885
+ textParts: textPayload.text,
886
+ options: textOptions,
887
+ });
888
+ // If no text, just draw the shape
889
+ } else {
890
+ items.push({
891
+ type: 'shape',
892
+ zIndex,
893
+ domOrder,
894
+ shapeType,
895
+ options: shapeOpts,
896
+ });
897
+ }
898
+
899
+ // ADD COMPOSITE BORDERS (if they exist)
900
+ if (hasCompositeBorder) {
901
+ // Generate a single SVG image that contains all the rounded border sides
902
+ const borderSvgData = generateCompositeBorderSVG(
903
+ widthPx,
904
+ heightPx,
905
+ borderRadius,
906
+ borderInfo.sides
907
+ );
908
+
909
+ if (borderSvgData) {
910
+ items.push({
911
+ type: 'image',
912
+ zIndex: zIndex + 1,
913
+ domOrder,
914
+ options: {
915
+ data: borderSvgData,
916
+ x: x,
917
+ y: y,
918
+ w: w,
919
+ h: h,
920
+ rotate: rotation,
921
+ },
922
+ });
923
+ }
924
+ }
925
+ }
926
+
927
+ return { items, stopRecursion: !!textPayload };
928
+ }
929
+
930
+ /**
931
+ * Helper function to create individual border shapes
932
+ */
933
+ function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
934
+ const items = [];
935
+ const pxToInch = 1 / 96;
936
+
937
+ // TOP BORDER
938
+ if (sides.top.width > 0) {
939
+ items.push({
940
+ type: 'shape',
941
+ zIndex: zIndex + 1,
942
+ domOrder,
943
+ shapeType: 'rect',
944
+ options: {
945
+ x: x,
946
+ y: y,
947
+ w: w,
948
+ h: sides.top.width * pxToInch * scale,
949
+ fill: { color: sides.top.color },
950
+ },
951
+ });
952
+ }
953
+ // RIGHT BORDER
954
+ if (sides.right.width > 0) {
955
+ items.push({
956
+ type: 'shape',
957
+ zIndex: zIndex + 1,
958
+ domOrder,
959
+ shapeType: 'rect',
960
+ options: {
961
+ x: x + w - sides.right.width * pxToInch * scale,
962
+ y: y,
963
+ w: sides.right.width * pxToInch * scale,
964
+ h: h,
965
+ fill: { color: sides.right.color },
966
+ },
967
+ });
968
+ }
969
+ // BOTTOM BORDER
970
+ if (sides.bottom.width > 0) {
971
+ items.push({
972
+ type: 'shape',
973
+ zIndex: zIndex + 1,
974
+ domOrder,
975
+ shapeType: 'rect',
976
+ options: {
977
+ x: x,
978
+ y: y + h - sides.bottom.width * pxToInch * scale,
979
+ w: w,
980
+ h: sides.bottom.width * pxToInch * scale,
981
+ fill: { color: sides.bottom.color },
982
+ },
983
+ });
984
+ }
985
+ // LEFT BORDER
986
+ if (sides.left.width > 0) {
987
+ items.push({
988
+ type: 'shape',
989
+ zIndex: zIndex + 1,
990
+ domOrder,
991
+ shapeType: 'rect',
992
+ options: {
993
+ x: x,
994
+ y: y,
995
+ w: sides.left.width * pxToInch * scale,
996
+ h: h,
997
+ fill: { color: sides.left.color },
998
+ },
999
+ });
1000
+ }
1001
+
1002
+ return items;
1003
+ }
1004
+
1005
+ exports.exportToPptx = exportToPptx;
1006
+
1007
+ }));