This repository was archived by the owner on Jul 31, 2022. It is now read-only.
forked from uxal/officegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicgen.js
More file actions
692 lines (591 loc) · 22.9 KB
/
basicgen.js
File metadata and controls
692 lines (591 loc) · 22.9 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//
// officegen: basic common code
//
// Please refer to README.md for this module's documentations.
//
// NOTE:
// - Before changing this code please refer to the hacking the code section on README.md.
//
// Copyright (c) 2013 Ziv Barber;
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
require("setimmediate"); // To be compatible with all versions of node.js
(function () {
var sys = require('util');
var events = require('events');
var Transform = require('stream').Transform || require('readable-stream/transform');
// Used by generate:
var archiver = require('archiver');
var fs = require('fs');
var PassThrough = require('stream').PassThrough || require('readable-stream/passthrough');
// Global data shared by all the officegen objects:
var officegenGlobals = {}; // Our internal global objects.
officegenGlobals.settings = {};
officegenGlobals.types = {};
officegenGlobals.docPrototypes = {};
officegenGlobals.resParserTypes = {};
/**
* The constructor of the office generator object.
* <br /><br />
* This constructor function is been called by makegen().
*
* <h3><b>The options:</b></h3>
*
* The configuration options effecting the operation of the officegen object. Some of them can be only been
* declared on the 'options' object passed to the constructor object and the rest can be configured by either
* a property with the same name or by special function.
*
* <h3><b>List of options:</b></h3>
*
* <ul>
* <li>'type' - the type of generator to create. Possible options: either 'pptx', 'docx' or 'xlsx'.</li>
* <li>'creator' - the name of the document's author. The default is 'officegen'.</li>
* <li>'onend' - callback that been fired after finishing to create the zip stream.</li>
* <li>'onerr' - callback that been fired on error.</li>
* </ul>
*
* @param {object} options List of configuration options (see in the description of this function).
* @constructor
* @name officegen
*/
var officegen = function ( options ) {
if ( false === ( this instanceof officegen )) {
return new officegen ( options );
} // Endif.
events.EventEmitter.call ( this );
// Transform.call ( this, { objectMode : true } );
// Internal events for plugins - NOT for the user:
// event 'beforeGen'
// event 'afterGen'
// event 'clearDoc'
var genobj = this; // Can be accessed by all the functions been declared inside the officegen object.
/**
* For all the private data of each officegen instance that we don't want the user of officegen to access it.
* Each officegen object has it's own copy of the private object so changes been done to the private object of one officegen document will not effect other objects.
* <br /><br />
* List of data members:
* <ul>
* <li>features (object) - ???.</li>
* <ul>
* <li>type</li>
* <li>outputType (string) - The type of the container to hold all the resources.</li>
* </ul>
* <li>pages</li>
* <li>resources</li>
* <li>type</li>
* <li>plugs</li>
* <li>length</li>
* </ul>
* @namespace officegen#private
*/
var privateData = {};
// Features been configured by the type selector and you can't change them:
privateData.features = {};
privateData.features.type = {};
privateData.features.outputType = 'zip';
// privateData.features.page_name
// Resources and "pages" of the document:
privateData.pages = []; // Information about all the pages to create.
privateData.resources = []; // List of all the resources to create inside the zip.
// Extra data needed by the document and it's specific to either to "document prototype" (like MS-office) or a document type (like pptx):
privateData.type = {};
/**
* Combine the given options and the default values.
* <br /><br />
*
* This function creating the real options object.
*
* @param {object} options The options to configure.
*/
function setOptions ( object, source ) {
object = object || {};
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
function isObject (value) {
return !!(value && objectTypes[typeof value]);
}
function keys (object) {
if (!isObject(object)) {
return [];
}
return Object.keys(object);
}
var index;
var iterable = object;
var result = iterable;
var args = arguments;
var argsIndex = 0;
var argsLength = args.length;
//loop variables
var ownIndex = -1;
var ownProps = objectTypes[typeof iterable] && keys(iterable);
var length = ownProps ? ownProps.length : 0;
while (++argsIndex < argsLength) {
iterable = args[argsIndex];
if (iterable && objectTypes[typeof iterable]) {
while (++ownIndex < length) {
index = ownProps[ownIndex];
if (typeof result[index] === 'undefined' || result[index] === null) {
result[index] = iterable[index];
} else if (isObject(result[index]) && isObject(iterable[index])) {
result[index] = setOptions(result[index], iterable[index]);
} // Endif.
} // End of while loop.
} // Endif.
} // End of while loop.
return result;
}
/**
* Configure this object to generate the given type of document.
* <br /><br />
*
* Called by the document constructor to configure the new document object to the given type.
*
* @param {string} new_type The type of document to create.
*/
function setGeneratorType ( new_type ) {
privateData.length = 0;
var is_ok = false;
if ( new_type ) {
for ( var cur_type in officegenGlobals.types ) {
if ( (cur_type == new_type) && officegenGlobals.types[cur_type] && officegenGlobals.types[cur_type].createFunc ) {
officegenGlobals.types[cur_type].createFunc ( genobj, new_type, genobj.options, privateData, officegenGlobals.types[cur_type] );
is_ok = true;
break;
} // Endif.
} // End of for loop.
if ( !is_ok ) {
// console.error ( '\nFATAL ERROR: Either unknown or unsupported file type - %s\n', options.type );
genobj.emit ( 'error', 'FATAL ERROR: Invalid file type.' );
} // Endif.
} // Endif.
}
/**
* API for plugins.
* <br /><br />
* Officegen plugins can extend officegen to support more document formats.
* <br /><br />
* Examples how to do it can be found on lib/gendocx.js, lib/genpptx.js and lib/genxlsx.js.
* @namespace officegen#private#plugs
* @example <caption>Adding a new document type to officegen</caption>
* var baseobj = require ( "officegen" );
*
* function makeMyDoc ( officegenObj, typeCodeName, options, officegenObjPlugins, typeInfo ) {
* // officegenObjPlugins = Plugins access to extend officegenObj.
* }
*
* baseobj.plugins.registerDocType (
* 'mydoctype', // The document type's code name.
* makeMyDoc,
* {},
* baseobj.docType.TEXT,
* "My Special Document File Format"
* );
*/
privateData.plugs = {
/**
* Add a resource to the list of resources to place inside the output zip file.
* <br /><br />
*
* This method adding a resource to the list of resources to place inside the output document ZIP.
* <br />
* Changed by vtloc in 2014Jan10.
*
* @param {string} resource_name The name of the resource (path).
* @param {string} type_of_res The type of this resource: either 'file', 'buffer', 'stream' or 'officegen' (the last one allow you to put office document inside office document).
* @param {object} res_data Optional data to use when creating this resource.
* @param {function} res_cb Callback to generate this resource (for 'buffer' mode only).
* @param {boolean} is_always Is true if this resource is perment for all the zip of this document type.
* @param {boolean} removed_after_used Is true if we need to delete this file after used.
* @memberof officegen#private#plugs
*/
intAddAnyResourceToParse: function ( resource_name, type_of_res, res_data, res_cb, is_always, removed_after_used ) {
var newRes = {};
newRes.name = resource_name;
newRes.type = type_of_res;
newRes.data = res_data;
newRes.callback = res_cb;
newRes.is_perment = is_always;
// delete the temporatory resources after used
// @author vtloc
// @date 2014Jan10
if ( removed_after_used ) {
newRes.removed_after_used = removed_after_used;
} else {
newRes.removed_after_used = false;
} // Endif.
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] Push new res : ", newRes);
} // Endif.
privateData.resources.push ( newRes );
},
/**
* Any additional plugin API must be placed here.
* @memberof officegen#private#plugs
*/
type: {}
};
// Public API:
/**
* Generating the output document stream.
* <br /><br />
*
* The user of officegen must call this method after filling all the information about what to put inside
* the generated document. This method is creating the output document directly into the given stream object.
*
* The options parameters properties:
*
* 'finalize' - callback to be called after finishing to generate the document.
* 'error' - callback to be called on error.
*
* @param {object} output_stream The stream to receive the generated document.
* @param {object} options Way to pass callbacks.
* @function generate
* @memberof officegen
* @instance
*/
this.generate = function ( output_stream, options ) {
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] Start generate() : ", {outputType: privateData.features.outputType });
}
if ( typeof options == 'object' ) {
if ( options.finalize ) {
genobj.on ( 'finalize', options.finalize );
} // Endif.
if ( options.error ) {
genobj.on ( 'error', options.error );
} // Endif.
} // Endif.
if ( privateData.features.page_name ) {
if ( privateData.pages.length == 0 ) {
genobj.emit ( 'error', 'ERROR: No ' + privateData.features.page_name + ' been found inside your document.' );
} // Endif.
} // Endif.
// Allow the type generator to prepare everything:
genobj.emit ( 'beforeGen', privateData );
var archive = archiver( privateData.features.outputType == 'zip' ? 'zip' : 'tar' );
/**
* Error handler.
* <br /><br />
*
* This is our error handler method for creating archive.
*
* @param {string} err The error string.
*/
function onArchiveError ( err ) {
genobj.emit ( 'error', err );
}
archive.on ( 'error', onArchiveError );
if ( privateData.features.outputType == 'gzip' ) {
var zlib = require('zlib');
var gzipper = zlib.createGzip ();
archive.pipe ( gzipper ).pipe ( output_stream );
} else {
archive.pipe ( output_stream );
} // Endif.
/**
* Add the next resource into the zip stream.
* <br /><br />
*
* This function adding the next resource into the zip stream.
*/
function generateNextResource ( cur_index )
{
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] generateNextResource("+cur_index+") : ", privateData.resources[cur_index]);
}
var resStream;
if ( cur_index < privateData.resources.length ) {
if ( typeof privateData.resources[cur_index] != 'undefined' ) {
switch ( privateData.resources[cur_index].type ) {
// Generate the resource text data by calling to provided function:
case 'buffer':
resStream = privateData.resources[cur_index].callback ( privateData.resources[cur_index].data );
break;
// Just copy the file as is:
case 'file':
resStream = fs.createReadStream ( privateData.resources[cur_index].data || privateData.resources[cur_index].name );
break;
// Just use this stream:
case 'stream':
resStream = privateData.resources[cur_index].data;
break;
// Officegen object:
case 'officegen':
resStream = new PassThrough ();
privateData.resources[cur_index].data.generate ( resStream );
break;
// Custom parser:
default:
for ( var cur_parserType in officegenGlobals.resParserTypes ) {
if ( (cur_parserType == privateData.resources[cur_index].type) && officegenGlobals.resParserTypes[cur_parserType] && officegenGlobals.resParserTypes[cur_parserType].parserFunc ) {
resStream = officegenGlobals.resParserTypes[cur_parserType].parserFunc (
genobj,
privateData.resources[cur_index].name,
privateData.resources[cur_index].callback, // Can be used as the template source for template engines.
privateData.resources[cur_index].data, // The data for the template engine.
officegenGlobals.resParserTypes[cur_parserType].extra_data
);
break;
} // Endif.
} // End of for loop.
} // End of switch.
if ( typeof resStream != 'undefined' ) {
if ( officegenGlobals.settings.verbose ) {
console.log ( '[officegen] Adding into archive : "' + privateData.resources[cur_index].name + '" (' + privateData.resources[cur_index].type + ')...' );
} // Endif.
archive.append ( resStream, { name: privateData.resources[cur_index].name } );
generateNextResource ( cur_index + 1 );
} else {
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] resStream is undefined"); // is it normal ??
}
generateNextResource ( cur_index + 1 );
// setImmediate ( function() { generateNextResource ( cur_index + 1 ); });
} // Endif.
} else {
// Removed resource - just ignore it:
generateNextResource ( cur_index + 1 );
// setImmediate ( function() { generateNextResource ( cur_index + 1 ); });
} // Endif.
} else {
// now we can remove all temporary resources
privateData.resources.forEach(function (resource) {
if (resource.removed_after_used){
var filename = resource.data || resource.name;
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] Removing resource: ", filename);
}
fs.unlinkSync(filename);
}
});
// No more resources to add - close the archive:
if ( officegenGlobals.settings.verbose ) {
console.log("[officegen] Finalizing archive ...");
}
archive.finalize ();
// Event to the type generator:
genobj.emit ( 'afterGen', privateData, null, archive.pointer () );
genobj.emit ( 'finalize', archive.pointer () );
} // Endif.
}
// Start the process of generating the output zip stream:
generateNextResource ( 0 );
};
/**
* Reuse this object for a new document of the same type.
* <br /><br />
*
* Call this method if you want to start generating a new document of the same type using this object.
* @function startNewDoc
* @memberof officegen
* @instance
*/
this.startNewDoc = function () {
var kill = [];
for ( var i = 0; i < privateData.resources.length; i++ ) {
if ( !privateData.resources[i].is_perment ) kill.push ( i );
} // End of for loop.
for ( var i = 0; i < kill.length; i++ ) privateData.resources.splice ( kill[i] - i, 1 );
privateData.pages.length = 0;
genobj.emit ( 'clearDoc', privateData );
};
// Public API - plugin API:
/**
* Register a new resource to add into the generated ZIP stream.
* <br /><br />
*
* Using this method the user can add extra custom resources into the generated ZIP stream.
*
* @param {string} resource_name The name of the resource (path).
* @param {string} type_of_res The type of this resource: either 'file' or 'buffer'.
* @param {object} res_data Optional data to use when creating this resource.
* @param {function} res_cb Callback to generate this resource (for 'buffer' mode only).
* @function addResourceToParse
* @memberof officegen
* @instance
*/
this.addResourceToParse = function ( resource_name, type_of_res, res_data, res_cb ) {
// We don't want the user to add permanent resources to the list of resources:
privateData.plugs.intAddAnyResourceToParse ( resource_name, type_of_res, res_data, res_cb, false );
};
if ( typeof options == 'string' ) {
options = { 'type': options };
} // Endif.
// See the officegen descriptions for the rules of the options:
genobj.options = setOptions ( options, { 'type': 'unknown' } );
if ( genobj.options && genobj.options.onerr ) {
genobj.on ( 'error', genobj.options.onerr );
} // Endif.
if ( genobj.options && genobj.options.onend ) {
genobj.on ( 'finalize', genobj.options.onend );
} // Endif.
// Configure this object depending on the user's selected type:
if ( genobj.options.type ) {
setGeneratorType ( genobj.options.type );
} // Endif.
return this;
};
sys.inherits ( officegen, events.EventEmitter );
/**
* Create a new officegen object.
* <br /><br />
*
* This method creating a new officegen based object.
*/
module.exports = function ( options ) {
return new officegen ( options );
};
/**
* Change the verbose state of officegen.
* <br /><br />
*
* This is a global settings effecting all the officegen objects in your application. You should
* use it only for debugging.
*
* @param {boolean} new_state Either true or false.
*/
module.exports.setVerboseMode = function setVerboseMode ( new_state ) {
officegenGlobals.settings.verbose = new_state;
}
/**
* Plugin API effecting all the instances of the officegen object.
*
* @namespace officegen#plugins
*/
var plugins = {
/**
* Register a new type of document that we can generate.
* <br /><br />
*
* This method registering a new type of document that we can generate. You can extend officegen to support any
* type of document that based on resources files inside ZIP stream.
*
* @param {string} typeName The type of the document file.
* @param {function} createFunc The function to use to create this type of file.
* @param {object} schema_data Information needed by Schema-API to generate this kind of document.
* @param {string} docType Document type.
* @param {string} displayName The display name of this type.
* @memberof officegen#plugins
*/
registerDocType: function ( typeName, createFunc, schema_data, docType, displayName ) {
officegenGlobals.types[typeName] = {};
officegenGlobals.types[typeName].createFunc = createFunc;
officegenGlobals.types[typeName].schema_data = schema_data;
officegenGlobals.types[typeName].type = docType;
officegenGlobals.types[typeName].display = displayName;
},
/**
* Get a document type object by name.
* <br /><br />
*
* This method get a document type object.
*
* @param {string} typeName The name of the document type.
* @return The plugin object of the document type.
* @memberof officegen#plugins
*/
getDocTypeByName: function ( typeName ) {
return officegenGlobals.types[typeName];
},
/**
* Register a document prototype object.
* <br /><br />
*
* This method registering a prototype document object. You can place all the common code needed by a group of document
* types in a single prototype object.
*
* @param {string} typeName The name of the prototype object.
* @param {object} baseObj The prototype object.
* @param {string} displayName The display name of this type.
* @memberof officegen#plugins
*/
registerPrototype: function ( typeName, baseObj, displayName ) {
officegenGlobals.docPrototypes[typeName] = {};
officegenGlobals.docPrototypes[typeName].baseObj = baseObj;
officegenGlobals.docPrototypes[typeName].display = displayName;
},
/**
* Get a document prototype object by name.
* <br /><br />
*
* This method get a prototype object.
*
* @param {string} typeName The name of the prototype object.
* @return The prototype plugin object.
* @memberof officegen#plugins
*/
getPrototypeByName: function getPrototypeByName ( typeName ) {
return officegenGlobals.docPrototypes[typeName];
},
/**
* Register a new resource parser.
* <br /><br />
*
* This method registering a new resource parser. One use of this feature is in case that you are developing a new
* type of document and you want to extend officegen to use some kind of template engine as jade, ejs, haml* or CoffeeKup.
* In this case you can use a template engine to generate one or more of the resources inside the output archive.
* Another use of this method is to replace an existing plugin with different implementation.
*
* @param {string} typeName The type of the parser plugin.
* @param {function} parserFunc The resource generating function.
* @param {object} extra_data Optional additional data that may be required by the parser function.
* @param {string} displayName The display name of this type.
* @memberof officegen#plugins
*/
registerParserType: function ( typeName, parserFunc, extra_data, displayName ) {
officegenGlobals.resParserTypes[typeName] = {};
officegenGlobals.resParserTypes[typeName].parserFunc = parserFunc;
officegenGlobals.resParserTypes[typeName].extra_data = extra_data;
officegenGlobals.resParserTypes[typeName].display = displayName;
},
/**
* Get if we need verbose mode.
* @param {string} docType Optional, Allow filtering by document type.
* @param {string} moduleName Optional, Allow filtering by feature / module.
* @memberof officegen#plugins
*/
getVerboseMode: function ( docType, moduleName ) {
if ( !docType && !moduleName ) {
return officegenGlobals.settings.verbose ? true : false;
} // Endif.
var verboseFlag;
if ( officegenGlobals.settings.verbose && typeof officegenGlobals.settings.verbose === 'object' ) {
if ( docType && officegenGlobals.settings.verbose.docType && typeof officegenGlobals.settings.verbose.docType === 'object' && officegenGlobals.settings.verbose.docType.indexOf ) {
verboseFlag = (officegenGlobals.settings.verbose.docType.indexOf ( docType ) >= 0) ? true : false;
} // Endif.
if ( verboseFlag !== false && moduleName && officegenGlobals.settings.verbose.moduleName && typeof officegenGlobals.settings.verbose.moduleName === 'object' && officegenGlobals.settings.verbose.moduleName.indexOf ) {
verboseFlag = (officegenGlobals.settings.verbose.moduleName.indexOf ( moduleName ) >= 0) ? true : false;
} // Endif.
} // Endif.
return verboseFlag ? true : false;
}
};
module.exports.plugins = plugins;
module.exports.schema = officegenGlobals.types;
module.exports.docType = { "TEXT" : 1, "SPREADSHEET" : 2, "PRESENTATION" : 3 };
}) ();