forked from voilab/voilab-pdf-table
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoilab-table.js
786 lines (710 loc) · 23.5 KB
/
voilab-table.js
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
/*jslint node: true, unparam: true, nomen: true */
'use strict';
var lodash = require('lodash'),
EventEmitter = require('events').EventEmitter,
getPaddingValue = function (direction, p) {
var l = p && p.length;
if (direction === 'vertical' || direction === 'horizontal') {
if (l === 1) {
return p[0] * 2;
}
if (l === 2) {
return direction === 'vertical' ? p[0] * 2 : p[1] * 2;
}
if (l === 3) {
return direction === 'vertical' ? p[0] + p[2] : p[1] * 2;
}
if (l === 4) {
return direction === 'vertical' ? p[0] + p[2] : p[1] + p[3];
}
}
if (l === 1) {
return p[0];
}
if (l === 2) {
return direction === 'top' || direction === 'bottom' ? p[0] : p[1];
}
if (l === 3) {
return direction === 'top' ? p[0] : (direction === 'bottom' ? p[2] : p[1]);
}
if (l === 4) {
return direction === 'top' ? p[0] : (
direction === 'bottom' ? p[2] : (
direction === 'left' ? p[3] : p[1]
)
);
}
return 0;
},
addCellBackground = function (self, column, row, pos, isHeader) {
self.pdf
.rect(pos.x, pos.y, column.width, row._renderedContent.height)
.fill();
},
addCellBorder = function (self, column, row, pos, isHeader) {
var border = isHeader ? column.headerBorder : column.border,
bpos = {
x: pos.x + column.width,
y: pos.y + row._renderedContent.height
};
if (border.indexOf('L') !== -1) {
self.pdf.moveTo(pos.x, pos.y).lineTo(pos.x, bpos.y).stroke();
}
if (border.indexOf('T') !== -1) {
self.pdf.moveTo(pos.x, pos.y).lineTo(bpos.x, pos.y).stroke();
}
if (border.indexOf('B') !== -1) {
self.pdf.moveTo(pos.x, bpos.y).lineTo(bpos.x, bpos.y).stroke();
}
if (border.indexOf('R') !== -1) {
self.pdf.moveTo(bpos.x, pos.y).lineTo(bpos.x, bpos.y).stroke();
}
},
addCell = function (self, column, row, pos, isHeader) {
var width = column.width,
padding = {
left: 0,
top: 0
},
data = row._renderedContent.data[column.id] || '',
renderer = isHeader ? column.headerRenderer : column.renderer,
y = pos.y;
if (!isHeader && column.padding) {
padding.left = getPaddingValue('left', column.padding);
padding.top = getPaddingValue('top', column.padding);
width -= getPaddingValue('horizontal', column.padding);
}
y += padding.top;
// if specified, cache is not used and renderer is called one more time
if (renderer && column.cache === false) {
data = renderer(self, row, true, column, lodash.clone(pos), padding);
}
// manage vertical alignement
if (column.valign === 'center') {
y += (row._renderedContent.height - row._renderedContent.dataHeight[column.id]) / 2;
} else if (column.valign === 'bottom') {
y += (row._renderedContent.height - row._renderedContent.dataHeight[column.id]);
}
self.pdf.text(data, pos.x + padding.left, y, lodash.assign({
height: row._renderedContent.height,
width: width
}, column));
pos.x += column.width;
},
addRow = function (self, row, isHeader) {
var pos = {
x: self.pdf.page.margins.left,
y: self.pdf.y
},
ev = {
cancel: false
};
// the content might be higher than the remaining height on the page.
if (self.pdf.y + row._renderedContent.height > self.pdf.page.height - self.pdf.page.margins.bottom - self.bottomMargin) {
self.emitter.emit('page-add', self, row, ev);
if (!ev.cancel) {
self.pdf.addPage();
// Reset Y position for next page
pos.y = self.pdf.page.margins.top;
}
self.emitter.emit('page-added', self, row);
}
lodash.forEach(self.getColumns(), function (column) {
if ((!isHeader && column.fill) || (isHeader && column.headerFill)) {
addCellBackground(self, column, row, pos, isHeader);
}
if ((!isHeader && column.border) || (isHeader && column.headerBorder)) {
addCellBorder(self, column, row, pos, isHeader);
}
addCell(self, column, row, pos, isHeader);
});
self.pdf.y = pos.y + row._renderedContent.height;
self.pdf.moveDown(self.minRowHeight);
},
setRowHeight = function (self, row, isHeader) {
var max_height = 0;
row._renderedContent = {data: {}, dataHeight: {}};
lodash.forEach(self.getColumns(), function (column) {
var renderer = isHeader ? column.headerRenderer : column.renderer,
content = renderer ? renderer(self, row, false) : row[column.id],
height = !content ? 1 : self.pdf.heightOfString(content, lodash.assign(lodash.clone(column), {
width: column.width - getPaddingValue('horizontal', column.padding)
})),
column_height = isHeader ? column.headerHeight : column.height;
if (height < column_height) {
height = column_height;
}
// backup content so we don't need to call the renderer a second
// time when really rendering the column
row._renderedContent.data[column.id] = content;
row._renderedContent.dataHeight[column.id] = height;
// check max row height
max_height = height > max_height ? height : max_height;
});
row._renderedContent.height = max_height;
},
PdfTable = function (pdf, conf) {
lodash.merge(this, {
/**
* List of columns
* @var {Array}
*/
columns: [],
/**
* Defaults for all new columns
* @var {Object}
*/
columnsDefaults: {},
/**
* List of plugins (do not set it at construction time)
* @var {Array}
*/
plugins: [],
/**
* The number to put inside the pdfkit.moveDown() method
* @var {Number}
*/
minRowHeight: 1,
/**
* Height of the bottom margin, in point
* @var {Number}
*/
bottomMargin: 5,
/**
* Check if we want to show headers when {@link addBody()}
* @var {Boolean}
*/
showHeaders: true,
/**
* Pdf in which the table will be drawn
* @var {PdfDocument}
*/
pdf: pdf,
/**
* Event emitter
* @var {EventEmitter}
*/
emitter: new EventEmitter()
}, lodash.cloneDeep(conf || {}));
};
lodash.assign(PdfTable.prototype, {
/**
* Add action before data rows are added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onBodyAdd: function (fn) {
this.emitter.on('body-add', fn);
return this;
},
/**
* Add action after data rows are added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onBodyAdded: function (fn) {
this.emitter.on('body-added', fn);
return this;
},
/**
* Add action before a row is added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the row to add</li>
* </ul>
* @return {PdfTable}
*/
onRowAdd: function (fn) {
this.emitter.on('row-add', fn);
return this;
},
/**
* Add action after a row is added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the added row</li>
* </ul>
* @return {PdfTable}
*/
onRowAdded: function (fn) {
this.emitter.on('row-added', fn);
return this;
},
/**
* Add action before a header is added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the header row to add</li>
* </ul>
* @return {PdfTable}
*/
onHeaderAdd: function (fn) {
this.emitter.on('header-add', fn);
return this;
},
/**
* Add action after a row is added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the added header row</li>
* </ul>
* @return {PdfTable}
*/
onHeaderAdded: function (fn) {
this.emitter.on('header-added', fn);
return this;
},
/**
* Add action before a page is added. You can use <em>ev.cancel = true</em>
* to cancel automatic page add, so you can do whatever you want to add
* a new page.
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the current row</li>
* <li><i>Object</i> <b>ev</b> the event</li>
* </ul>
* @return {PdfTable}
*/
onPageAdd: function (fn) {
this.emitter.on('page-add', fn);
return this;
},
/**
* Add action after a page is added.
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>row</b> the current row</li>
* </ul>
* @return {PdfTable}
*/
onPageAdded: function (fn) {
this.emitter.on('page-added', fn);
return this;
},
/**
* Add action before height is calculated for every row
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onRowHeightCalculate: function (fn) {
this.emitter.on('row-height-calculate', fn);
return this;
},
/**
* Add action after height is calculated for every row
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onRowHeightCalculated: function (fn) {
this.emitter.on('row-height-calculated', fn);
return this;
},
/**
* Add action before height is calculated for the header
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onHeaderHeightCalculate: function (fn) {
this.emitter.on('header-height-calculate', fn);
return this;
},
/**
* Add action after height is calculated for the header
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Array</i> <b>data</b> complete set of data rows</li>
* </ul>
* @return {PdfTable}
*/
onHeaderHeightCalculated: function (fn) {
this.emitter.on('header-height-calculated', fn);
return this;
},
/**
* Add action after a column is added
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>column</b> the added column</li>
* </ul>
* @return {PdfTable}
*/
onColumnAdded: function (fn) {
this.emitter.on('column-added', fn);
return this;
},
/**
* Add action after a column's property is changed
* <ul>
* <li><i>PdfTable</i> <b>table</b> PdfTable behind the event</li>
* <li><i>Object</i> <b>column</b> the column< that changed/li>
* <li><i>string</i> <b>prop</b> the property that changed</li>
* <li><i>mixed</i> <b>oldValue</b> the property value before change/li>
* </ul>
* @return {PdfTable}
*/
onColumnPropertyChanged: function (fn) {
this.emitter.on('column-property-changed', fn);
return this;
},
/**
* Temporary hack to manage overriden addPage() for pdfkit
*
* @deprecated
* @param {Function} fn
* @return {PdfTable}
*/
setNewPageFn: function (fn) {
console.log('setNewPageFn is deprecated. Adding a page during process is automatic now. It will be removed on the next release');
return this;
},
/**
* Add a plugin
*
* @param {Object} plugin the instanciated plugin
* @return {PdfTable}
*/
addPlugin: function (plugin) {
if (!plugin || !plugin.configure) {
throw new Error('Plugin [' + (plugin && plugin.id) + '] must have a configure() method.');
}
this.plugins.push(plugin);
plugin.configure(this);
return this;
},
/**
* Get a plugin
*
* @param {String} the plugin id
* @return {Object} the instanciated plugin
*/
getPlugin: function (id) {
return lodash.find(this.plugins, {id: id});
},
/**
* Remove a plugin and its events by the key
*
* @param {String} id the plugin id
* @return {PdfTable}
*/
removePlugin: function (id) {
lodash.remove(this.plugins, {id: id});
return this;
},
/**
* Determine if headers need to be displayed or not when .addBody
*
* @param {Boolean} show
* @return {PdfTable}
*/
setShowHeaders: function (show) {
this.showHeaders = !!show;
return this;
},
/**
* Define a column. Config array is mostly what we find in .text()
*
* <ul>
* <li><i>String</i> <b>id</b>: column id</li>
* <li><i>Function</i> <b>renderer</b>: renderer function for cell.
* Recieve (PdfTable table, row, draw).</li>
* <li><i>Boolean</i> <b>hidden</b>: True to define the column as
* hidden (default to false)</li>
* <li><i>String</i> <b>border</b>: cell border (LTBR)</li>
* <li><i>Number</i> <b>width</b>: column width</li>
* <li><i>Number</i> <b>height</b>: min height for cell (default to
* standard linebreak)</li>
* <li><i>String</i> <b>align</b>: text horizontal align (left, center,
* right)</li>
* <li><i>String</i> <b>valign</b>: text vertical align (top, center,
* bottom)</li>
* <li><i>Boolean</i> <b>fill</b>: True to fill the cell with the
* predefined color (with pdf.fillColor(color))</li>
* <li><i>Boolean</i> <b>cache</b>: false to disable cache content. The
* renderer will be called twice (at height calculation time and when
* really rendering the content)</li>
* </ul>
*
* Specific to column header
* <ul>
* <li><i>String</i> <b>header</b>: column header text</li>
* <li><i>Function</i> <b>headerRenderer</b>: renderer function for
* header cell. Recieve (PdfTable table, row)</li>
* <li><i>String</i> <b>headerBorder</b>: cell border (LTBR)</li>
* <li><i>Boolean</i> <b>headerFill</b>: True to fill the header with
* the predefined color (with pdf.fillColor(color))</li>
* <li><i>Number</i> <b>headerHeight</b>: min height for cell (default
* to standard linebreak)</li>
* </ul>
*
* Work in progress
* <ul>
* <li><i>Array</i> <b>padding</b>: padding for cell. Can be one number
* (same padding for LTBR), 2 numbers (same TB and LR) or 4 numbers</li>
* </ul>
*
* @param {Object} column
* @return {PdfTable}
*/
addColumn: function (column) {
this.columns.push(lodash.assign(lodash.clone(this.columnsDefaults || {}), column));
this.emitter.emit('column-added', this, column);
return this;
},
/**
* Set defaults for all new columns to add
*
* @see addColumn
* @param {Object} params
* @return {PdfTable}
*/
setColumnsDefaults: function (params) {
this.columnsDefaults = params;
return this;
},
/**
* Add many columns in one shot
*
* @see addColumn
* @param {Array} columns
* @return {PdfTable}
*/
addColumns: function (columns) {
return this.setColumns(columns, true);
},
/**
* Set columns in one shot
*
* @see addColumn
* @param {Array} columns
* @param {Boolean} add true to add these columns to existing columns
* @return {PdfTable}
*/
setColumns: function (columns, add) {
var self = this;
if (!add) {
this.columns = [];
}
lodash.forEach(columns, function (column) {
self.addColumn(column);
});
return this;
},
/**
* Get all table columns
*
* @param {Boolean} withHidden true to get hidden columns too
* @return {Array}
*/
getColumns: function (withHidden) {
return !withHidden
? lodash.filter(this.columns, function (column) {
return !column.hidden;
})
: this.columns;
},
/**
* Get a definition for a column
*
* @param {String} columnId
* @return {Object}
*/
getColumn: function (columnId) {
return lodash.find(this.columns, {id: columnId});
},
/**
* Get width between two columns. Widths of these columns are included in
* the sum.
*
* Example: table.getColumnWidthBetween('B', 'D');
* <pre>
* | A | B | C | D | E |
* | |-> | ->| ->| |
* </pre>
*
* If column A is empty, behave like {@link PdfTable.getColumnWidthUntil()}.
* If column B is empty, behave like {@link PdfTable.getColumnWidthFrom()}.
*
* @param {String} columnA start column
* @param {String} columnB last column
* @return {Number}
*/
getColumnWidthBetween: function (columnA, columnB) {
var width = 0,
check = false;
lodash.some(this.getColumns(), function (column) {
// begin sum either from start, or from column A
if (column.id === columnA || !columnA) {
check = true;
}
// stop sum if we want width from start to column B
if (!columnA && column.id === columnB) {
return true;
}
if (check) {
width += column.width;
}
if (column.id === columnB) {
return true;
}
});
return width;
},
/**
* Get width from start to the given column. Given width's column is not
* included in the sum.
*
* Example: table.getColumnWidthUntil('D');
* <pre>
* | A | B | C | D | E |
* |-> | ->| ->| | |
* </pre>
*
* @param {String} columnId column to stop sum
* @return {Number}
*/
getColumnWidthUntil: function (columnId) {
return this.getColumnWidthBetween(null, columnId);
},
/**
* Get width from a column to the end of the table. Given column's width is
* added to the sum.
*
* Example: table.getColumnWidthFrom('D');
* <pre>
* | A | B | C | D | E |
* | | | |-> | ->|
* </pre>
*
* @param {String} columnId the column from which we want to find the width
* @return {Number}
*/
getColumnWidthFrom: function (columnId) {
return this.getColumnWidthBetween(columnId, null);
},
/**
* Get table width (sum of all columns)
*
* @return {Number}
*/
getWidth: function () {
return this.getColumnWidthUntil(null, null);
},
/**
* Get column width
*
* @param {String} columnId
* @return {Number}
*/
getColumnWidth: function (columnId) {
return this.getColumnParam(columnId, 'width');
},
/**
* Set column width
*
* @param {String} columnId
* @param {Number} width
* @param {Boolean} silent True to prevent event to be emitted
* @return {PdfTable}
*/
setColumnWidth: function (columnId, width, silent) {
return this.setColumnParam(columnId, 'width', width, silent);
},
/**
* Get column param
*
* @param {String} columnId
* @param {String} param the desired param to fetch
* @return {mixed}
*/
getColumnParam: function (columnId, param) {
var column = this.getColumn(columnId);
return column && column[param];
},
/**
* Set a specific definition for a column
*
* @param {String} columnId column string index
* @param {String} key definition name (align, etc.)
* @param {mixed} value definition value
* @param {Boolean} silent True to prevent event to be emitted
* @return {PdfTable}
*/
setColumnParam: function (columnId, key, value, silent) {
var column = this.getColumn(columnId),
old_value;
if (column) {
old_value = column[key];
column[key] = value;
if (!silent) {
this.emitter.emit('column-property-changed', this, column, key, old_value);
}
}
return this;
},
/**
* Add content to the table
*
* @param {Array} data the complete set of data
* @return {PdfTable}
*/
addBody: function (data) {
var self = this;
this.emitter.emit('body-add', this, data);
if (!this.pdf.page) {
throw new Error("No page available. Add a page to the PDF before calling addBody()");
}
if (this.showHeaders) {
this.addHeader();
}
// calculate height for each row, depending on multiline contents
this.emitter.emit('row-height-calculate', this, data);
lodash.forEach(data, function (row) {
setRowHeight(self, row);
});
this.emitter.emit('row-height-calculated', this, data);
// really add rows, but now we know the exact height of each one
lodash.forEach(data, function (row) {
self.emitter.emit('row-add', self, row);
addRow(self, row);
self.emitter.emit('row-added', self, row);
});
this.emitter.emit('body-added', this, data);
// Issue #1, restore x position after table is drawn
this.pdf.x = this.pdf.page.margins.left;
return this;
},
/**
* Add table headers
*
* @return {PdfTable}
*/
addHeader: function () {
var row = lodash.reduce(this.getColumns(), function (acc, column) {
acc[column.id] = column.header;
return acc;
}, {});
this.emitter.emit('header-add', this, row);
this.emitter.emit('header-height-calculate', this, row);
setRowHeight(this, row, true);
this.emitter.emit('header-height-calculated', this, row);
addRow(this, row, true);
this.emitter.emit('header-added', this, row);
return this;
}
});
module.exports = PdfTable;