forked from carboneio/carbone
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcarbone.diff
More file actions
4552 lines (4525 loc) · 172 KB
/
carbone.diff
File metadata and controls
4552 lines (4525 loc) · 172 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git .gitignore .gitignore
index 063d4af..c583cef 100644
--- .gitignore
+++ .gitignore
@@ -42,4 +42,7 @@ render/*
template/*
asset/*
0formation/*
+examples/*
+out/*
+request/*
diff --git formatters/array.js formatters/array.js
index 5ab21c6..f0a9012 100644
--- formatters/array.js
+++ formatters/array.js
@@ -1,3 +1,4 @@
+var get = require('lodash/get');
/**
* Flatten an array of String or Number
@@ -74,7 +75,7 @@ function arrayMap (d, objSeparator, attributeSeparator) {
if (_isAttributeFilterActive === true) {
for (var j = 3; j < arguments.length; j++) {
var _att = arguments[j];
- _flatObj.push(_obj[_att]);
+ _flatObj.push(get(_obj,_att));
}
}
else if (_obj instanceof Object === false) {
diff --git licarbone-cli.js licarbone-cli.js
new file mode 100755
index 0000000..da85ecc
--- /dev/null
+++ licarbone-cli.js
@@ -0,0 +1,121 @@
+#!/usr/bin/env node
+
+const yargonaut = require("yargonaut").style("blue");
+const yargs = require("yargs");
+const fs = require("fs");
+const carbone = require("../liindex");
+const figlet = require("figlet");
+const printgenericfields = require("./printgenericfields");
+const get = require("lodash/get");
+const chalk = yargonaut.chalk();
+
+const options = yargs
+ .usage(
+ chalk.red(figlet.textSync("KEEP SOLUTIONS")) +
+ "\n\n" +
+ chalk.blue("CARBONE by David Grealund") +
+ "\n\n" +
+ "Generate reports (odt, docx, txt, pdf, ods, xlsx, csv) via a template (odt, docx, xlsx, csv)." +
+ "\n\nUsage\n -d <json data> -t <path to template> -o <json with options> -r <path of the file to render>"
+ )
+ .option("d", {
+ alias: "data",
+ describe: "path to json with data",
+ type: "string",
+ demandOption: true,
+ })
+ .option("t", {
+ alias: "template",
+ describe: "path to document template",
+ type: "string",
+ demandOption: true,
+ })
+ .option("r", {
+ alias: "render",
+ describe: "path to render the new file",
+ type: "string",
+ demandOption: true,
+ })
+ .option("o", {
+ alias: "options",
+ describe: "path to json with options",
+ type: "string",
+ demandOption: false,
+ })
+ .option("l", {
+ alias: "language",
+ describe: "the language code",
+ type: "string",
+ demandOption: false,
+ })
+ .version().argv;
+
+let rawdata = fs.readFileSync(options.data);
+let data = JSON.parse(rawdata);
+
+let rawoptions = options.options ? fs.readFileSync(options.options) : null;
+let carboneoptions = rawoptions ? JSON.parse(rawoptions) : "";
+carboneoptions.lang = options.language || carboneoptions.lang || "en";
+
+// Process the data if there are genericOptions
+if (carboneoptions.generic) {
+ let genericFields = carboneoptions.generic.fields;
+
+ if (data.record) {
+ let fields = [];
+ genericFields.map((genericField) => {
+ let value = get(data.record, genericField.field);
+ let label = genericField.label[carboneoptions.lang];
+
+ if (value) {
+ fields.push({
+ label: label,
+ value: printgenericfields.print(
+ genericField,
+ value,
+ carboneoptions.lang
+ ),
+ });
+ }
+ });
+
+ data.generic = { record: { fields: fields } };
+ } else if (data.records) {
+ let fields = [];
+
+ data.records.map((record) => {
+ let recordFields = [];
+ genericFields.map((genericField) => {
+ let value = get(record, genericField.field);
+ let label = genericField.label[carboneoptions.lang];
+
+ if (value) {
+ recordFields.push({
+ label: label,
+ value: printgenericfields.print(
+ genericField,
+ value,
+ carboneoptions.lang
+ ),
+ });
+ }
+ });
+ fields.push({ fields: recordFields });
+ });
+
+ data.generic = { records: fields };
+ }
+}
+
+// Generate a report using the sample template provided by carbone module
+// This LibreOffice template contains "Hello {d.firstname} {d.lastname} !"
+// Of course, you can create your own templates!
+carbone.render(options.template, data, carboneoptions, function (err, result) {
+ if (err) {
+ return console.log(err);
+ }
+ // write the result
+ fs.writeFileSync(options.render, result);
+ console.log(chalk.green("File generated in " + options.render));
+ process.exit();
+});
diff --git lifile.js lifile.js
index 27e0880..ba9579f 100644
--- lifile.js
+++ lifile.js
@@ -1,27 +1,28 @@
-var path = require('path');
-var fs = require('fs');
-var params = require('./params');
-var yauzl = require('yauzl');
-var unzipEmbeddedFileTypes = ['.xlsx', '.ods'];
-var yazl = require('yazl');
-var debug = require('debug')('carbone');
+var path = require("path");
+var fs = require("fs");
+var params = require("./params");
+var yauzl = require("yauzl");
+var unzipEmbeddedFileTypes = [".xlsx", ".ods"];
+var yazl = require("yazl");
+var debug = require("debug")("carbone");
+var QRCode = require("qrcode");
+var svg = require("qrcode/lirenderer/svg-tag");
var file = {
-
/**
* is Zipped return callback(true) if the file is zipped
* @param {String} filePath file path
* @param {Function} callback(err, isZipped)
*/
- isZipped : function (filePath, callback) {
+ isZipped: function (filePath, callback) {
var _buf = Buffer.allocUnsafe(10);
- fs.open(filePath, 'r', function (err, fd) {
+ fs.open(filePath, "r", function (err, fd) {
if (err) {
return callback(err, false);
}
fs.read(fd, _buf, 0, 10, 0, function (err, bytesRead, buffer) {
fs.close(fd, function () {
- callback(err, (buffer.slice(0, 2).toString() === 'PK'));
+ callback(err, buffer.slice(0, 2).toString() === "PK");
});
});
});
@@ -32,47 +33,49 @@ var file = {
* @param {String} filePath file to unzip
* @param {Function} callback(err, files) files is an array of files ['name':'filename', 'buffer':Buffer]
*/
- unzip : function (filePath, callback) {
+ unzip: function (filePath, callback) {
var _unzippedFiles = [];
var _unzipFn = yauzl.open;
if (Buffer.isBuffer(filePath) === true) {
_unzipFn = yauzl.fromBuffer;
}
- _unzipFn(filePath, {lazyEntries : true, decodeStrings : true}, function (err, zipfile) {
+ _unzipFn(filePath, { lazyEntries: true, decodeStrings: true }, function (
+ err,
+ zipfile
+ ) {
if (err) {
return callback(err);
}
- zipfile.on('end', function () {
+ zipfile.on("end", function () {
zipfile.close();
return callback(null, _unzippedFiles);
});
- zipfile.on('error', callback);
+ zipfile.on("error", callback);
zipfile.readEntry();
- zipfile.on('entry', function (entry) {
+ zipfile.on("entry", function (entry) {
var _unzippedFile = {
- name : entry.fileName,
- data : Buffer.from([])
+ name: entry.fileName,
+ data: Buffer.from([]),
};
_unzippedFiles.push(_unzippedFile);
if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
zipfile.readEntry();
- }
- else {
+ } else {
zipfile.openReadStream(entry, function (err, readStream) {
if (err) {
zipfile.close();
return callback(err);
}
var buffers = [];
- readStream.on('data', function (data) {
+ readStream.on("data", function (data) {
buffers.push(data);
});
- readStream.on('end', function () {
+ readStream.on("end", function () {
_unzippedFile.data = Buffer.concat(buffers);
zipfile.readEntry();
});
- readStream.on('error', function (err) {
+ readStream.on("error", function (err) {
zipfile.close();
return callback(err);
});
@@ -87,25 +90,24 @@ var file = {
* @param {Array} files files is an array of files ['name':'filename', 'data':Buffer]
* @param {Function} callback(err, result) result is a buffer (the zip file)
*/
- zip : function (files, callback) {
+ zip: function (files, callback) {
var _buffer = [];
var _zip = new yazl.ZipFile();
- _zip.outputStream.on('data', function (data) {
+ _zip.outputStream.on("data", function (data) {
_buffer.push(data);
});
- _zip.outputStream.on('error', function (err) {
- debug('Error when building zip file ' + err);
+ _zip.outputStream.on("error", function (err) {
+ debug("Error when building zip file " + err);
});
- _zip.outputStream.on('end', function () {
+ _zip.outputStream.on("end", function () {
var _finalBuffer = Buffer.concat(_buffer);
callback(null, _finalBuffer);
});
for (var i = 0; i < files.length; i++) {
var _file = files[i];
- if (_file.name.endsWith('/') === true) {
+ if (_file.name.endsWith("/") === true) {
_zip.addEmptyDirectory(_file.name);
- }
- else {
+ } else {
_zip.addBuffer(Buffer.from(_file.data), _file.name);
}
}
@@ -117,12 +119,12 @@ var file = {
* @param {String} templateId template name (with or without the path)
* @param {Function} callback(err, template)
*/
- openTemplate : function (templateId, callback) {
+ openTemplate: function (templateId, callback) {
var _template = {
- isZipped : false,
- filename : templateId,
- embeddings : [],
- files : []
+ isZipped: false,
+ filename: templateId,
+ embeddings: [],
+ files: [],
};
// security, remove access on parent directory
// if (/\.\./.test(path.dirname(templateId)) === true) {
@@ -136,19 +138,20 @@ var file = {
}
if (isZipped === true) {
_template.isZipped = true;
- var _filesToUnzip = [{
- name : '',
- data : _templateFile
- }];
+ var _filesToUnzip = [
+ {
+ name: "",
+ data: _templateFile,
+ },
+ ];
return unzipFiles(_template, _filesToUnzip, callback);
- }
- else {
- fs.readFile(_templateFile, 'utf8', function (err, data) {
+ } else {
+ fs.readFile(_templateFile, "utf8", function (err, data) {
var _file = {
- name : path.basename(templateId),
- data : data,
- isMarked : true,
- parent : ''
+ name: path.basename(templateId),
+ data: data,
+ isMarked: true,
+ parent: "",
};
_template.files.push(_file);
return callback(err, _template);
@@ -161,36 +164,51 @@ var file = {
* Check the extension of template
* @param {Object} template Template to analyze
*/
- detectType : function (template) {
- if (this._checkWordInFilename(template, 'word/')) {
- return 'docx';
+ detectType: function (template) {
+ if (this._checkWordInFilename(template, "word/")) {
+ return "docx";
}
- if (this._checkWordInFilename(template, 'xl/')) {
- return 'xlsx';
+ if (this._checkWordInFilename(template, "xl/")) {
+ return "xlsx";
}
- if (this._checkWordInFilename(template, 'ppt/')) {
- return 'pptx';
+ if (this._checkWordInFilename(template, "ppt/")) {
+ return "pptx";
}
- if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.text')) {
- return 'odt';
+ if (
+ this._checkMimetypeFile(
+ template,
+ "application/vnd.oasis.opendocument.text"
+ )
+ ) {
+ return "odt";
}
- if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.spreadsheet')) {
- return 'ods';
+ if (
+ this._checkMimetypeFile(
+ template,
+ "application/vnd.oasis.opendocument.spreadsheet"
+ )
+ ) {
+ return "ods";
}
- if (this._checkMimetypeFile(template, 'application/vnd.oasis.opendocument.presentation')) {
- return 'odp';
+ if (
+ this._checkMimetypeFile(
+ template,
+ "application/vnd.oasis.opendocument.presentation"
+ )
+ ) {
+ return "odp";
}
if (this._isXHTMLFile(template)) {
- return 'xhtml';
+ return "xhtml";
}
if (this._isHTMLFile(template)) {
- return 'html';
+ return "html";
}
if (this._isXMLFile(template)) {
- return 'xml';
+ return "xml";
}
var _extname = path.extname(template.filename).slice(1);
- if (template.isZipped === false && _extname !== '') {
+ if (template.isZipped === false && _extname !== "") {
return _extname;
}
return null;
@@ -200,11 +218,11 @@ var file = {
* Check if the file is a XML file
* @param {Object} template File content to analyze
*/
- _isXMLFile : function (template) {
+ _isXMLFile: function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
- if (_trimmedTemplate.startsWith('<')) {
+ if (_trimmedTemplate.startsWith("<")) {
return true;
}
}
@@ -216,12 +234,12 @@ var file = {
* Check if the file is an XHTML file
* @param {Object} template File content to analyze
*/
- _isXHTMLFile : function (template) {
+ _isXHTMLFile: function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
var _xmlnsRegex = /<html xmlns="/gm;
- if (_trimmedTemplate.startsWith('<!DOCTYPE')) {
+ if (_trimmedTemplate.startsWith("<!DOCTYPE")) {
if (_xmlnsRegex.test(_trimmedTemplate)) {
return true;
}
@@ -235,12 +253,12 @@ var file = {
* Check if the file is an HTML file
* @param {Object} template File content to analyze
*/
- _isHTMLFile : function (template) {
+ _isHTMLFile: function (template) {
for (var i = 0; i < template.files.length; i++) {
var _trimmedTemplate = template.files[i].data.trim();
var _htmlRegex = /<html/gm;
- if (_trimmedTemplate.startsWith('<!DOCTYPE')) {
+ if (_trimmedTemplate.startsWith("<!DOCTYPE")) {
if (_htmlRegex.test(_trimmedTemplate)) {
return true;
}
@@ -255,9 +273,9 @@ var file = {
* @param {Object} template Template object if unzipped. Else it's a string
* @param {String} string String to match in mimetype file
*/
- _checkMimetypeFile : function (template, string) {
+ _checkMimetypeFile: function (template, string) {
for (var i = 0; i < template.files.length; i++) {
- if (template.files[i].name === 'mimetype') {
+ if (template.files[i].name === "mimetype") {
if (template.files[i].data.toString() === string) {
return true;
}
@@ -272,7 +290,7 @@ var file = {
* @param {Object} template Template object if unzipped. Else it's a string
* @param {String} string String to check
*/
- _checkWordInFilename : function (template, string) {
+ _checkWordInFilename: function (template, string) {
for (var i = 0; i < template.files.length; i++) {
if (template.files[i].name.startsWith(string)) {
return true;
@@ -287,18 +305,18 @@ var file = {
* @param {Object} report report object. Example: {'isZipped': true, files:[{'name': 'bla', 'data': 'buffer or string'}]}
* @param {Function} callback(err, data) data can be a buffer (docx,...) or a string (xml)
*/
- buildFile : function (report, callback) {
- if (report.isZipped===true) {
+ buildFile: function (report, callback) {
+ if (report.isZipped === true) {
return zipFiles(report.files, callback);
- }
- else {
+ } else {
if (report.files.length !== 1) {
- throw Error('This report is not zipped and does not contain exactly one file');
+ throw Error(
+ "This report is not zipped and does not contain exactly one file"
+ );
}
return callback(null, report.files[0].data);
}
- }
-
+ },
};
/**
@@ -307,7 +325,7 @@ var file = {
* @param {Array} filesToUnzip
* @param {Function} callback(err, template)
*/
-function unzipFiles (template, filesToUnzip, callback) {
+function unzipFiles(template, filesToUnzip, callback) {
if (filesToUnzip.length === 0) {
return callback(null, template);
}
@@ -321,17 +339,20 @@ function unzipFiles (template, filesToUnzip, callback) {
var _extname = path.extname(_file.name);
_file.isMarked = false;
_file.parent = _fileToUnzip.name;
- if (_extname === '.xml' || _extname === '.rels') {
+ // Search xml and rels files for carbone tags by default
+ if (_extname === ".xml" || _extname === ".rels") {
_file.isMarked = true;
_file.data = _file.data.toString();
template.files.push(_file);
}
// only unzip first level
- else if (_file.parent === '' && unzipEmbeddedFileTypes.indexOf(_extname) !== -1) {
+ else if (
+ _file.parent === "" &&
+ unzipEmbeddedFileTypes.indexOf(_extname) !== -1
+ ) {
template.embeddings.push(_file.name);
filesToUnzip.push(_file);
- }
- else {
+ } else {
template.files.push(_file);
}
}
@@ -344,7 +365,7 @@ function unzipFiles (template, filesToUnzip, callback) {
* @param {Array} filesToZip
* @param {Function} callback(err, buffer)
*/
-function zipFiles (filesToZip, callback) {
+async function zipFiles(filesToZip, callback) {
var _previousParentName = null;
var _index = filesToZip.length - 1;
for (; _index >= 0; _index--) {
@@ -352,12 +373,57 @@ function zipFiles (filesToZip, callback) {
if (_file.parent !== _previousParentName && _previousParentName !== null) {
break;
}
- if (Buffer.isBuffer(_file.data) === false) {
- try {
- _file.data = Buffer.from(_file.data, 'utf8');
+
+ // Check if there are odt binary tags in file data
+ if (_file.data.includes("<office:binary-data>")) {
+ let rx = /<office:binary-data>(.*)<\/office:binary-data>/g;
+ var match;
+ // eslint-disable-next-line no-cond-assign
+ while ((match = rx.exec(_file.data)) !== null) {
+ let url = match[1];
+ // Replace the base 64 url by the base64 file binary
+ if (url.includes("base64")) {
+ let str = url.split(";base64,").pop();
+ _file.data = file.data.split(url).join(Buffer.from(str, "base64"));
+ }
+ // Replace qrcode url by a base64 binary
+ else if (_file.data.includes("qrcode://")) {
+ let url = _file.data.replace("qrcode://", "");
+ let result = await generateQR(url);
+ let str = result.split(";base64,").pop();
+ _file.data = Buffer.from(str, 'base64');
+ }
+ // Replace the system file url by a base64 binary (odt must have only base64 binary)
+ else if (url.includes("file://")) {
+ let str = url.replace("file://", "");
+ _file.data = _file.data
+ .split(url)
+ .join(fs.readFileSync(str, { encoding: "base64" }));
+ }
}
- catch (e) {
- _file.data = Buffer.from('', 'utf8');
+ }
+ // Check if file data is a base64 file (docx), if so, encode it in a base64 buffer.
+ else if (_file.data.includes("base64")) {
+ let str = _file.data.split(";base64,").pop();
+ _file.data = Buffer.from(str, "base64");
+ }
+ // Check if file data is a file system url (docx), if so, encode it in a base64 buffer.
+ else if (_file.data.includes("file://")) {
+ let url = _file.data.replace("file://", "");
+ _file.data = fs.readFileSync(url);
+ }
+ else if (_file.data.includes("qrcode://")) {
+ let url = _file.data.replace("qrcode://", "");
+ let result = await generateQR(url);
+ let str = result.split(";base64,").pop();
+ _file.data = Buffer.from(str, 'base64');
+ }
+ // Otherwise encode the xml data in utf8 format (default)
+ else if (Buffer.isBuffer(_file.data) === false) {
+ try {
+ _file.data = Buffer.from(_file.data, "utf8");
+ } catch (e) {
+ _file.data = Buffer.from("", "utf8");
}
}
_previousParentName = _file.parent;
@@ -368,12 +434,19 @@ function zipFiles (filesToZip, callback) {
return callback(err, buffer);
}
filesToZip.unshift({
- name : _previousParentName,
- data : buffer,
- parent : ''
+ name: _previousParentName,
+ data: buffer,
+ parent: "",
});
return zipFiles(filesToZip, callback);
});
}
+const generateQR = async text => {
+
+ let res = await QRCode.toDataURL(text);
+ console.log(res);
+ return res;
+}
+
module.exports = file;
diff --git liimageprocessor.js liimageprocessor.js
new file mode 100644
index 0000000..4df6400
--- /dev/null
+++ liimageprocessor.js
@@ -0,0 +1,209 @@
+/* eslint-disable array-callback-return */
+var path = require("path");
+var xml2js = require("xml2js");
+var xpath = require("xml2js-xpath");
+var extend = require("util")._extend;
+var sizeOf = require("image-size");
+
+var imageprocessor = {
+ clearEmptyImages: function(document) {
+ xml2js.parseString(document.data, (err, root) => {
+ let builder = new xml2js.Builder();
+ var empty = xpath
+ .find(root, "//w:drawing")
+ .filter(
+ (x) => xpath.find(x, "//pic:pic/pic:nvPicPr/pic:cNvPr")[0].$.descr === '' && xpath.find(x, "//pic:pic/pic:nvPicPr/pic:cNvPr")[0].$.dynamic === "true");
+
+ empty.map(item => {
+ item["wp:anchor"] = null;
+ });
+
+ document.data = builder.buildObject(root);
+
+ });
+ return document;
+ },
+
+ processDynamicImage: function (
+ report,
+ state,
+ document,
+ drawing,
+ picture,
+ definition,
+ fullUrl
+ ) {
+ let builder = new xml2js.Builder();
+
+ var contains = definition.contains;
+
+ // If image is to be contained and not stretched
+ if (contains === "true") {
+ xml2js.parseString(document.data, (err, result) => {
+ document.data = imageprocessor.processImageUrl(
+ result,
+ true,
+ fullUrl,
+ picture,
+ drawing,
+ builder
+ );
+ });
+ }
+
+ var qrcode = definition.sqrcode ? true : false;
+
+ // Get the relation element
+ var relationId = xpath.find(
+ xpath.find(picture, "//pic:blipFill")[0],
+ "//a:blip"
+ )[0].$["r:embed"];
+
+ var relationNode = undefined;
+
+ // Get the relation node in relations document
+ if (document.name.includes("word/header")) {
+ var header = document.name.split("word/").join("");
+ relationNode = report.files.find((x) =>
+ x.name.includes("word/_rels/" + header + ".rels")
+ );
+ } else if (document.name.includes("word/footer")) {
+ var footer = document.name.split("word/").join("");
+ relationNode = report.files.find((x) =>
+ x.name.includes("word/_rels/" + footer + "rels")
+ );
+ } else {
+ relationNode = report.files.find((x) =>
+ x.name.includes("word/_rels/document.xml.rels")
+ );
+ }
+
+ // Parse the relation document
+ xml2js.parseString(relationNode.data, (err, relationMatch) => {
+ // Get all relations
+ var relations = xpath.find(relationMatch, "//Relationships");
+
+ // Get the relation with our id
+ var relation = xpath
+ .find(relationMatch, "//Relationships/Relationship")
+ .find((x) => x.$.Id === relationId);
+ let relationState = state.find((x) => x.key === relationId);
+
+ // If it as a tag in description and its not the first iteration
+ if (relationState && fullUrl) {
+ relationState.number += 1;
+
+ // Get the media of the relation
+ let media = report.files.find(
+ (x) => x.name === "word/" + relation.$.Target
+ );
+
+ // Get the corresponding relation node
+ let rel = relations[0].Relationship.find(
+ (x) => x.$.Id === relationId && x.$.Target === relation.$.Target
+ );
+
+ // Copy the relation and change media values
+ let newRel = {};
+ var name = relation.$.Target.split(".").join(relationState.number + ".");
+ newRel.$ = extend({}, rel.$);
+ newRel.$.Id = relationId + "_" + relationState.number;
+ newRel.$.Target = name;
+ relationMatch.Relationships.Relationship.push(newRel);
+
+ // Build the new relation document node
+
+ relationNode.data = builder.buildObject(relationMatch);
+
+ xml2js.parseString(document.data, (err, newResult) => {
+ // Find all pics
+ var pics = xpath.find(newResult, "//pic:pic");
+
+ // Find out working pic
+ let pic = pics.find(
+ (x) =>
+ xpath.find(xpath.find(x, "//pic:nvPicPr")[0], "//pic:cNvPr")[0].$
+ .descr === fullUrl
+ );
+
+ // Get the blip where the relation is setted and replace him by the new relation
+ let blip = pic["pic:blipFill"][0]["a:blip"][0];
+ blip.$["r:embed"] = blip.$["r:embed"] + "_" + relationState.number;
+ document.data = builder.buildObject(newResult);
+
+ // Extend the media
+ let newMedia = extend({}, media);
+ newMedia.name = "word/" + name;
+ newMedia.data = fullUrl;
+
+ // Remove the processed url for a inoquos relation tag
+ document.data = document.data
+ .split(fullUrl)
+ .join(relationId + "_" + relationState.number);
+
+ // Add the new media to report files
+ report.files.push(newMedia);
+ });
+ }
+ // If has tag and its first iterationresult
+ else if (fullUrl) {
+ state.push({key: relationId, number: 1});
+
+ // Find the media of the picture
+ let media = report.files.find(
+ (x) => x.name === "word/" + relation.$.Target
+ );
+
+ // Remove the processed url for a inoquos relation tag
+ document.data = document.data.split(fullUrl).join(relationId);
+
+ // Change the mock media binary data for the url (will be replaced in files.js by the binary)
+ media.data = qrcode ? "qrcode://" + fullUrl : fullUrl;
+ }
+ });
+ return {report: report, state: state};
+ },
+ processImageUrl: function(result, contains, fullUrl, match, drawing, builder) {
+ if (contains) {
+ let url = fullUrl;
+ let dimensions = null;
+ if (fullUrl.includes("file://")) {
+ url = fullUrl.replace("file://", "");
+ dimensions = sizeOf(url);
+ }
+ if (fullUrl.includes(";base64,")) {
+ url = fullUrl.split(";base64,").pop();
+ dimensions = sizeOf(Buffer.from(url, "base64"));
+ }
+
+ let spPr = xpath.find(match, "//pic:spPr")[0];
+ let size = spPr["a:xfrm"][0]["a:ext"][0].$;
+ if (dimensions) {
+ if (dimensions.width > dimensions.height) {
+ let heigth = Math.round(
+ (size.cx * (dimensions.height * 10000)) / (dimensions.width * 10000)
+ );
+ size.cy = heigth.toString();
+ drawing["wp:anchor"][0]["wp:extent"][0] = { $: size };
+ spPr["a:xfrm"][0]["a:ext"][0] = { $: size };
+ } else {
+ let width = Math.round(
+ (size.cy * (dimensions.width * 10000)) / (dimensions.height * 10000)
+ );
+ size.cx = width.toString();
+ drawing["wp:anchor"][0]["wp:extent"][0] = { $: size };
+ spPr["a:xfrm"][0]["a:ext"][0] = { $: size };
+ }
+ } else {
+ size.cx = "0";
+ size.cy = "0";
+ drawing["wp:anchor"][0]["wp:extent"][0] = { $: size };
+ spPr["a:xfrm"][0]["a:ext"][0] = { $: size };
+ spPr = null;
+ }
+ }
+ return builder.buildObject(result);
+ }
+}
+
+module.exports = imageprocessor;
\ No newline at end of file
diff --git liindex.js liindex.js
index e179a33..f473cca 100644
--- liindex.js
+++ liindex.js
@@ -1,22 +1,22 @@
-var fs = require('fs');
-var os = require('os');
-var path = require('path');
-var file = require('./file');
-var params = require('./params');
-var helper = require('./helper');
-var format = require('./format');
-var builder = require('./builder');
-var parser = require('./parser');
-var preprocessor = require('./preprocessor');
-var translator = require('./translator');
-var converter = require('./converter');
-var moment = require('moment');
-var locale = require('../formatters/_locale.js');
-var debug = require('debug')('carbone');
+var fs = require("fs");
+var os = require("os");
+var path = require("path");
+var file = require("./file");
+var params = require("./params");
+var helper = require("./helper");
+var format = require("./format");
+var builder = require("./builder");
+var parser = require("./parser");
+var preprocessor = require("./preprocessor");
+var postprocessor = require("./postprocessor");
+var translator = require("./translator");
+var converter = require("./converter");
+var moment = require("moment");
+var locale = require("../formatters/_locale.js");
+var debug = require("debug")("carbone");
var carbone = {
-
- formatters : {},
+ formatters: {},
/**
* This function is NOT asynchrone (It may create the template or temp directory synchronously)
@@ -31,28 +31,30 @@ var carbone = {
* currencyRates : rates, based on EUR { EUR : 1, USD : 1.14 }
* }
*/
- set : function (options) {
+ set: function (options) {
for (var attr in options) {
if (params[attr] !== undefined) {
params[attr] = options[attr];
- }
- else {
- throw Error('Undefined options :' + attr);
+ } else {
+ throw Error("Undefined options :" + attr);
}
}
if (options.templatePath !== undefined) {
if (fs.existsSync(params.templatePath) === false) {
- fs.mkdirSync(params.templatePath, '0755');
+ fs.mkdirSync(params.templatePath, "0755");
}
- if (fs.existsSync(path.join(params.templatePath, 'lang')) === false) {
- fs.mkdirSync(path.join(params.templatePath, 'lang'), '0755');
+ if (fs.existsSync(path.join(params.templatePath, "lang")) === false) {
+ fs.mkdirSync(path.join(params.templatePath, "lang"), "0755");
}
if (options.translations === undefined) {
translator.loadTranslations(params.templatePath);
}
}
- if (options.tempPath !== undefined && fs.existsSync(params.tempPath) === false) {
- fs.mkdirSync(params.tempPath, '0755');
+ if (
+ options.tempPath !== undefined &&
+ fs.existsSync(params.tempPath) === false
+ ) {
+ fs.mkdirSync(params.tempPath, "0755");
}
if (options.factories !== undefined || options.startFactory !== undefined) {
converter.init();
@@ -64,26 +66,29 @@ var carbone = {
/**
* Reset parameters (for test purpose)
*/
- reset : function () {
+ reset: function () {
// manage node 0.8 / 0.10 differences
- var _nodeVersion = process.versions.node.split('.');
- var _tmpDir = (parseInt(_nodeVersion[0], 10) === 0 && parseInt(_nodeVersion[1], 10) < 10) ? os.tmpDir() : os.tmpdir();
+ var _nodeVersion = process.versions.node.split(".");
+ var _tmpDir =
+ parseInt(_nodeVersion[0], 10) === 0 && parseInt(_nodeVersion[1], 10) < 10
+ ? os.tmpDir()
+ : os.tmpdir();
- params.tempPath = _tmpDir;
- params.templatePath = process.cwd();
- params.factories = 1;
- params.attempts = 2;
- params.startFactory = false;
- params.factoryMemoryFileSize = 1;
- params.factoryMemoryThreshold = 50;
+ params.tempPath = _tmpDir;
+ params.templatePath = process.cwd();
+ params.factories = 1;
+ params.attempts = 2;
+ params.startFactory = false;
+ params.factoryMemoryFileSize = 1;
+ params.factoryMemoryThreshold = 50;
params.converterFactoryTimeout = 60000;
- params.uidPrefix = 'c';
- params.pipeNamePrefix = '_carbone';
- params.lang = 'en';
- params.translations = {};
- params.currencySource = '';
- params.currencyTarget = '';
- params.currencyRates = { EUR : 1, USD : 1.14 };
+ params.uidPrefix = "c";
+ params.pipeNamePrefix = "_carbone";
+ params.lang = "en";
+ params.translations = {};
+ params.currencySource = "";
+ params.currencyTarget = "";
+ params.currencyRates = { EUR: 1, USD: 1.14 };
},
/**
@@ -92,7 +97,7 @@ var carbone = {
* @param {String|Buffer} data The content of the template
* @param {Function} callback(err) called when done
*/
- addTemplate : function (fileId, data, callback) {
+ addTemplate: function (fileId, data, callback) {
/* if(path.isAbsolute(fileId)===true){ //possible with Node v0.11
return callback('The file id should not be an absolute path: '+fileId);
}*/
@@ -106,7 +111,7 @@ var carbone = {
* add formatters
* @param {Object} formatters {toInt: function(d, args, agrs, ...)}
*/
- addFormatters : function (customFormatters) {
+ addFormatters: function (customFormatters) {
for (var f in customFormatters) {
carbone.formatters[f] = customFormatters[f];
}