dynamic-docx-generator 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dynamic-docx-generator
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,315 @@
1
+ # dynamic-docx-generator
2
+
3
+ Generate dynamic DOCX documents from templates with placeholder replacement, tables, and images.
4
+
5
+ [![npm version](https://badge.fury.io/js/dynamic-docx-generator.svg)](https://www.npmjs.com/package/dynamic-docx-generator)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Features
9
+
10
+ - 📝 **Template-based generation** - Use existing DOCX files as templates
11
+ - 🔄 **Placeholder replacement** - Replace `{{placeholder}}` tags with dynamic data
12
+ - 📊 **Dynamic tables** - Generate tables from data arrays
13
+ - 🖼️ **Image insertion** - Embed images from files, URLs, or buffers
14
+ - 📄 **Header/Footer support** - Customize document headers and footers
15
+ - ⚡ **Fluent API** - Chain methods for clean, readable code
16
+ - 📦 **Zero system dependencies** - No external tools like LibreOffice needed
17
+ - 🔧 **TypeScript support** - Full type definitions included
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install dynamic-docx-generator
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```javascript
28
+ const { DocxGenerator } = require('dynamic-docx-generator');
29
+
30
+ async function generateDocument() {
31
+ const generator = new DocxGenerator();
32
+
33
+ // Load a DOCX template
34
+ await generator.loadTemplate('./template.docx');
35
+
36
+ // Replace placeholders
37
+ generator.setData({
38
+ companyName: 'Acme Corporation',
39
+ productName: 'Widget Pro',
40
+ date: '2026-01-09'
41
+ });
42
+
43
+ // Save the generated document
44
+ await generator.save('./output.docx');
45
+
46
+ console.log('Document generated successfully!');
47
+ }
48
+
49
+ generateDocument();
50
+ ```
51
+
52
+ ## API Reference
53
+
54
+ ### DocxGenerator
55
+
56
+ The main class for document generation.
57
+
58
+ #### Constructor
59
+
60
+ ```typescript
61
+ const generator = new DocxGenerator(options?: GeneratorOptions);
62
+ ```
63
+
64
+ **Options:**
65
+ - `tempDir?: string` - Custom temporary directory for processing
66
+
67
+ #### Methods
68
+
69
+ ##### loadTemplate(source)
70
+
71
+ Load a DOCX template from a file path or buffer.
72
+
73
+ ```typescript
74
+ await generator.loadTemplate('./template.docx');
75
+ // or
76
+ await generator.loadTemplate(buffer);
77
+ ```
78
+
79
+ ##### setData(data)
80
+
81
+ Set placeholder values for the document body.
82
+
83
+ ```typescript
84
+ generator.setData({
85
+ name: 'John Doe',
86
+ company: 'Acme Corp',
87
+ date: new Date().toLocaleDateString()
88
+ });
89
+ ```
90
+
91
+ ##### setHeader(data)
92
+
93
+ Set placeholder values for document headers.
94
+
95
+ ```typescript
96
+ generator.setHeader({
97
+ documentTitle: 'Annual Report',
98
+ version: '1.0'
99
+ });
100
+ ```
101
+
102
+ ##### setFooter(data)
103
+
104
+ Set placeholder values for document footers.
105
+
106
+ ```typescript
107
+ generator.setFooter({
108
+ copyright: '© 2026 Acme Corp'
109
+ });
110
+ ```
111
+
112
+ ##### setImages(images)
113
+
114
+ Add images to be inserted into the document.
115
+
116
+ ```typescript
117
+ generator.setImages([
118
+ {
119
+ placeholder: 'logo',
120
+ path: './logo.png',
121
+ width: 914400 // In EMUs (914400 EMUs = 1 inch)
122
+ },
123
+ {
124
+ placeholder: 'signature',
125
+ url: 'https://example.com/signature.png',
126
+ width: 457200,
127
+ height: 228600
128
+ }
129
+ ]);
130
+ ```
131
+
132
+ ##### addTable(config)
133
+
134
+ Add a dynamic table to the document.
135
+
136
+ ```typescript
137
+ generator.addTable({
138
+ placeholder: 'itemsTable',
139
+ headers: [
140
+ { name: 'Item', key: 'item', width: 3000 },
141
+ { name: 'Quantity', key: 'qty', width: 1500 },
142
+ { name: 'Price', key: 'price', width: 1500 }
143
+ ],
144
+ rows: [
145
+ ['Widget A', '10', '$99.00'],
146
+ ['Widget B', '5', '$149.00'],
147
+ ['Widget C', '3', '$199.00']
148
+ ],
149
+ style: {
150
+ headerBgColor: 'C9DAF8',
151
+ fontSize: 24
152
+ }
153
+ });
154
+ ```
155
+
156
+ ##### generate()
157
+
158
+ Generate the document and return as a Buffer.
159
+
160
+ ```typescript
161
+ const buffer = await generator.generate();
162
+ ```
163
+
164
+ ##### save(outputPath)
165
+
166
+ Generate and save the document to a file.
167
+
168
+ ```typescript
169
+ await generator.save('./output.docx');
170
+ ```
171
+
172
+ ##### reset()
173
+
174
+ Reset generator state while keeping the template loaded.
175
+
176
+ ```typescript
177
+ generator.reset();
178
+ ```
179
+
180
+ ## Template Format
181
+
182
+ Create your template in Microsoft Word or any DOCX-compatible editor:
183
+
184
+ 1. Add placeholders using `{{placeholderName}}` syntax
185
+ 2. For tables, add a placeholder like `{{itemsTable}}`
186
+ 3. For images, add a placeholder like `{{logo}}`
187
+
188
+ **Example template content:**
189
+
190
+ ```
191
+ Document Title: {{documentTitle}}
192
+ Company: {{companyName}}
193
+ Date: {{date}}
194
+
195
+ {{itemsTable}}
196
+
197
+ Signature: {{signature}}
198
+ ```
199
+
200
+ ## Image Units (EMUs)
201
+
202
+ DOCX uses English Metric Units (EMUs) for dimensions:
203
+ - **914400 EMUs = 1 inch**
204
+ - **360000 EMUs = 1 cm**
205
+ - **9525 EMUs = 1 pixel (at 96 DPI)**
206
+
207
+ Helper functions are available:
208
+
209
+ ```typescript
210
+ const { ImageUtils } = require('dynamic-docx-generator');
211
+
212
+ // Convert to EMUs
213
+ const widthInEmu = ImageUtils.pixelsToEmu(200); // 200px -> EMUs
214
+ const heightInEmu = ImageUtils.inchesToEmu(2); // 2 inches -> EMUs
215
+ const sizeInEmu = ImageUtils.cmToEmu(5); // 5cm -> EMUs
216
+ ```
217
+
218
+ ## Complete Example
219
+
220
+ ```javascript
221
+ const { DocxGenerator, ImageUtils } = require('dynamic-docx-generator');
222
+ const path = require('path');
223
+
224
+ async function createInvoice() {
225
+ const generator = new DocxGenerator();
226
+
227
+ await generator.loadTemplate('./invoice-template.docx');
228
+
229
+ // Company details
230
+ generator.setData({
231
+ invoiceNumber: 'INV-2026-001',
232
+ date: '2026-01-09',
233
+ customerName: 'John Doe',
234
+ customerAddress: '123 Main Street, City',
235
+ total: '$447.00',
236
+ tax: '$44.70',
237
+ grandTotal: '$491.70'
238
+ });
239
+
240
+ // Header
241
+ generator.setHeader({
242
+ companyName: 'Acme Corp'
243
+ });
244
+
245
+ // Company logo
246
+ generator.setImages([
247
+ {
248
+ placeholder: 'companyLogo',
249
+ path: './assets/logo.png',
250
+ width: ImageUtils.inchesToEmu(1.5)
251
+ }
252
+ ]);
253
+
254
+ // Line items table
255
+ generator.addTable({
256
+ placeholder: 'lineItems',
257
+ headers: [
258
+ { name: 'Description', key: 'desc', width: 4000 },
259
+ { name: 'Qty', key: 'qty', width: 1000 },
260
+ { name: 'Unit Price', key: 'price', width: 1500 },
261
+ { name: 'Total', key: 'total', width: 1500 }
262
+ ],
263
+ rows: [
264
+ ['Widget Pro', '2', '$99.00', '$198.00'],
265
+ ['Widget Plus', '1', '$149.00', '$149.00'],
266
+ ['Premium Support', '1', '$100.00', '$100.00']
267
+ ]
268
+ });
269
+
270
+ await generator.save('./generated-invoice.docx');
271
+ console.log('Invoice generated!');
272
+ }
273
+
274
+ createInvoice();
275
+ ```
276
+
277
+ ## TypeScript Usage
278
+
279
+ ```typescript
280
+ import { DocxGenerator, ImageConfig, TableConfig } from 'dynamic-docx-generator';
281
+
282
+ async function generateReport(): Promise<void> {
283
+ const generator = new DocxGenerator();
284
+
285
+ await generator.loadTemplate('./template.docx');
286
+
287
+ const images: ImageConfig[] = [
288
+ { placeholder: 'chart', path: './chart.png', width: 914400 }
289
+ ];
290
+
291
+ const table: TableConfig = {
292
+ placeholder: 'dataTable',
293
+ headers: [
294
+ { name: 'Name', key: 'name', width: 3000 },
295
+ { name: 'Value', key: 'value', width: 2000 }
296
+ ],
297
+ rows: [['Item 1', '100'], ['Item 2', '200']]
298
+ };
299
+
300
+ generator
301
+ .setData({ title: 'Monthly Report' })
302
+ .setImages(images)
303
+ .addTable(table);
304
+
305
+ await generator.save('./report.docx');
306
+ }
307
+ ```
308
+
309
+ ## Contributing
310
+
311
+ Contributions are welcome! Please feel free to submit a Pull Request.
312
+
313
+ ## License
314
+
315
+ MIT © 2026
@@ -0,0 +1,135 @@
1
+ /**
2
+ * DocxGenerator - Main class for dynamic DOCX document generation
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * const generator = new DocxGenerator();
7
+ * await generator.loadTemplate('./template.docx');
8
+ * generator.setData({ name: 'John', company: 'Acme' });
9
+ * await generator.save('./output.docx');
10
+ * ```
11
+ */
12
+ import { GeneratorOptions, PlaceholderData, ImageConfig, TableConfig } from './types';
13
+ export declare class DocxGenerator {
14
+ private options;
15
+ private zip;
16
+ private templateLoaded;
17
+ private data;
18
+ private headerData;
19
+ private footerData;
20
+ private images;
21
+ private tables;
22
+ private tempDir;
23
+ /**
24
+ * Create a new DocxGenerator instance
25
+ * @param options - Configuration options
26
+ */
27
+ constructor(options?: GeneratorOptions);
28
+ /**
29
+ * Load a DOCX template from file path or buffer
30
+ * @param source - Path to template file or Buffer containing template
31
+ * @returns this for method chaining
32
+ */
33
+ loadTemplate(source: string | Buffer): Promise<this>;
34
+ /**
35
+ * Set placeholder data for document body
36
+ * @param data - Key-value pairs where key is placeholder name and value is replacement text
37
+ * @returns this for method chaining
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * generator.setData({
42
+ * companyName: 'Acme Corp',
43
+ * productName: 'Widget Pro',
44
+ * date: '2026-01-09'
45
+ * });
46
+ * ```
47
+ */
48
+ setData(data: PlaceholderData): this;
49
+ /**
50
+ * Set placeholder data for document header
51
+ * @param data - Key-value pairs for header placeholders
52
+ * @returns this for method chaining
53
+ */
54
+ setHeader(data: PlaceholderData): this;
55
+ /**
56
+ * Set placeholder data for document footer
57
+ * @param data - Key-value pairs for footer placeholders
58
+ * @returns this for method chaining
59
+ */
60
+ setFooter(data: PlaceholderData): this;
61
+ /**
62
+ * Add images to be inserted into the document
63
+ * @param images - Array of image configurations
64
+ * @returns this for method chaining
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * generator.setImages([
69
+ * { placeholder: '{{logo}}', path: './logo.png', width: 200 }
70
+ * ]);
71
+ * ```
72
+ */
73
+ setImages(images: ImageConfig[]): this;
74
+ /**
75
+ * Add a dynamic table to the document
76
+ * @param config - Table configuration
77
+ * @returns this for method chaining
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * generator.addTable({
82
+ * placeholder: '{{itemsTable}}',
83
+ * headers: [
84
+ * { name: 'Item', key: 'item', width: 3000 },
85
+ * { name: 'Quantity', key: 'qty', width: 1500 }
86
+ * ],
87
+ * rows: [['Widget A', '10'], ['Widget B', '5']]
88
+ * });
89
+ * ```
90
+ */
91
+ addTable(config: TableConfig): this;
92
+ /**
93
+ * Process placeholders in XML content
94
+ */
95
+ private processPlaceholders;
96
+ /**
97
+ * Process tables in XML content
98
+ */
99
+ private processTables;
100
+ /**
101
+ * Process images and add them to the document
102
+ */
103
+ private processImages;
104
+ /**
105
+ * Update document relationships with images
106
+ */
107
+ private updateRelationships;
108
+ /**
109
+ * Add image files to the media folder
110
+ */
111
+ private addImageFiles;
112
+ /**
113
+ * Replace image placeholders in document content
114
+ */
115
+ private replaceImagePlaceholders;
116
+ /**
117
+ * Generate the final DOCX document as a Buffer
118
+ * @returns Buffer containing the generated DOCX file
119
+ */
120
+ generate(): Promise<Buffer>;
121
+ /**
122
+ * Save the generated document to a file
123
+ * @param outputPath - Path where the document should be saved
124
+ */
125
+ save(outputPath: string): Promise<void>;
126
+ /**
127
+ * Reset the generator state (keeps template loaded)
128
+ */
129
+ reset(): this;
130
+ /**
131
+ * Check if a template has been loaded
132
+ */
133
+ isTemplateLoaded(): boolean;
134
+ }
135
+ //# sourceMappingURL=DocxGenerator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DocxGenerator.d.ts","sourceRoot":"","sources":["../src/DocxGenerator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,OAAO,EACH,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,WAAW,EAEd,MAAM,SAAS,CAAC;AAOjB,qBAAa,aAAa;IACtB,OAAO,CAAC,OAAO,CAAmB;IAClC,OAAO,CAAC,GAAG,CAAuB;IAClC,OAAO,CAAC,cAAc,CAAkB;IACxC,OAAO,CAAC,IAAI,CAAuB;IACnC,OAAO,CAAC,UAAU,CAAuB;IACzC,OAAO,CAAC,UAAU,CAAuB;IACzC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,OAAO,CAAS;IAExB;;;OAGG;gBACS,OAAO,GAAE,gBAAqB;IAK1C;;;;OAIG;IACG,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB1D;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAKpC;;;;OAIG;IACH,SAAS,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAKtC;;;;OAIG;IACH,SAAS,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAKtC;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,IAAI;IAKtC;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAKnC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAa3B;;OAEG;IACH,OAAO,CAAC,aAAa;IAwBrB;;OAEG;YACW,aAAa;IAuB3B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAqC3B;;OAEG;IACH,OAAO,CAAC,aAAa;IASrB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAYhC;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IA+DjC;;;OAGG;IACG,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY7C;;OAEG;IACH,KAAK,IAAI,IAAI;IASb;;OAEG;IACH,gBAAgB,IAAI,OAAO;CAG9B"}