dom-to-pptx 1.0.9 → 1.1.1

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,163 @@
1
+ // src/font-embedder.js
2
+ import opentype from 'opentype.js';
3
+ import { fontToEot } from './font-utils.js';
4
+
5
+ const START_RID = 201314;
6
+
7
+ export class PPTXEmbedFonts {
8
+ constructor() {
9
+ this.zip = null;
10
+ this.rId = START_RID;
11
+ this.fonts = []; // { name, data, rid }
12
+ }
13
+
14
+ async loadZip(zip) {
15
+ this.zip = zip;
16
+ }
17
+
18
+ /**
19
+ * Reads the font name from the buffer using opentype.js
20
+ */
21
+ getFontInfo(fontBuffer) {
22
+ try {
23
+ const font = opentype.parse(fontBuffer);
24
+ const names = font.names;
25
+ // Prefer English name, fallback to others
26
+ const fontFamily = names.fontFamily.en || Object.values(names.fontFamily)[0];
27
+ return { name: fontFamily };
28
+ } catch (e) {
29
+ console.warn('Could not parse font info', e);
30
+ return { name: 'Unknown' };
31
+ }
32
+ }
33
+
34
+ async addFont(fontFace, fontBuffer, type) {
35
+ // Convert to EOT/fntdata for PPTX compatibility
36
+ const eotData = await fontToEot(type, fontBuffer);
37
+ const rid = this.rId++;
38
+ this.fonts.push({ name: fontFace, data: eotData, rid });
39
+ }
40
+
41
+ async updateFiles() {
42
+ await this.updateContentTypesXML();
43
+ await this.updatePresentationXML();
44
+ await this.updateRelsPresentationXML();
45
+ this.updateFontFiles();
46
+ }
47
+
48
+ async generateBlob() {
49
+ if (!this.zip) throw new Error('Zip not loaded');
50
+ return this.zip.generateAsync({
51
+ type: 'blob',
52
+ compression: 'DEFLATE',
53
+ compressionOptions: { level: 6 },
54
+ });
55
+ }
56
+
57
+ // --- XML Manipulation Methods ---
58
+
59
+ async updateContentTypesXML() {
60
+ const file = this.zip.file('[Content_Types].xml');
61
+ if (!file) throw new Error('[Content_Types].xml not found');
62
+
63
+ const xmlStr = await file.async('string');
64
+ const parser = new DOMParser();
65
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
66
+
67
+ const types = doc.getElementsByTagName('Types')[0];
68
+ const defaults = Array.from(doc.getElementsByTagName('Default'));
69
+
70
+ const hasFntData = defaults.some((el) => el.getAttribute('Extension') === 'fntdata');
71
+
72
+ if (!hasFntData) {
73
+ const el = doc.createElement('Default');
74
+ el.setAttribute('Extension', 'fntdata');
75
+ el.setAttribute('ContentType', 'application/x-fontdata');
76
+ types.insertBefore(el, types.firstChild);
77
+ }
78
+
79
+ this.zip.file('[Content_Types].xml', new XMLSerializer().serializeToString(doc));
80
+ }
81
+
82
+ async updatePresentationXML() {
83
+ const file = this.zip.file('ppt/presentation.xml');
84
+ if (!file) throw new Error('ppt/presentation.xml not found');
85
+
86
+ const xmlStr = await file.async('string');
87
+ const parser = new DOMParser();
88
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
89
+ const presentation = doc.getElementsByTagName('p:presentation')[0];
90
+
91
+ // Enable embedding flags
92
+ presentation.setAttribute('saveSubsetFonts', 'true');
93
+ presentation.setAttribute('embedTrueTypeFonts', 'true');
94
+
95
+ // Find or create embeddedFontLst
96
+ let embeddedFontLst = presentation.getElementsByTagName('p:embeddedFontLst')[0];
97
+
98
+ if (!embeddedFontLst) {
99
+ embeddedFontLst = doc.createElement('p:embeddedFontLst');
100
+
101
+ // Insert before defaultTextStyle or at end
102
+ const defaultTextStyle = presentation.getElementsByTagName('p:defaultTextStyle')[0];
103
+ if (defaultTextStyle) {
104
+ presentation.insertBefore(embeddedFontLst, defaultTextStyle);
105
+ } else {
106
+ presentation.appendChild(embeddedFontLst);
107
+ }
108
+ }
109
+
110
+ // Add font references
111
+ this.fonts.forEach((font) => {
112
+ // Check if already exists
113
+ const existing = Array.from(embeddedFontLst.getElementsByTagName('p:font')).find(
114
+ (node) => node.getAttribute('typeface') === font.name
115
+ );
116
+
117
+ if (!existing) {
118
+ const embedFont = doc.createElement('p:embeddedFont');
119
+
120
+ const fontNode = doc.createElement('p:font');
121
+ fontNode.setAttribute('typeface', font.name);
122
+ embedFont.appendChild(fontNode);
123
+
124
+ const regular = doc.createElement('p:regular');
125
+ regular.setAttribute('r:id', `rId${font.rid}`);
126
+ embedFont.appendChild(regular);
127
+
128
+ embeddedFontLst.appendChild(embedFont);
129
+ }
130
+ });
131
+
132
+ this.zip.file('ppt/presentation.xml', new XMLSerializer().serializeToString(doc));
133
+ }
134
+
135
+ async updateRelsPresentationXML() {
136
+ const file = this.zip.file('ppt/_rels/presentation.xml.rels');
137
+ if (!file) throw new Error('presentation.xml.rels not found');
138
+
139
+ const xmlStr = await file.async('string');
140
+ const parser = new DOMParser();
141
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
142
+ const relationships = doc.getElementsByTagName('Relationships')[0];
143
+
144
+ this.fonts.forEach((font) => {
145
+ const rel = doc.createElement('Relationship');
146
+ rel.setAttribute('Id', `rId${font.rid}`);
147
+ rel.setAttribute('Target', `fonts/${font.rid}.fntdata`);
148
+ rel.setAttribute(
149
+ 'Type',
150
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font'
151
+ );
152
+ relationships.appendChild(rel);
153
+ });
154
+
155
+ this.zip.file('ppt/_rels/presentation.xml.rels', new XMLSerializer().serializeToString(doc));
156
+ }
157
+
158
+ updateFontFiles() {
159
+ this.fonts.forEach((font) => {
160
+ this.zip.file(`ppt/fonts/${font.rid}.fntdata`, font.data);
161
+ });
162
+ }
163
+ }
@@ -0,0 +1,32 @@
1
+ // src/font-utils.js
2
+ import { Font } from 'fonteditor-core';
3
+ import pako from 'pako';
4
+
5
+ /**
6
+ * Converts various font formats to EOT (Embedded OpenType),
7
+ * which is highly compatible with PowerPoint embedding.
8
+ * @param {string} type - 'ttf', 'woff', or 'otf'
9
+ * @param {ArrayBuffer} fontBuffer - The raw font data
10
+ */
11
+ export async function fontToEot(type, fontBuffer) {
12
+ const options = {
13
+ type,
14
+ hinting: true,
15
+ // inflate is required for WOFF decoding
16
+ inflate: type === 'woff' ? pako.inflate : undefined,
17
+ };
18
+
19
+ const font = Font.create(fontBuffer, options);
20
+
21
+ const eotBuffer = font.write({
22
+ type: 'eot',
23
+ toBuffer: true,
24
+ });
25
+
26
+ if (eotBuffer instanceof ArrayBuffer) {
27
+ return eotBuffer;
28
+ }
29
+
30
+ // Ensure we return an ArrayBuffer
31
+ return eotBuffer.buffer.slice(eotBuffer.byteOffset, eotBuffer.byteOffset + eotBuffer.byteLength);
32
+ }
@@ -1,32 +1,36 @@
1
1
  // src/image-processor.js
