jspdf-autotable
Version:
Generate pdf tables with javascript (jsPDF plugin)
1,348 lines (1,263 loc) • 675 kB
JavaScript
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var jsPDF = require('jspdf');
require('jspdf-autotable');
document.getElementById("pdf-button").onclick = function() {
generatePdf();
};
function generatePdf() {
var columns = ["ID", "Country", "Rank", "Capital"];
var data = [
[1, "Denmark", 7.526, "Copenhagen"],
[2, "Switzerland", 7.509, "Bern"],
[3, "Iceland", 7.501, "Reykjavík"],
[4, "Norway", 7.498, "Oslo"],
[5, "Finland", 7.413, "Helsinki"]
];
var doc = new jsPDF();
doc.autoTable(columns, data);
doc.output("dataurlnewwindow");
}
},{"jspdf":3,"jspdf-autotable":2}],2:[function(require,module,exports){
/*!
* jsPDF AutoTable plugin v2.2.0
* Copyright (c) 2014 Simon Bengtsson, https://github.com/simonbengtsson/jsPDF-AutoTable
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*
* */if (typeof window === 'object') window.jspdfAutoTableVersion = '2.2.0';/*
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("jspdf"));
else if(typeof define === 'function' && define.amd)
define(["jspdf"], factory);
else {
var a = typeof exports === 'object' ? factory(require("jspdf")) : factory(root["jsPDF"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function(__WEBPACK_EXTERNAL_MODULE_7__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 8);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
/**
* Ratio between font size and font height. The number comes from jspdf's source code
*/
exports.FONT_ROW_RATIO = 1.15;
var models_1 = __webpack_require__(4);
var jspdfInstance = null;
var userStyles = null;
var table = null;
var globalAddPageContent = null; // Set with doc.autoTableAddPageContent
var assign = __webpack_require__(3);
/**
* Styles for the themes (overriding the default styles)
*/
exports.getTheme = function (name) {
var themes = {
'striped': {
table: { fillColor: 255, textColor: 80, fontStyle: 'normal' },
header: { textColor: 255, fillColor: [41, 128, 185], fontStyle: 'bold' },
body: {},
alternateRow: { fillColor: 245 }
},
'grid': {
table: { fillColor: 255, textColor: 80, fontStyle: 'normal', lineWidth: 0.1 },
header: { textColor: 255, fillColor: [26, 188, 156], fontStyle: 'bold', lineWidth: 0 },
body: {},
alternateRow: {}
},
'plain': {
header: { fontStyle: 'bold' }
}
};
return themes[name];
};
function getDefaults() {
var scaleFactor = Config.scaleFactor();
return {
// Styling
theme: 'striped',
styles: {},
headerStyles: {},
bodyStyles: {},
alternateRowStyles: {},
columnStyles: {},
// Properties
startY: false,
margin: 40 / scaleFactor,
pageBreak: 'auto',
tableWidth: 'auto',
showHeader: 'everyPage',
// Hooks
createdHeaderCell: function (cell, data) { },
createdCell: function (cell, data) { },
drawHeaderRow: function (row, data) { },
drawRow: function (row, data) { },
drawHeaderCell: function (cell, data) { },
drawCell: function (cell, data) { },
addPageContent: function (data) { }
};
}
// Base style for all themes
function defaultStyles() {
var scaleFactor = Config.scaleFactor();
return {
font: "helvetica",
lineColor: 200,
fontStyle: 'normal',
overflow: 'ellipsize',
fillColor: false,
textColor: 20,
halign: 'left',
valign: 'top',
fontSize: 10,
cellPadding: 5 / scaleFactor,
lineWidth: 0 / scaleFactor,
columnWidth: 'auto'
};
}
var Config = (function () {
function Config() {
}
Config.pageSize = function () {
return Config.getJspdfInstance().internal.pageSize;
};
Config.setJspdfInstance = function (instance) {
jspdfInstance = instance;
userStyles = {
textColor: 30,
fontSize: jspdfInstance.internal.getFontSize(),
fontStyle: jspdfInstance.internal.getFont().fontStyle
};
};
Config.getJspdfInstance = function () {
return jspdfInstance;
};
// Styles before autotable was called
Config.getUserStyles = function () {
return userStyles;
};
Config.createTable = function (settings) {
table = new models_1.Table(settings);
};
Config.setPageContentHook = function (hook) {
globalAddPageContent = hook;
};
Config.callPageContentHook = function (data) {
if (typeof globalAddPageContent === 'function') {
globalAddPageContent(data);
}
};
Config.tableInstance = function () {
return table;
};
Config.scaleFactor = function () {
return jspdfInstance.internal.scaleFactor;
};
Config.hooksData = function (additionalData) {
if (additionalData === void 0) { additionalData = {}; }
return assign({
pageCount: table.pageCount,
settings: table.settings,
table: table,
doc: jspdfInstance,
cursor: table.cursor
}, additionalData || {});
};
Config.initSettings = function (userOptions) {
var settings = assign({}, getDefaults(), userOptions);
// Options
if (typeof settings.extendWidth !== 'undefined') {
settings.tableWidth = settings.extendWidth ? 'auto' : 'wrap';
console.error("Use of deprecated option: extendWidth, use tableWidth instead.");
}
if (typeof settings.margins !== 'undefined') {
if (typeof settings.margin === 'undefined')
settings.margin = settings.margins;
console.error("Use of deprecated option: margins, use margin instead.");
}
if (typeof settings.afterPageContent !== 'undefined' || typeof settings.beforePageContent !== 'undefined' || typeof settings.afterPageAdd !== 'undefined') {
console.error("The afterPageContent, beforePageContent and afterPageAdd hooks are deprecated. Use addPageContent instead");
if (typeof userOptions.addPageContent === 'undefined') {
settings.addPageContent = function (data) {
Config.applyStyles(Config.getUserStyles());
if (settings.beforePageContent)
settings.beforePageContent(data);
Config.applyStyles(Config.getUserStyles());
if (settings.afterPageContent)
settings.afterPageContent(data);
Config.applyStyles(Config.getUserStyles());
if (settings.afterPageAdd && data.pageCount > 1) {
data.afterPageAdd(data);
}
Config.applyStyles(Config.getUserStyles());
};
}
}
[['padding', 'cellPadding'], ['lineHeight', 'rowHeight'], 'fontSize', 'overflow'].forEach(function (o) {
var deprecatedOption = typeof o === 'string' ? o : o[0];
var style = typeof o === 'string' ? o : o[1];
if (typeof settings[deprecatedOption] !== 'undefined') {
if (typeof settings.styles[style] === 'undefined') {
settings.styles[style] = settings[deprecatedOption];
}
console.error("Use of deprecated option: " + deprecatedOption + ", use the style " + style + " instead.");
}
});
settings.margin = Config.marginOrPadding(settings.margin, 40);
return settings;
};
Config.marginOrPadding = function (value, defaultVal) {
var newValue = {};
['top', 'right', 'bottom', 'left'].forEach(function (side, i) {
newValue[side] = defaultVal / Config.scaleFactor();
if (typeof value === 'number') {
newValue[side] = value;
}
else if (Array.isArray(value) && typeof value[i] === 'number') {
newValue[side] = value[i];
}
else if (typeof value === 'object') {
if (typeof value[side] === 'number') {
newValue[side] = value[side];
}
else if ((side === 'right' || side === 'left') && typeof value['horizontal'] === 'number') {
newValue[side] = value['horizontal'];
}
else if ((side === 'top' || side === 'bottom') && typeof value['vertical'] === 'number') {
newValue[side] = value['vertical'];
}
}
});
return newValue;
};
Config.styles = function (styles) {
var defStyles = defaultStyles();
var newStyles = assign.apply(void 0, [{}, defStyles].concat(styles));
newStyles.cellPadding = Config.marginOrPadding(newStyles.cellPadding, defStyles.cellPadding);
return newStyles;
};
Config.applyStyles = function (styles) {
var doc = Config.getJspdfInstance();
var styleModifiers = {
fillColor: doc.setFillColor,
textColor: doc.setTextColor,
fontStyle: doc.setFontStyle,
lineColor: doc.setDrawColor,
lineWidth: doc.setLineWidth,
font: doc.setFont,
fontSize: doc.setFontSize
};
Object.keys(styleModifiers).forEach(function (name) {
var style = styles[name];
var modifier = styleModifiers[name];
if (typeof style !== 'undefined') {
if (Array.isArray(style)) {
modifier.apply(this, style);
}
else {
modifier(style);
}
}
});
};
return Config;
}());
exports.Config = Config;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var config_1 = __webpack_require__(0);
var painter_1 = __webpack_require__(2);
function getStringWidth(text, styles) {
var k = config_1.Config.scaleFactor();
var fontSize = styles.fontSize / k;
config_1.Config.applyStyles(styles);
text = Array.isArray(text) ? text : [text];
var maxWidth = 0;
text.forEach(function (line) {
var width = config_1.Config.getJspdfInstance().getStringUnitWidth(line);
if (width > maxWidth) {
maxWidth = width;
}
});
var precision = 10000 * k;
maxWidth = Math.floor(maxWidth * precision) / precision;
return maxWidth * fontSize;
}
exports.getStringWidth = getStringWidth;
/**
* Ellipsize the text to fit in the width
*/
function ellipsize(text, width, styles, ellipsizeStr) {
if (ellipsizeStr === void 0) { ellipsizeStr = '...'; }
if (Array.isArray(text)) {
var value_1 = [];
text.forEach(function (str, i) {
value_1[i] = ellipsize(str, width, styles, ellipsizeStr);
});
return value_1;
}
var precision = 10000 * config_1.Config.scaleFactor();
width = Math.ceil(width * precision) / precision;
if (width >= getStringWidth(text, styles)) {
return text;
}
while (width < getStringWidth(text + ellipsizeStr, styles)) {
if (text.length <= 1) {
break;
}
text = text.substring(0, text.length - 1);
}
return text.trim() + ellipsizeStr;
}
exports.ellipsize = ellipsize;
function addPage() {
// Add user content just before adding new page ensure it will
// be drawn above other things on the page
addContentHooks();
config_1.Config.getJspdfInstance().addPage();
var table = config_1.Config.tableInstance();
table.pageCount++;
table.cursor = { x: table.margin('left'), y: table.margin('top') };
if (table.settings.showHeader === true || table.settings.showHeader === 'everyPage') {
painter_1.printRow(table.headerRow, table.settings.drawHeaderRow, table.settings.drawHeaderCell);
}
}
exports.addPage = addPage;
function addContentHooks() {
config_1.Config.applyStyles(config_1.Config.getUserStyles());
config_1.Config.tableInstance().settings.addPageContent(config_1.Config.hooksData());
config_1.Config.applyStyles(config_1.Config.getUserStyles());
config_1.Config.callPageContentHook(config_1.Config.hooksData());
config_1.Config.applyStyles(config_1.Config.getUserStyles());
}
exports.addContentHooks = addContentHooks;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var config_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
function printFullRow(row, drawRowHook, drawCellHook) {
var remainingRowHeight = 0;
var remainingTexts = {};
var table = config_1.Config.tableInstance();
if (!canFitOnPage(row.height)) {
if (row.maxLineCount <= 1) {
common_1.addPage();
}
else {
// Modify the row to fit the current page and calculate text and height of partial row
row.spansMultiplePages = true;
var pageHeight = config_1.Config.getJspdfInstance().internal.pageSize.height;
var maxCellHeight = 0;
for (var j = 0; j < table.columns.length; j++) {
var col = table.columns[j];
var cell = row.cells[col.dataKey];
var k = config_1.Config.scaleFactor();
var fontHeight = cell.styles.fontSize / k * config_1.FONT_ROW_RATIO;
var vPadding = cell.styles.cellPadding.top + cell.styles.cellPadding.bottom / k;
var remainingPageSpace = pageHeight - table.cursor.y - table.margin('bottom');
var remainingLineCount = Math.floor((remainingPageSpace - vPadding) / fontHeight);
if (Array.isArray(cell.text) && cell.text.length > remainingLineCount) {
var remainingLines = cell.text.splice(remainingLineCount, cell.text.length);
remainingTexts[col.dataKey] = remainingLines;
var cellHeight = cell.text.length * fontHeight + vPadding;
if (cellHeight > maxCellHeight) {
maxCellHeight = cellHeight;
}
var rCellHeight = remainingLines.length * fontHeight + vPadding;
if (rCellHeight > remainingRowHeight) {
remainingRowHeight = rCellHeight;
}
}
}
// Reset row height since text are now removed
row.height = maxCellHeight;
}
}
printRow(row, drawRowHook, drawCellHook);
// Parts of the row is now printed. Time for adding a new page, prune
// the text and start over
if (Object.keys(remainingTexts).length > 0) {
for (var j = 0; j < table.columns.length; j++) {
var col = table.columns[j];
var cell = row.cells[col.dataKey];
cell.text = remainingTexts[col.dataKey] || '';
}
common_1.addPage();
row.pageCount++;
row.height = remainingRowHeight;
printFullRow(row, drawRowHook, drawCellHook);
}
}
exports.printFullRow = printFullRow;
function printRow(row, drawRowHook, drawCellHook) {
var table = config_1.Config.tableInstance();
row.y = table.cursor.y;
if (drawRowHook(row, config_1.Config.hooksData({ row: row, addPage: common_1.addPage })) === false) {
return;
}
table.cursor.x = table.margin('left');
for (var i = 0; i < table.columns.length; i++) {
var column = table.columns[i];
var cell = row.cells[column.dataKey];
if (!cell) {
continue;
}
config_1.Config.applyStyles(cell.styles);
cell.x = table.cursor.x;
cell.y = table.cursor.y;
cell.height = row.height;
cell.width = column.width;
if (cell.styles.valign === 'top') {
cell.textPos.y = table.cursor.y + cell.styles.cellPadding.top;
}
else if (cell.styles.valign === 'bottom') {
cell.textPos.y = table.cursor.y + row.height - cell.styles.cellPadding.bottom;
}
else {
cell.textPos.y = table.cursor.y + row.height / 2;
}
if (cell.styles.halign === 'right') {
cell.textPos.x = cell.x + cell.width - cell.styles.cellPadding.right;
}
else if (cell.styles.halign === 'center') {
cell.textPos.x = cell.x + cell.width / 2;
}
else {
cell.textPos.x = cell.x + cell.styles.cellPadding.left;
}
var data = config_1.Config.hooksData({ column: column, row: row, addPage: common_1.addPage });
if (drawCellHook(cell, data) !== false) {
var fillStyle = getFillStyle(cell.styles);
if (fillStyle) {
config_1.Config.getJspdfInstance().rect(cell.x, cell.y, cell.width, cell.height, fillStyle);
}
config_1.Config.getJspdfInstance().autoTableText(cell.text, cell.textPos.x, cell.textPos.y, {
halign: cell.styles.halign,
valign: cell.styles.valign
});
}
table.cursor.x += cell.width;
}
table.cursor.y += row.height;
}
exports.printRow = printRow;
function canFitOnPage(rowHeight) {
var table = config_1.Config.tableInstance();
var pos = rowHeight + table.cursor.y + table.margin('bottom');
return pos < config_1.Config.pageSize().height;
}
function getFillStyle(styles) {
var drawLine = styles.lineWidth > 0;
var drawBackground = styles.fillColor !== false;
if (drawLine && drawBackground) {
return 'DF'; // Fill then stroke
}
else if (drawLine) {
return 'S'; // Only stroke (transparent background)
}
else if (drawBackground) {
return 'F'; // Only fill, no stroke
}
else {
return false;
}
}
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
exports.table = {};
var Table = (function () {
function Table(settings) {
this.height = 0;
this.width = 0;
this.contentWidth = 0;
this.preferredWidth = 0;
this.rows = [];
this.columns = [];
this.headerRow = null;
this.pageCount = 1;
this.settings = settings;
this.cursor = {
x: this.margin('left'),
y: settings.startY === false ? this.margin('top') : settings.startY
};
}
Table.prototype.margin = function (side) {
return this.settings.margin[side];
};
return Table;
}());
exports.Table = Table;
var Row = (function () {
function Row(raw, index) {
this.cells = {};
this.spansMultiplePages = false;
this.pageCount = 1;
this.height = 0;
this.y = 0;
this.maxLineCount = 1;
this.raw = raw;
this.index = index;
}
return Row;
}());
exports.Row = Row;
var Cell = (function () {
function Cell(raw) {
this.styles = {};
this.text = '';
this.contentWidth = 0;
this.textPos = {};
this.height = 0;
this.width = 0;
this.x = 0;
this.y = 0;
this.raw = raw;
}
return Cell;
}());
exports.Cell = Cell;
var Column = (function () {
function Column(dataKey, index) {
this.options = {};
this.contentWidth = 0;
this.preferredWidth = 0;
this.widthStyle = 'auto';
this.width = 0;
this.x = 0;
this.dataKey = dataKey;
this.index = index;
}
return Column;
}());
exports.Column = Column;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var config_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
/**
* Calculate the column widths
*/
function calculateWidths(doc, pageWidth) {
var table = config_1.Config.tableInstance();
// Column and table content width
var fixedWidth = 0;
var autoWidth = 0;
var dynamicColumns = [];
table.columns.forEach(function (column) {
column.contentWidth = 0;
table.rows.concat(table.headerRow).forEach(function (row) {
var cell = row.cells[column.dataKey];
var hPadding = cell.styles.cellPadding.left + cell.styles.cellPadding.right;
cell.contentWidth = hPadding + common_1.getStringWidth(cell.text, cell.styles);
if (cell.contentWidth > column.contentWidth) {
column.contentWidth = cell.contentWidth;
}
});
table.contentWidth += column.contentWidth;
if (typeof column.widthStyle === 'number') {
column.preferredWidth = column.widthStyle;
fixedWidth += column.preferredWidth;
column.width = column.preferredWidth;
}
else if (column.widthStyle === 'wrap') {
column.preferredWidth = column.contentWidth;
fixedWidth += column.preferredWidth;
column.width = column.preferredWidth;
}
else {
column.preferredWidth = column.contentWidth;
autoWidth += column.contentWidth;
dynamicColumns.push(column);
}
table.preferredWidth += column.preferredWidth;
});
if (typeof table.settings.tableWidth === 'number') {
table.width = table.settings.tableWidth;
}
else if (table.settings.tableWidth === 'wrap') {
table.width = table.preferredWidth;
}
else {
table.width = pageWidth - table.margin('left') - table.margin('right');
}
distributeWidth(dynamicColumns, fixedWidth, autoWidth, 0);
// Row height, table height and text overflow
var all = table.rows.concat(table.headerRow);
all.forEach(function (row) {
table.columns.forEach(function (col) {
var cell = row.cells[col.dataKey];
config_1.Config.applyStyles(cell.styles);
var textSpace = col.width - cell.styles.cellPadding.left - cell.styles.cellPadding.right;
if (cell.styles.overflow === 'linebreak') {
// Add one pt to textSpace to fix rounding error
try {
cell.text = doc.splitTextToSize(cell.text, textSpace + 1, { fontSize: cell.styles.fontSize });
}
catch (e) {
if (e instanceof TypeError && Array.isArray(cell.text)) {
cell.text = doc.splitTextToSize(cell.text.join(' '), textSpace + 1, { fontSize: cell.styles.fontSize });
}
else {
throw e;
}
}
}
else if (cell.styles.overflow === 'ellipsize') {
cell.text = common_1.ellipsize(cell.text, textSpace, cell.styles);
}
else if (cell.styles.overflow === 'visible') {
}
else if (cell.styles.overflow === 'hidden') {
cell.text = common_1.ellipsize(cell.text, textSpace, cell.styles, '');
}
else if (typeof cell.styles.overflow === 'function') {
cell.text = cell.styles.overflow(cell.text, textSpace);
}
else {
console.error("Unrecognized overflow type: " + cell.styles.overflow);
}
var k = config_1.Config.scaleFactor();
var lineCount = Array.isArray(cell.text) ? cell.text.length : 1;
var fontHeight = cell.styles.fontSize / k * config_1.FONT_ROW_RATIO;
var vPadding = cell.styles.cellPadding.top + cell.styles.cellPadding.bottom;
cell.contentHeight = lineCount * fontHeight + vPadding;
if (cell.contentHeight > row.height) {
row.height = cell.contentHeight;
row.maxLineCount = lineCount;
}
});
table.height += row.height;
});
}
exports.calculateWidths = calculateWidths;
function distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth) {
var table = config_1.Config.tableInstance();
var extraWidth = table.width - staticWidth - dynamicColumnsContentWidth;
for (var i = 0; i < dynamicColumns.length; i++) {
var col = dynamicColumns[i];
var ratio = col.contentWidth / dynamicColumnsContentWidth;
// A column turned out to be none dynamic, start over recursively
var isNoneDynamic = col.contentWidth + extraWidth * ratio < fairWidth;
if (extraWidth < 0 && isNoneDynamic) {
dynamicColumns.splice(i, 1);
dynamicColumnsContentWidth -= col.contentWidth;
col.width = fairWidth;
staticWidth += col.width;
distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth);
break;
}
else {
col.width = col.contentWidth + extraWidth * ratio;
}
}
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var models_1 = __webpack_require__(4);
var config_1 = __webpack_require__(0);
var assign = __webpack_require__(3);
function validateInput(headers, data, options) {
if (!headers || typeof headers !== 'object') {
console.error("The headers should be an object or array, is: " + typeof headers);
}
if (!data || typeof data !== 'object') {
console.error("The data should be an object or array, is: " + typeof data);
}
if (!!options && typeof options !== 'object') {
console.error("The data should be an object or array, is: " + typeof data);
}
if (!Array.prototype.forEach) {
console.error("The current browser does not support Array.prototype.forEach which is required for " +
"jsPDF-AutoTable. You can try to polyfill it by including this script " +
"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill");
}
}
exports.validateInput = validateInput;
/**
* Create models from the user input
*
* @param inputHeaders
* @param inputData
*/
function createModels(inputHeaders, inputData) {
var splitRegex = /\r\n|\r|\n/g;
var table = config_1.Config.tableInstance();
var settings = table.settings;
var theme = config_1.getTheme(settings.theme);
// Header row and columns
var headerRow = new models_1.Row(inputHeaders, -1);
headerRow.index = -1;
// Columns and header row
inputHeaders.forEach(function (rawColumn, index) {
var dataKey = index;
if (typeof rawColumn.dataKey !== 'undefined') {
dataKey = rawColumn.dataKey;
}
else if (typeof rawColumn.key !== 'undefined') {
console.error("Deprecation warning: Use dataKey instead of key");
dataKey = rawColumn.key; // deprecated since 2.x
}
var col = new models_1.Column(dataKey, index);
col.widthStyle = config_1.Config.styles([theme.table, theme.header, settings.styles, settings.columnStyles[col.dataKey] || {}]).columnWidth;
table.columns.push(col);
var cell = new models_1.Cell(rawColumn);
cell.styles = config_1.Config.styles([theme.table, theme.header, settings.styles, settings.headerStyles]);
if (cell.raw instanceof HTMLElement) {
cell.text = (cell.raw.innerText || '').trim();
}
else {
var text = typeof cell.raw === 'object' ? cell.raw.title : cell.raw;
// Stringify 0 and false, but not undefined
cell.text = typeof cell.raw !== 'undefined' ? '' + text : '';
}
cell.text = cell.text.split(splitRegex);
headerRow.cells[dataKey] = cell;
settings.createdHeaderCell(cell, { column: col, row: headerRow, settings: settings });
});
table.headerRow = headerRow;
// Rows och cells
inputData.forEach(function (rawRow, i) {
var row = new models_1.Row(rawRow, i);
var rowStyles = i % 2 === 0 ? assign({}, theme.alternateRow, settings.alternateRowStyles) : {};
table.columns.forEach(function (column) {
var cell = new models_1.Cell(rawRow[column.dataKey]);
var colStyles = settings.columnStyles[column.dataKey] || {};
cell.styles = config_1.Config.styles([theme.table, theme.body, settings.styles, settings.bodyStyles, rowStyles, colStyles]);
if (cell.raw && cell.raw instanceof HTMLElement) {
cell.text = (cell.raw.innerText || '').trim();
}
else {
// Stringify 0 and false, but not undefined
cell.text = typeof cell.raw !== 'undefined' ? '' + cell.raw : '';
}
cell.text = cell.text.split(splitRegex);
row.cells[column.dataKey] = cell;
settings.createdCell(cell, config_1.Config.hooksData({ column: column, row: row }));
});
table.rows.push(row);
});
}
exports.createModels = createModels;
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_7__;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var jsPDF = __webpack_require__(7);
var config_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var painter_1 = __webpack_require__(2);
var calculator_1 = __webpack_require__(5);
var creator_1 = __webpack_require__(6);
/**
* Create a table from a set of rows and columns.
*
* @param {Object[]|String[]} headers 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} [userOptions={}] Options that will override the default ones
*/
jsPDF.API.autoTable = function (headers, data, userOptions) {
if (userOptions === void 0) { userOptions = {}; }
creator_1.validateInput(headers, data, userOptions);
config_1.Config.setJspdfInstance(this);
var doc = config_1.Config.getJspdfInstance();
config_1.Config.createTable(config_1.Config.initSettings(userOptions));
var table = config_1.Config.tableInstance();
var settings = table.settings;
// Create the table model with its columns, rows and cells
creator_1.createModels(headers, data);
calculator_1.calculateWidths(this, config_1.Config.pageSize().width);
var minTableBottomPos = settings.startY + settings.margin.bottom + table.headerRow.height;
if (settings.pageBreak === 'avoid') {
minTableBottomPos += table.height;
}
var pageHeight = config_1.Config.pageSize().height;
if ((settings.pageBreak === 'always' && settings.startY !== false) ||
(settings.startY !== false && minTableBottomPos > pageHeight)) {
config_1.Config.getJspdfInstance().addPage();
table.cursor.y = settings.margin.top;
}
config_1.Config.applyStyles(config_1.Config.getUserStyles());
if (settings.showHeader === true || settings.showHeader === 'firstPage' || settings.showHeader === 'everyPage') {
painter_1.printRow(table.headerRow, settings.drawHeaderRow, settings.drawHeaderCell);
}
config_1.Config.applyStyles(config_1.Config.getUserStyles());
table.rows.forEach(function (row) {
painter_1.printFullRow(row, settings.drawRow, settings.drawCell);
});
common_1.addContentHooks();
doc.autoTablePreviousCursor = table.cursor;
return this;
};
/**
* Returns the Y position of the last drawn cell
* @returns int
*/
jsPDF.API.autoTableEndPosY = function () {
var cursor = config_1.Config.getJspdfInstance().autoTablePreviousCursor;
if (cursor && typeof cursor.y === 'number') {
return cursor.y;
}
else {
return 0;
}
};
jsPDF.API.autoTableAddPageContent = function (hook) {
if (typeof hook !== "function") {
console.error("A function has to be provided to autoTableAddPageContent, got: " + typeof hook);
return;
}
config_1.Config.setPageContentHook(hook);
};
/**
* @deprecated Use data.addPage in hooks instead
*/
jsPDF.API.autoTableAddPage = function () {
common_1.addPage();
};
/**
* Parses an html table
*
* @param tableElem Html table element
* @param includeHiddenElements If to include hidden rows and columns (defaults to false)
* @returns Object Object with two properties, columns and rows
*/
jsPDF.API.autoTableHtmlToJson = function (tableElem, includeHiddenElements) {
includeHiddenElements = includeHiddenElements || false;
if (!tableElem || !(tableElem instanceof HTMLTableElement)) {
console.error("A HTMLTableElement has to be sent to autoTableHtmlToJson");
return null;
}
var columns = {}, rows = [];
var header = tableElem.rows[0];
for (var i = 0; i < header.cells.length; i++) {
var cell = header.cells[i];
var style = window.getComputedStyle(cell);
if (includeHiddenElements || style.display !== 'none') {
columns[i] = cell;
}
}
var _loop_1 = function (i) {
var tableRow = tableElem.rows[i];
var style = window.getComputedStyle(tableRow);
if (includeHiddenElements || style.display !== 'none') {
var rowData_1 = [];
Object.keys(columns).forEach(function (key) {
var cell = tableRow.cells[key];
rowData_1.push(cell);
});
rows.push(rowData_1);
}
};
for (var i = 1; i < tableElem.rows.length; i++) {
_loop_1(i);
}
var values = Object.keys(columns).map(function (key) { return columns[key]; });
return { columns: values, rows: rows, data: rows };
};
/**
* Improved text function with halign and valign support
* Inspiration from: http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113
*/
jsPDF.API.autoTableText = function (text, x, y, styles) {
if (typeof x !== 'number' || typeof y !== 'number') {
console.error('The x and y parameters are required. Missing for the text: ', text);
}
var k = this.internal.scaleFactor;
var fontSize = this.internal.getFontSize() / k;
var splitRegex = /\r\n|\r|\n/g;
var splitText = null;
var lineCount = 1;
if (styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right') {
splitText = typeof text === 'string' ? text.split(splitRegex) : text;
lineCount = splitText.length || 1;
}
// Align the top
y += fontSize * (2 - config_1.FONT_ROW_RATIO);
if (styles.valign === 'middle')
y -= (lineCount / 2) * fontSize * config_1.FONT_ROW_RATIO;
else if (styles.valign === 'bottom')
y -= lineCount * fontSize * config_1.FONT_ROW_RATIO;
if (styles.halign === 'center' || styles.halign === 'right') {
var alignSize = fontSize;
if (styles.halign === 'center')
alignSize *= 0.5;
if (lineCount >= 1) {
for (var iLine = 0; iLine < splitText.length; iLine++) {
this.text(splitText[iLine], x - this.getStringUnitWidth(splitText[iLine]) * alignSize, y);
y += fontSize;
}
return config_1.Config.getJspdfInstance();
}
x -= this.getStringUnitWidth(text) * alignSize;
}
this.text(text, x, y);
return config_1.Config.getJspdfInstance();
};
/***/ }
/******/ ]);
});
},{"jspdf":3}],3:[function(require,module,exports){
(function (global){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.jspdf = factory());
}(this, function () { 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
/** @preserve
* jsPDF - PDF Document creation from JavaScript
* Version 1.3.2 Built on 2016-09-30T20:33:17.116Z
* CommitID 7d854cc77d
*
* Copyright (c) 2010-2014 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
* 2010 Aaron Spike, https://github.com/acspike
* 2012 Willow Systems Corporation, willow-systems.com
* 2012 Pablo Hess, https://github.com/pablohess
* 2012 Florian Jenett, https://github.com/fjenett
* 2013 Warren Weckesser, https://github.com/warrenweckesser
* 2013 Youssef Beddad, https://github.com/lifof
* 2013 Lee Driscoll, https://github.com/lsdriscoll
* 2013 Stefan Slonevskiy, https://github.com/stefslon
* 2013 Jeremy Morel, https://github.com/jmorel
* 2013 Christoph Hartmann, https://github.com/chris-rock
* 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
* 2014 James Makes, https://github.com/dollaruw
* 2014 Diego Casorran, https://github.com/diegocr
* 2014 Steven Spungin, https://github.com/Flamenco
* 2014 Kenneth Glassey, https://github.com/Gavvers
*
* Licensed under the MIT License
*
* Contributor(s):
* siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
* kim3er, mfo, alnorth, Flamenco
*/
/**
* Creates new jsPDF document object instance.
*
* @class
* @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
* @param unit Measurement unit to be used when coordinates are specified.
* One of "pt" (points), "mm" (Default), "cm", "in"
* @param format One of 'pageFormats' as shown below, default: a4
* @returns {jsPDF}
* @name jsPDF
*/
var jsPDF = function (global) {
'use strict';
var pdfVersion = '1.3',
pageFormats = { // Size in pt of various paper formats
'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
'a6': [297.64, 419.53], 'a7': [209.76, 297.64],
'a8': [147.40, 209.76], 'a9': [104.88, 147.40],
'a10': [73.70, 104.88], 'b0': [2834.65, 4008.19],
'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63],
'b5': [498.90, 708.66], 'b6': [354.33, 498.90],
'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
'c0': [2599.37, 3676.54], 'c1': [1836.85, 2599.37],
'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
'c4': [649.13, 918.43], 'c5': [459.21, 649.13],
'c6': [323.15, 459.21], 'c7': [229.61, 323.15],
'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
'c10': [79.37, 113.39], 'dl': [311.81, 623.62],
'letter': [612, 792],
'government-letter': [576, 756],
'legal': [612, 1008],
'junior-legal': [576, 360],
'ledger': [1224, 792],
'tabloid': [792, 1224],
'credit-card': [153, 243]
};
/**
* jsPDF's Internal PubSub Implementation.
* See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
* Backward compatible rewritten on 2014 by
* Diego Casorran, https://github.com/diegocr
*
* @class
* @name PubSub
*/
function PubSub(context) {
var topics = {};
this.subscribe = function (topic, callback, once) {
if (typeof callback !== 'function') {
return false;
}
if (!topics.hasOwnProperty(topic)) {
topics[topic] = {};
}
var id = Math.random().toString(35);
topics[topic][id] = [callback, !!once];
return id;
};
this.unsubscribe = function (token) {
for (var topic in topics) {
if (topics[topic][token]) {
delete topics[topic][token];
return true;
}
}
return false;
};
this.publish = function (topic) {
if (topics.hasOwnProperty(topic)) {
var args = Array.prototype.slice.call(arguments, 1),
idr = [];
for (var id in topics[topic]) {
var sub = topics[topic][id];
try {
sub[0].apply(context, args);
} catch (ex) {
if (global.console) {
console.error('jsPDF PubSub Error', ex.message, ex);
}
}
if (sub[1]) idr.push(id);
}
if (idr.length) idr.forEach(this.unsubscribe);
}
};
}
/**
* @constructor
* @private
*/
function jsPDF(orientation, unit, format, compressPdf) {
var options = {};
if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
options = orientation;
orientation = options.orientation;
unit = options.unit || unit;
format = options.format || format;
compressPdf = options.compress || options.compressPdf || compressPdf;
}
// Default options
unit = unit || 'mm';
format = format || 'a4';
orientation = ('' + (orientation || 'P')).toLowerCase();
var format_as_string = ('' + format).toLowerCase(),
compress = !!compressPdf && typeof Uint8Array === 'function',
textColor = options.textColor || '0 g',
drawColor = options.drawColor || '0 G',
activeFontSize = options.fontSize || 16,
lineHeightProportion = options.lineHeight || 1.15,
lineWidth = options.lineWidth || 0.200025,
// 2mm
objectNumber = 2,
// 'n' Current object number
outToPages = !1,
// switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
offsets = [],
// List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
fonts = {},
// collection of font objects, where key is fontKey - a dynamically created label for a given font.
fontmap = {},
// mapping structure fontName > fontStyle > font key - performance layer. See addFont()
activeFontKey,
// will be string representing the KEY of the font as combination of fontName + fontStyle
k,
// Scale factor
tmp,
page = 0,
currentPage,
pages = [],
pagesContext = [],
// same index as pages and pagedim
pagedim = [],
content = [],
additionalObjects = [],
lineCapID = 0,
lineJoinID = 0,
content_length = 0,
pageWidth,
pageHeight,
pageMode,
zoomMode,
layoutMode,
documentProperties = {
'title': '',
'subject': '',
'author': '',
'keywords': '',
'creator': ''
},
API = {},
events = new PubSub(API),
/////////////////////
// Private functions
/////////////////////
f2 = function f2(number) {
return number.toFixed(2); // Ie, %.2f
},
f3 = function f3(number) {
return number.toFixed(3); // Ie, %.3f
},
padd2 = function padd2(number) {
return ('0' + parseInt(number)).slice(-2);
},
out = function out(string) {
if (outToPages) {
/* set by beginPage */
pages[currentPage].push(string);
} else {
// +1 for '\n' that will be used to join 'content'
content_length += string.length + 1;
content.push(string);
}
},
newObject = function newObject() {
// Begin a new object
objectNumber++;
offsets[objectNumber] = content_length;
out(objectNumber + ' 0 obj');