html-to-native-pptx 0.1.1__py3-none-any.whl

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,32 @@
1
+ """High-fidelity HTML to native, editable PowerPoint."""
2
+
3
+ from html_to_native_pptx.convert import convert, measure
4
+ from html_to_native_pptx.errors import ConversionError
5
+ from html_to_native_pptx.fontfiles import FontResponses
6
+ from html_to_native_pptx.measurer import (
7
+ BACKGROUND,
8
+ MARK,
9
+ SERIES_PROPERTIES,
10
+ WHOLE,
11
+ measure_deck,
12
+ measure_script,
13
+ )
14
+ from html_to_native_pptx.model import DeckFont, MeasuredDeck
15
+ from html_to_native_pptx.writer import deck_pptx
16
+
17
+ __version__ = "0.1.1"
18
+ __all__ = [
19
+ "BACKGROUND",
20
+ "MARK",
21
+ "SERIES_PROPERTIES",
22
+ "WHOLE",
23
+ "ConversionError",
24
+ "DeckFont",
25
+ "FontResponses",
26
+ "MeasuredDeck",
27
+ "convert",
28
+ "deck_pptx",
29
+ "measure",
30
+ "measure_deck",
31
+ "measure_script",
32
+ ]
@@ -0,0 +1,7 @@
1
+ """Run the CLI as `python -m html_to_native_pptx`."""
2
+
3
+ import sys
4
+
5
+ from html_to_native_pptx.cli import main
6
+
7
+ sys.exit(main())
@@ -0,0 +1,497 @@
1
+ /**
2
+ * Runs inside the page, once, and returns the measurements of every slide as JSON.
3
+ * Called as `page.evaluate(script, options)`; `options` is `{ selector, series }`: the selector names
4
+ * one element per slide, and `series` lists the CSS custom properties a chart's series colours are read from.
5
+ * The result is `{ slides, pictures, fonts }`; see html_to_native_pptx/model.py for what each part means.
6
+ */
7
+ ({ selector, series }) => {
8
+ const MARK = "data-html-to-native-pptx";
9
+ const probe = document.createElement("i");
10
+ document.body.appendChild(probe);
11
+ const hex = (value, clear = false) => {
12
+ if (!value) return null;
13
+ probe.style.color = "";
14
+ probe.style.color = value;
15
+ const found = getComputedStyle(probe).color.match(/[\d.]+/g);
16
+ if (!found || found.length < 3) return null;
17
+ const alpha = found.length > 3 ? Number(found[3]) : 1;
18
+ if (alpha === 0) return clear ? "#00000000" : null;
19
+ const channels = found.slice(0, 3).map((n) => Math.round(Number(n)));
20
+ // A see-through colour keeps its alpha as a fourth byte, so it is not written solid.
21
+ if (alpha < 1) channels.push(Math.round(alpha * 255));
22
+ return "#" + channels.map((n) => n.toString(16).padStart(2, "0")).join("");
23
+ };
24
+ const px = (value) => { const n = parseFloat(value); return Number.isFinite(n) ? n : 0; };
25
+ // A colour seen through `opacity`: the element's own and its ancestors' up to `stop`, which
26
+ // the browser applies as a group but PowerPoint only knows as each colour's alpha.
27
+ const fade = (colour, opacity) => {
28
+ if (!colour || opacity >= 0.999) return colour;
29
+ const digits = colour.slice(1);
30
+ const alpha = (digits.length === 8 ? parseInt(digits.slice(6), 16) / 255 : 1) * opacity;
31
+ return "#" + digits.slice(0, 6) + Math.round(alpha * 255).toString(16).padStart(2, "0");
32
+ };
33
+ const opacityOf = (el, stop = null) => {
34
+ let opacity = 1;
35
+ for (let at = el; at && at !== stop && at !== document.documentElement; at = at.parentElement)
36
+ opacity *= Number(getComputedStyle(at).opacity);
37
+ return opacity;
38
+ };
39
+ // How far an element and its ancestors turn and scale it, from their 2D transforms.
40
+ const turn = (el) => {
41
+ let angle = 0;
42
+ let scale = 1;
43
+ for (let at = el; at && at !== document.documentElement; at = at.parentElement) {
44
+ const matrix = getComputedStyle(at).transform;
45
+ if (!matrix || matrix === "none") continue;
46
+ const [a, b] = matrix.slice(matrix.indexOf("(") + 1, -1).split(",").map(Number);
47
+ angle += Math.atan2(b, a) * 180 / Math.PI;
48
+ scale *= Math.hypot(a, b);
49
+ }
50
+ return { angle: ((angle % 360) + 360) % 360, scale };
51
+ };
52
+ const shown = (el) => {
53
+ const s = getComputedStyle(el);
54
+ if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
55
+ const r = el.getBoundingClientRect();
56
+ return r.width > 0 && r.height > 0;
57
+ };
58
+ const decorated = (el) => ["::before", "::after"].some((part) => {
59
+ const c = getComputedStyle(el, part).content;
60
+ return c && c !== "none" && c !== "normal";
61
+ });
62
+ let marks = 0;
63
+ const pictures = [];
64
+ const mark = (el, mode, origin) => {
65
+ const id = String(++marks);
66
+ el.setAttribute(MARK, id);
67
+ pictures.push({ id, mode, box: place(el, origin) });
68
+ return id;
69
+ };
70
+ const place = (el, origin) => {
71
+ const r = el.getBoundingClientRect();
72
+ return { x: r.left - origin.left, y: r.top - origin.top, width: r.width, height: r.height };
73
+ };
74
+ const placed = (el, origin) => {
75
+ const box = place(el, origin);
76
+ const { angle, scale } = turn(el);
77
+ if (Math.min(angle, 360 - angle) < 0.1 || !(el.offsetWidth > 0)) return { box, rotation: 0 };
78
+ const width = el.offsetWidth * scale;
79
+ const height = el.offsetHeight * scale;
80
+ const cx = box.x + box.width / 2;
81
+ const cy = box.y + box.height / 2;
82
+ return { box: { x: cx - width / 2, y: cy - height / 2, width, height }, rotation: angle };
83
+ };
84
+ const insets = (s) => ({ left: px(s.paddingLeft), top: px(s.paddingTop), right: px(s.paddingRight), bottom: px(s.paddingBottom) });
85
+ const ALIGN = { start: "left", left: "left", center: "center", right: "right", end: "right", justify: "justify" };
86
+ const within = (el, stop, test) => {
87
+ for (let at = el; at && at !== stop.parentElement; at = at.parentElement) if (test(getComputedStyle(at))) return true;
88
+ return false;
89
+ };
90
+ const family = (value) => (value || "").split(",")[0].replace(/["']/g, "").trim() || null;
91
+ const textRun = (node, block, link) => {
92
+ const parent = node.parentElement;
93
+ const s = getComputedStyle(parent);
94
+ if (s.visibility !== "visible" || Number(s.opacity) === 0) return null;
95
+ let value = node.textContent.replace(/[ \t\n\r\f]+/g, " ");
96
+ if (!value) return null;
97
+ if (s.textTransform === "uppercase") value = value.toUpperCase();
98
+ else if (s.textTransform === "lowercase") value = value.toLowerCase();
99
+ const script = within(parent, block, (t) => t.verticalAlign === "super") ? "super"
100
+ : within(parent, block, (t) => t.verticalAlign === "sub") ? "sub" : null;
101
+ let highlight = null;
102
+ for (let at = parent; at && at !== block && !highlight; at = at.parentElement)
103
+ highlight = fade(fillOf(getComputedStyle(at)), opacityOf(at, block));
104
+ const fill = s.webkitTextFillColor && s.webkitTextFillColor !== s.color ? s.webkitTextFillColor : s.color;
105
+ return {
106
+ text: value,
107
+ spacing: s.letterSpacing === "normal" ? 0 : px(s.letterSpacing),
108
+ highlight,
109
+ bold: Number(s.fontWeight) >= 600,
110
+ italic: s.fontStyle !== "normal",
111
+ underline: within(parent, block, (t) => t.textDecorationLine.includes("underline")),
112
+ strike: within(parent, block, (t) => t.textDecorationLine.includes("line-through")),
113
+ script, colour: fade(hex(fill, true), opacityOf(parent, block)),
114
+ size: (px(s.fontSize) * turn(parent).scale) || null, font: family(s.fontFamily),
115
+ weight: Number(s.fontWeight) || null, link,
116
+ };
117
+ };
118
+ const runsOf = (node, block, out, link) => {
119
+ for (const child of node.childNodes) {
120
+ if (child.nodeType === 3) {
121
+ const run = textRun(child, block, link);
122
+ if (run) out.push(run);
123
+ } else if (child.nodeType === 1) {
124
+ const tag = child.tagName;
125
+ if (tag === "BR") out.push({ text: "\n" });
126
+ else if (tag === "UL" || tag === "OL" || tag === "TABLE" || tag === "svg") continue;
127
+ else {
128
+ const style = getComputedStyle(child);
129
+ if (style.display !== "none" && Number(style.opacity) !== 0) {
130
+ const before = px(style.marginLeft) + px(style.borderLeftWidth) + px(style.paddingLeft);
131
+ const after = px(style.paddingRight) + px(style.borderRightWidth) + px(style.marginRight);
132
+ if (before > 1) out.push(gap(style, before));
133
+ runsOf(child, block, out, tag === "A" ? child.href : link);
134
+ if (after > 1) out.push(gap(style, after));
135
+ }
136
+ }
137
+ }
138
+ }
139
+ return out;
140
+ };
141
+ const measurer = document.createElement("canvas").getContext("2d");
142
+ const gap = (style, width) => {
143
+ measurer.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
144
+ const space = measurer.measureText("\u00a0").width;
145
+ return { text: "\u00a0", spacing: width - space, size: px(style.fontSize) || null, font: family(style.fontFamily), weight: Number(style.fontWeight) || null };
146
+ };
147
+ const tidy = (runs) => {
148
+ // Spaces collapse across runs as the browser collapses them across elements.
149
+ runs.forEach((run, at) => {
150
+ const previous = runs[at - 1];
151
+ if (previous && previous.text.endsWith(" ") && run.text.startsWith(" ")) run.text = run.text.slice(1);
152
+ if (previous && previous.text === "\n") run.text = run.text.replace(/^ +/, "");
153
+ if (runs[at + 1] && runs[at + 1].text === "\n") run.text = run.text.replace(/ +$/, "");
154
+ });
155
+ const kept = runs.filter((run) => run.text !== "");
156
+ if (kept.length && kept[0].text !== "\n") kept[0].text = kept[0].text.replace(/^ +/, "");
157
+ const last = kept[kept.length - 1];
158
+ if (last && last.text !== "\n") last.text = last.text.replace(/ +$/, "");
159
+ return kept.filter((run) => run.text !== "");
160
+ };
161
+ const paragraph = (el, extra) => {
162
+ const s = getComputedStyle(el);
163
+ return Object.assign({
164
+ runs: tidy(runsOf(el, el, [], el.closest("a")?.href || null)),
165
+ align: ALIGN[s.textAlign] || "left",
166
+ line_height: s.lineHeight === "normal" ? null : px(s.lineHeight) || null,
167
+ space_before: 0,
168
+ }, extra || {});
169
+ };
170
+ const listed = (list, level, out) => {
171
+ const ordered = list.tagName === "OL";
172
+ let first = out.length === 0;
173
+ for (const item of list.children) {
174
+ if (item.tagName !== "LI" || !shown(item)) continue;
175
+ const style = getComputedStyle(item).listStyleType;
176
+ out.push(paragraph(item, {
177
+ level,
178
+ bullet: style === "none" ? null : ordered || style === "decimal" ? "number" : "disc",
179
+ space_before: first ? 0 : px(getComputedStyle(item).marginTop),
180
+ }));
181
+ first = false;
182
+ for (const inner of item.children) if (inner.tagName === "UL" || inner.tagName === "OL") listed(inner, level + 1, out);
183
+ }
184
+ return out;
185
+ };
186
+ const fillOf = (s) => (s.backgroundImage === "none" ? hex(s.backgroundColor) : null);
187
+ const text = (el, origin, paragraphs) => {
188
+ const s = getComputedStyle(el);
189
+ const line = s.lineHeight === "normal" ? px(s.fontSize) * 1.2 : px(s.lineHeight);
190
+ const inner = el.getBoundingClientRect().height - px(s.paddingTop) - px(s.paddingBottom);
191
+ const drawn = outline(el, s, origin);
192
+ const { box, rotation } = placed(el, origin);
193
+ return {
194
+ kind: "text", box, rotation, opacity: opacityOf(el), paragraphs, insets: insets(s), fill: fillOf(s),
195
+ radius: px(s.borderTopLeftRadius), line: drawn.line, line_width: drawn.line_width, edges: drawn.edges,
196
+ wrap: paragraphs.length > 1 || !(line > 0) || inner > line * 1.5,
197
+ };
198
+ };
199
+ const border = (s, side) => {
200
+ const width = px(s["border" + side + "Width"]);
201
+ const colour = hex(s["border" + side + "Color"]);
202
+ return width > 0 && colour && s["border" + side + "Style"] !== "none" ? { width, colour } : null;
203
+ };
204
+ // A border on every side alike is an outline. A border on only some sides, such as a rule
205
+ // above a card, is drawn as a strip on each of those sides, never as a box around it.
206
+ const outline = (el, s, origin) => {
207
+ const sides = ["Top", "Right", "Bottom", "Left"].map((side) => border(s, side));
208
+ const [top] = sides;
209
+ if (top && sides.every((b) => b && b.width === top.width && b.colour === top.colour))
210
+ return { line: top.colour, line_width: top.width, edges: [] };
211
+ const { box, rotation } = placed(el, origin);
212
+ const radians = rotation * Math.PI / 180;
213
+ const cx = box.x + box.width / 2;
214
+ const cy = box.y + box.height / 2;
215
+ const edges = [];
216
+ sides.forEach((b, at) => {
217
+ if (!b) return;
218
+ const strip = [
219
+ { x: box.x, y: box.y, width: box.width, height: b.width },
220
+ { x: box.x + box.width - b.width, y: box.y, width: b.width, height: box.height },
221
+ { x: box.x, y: box.y + box.height - b.width, width: box.width, height: b.width },
222
+ { x: box.x, y: box.y, width: b.width, height: box.height },
223
+ ][at];
224
+ const dx = strip.x + strip.width / 2 - cx;
225
+ const dy = strip.y + strip.height / 2 - cy;
226
+ const sx = cx + dx * Math.cos(radians) - dy * Math.sin(radians);
227
+ const sy = cy + dx * Math.sin(radians) + dy * Math.cos(radians);
228
+ edges.push({ kind: "shape", box: { ...strip, x: sx - strip.width / 2, y: sy - strip.height / 2 }, rotation,
229
+ opacity: opacityOf(el), shape: "rect", fill: b.colour, line: null, line_width: 0, radius: 0 });
230
+ });
231
+ return { line: null, line_width: 0, edges };
232
+ };
233
+ const MOST_COLUMNS = 75;
234
+ const BLOCKS = new Set(["P", "H1", "H2", "H3", "H4", "H5", "H6", "BLOCKQUOTE", "UL", "OL", "FIGCAPTION", "CITE", "DIV"]);
235
+ const cellFill = (cell, table) => {
236
+ for (let at = cell; at && at !== table.parentElement; at = at.parentElement) {
237
+ const fill = fillOf(getComputedStyle(at));
238
+ if (fill) return fill;
239
+ }
240
+ return null;
241
+ };
242
+ const cellParagraphs = (cell) => {
243
+ const blocks = [...cell.children].filter((child) => BLOCKS.has(child.tagName));
244
+ if (!blocks.length) return [paragraph(cell)];
245
+ return blocks.flatMap((block) => block.tagName === "UL" || block.tagName === "OL" ? listed(block, 0, []) : [paragraph(block)]);
246
+ };
247
+ const table = (el, origin, items) => {
248
+ const caption = el.querySelector(":scope > caption");
249
+ if (caption && shown(caption)) items.push(text(caption, origin, [paragraph(caption)]));
250
+ const rows = [...el.rows].filter(shown);
251
+ if (!rows.length) return;
252
+ const grid = [];
253
+ const cells = [];
254
+ // A span never reaches past the widest row's own cells, or PowerPoint's column limit: a
255
+ // colspan of 1000 is a thousand empty columns the browser draws at no width.
256
+ const widest = Math.min(MOST_COLUMNS, Math.max(1, ...rows.map((row) => row.cells.length)));
257
+ rows.forEach((row, r) => {
258
+ grid[r] = grid[r] || [];
259
+ let c = 0;
260
+ for (const cell of row.cells) {
261
+ while (grid[r][c]) c += 1;
262
+ if (c >= MOST_COLUMNS) break;
263
+ const rowspan = Math.max(1, Math.min(cell.rowSpan || 1, rows.length - r));
264
+ const colspan = Math.max(1, Math.min(cell.colSpan || 1, widest - c, MOST_COLUMNS - c));
265
+ for (let i = 0; i < rowspan; i += 1) {
266
+ grid[r + i] = grid[r + i] || [];
267
+ for (let j = 0; j < colspan; j += 1) grid[r + i][c + j] = true;
268
+ }
269
+ const s = getComputedStyle(cell);
270
+ const valign = s.verticalAlign;
271
+ cells.push({
272
+ el: cell,
273
+ data: {
274
+ row: r, column: c, rowspan, colspan,
275
+ paragraphs: cellParagraphs(cell),
276
+ fill: cellFill(cell, el),
277
+ insets: insets(s),
278
+ vertical: valign === "top" ? "top" : valign === "bottom" ? "bottom" : "middle",
279
+ left: border(s, "Left"), right: border(s, "Right"), top: border(s, "Top"), bottom: border(s, "Bottom"),
280
+ },
281
+ });
282
+ c += colspan;
283
+ }
284
+ });
285
+ const count = Math.max(...grid.map((row) => row.length));
286
+ const first = rows[0].getBoundingClientRect();
287
+ const last = rows[rows.length - 1].getBoundingClientRect();
288
+ const whole = el.getBoundingClientRect();
289
+ const columns = [];
290
+ for (let c = 0; c < count; c += 1) {
291
+ const single = cells.find((cell) => cell.data.column === c && cell.data.colspan === 1);
292
+ columns.push(single ? single.el.getBoundingClientRect().width : whole.width / count);
293
+ }
294
+ items.push({
295
+ kind: "table",
296
+ opacity: opacityOf(el),
297
+ box: { x: whole.left - origin.left, y: first.top - origin.top, width: whole.width, height: last.bottom - first.top },
298
+ columns,
299
+ rows: rows.map((row) => row.getBoundingClientRect().height),
300
+ cells: cells.map((cell) => cell.data),
301
+ });
302
+ };
303
+ const SERIES = series;
304
+ const chart = (el, origin, items, section) => {
305
+ const caption = el.querySelector(":scope > figcaption");
306
+ if (caption && shown(caption)) items.push(text(caption, origin, [paragraph(caption)]));
307
+ const data = el.querySelector(":scope > table[data-chart-data]");
308
+ if (!data) return;
309
+ const head = data.tHead && data.tHead.rows[0] ? [...data.tHead.rows[0].cells] : [];
310
+ const body = data.tBodies[0] ? [...data.tBodies[0].rows] : [];
311
+ const clean = (cell) => (cell.textContent || "").replace(/\s+/g, " ").trim();
312
+ const number = (cell) => { const value = clean(cell); return value === "" ? null : Number(value); };
313
+ const series = head.slice(1).map((cell, at) => ({ name: clean(cell), values: body.map((row) => row.cells[at + 1] ? number(row.cells[at + 1]) : null) }));
314
+ // The page draws no chart without rows, so neither does the export.
315
+ if (!series.length || !body.length) return;
316
+ const drawing = el.querySelector(":scope > [data-chart-drawing]");
317
+ let box = place(drawing && shown(drawing) ? drawing : el, origin);
318
+ if (!(drawing && shown(drawing)) && caption && shown(caption)) {
319
+ const below = caption.getBoundingClientRect().bottom - origin.top;
320
+ box = { x: box.x, y: below, width: box.width, height: Math.max(1, box.y + box.height - below) };
321
+ }
322
+ const tokens = getComputedStyle(el);
323
+ const fromSection = getComputedStyle(section);
324
+ const colours = SERIES.map((name) => hex(tokens.getPropertyValue(name).trim() || fromSection.getPropertyValue(name).trim())).filter(Boolean);
325
+ const s = getComputedStyle(el);
326
+ const attr = (name) => el.getAttribute(name);
327
+ const bound = (name) => { const value = attr(name); return value === null || value === "" ? null : Number(value); };
328
+ let [low, high] = [bound("data-axis-min"), bound("data-axis-max")];
329
+ if (low !== null && high !== null && !(low < high)) [low, high] = [null, null];
330
+ items.push({
331
+ kind: "chart",
332
+ opacity: opacityOf(el),
333
+ box,
334
+ chart: attr("data-chart"),
335
+ categories: body.map((row) => row.cells[0] ? clean(row.cells[0]) : ""),
336
+ series,
337
+ legend: attr("data-legend") || "bottom",
338
+ labels: attr("data-labels") === "on",
339
+ axis_min: low,
340
+ axis_max: high,
341
+ format: attr("data-format"),
342
+ colours,
343
+ text_colour: hex(s.color),
344
+ font: family(s.fontFamily),
345
+ size: px(s.fontSize) || null,
346
+ caption: caption ? clean(caption) : null,
347
+ });
348
+ };
349
+ const TEXT = new Set(["P", "H1", "H2", "H3", "H4", "H5", "H6", "FIGCAPTION"]);
350
+ // Free HTML can put a paragraph in any element. Keep inline marks together, but
351
+ // retain separate measured boxes for layout children, media and native tables/charts.
352
+ const inlineContent = (el) => {
353
+ if (/flex|grid/.test(getComputedStyle(el).display)) return false;
354
+ return [...el.children].every((child) => {
355
+ if (child.tagName === "BR") return true;
356
+ const s = getComputedStyle(child);
357
+ if (s.display === "none" || Number(s.opacity) === 0) return true;
358
+ return s.display === "inline" && !["absolute", "fixed"].includes(s.position)
359
+ && !["IMG", "SVG", "TABLE", "FIGURE"].includes(child.tagName.toUpperCase())
360
+ && s.backgroundImage === "none" && !decorated(child)
361
+ && !["Top", "Right", "Bottom", "Left"].some((side) => border(s, side))
362
+ && inlineContent(child);
363
+ });
364
+ };
365
+ const contents = (el, origin, items, section) => {
366
+ for (const child of el.childNodes) {
367
+ if (child.nodeType === 1) walk(child, origin, items, section);
368
+ else if (child.nodeType === 3 && child.textContent.trim()) {
369
+ // Mixed block/inline content has no element box for its own text. A Range
370
+ // measures just that text, without copying text already handled by children.
371
+ const range = document.createRange();
372
+ range.selectNodeContents(child);
373
+ const box = place(range, origin);
374
+ if (!box.width || !box.height) continue;
375
+ const run = textRun(child, el, el.closest("a")?.href || null);
376
+ if (!run) continue;
377
+ const measured = text(el, origin, [paragraph(el, { runs: tidy([run]), align: "left" })]);
378
+ items.push({ ...measured, box, rotation: 0, insets: { left: 0, top: 0, right: 0, bottom: 0 },
379
+ fill: null, radius: 0, line: null, line_width: 0, edges: [], wrap: range.getClientRects().length > 1 });
380
+ }
381
+ }
382
+ };
383
+ const walk = (el, origin, items, section) => {
384
+ const s = getComputedStyle(el);
385
+ if (s.display === "none" || Number(s.opacity) === 0) return;
386
+ // An element with no box of its own, such as a wrapper whose children are all positioned,
387
+ // or one hidden while a child is shown, paints nothing itself but its children still show.
388
+ if (!shown(el)) {
389
+ if (s.overflow === "visible" || s.visibility === "hidden") contents(el, origin, items, section);
390
+ return;
391
+ }
392
+ const tag = el.tagName;
393
+ if (tag === "FIGURE" && el.hasAttribute("data-chart")) return chart(el, origin, items, section);
394
+ if (tag === "TABLE") return table(el, origin, items);
395
+ if (tag === "IMG" || tag.toLowerCase() === "svg") {
396
+ mark(el, "whole", origin);
397
+ items.push({ kind: "picture", id: el.getAttribute(MARK) });
398
+ return;
399
+ }
400
+ if (el.hasAttribute("data-shape")) {
401
+ if (s.backgroundImage !== "none" || decorated(el)) {
402
+ mark(el, "whole", origin);
403
+ items.push({ kind: "picture", id: el.getAttribute(MARK) });
404
+ return;
405
+ }
406
+ const shape = el.getAttribute("data-shape");
407
+ items.push({
408
+ kind: "shape", ...placed(el, origin), opacity: opacityOf(el), shape: shape === "ellipse" || shape === "line" ? shape : "rect",
409
+ fill: hex(s.backgroundColor), line: border(s, "Top") ? border(s, "Top").colour : null,
410
+ line_width: border(s, "Top") ? border(s, "Top").width : 0, radius: px(s.borderTopLeftRadius),
411
+ });
412
+ return;
413
+ }
414
+ const pictured = s.backgroundImage !== "none" || decorated(el);
415
+ const block = (paragraphs) => {
416
+ if (pictured) {
417
+ mark(el, "background", origin);
418
+ items.push({ kind: "picture", id: el.getAttribute(MARK) });
419
+ }
420
+ const item = text(el, origin, paragraphs);
421
+ items.push(pictured ? { ...item, fill: null } : item);
422
+ };
423
+ if (TEXT.has(tag)) return void block([paragraph(el)]);
424
+ if (tag === "UL" || tag === "OL") return void block(listed(el, 0, []));
425
+ if (tag === "BLOCKQUOTE") {
426
+ const parts = [...el.children].filter((child) => (child.tagName === "P" || child.tagName === "CITE") && shown(child));
427
+ // Text written straight into the quote, ahead of or around a <cite>, is a paragraph too.
428
+ const lead = [...el.childNodes].filter((n) => n.nodeType === 3 && n.textContent.trim()).map((n) => textRun(n, el, null)).filter(Boolean);
429
+ const lines = parts.map((part, at) => paragraph(part, { space_before: at || lead.length ? px(getComputedStyle(part).marginTop) : 0 }));
430
+ return void block(lead.length ? [paragraph(el, { runs: tidy(lead) }), ...lines] : lines.length ? lines : [paragraph(el)]);
431
+ }
432
+ if (inlineContent(el) && el.textContent.trim()) return void block([paragraph(el)]);
433
+ const filled = s.backgroundImage === "none" ? hex(s.backgroundColor) : null;
434
+ if (s.backgroundImage !== "none" || decorated(el)) {
435
+ mark(el, "background", origin);
436
+ items.push({ kind: "picture", id: el.getAttribute(MARK) });
437
+ } else {
438
+ const drawn = outline(el, s, origin);
439
+ if (filled || drawn.line) items.push({ kind: "shape", ...placed(el, origin), opacity: opacityOf(el), shape: "rect", fill: filled, line: drawn.line, line_width: drawn.line_width, radius: px(s.borderTopLeftRadius) });
440
+ items.push(...drawn.edges);
441
+ }
442
+ contents(el, origin, items, section);
443
+ };
444
+ const fadedRuns = (paragraphs, opacity) => paragraphs.map((p) => ({ ...p, runs: p.runs.map((run) =>
445
+ ({ ...run, colour: fade(run.colour, opacity), highlight: fade(run.highlight, opacity) })) }));
446
+ const fadedSide = (side, opacity) => side && { ...side, colour: fade(side.colour, opacity) };
447
+ const faded = ({ opacity = 1, ...item }) => {
448
+ if (item.kind === "picture" || opacity >= 0.999) return item;
449
+ if (item.kind === "text") return { ...item, fill: fade(item.fill, opacity), line: fade(item.line, opacity), paragraphs: fadedRuns(item.paragraphs, opacity) };
450
+ if (item.kind === "shape") return { ...item, fill: fade(item.fill, opacity), line: fade(item.line, opacity) };
451
+ if (item.kind === "table") return { ...item, cells: item.cells.map((cell) => ({ ...cell, fill: fade(cell.fill, opacity), paragraphs: fadedRuns(cell.paragraphs, opacity),
452
+ left: fadedSide(cell.left, opacity), right: fadedSide(cell.right, opacity), top: fadedSide(cell.top, opacity), bottom: fadedSide(cell.bottom, opacity) })) };
453
+ if (item.kind === "chart") return { ...item, colours: item.colours.map((c) => fade(c, opacity)), text_colour: fade(item.text_colour, opacity) };
454
+ return item;
455
+ };
456
+ // A match nested inside another match is content of that slide, not a slide of its own.
457
+ const found = [...document.querySelectorAll(selector)];
458
+ const sections = found.filter((el) => !found.some((other) => other !== el && other.contains(el)));
459
+ const slides = sections.map((section) => {
460
+ const origin = section.getBoundingClientRect();
461
+ const s = getComputedStyle(section);
462
+ const items = [];
463
+ let background = null;
464
+ let picture = null;
465
+ if (s.backgroundImage !== "none" || decorated(section)) picture = mark(section, "background", origin);
466
+ else background = hex(s.backgroundColor);
467
+ contents(section, origin, items, section);
468
+ // A side's strip goes over its box, so the box's own fill never hides it.
469
+ const drawn = items.flatMap(({ edges, ...item }) => [item, ...(edges || [])]).map(faded);
470
+ return { background, picture, items: drawn, size: { width: origin.width, height: origin.height } };
471
+ });
472
+ // The fonts the stylesheets declare, each with the absolute addresses of its sources, so the
473
+ // export can carry the files a run was drawn with.
474
+ const WEIGHTS = { normal: 400, bold: 700 };
475
+ const weightOf = (word) => WEIGHTS[word] || Number(word) || 400;
476
+ const fonts = [];
477
+ for (const sheet of document.styleSheets) {
478
+ let rules;
479
+ try { rules = sheet.cssRules; } catch { continue; }
480
+ for (const rule of rules) {
481
+ if (!(rule instanceof CSSFontFaceRule)) continue;
482
+ const sources = [...rule.style.getPropertyValue("src").matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)].map((m) => m[1]);
483
+ const named = family(rule.style.getPropertyValue("font-family"));
484
+ if (!sources.length || !named) continue;
485
+ const declared = (rule.style.getPropertyValue("font-weight") || "normal").trim().split(/\s+/);
486
+ fonts.push({
487
+ family: named,
488
+ weight: weightOf(declared[0]),
489
+ weight_max: weightOf(declared[declared.length - 1]),
490
+ italic: /italic|oblique/.test(rule.style.getPropertyValue("font-style")),
491
+ sources: sources.map((url) => (url.startsWith("data:") ? url : new URL(url, sheet.href || document.baseURI).href)),
492
+ });
493
+ }
494
+ }
495
+ probe.remove();
496
+ return JSON.stringify({ slides, pictures, fonts });
497
+ }
@@ -0,0 +1,75 @@
1
+ """The `html-to-native-pptx` command: `html-to-native-pptx deck.html -o deck.pptx`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from html_to_native_pptx import __version__
11
+ from html_to_native_pptx.convert import convert
12
+ from html_to_native_pptx.errors import ConversionError
13
+
14
+
15
+ def parser() -> argparse.ArgumentParser:
16
+ """The command's arguments."""
17
+ found = argparse.ArgumentParser(
18
+ prog="html-to-native-pptx", description="High-fidelity HTML to native, editable PowerPoint."
19
+ )
20
+ found.add_argument("html", type=Path, help="the HTML file holding the slides")
21
+ found.add_argument(
22
+ "-o", "--out", type=Path, help="the .pptx to write (default: beside the input)"
23
+ )
24
+ found.add_argument(
25
+ "-s",
26
+ "--slide-selector",
27
+ default="section",
28
+ help="CSS selector of one slide (default: section)",
29
+ )
30
+ found.add_argument(
31
+ "--width", type=int, default=1280, help="slide width in CSS pixels (default: 1280)"
32
+ )
33
+ found.add_argument(
34
+ "--height", type=int, default=720, help="slide height in CSS pixels (default: 720)"
35
+ )
36
+ found.add_argument(
37
+ "--no-embed-fonts", action="store_true", help="name fonts only; do not embed them"
38
+ )
39
+ found.add_argument(
40
+ "--no-freeze-animations", action="store_true", help="measure animations as they stand"
41
+ )
42
+ found.add_argument("--chromium", help="path of a Chromium binary to drive")
43
+ found.add_argument(
44
+ "--timeout", type=int, default=60, help="seconds to wait on the page (default: 60)"
45
+ )
46
+ found.add_argument("--version", action="version", version=f"html-to-native-pptx {__version__}")
47
+ return found
48
+
49
+
50
+ def main(argv: list[str] | None = None) -> int:
51
+ """Run the command; returns the exit status."""
52
+ args = parser().parse_args(argv)
53
+ logging.basicConfig(level=logging.WARNING, format="html-to-native-pptx: %(message)s")
54
+ out = args.out or args.html.with_suffix(".pptx")
55
+ try:
56
+ convert(
57
+ args.html,
58
+ out,
59
+ slide_selector=args.slide_selector,
60
+ width=args.width,
61
+ height=args.height,
62
+ embed_fonts=not args.no_embed_fonts,
63
+ freeze_animations=not args.no_freeze_animations,
64
+ timeout_ms=args.timeout * 1000,
65
+ executable_path=args.chromium,
66
+ )
67
+ except ConversionError as error:
68
+ print(f"html-to-native-pptx: {error}", file=sys.stderr)
69
+ return 1
70
+ print(out)
71
+ return 0
72
+
73
+
74
+ if __name__ == "__main__":
75
+ sys.exit(main())