2
2
 
3
- export async function getProcessedImage(src, targetW, targetH, radius) {
3
+ export async function getProcessedImage(
4
+ src,
5
+ targetW,
6
+ targetH,
7
+ radius,
8
+ objectFit = 'fill',
9
+ objectPosition = '50% 50%'
10
+ ) {
4
11
  return new Promise((resolve) => {
5
12
  const img = new Image();
6
- img.crossOrigin = 'Anonymous'; // Critical for canvas manipulation
13
+ img.crossOrigin = 'Anonymous';
7
14
 
8
15
  img.onload = () => {
9
16
  const canvas = document.createElement('canvas');
10
- // Double resolution for better quality
11
- const scale = 2;
17
+ const scale = 2; // Double resolution
12
18
  canvas.width = targetW * scale;
13
19
  canvas.height = targetH * scale;
14
20
  const ctx = canvas.getContext('2d');
15
21
  ctx.scale(scale, scale);
16
22
 
17
- // Normalize radius input to an object { tl, tr, br, bl }
23
+ // Normalize radius
18
24
  let r = { tl: 0, tr: 0, br: 0, bl: 0 };
19
25
  if (typeof radius === 'number') {
20
26
  r = { tl: radius, tr: radius, br: radius, bl: radius };
21
27
  } else if (typeof radius === 'object' && radius !== null) {
22
- r = { ...r, ...radius }; // Merge with defaults
28
+ r = { ...r, ...radius };
23
29
  }
24
30
 
25
- // 1. Draw the Mask (Custom Shape with specific corners)
31
+ // 1. Draw Mask
26
32
  ctx.beginPath();
27
-
28
- // Border Radius Clamping Logic (CSS Spec)
29
- // Prevents corners from overlapping if radii are too large for the container
33
+ // ... (radius clamping logic remains the same) ...
30
34
  const factor = Math.min(
31
35
  targetW / (r.tl + r.tr) || Infinity,
32
36
  targetH / (r.tr + r.br) || Infinity,
@@ -41,7 +45,6 @@ export async function getProcessedImage(src, targetW, targetH, radius) {
41
45
  r.bl *= factor;
42
46
  }
43
47
 
44
- // Draw path: Top-Left -> Top-Right -> Bottom-Right -> Bottom-Left
45
48
  ctx.moveTo(r.tl, 0);
46
49
  ctx.lineTo(targetW - r.tr, 0);
47
50
  ctx.arcTo(targetW, 0, targetW, r.tr, r.tr);
@@ -51,22 +54,58 @@ export async function getProcessedImage(src, targetW, targetH, radius) {
51
54
  ctx.arcTo(0, targetH, 0, targetH - r.bl, r.bl);
52
55
  ctx.lineTo(0, r.tl);
53
56
  ctx.arcTo(0, 0, r.tl, 0, r.tl);
54
-
55
57
  ctx.closePath();
56
58
  ctx.fillStyle = '#000';
57
59
  ctx.fill();
58
60
 
59
- // 2. Composite Source-In (Crops the next image draw to the mask)
61
+ // 2. Composite Source-In
60
62
  ctx.globalCompositeOperation = 'source-in';
61
63
 
62
- // 3. Draw Image (Object Cover Logic)
64
+ // 3. Draw Image with Object Fit logic
63
65
  const wRatio = targetW / img.width;
64
66
  const hRatio = targetH / img.height;
65
- const maxRatio = Math.max(wRatio, hRatio);
66
- const renderW = img.width * maxRatio;
67
- const renderH = img.height * maxRatio;
68
- const renderX = (targetW - renderW) / 2;
69
- const renderY = (targetH - renderH) / 2;
67
+ let renderW, renderH;
68
+
69
+ if (objectFit === 'contain') {
70
+ const fitScale = Math.min(wRatio, hRatio);
71
+ renderW = img.width * fitScale;
72
+ renderH = img.height * fitScale;
73
+ } else if (objectFit === 'cover') {
74
+ const coverScale = Math.max(wRatio, hRatio);
75
+ renderW = img.width * coverScale;
76
+ renderH = img.height * coverScale;
77
+ } else if (objectFit === 'none') {
78
+ renderW = img.width;
79
+ renderH = img.height;
80
+ } else if (objectFit === 'scale-down') {
81
+ const scaleDown = Math.min(1, Math.min(wRatio, hRatio));
82
+ renderW = img.width * scaleDown;
83
+ renderH = img.height * scaleDown;
84
+ } else {
85
+ // 'fill' (default)
86
+ renderW = targetW;
87
+ renderH = targetH;
88
+ }
89
+
90
+ // Handle Object Position (simplified parsing for "x% y%" or keywords)
91
+ let posX = 0.5; // Default center
92
+ let posY = 0.5;
93
+
94
+ const posParts = objectPosition.split(' ');
95
+ if (posParts.length > 0) {
96
+ const parsePos = (val) => {
97
+ if (val === 'left' || val === 'top') return 0;
98
+ if (val === 'center') return 0.5;
99
+ if (val === 'right' || val === 'bottom') return 1;
100
+ if (val.includes('%')) return parseFloat(val) / 100;
101
+ return 0.5; // fallback
102
+ };
103
+ posX = parsePos(posParts[0]);
104
+ posY = posParts.length > 1 ? parsePos(posParts[1]) : 0.5;
105
+ }
106
+
107
+ const renderX = (targetW - renderW) * posX;
108
+ const renderY = (targetH - renderH) * posY;
70
109
 
71
110
  ctx.drawImage(img, renderX, renderY, renderW, renderH);
72
111