forked from simonbengtsson/jsPDF-AutoTable
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjspdf.plugin.autotable.js
318 lines (283 loc) · 11.6 KB
/
jspdf.plugin.autotable.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
/**
* jsPDF AutoTable plugin
* Copyright (c) 2014 Simon Bengtsson, https://github.com/someatoms/jsPDF-AutoTable
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*/
(function (API) {
'use strict';
// On every new jsPDF object, clear variables
API.events.push(['initialized', function () {
doc = undefined;
cellPos = undefined;
pageCount = 1;
settings = undefined;
}], false);
var MIN_COLUMN_WIDTH = 25;
var doc, cellPos, pageCount = 1, settings;
// See README.md or examples for documentation of the options
// return a new instance every time to avoid references issues
var defaultOptions = function () {
return {
padding: 5,
fontSize: 10,
lineHeight: 20,
renderHeader: function (doc, pageNumber, settings) {
},
renderFooter: function (doc, lastCellPos, pageNumber, settings) {
},
renderHeaderCell: function (x, y, width, height, key, value, settings) {
doc.setFillColor(52, 73, 94); // Asphalt
doc.setTextColor(255, 255, 255);
doc.setFontStyle('bold');
doc.rect(x, y, width, height, 'F');
y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2;
doc.text(value, x + settings.padding, y);
},
renderCell: function (x, y, width, height, key, value, row, settings) {
doc.setFillColor(row % 2 === 0 ? 245 : 255);
doc.setTextColor(50);
doc.rect(x, y, width, height, 'F');
y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5;
doc.text(value, x + settings.padding, y);
},
margins: {horizontal: 40, top: 50, bottom: 40},
startY: false,
overflow: 'ellipsize', // false, ellipsize or linebreak (false passes the raw text to renderCell)
overflowColumns: false, // Specify which colums that gets subjected to the overflow method chosen. false indicates all
avoidPageSplit: false,
extendWidth: true
}
};
/**
* Create a table from a set of rows and columns.
*
* @param {Object[]|String[]} columns Either as an array of objects or array of strings
* @param {Object[][]|String[][]} data Either as an array of objects or array of strings
* @param {Object} [options={}] Options that will override the default ones (above)
*/
API.autoTable = function (columns, data, options) {
options = options || {};
columns = columns || [];
doc = this;
var userFontSize = doc.internal.getFontSize();
initData({columns: columns, data: data});
initOptions(options);
cellPos = {
x: settings.margins.horizontal,
y: settings.startY === false ? settings.margins.top : settings.startY
};
var tableHeight = settings.margins.bottom + settings.margins.top + settings.lineHeight * (data.length + 1) + 5 + settings.startY;
if (settings.startY !== false && settings.avoidPageSplit && tableHeight > doc.internal.pageSize.height) {
doc.addPage();
cellPos.y = settings.margins.top;
}
settings.renderHeader(doc, pageCount, settings);
var columnWidths = calculateColumnWidths(data, columns);
printHeader(columns, columnWidths);
printRows(columns, data, columnWidths);
settings.renderFooter(doc, cellPos, pageCount, settings);
doc.setFontSize(userFontSize);
return this;
};
/**
* Returns the Y position of the last drawn cell
* @returns int
*/
API.autoTableEndPosY = function () {
// If cellPos is not set, autoTable() has probably not been called
return cellPos ? cellPos.y : false;
};
/**
* @deprecated Use autoTableEndPosY()
*/
API.autoTableEndPos = function () {
return cellPos;
};
/**
* Parses an html table. To draw a table, use it like this:
* `doc.autoTable(false, doc.autoTableHtmlToJson(tableDomElem))`
*
* @param table Html table element
* @returns [] Array of objects with object keys as headers
*/
API.autoTableHtmlToJson = function (table) {
var data = [], headers = {}, header = table.rows[0];
for (var i = 0; i < header.cells.length; i++) {
headers[i] = header.cells[i] ? header.cells[i].textContent : '';
}
for (i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < header.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j] ? tableRow.cells[j].textContent : '';
}
data.push(rowData);
}
return data;
};
/**
* Transform all to the object initialization form
* @param params
*/
function initData(params) {
// Object only initial
if (!params.columns || params.columns.length === 0) {
var keys = Object.keys(params.data[0]);
Array.prototype.push.apply(params.columns, keys);
params.columns.forEach(function (title, i) {
params.columns[i] = {title: title, key: keys[i]};
});
}
// Array initialization form
else if (typeof params.columns[0] === 'string') {
params.data.forEach(function (row, i) {
var obj = {};
for (var j = 0; j < row.length; j++) {
obj[j] = params.data[i][j];
}
params.data[i] = obj;
});
params.columns.forEach(function (title, i) {
params.columns[i] = {title: title, key: i};
});
}
}
function initOptions(raw) {
settings = defaultOptions();
Object.keys(raw).forEach(function (key) {
settings[key] = raw[key];
});
doc.setFontSize(settings.fontSize);
}
function calculateColumnWidths(rows, columns) {
var widths = {};
// Optimal widths
var optimalTableWidth = 0;
columns.forEach(function (header) {
var widest = getStringWidth(header.title || '');
rows.forEach(function (row) {
if (!header.hasOwnProperty('key'))
throw new Error("The key attribute is required in every header");
var w = getStringWidth(prop(row, header.key));
if (w > widest) {
widest = w;
}
});
widths[header.key] = widest;
optimalTableWidth += widest;
});
var paddingAndMargin = settings.padding * 2 * columns.length + settings.margins.horizontal * 2;
var spaceDiff = doc.internal.pageSize.width - optimalTableWidth - paddingAndMargin;
var keys = Object.keys(widths);
if (spaceDiff < 0) {
// Shrink columns
var shrinkableColumns = [];
var shrinkableColumnWidths = 0;
if(settings.overflowColumns === false) {
keys.forEach(function (key) {
if (widths[key] > MIN_COLUMN_WIDTH) {
shrinkableColumns.push(key);
shrinkableColumnWidths += widths[key];
}
});
} else {
shrinkableColumns = settings.overflowColumns;
shrinkableColumns.forEach(function(col) {
shrinkableColumnWidths += widths[col];
});
}
shrinkableColumns.forEach(function (key) {
widths[key] += spaceDiff * (widths[key] / shrinkableColumnWidths);
});
} else if (spaceDiff > 0 && settings.extendWidth) {
// Fill page horizontally
keys.forEach(function (key) {
widths[key] += spaceDiff / keys.length;
});
}
return widths;
}
function printHeader(headers, columnWidths) {
if (!headers) return;
headers.forEach(function (header) {
var width = columnWidths[header.key] + settings.padding * 2;
var title = ellipsize(columnWidths[header.key] || '', header.title || '');
settings.renderHeaderCell(cellPos.x, cellPos.y, width, settings.lineHeight + 5, header.key, title, settings);
cellPos.x += width;
});
doc.setTextColor(70, 70, 70);
doc.setFontStyle('normal');
cellPos.y += settings.lineHeight + 5;
cellPos.x = settings.margins.horizontal;
}
function printRows(headers, rows, columnWidths) {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var maxRows = 1;
if(settings.overflow === 'linebreak') {
headers.forEach(function (header) {
if(settings.overflowColumns !== false && settings.overflowColumns.indexOf(header.key) !== -1) {
var value = prop(row, header.key);
var arr = doc.splitTextToSize(value, columnWidths[header.key]);
if(arr.length > maxRows) {
maxRows = arr.length;
}
}
});
}
var rowHeight = settings.lineHeight + (maxRows - 1) * doc.internal.getLineHeight();
headers.forEach(function (header) {
var value = prop(row, header.key);
if(settings.overflow === 'linebreak') {
if(settings.overflowColumns !== false && settings.overflowColumns.indexOf(header.key) !== -1) {
value = doc.splitTextToSize(value, columnWidths[header.key]);
}
} else if(settings.overflow === 'ellipsize') {
value = ellipsize(columnWidths[header.key], value);
}
var width = columnWidths[header.key] + settings.padding * 2;
settings.renderCell(cellPos.x, cellPos.y, width, rowHeight, header.key, value, i, settings);
cellPos.x = cellPos.x + columnWidths[header.key] + settings.padding * 2;
});
var newPage = (cellPos.y + settings.margins.bottom + settings.lineHeight * 2) >= doc.internal.pageSize.height;
if (newPage) {
settings.renderFooter(doc, cellPos, pageCount, settings);
doc.addPage();
cellPos = {x: settings.margins.horizontal, y: settings.margins.top};
pageCount++;
settings.renderHeader(doc, pageCount, settings);
printHeader(headers, columnWidths);
} else {
cellPos.y += rowHeight;
cellPos.x = settings.margins.horizontal;
}
}
}
/**
* Ellipsize the text to fit in the width
* @param width
* @param text
*/
function ellipsize(width, text) {
if (width >= getStringWidth(text)) {
return text;
}
while (width < getStringWidth(text + "...")) {
if (text.length < 2) {
break;
}
text = text.substring(0, text.length - 1);
}
text += "...";
return text;
}
function prop(row, key) {
return row.hasOwnProperty(key) ? '' + row[key] : '';
}
function getStringWidth(txt) {
var isBold = doc.internal.getFont().fontStyle === 'bold';
return doc.getStringUnitWidth(txt) * doc.internal.getFontSize() + (isBold ? 5 : 0);
}
})(jsPDF.API);