You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2568 lines
97 KiB

  1. /**
  2. * @preserve tableExport.jquery.plugin
  3. *
  4. * Version 1.10.21
  5. *
  6. * Copyright (c) 2015-2020 hhurz, https://github.com/hhurz/tableExport.jquery.plugin
  7. *
  8. * Based on https://github.com/kayalshri/tableExport.jquery.plugin
  9. *
  10. * Licensed under the MIT License
  11. **/
  12. 'use strict';
  13. (function ($) {
  14. $.fn.tableExport = function (options) {
  15. var defaults = {
  16. csvEnclosure: '"',
  17. csvSeparator: ',',
  18. csvUseBOM: true,
  19. date: {
  20. html: 'dd/mm/yyyy' // Date format used in html source. Supported placeholders: dd, mm, yy, yyyy and a arbitrary single separator character
  21. },
  22. displayTableName: false, // Deprecated
  23. escape: false, // Deprecated
  24. exportHiddenCells: false, // true = speed up export of large tables with hidden cells (hidden cells will be exported !)
  25. fileName: 'tableExport',
  26. htmlContent: false,
  27. htmlHyperlink: 'content', // Export the 'content' or the 'href' link of <a> tags unless onCellHtmlHyperlink is not defined
  28. ignoreColumn: [],
  29. ignoreRow: [],
  30. jsonScope: 'all', // One of 'head', 'data', 'all'
  31. jspdf: { // jsPDF / jsPDF-AutoTable related options
  32. orientation: 'p',
  33. unit: 'pt',
  34. format: 'a4', // One of jsPDF page formats or 'bestfit' for automatic paper format selection
  35. margins: {left: 20, right: 10, top: 10, bottom: 10},
  36. onDocCreated: null,
  37. autotable: {
  38. styles: {
  39. cellPadding: 2,
  40. rowHeight: 12,
  41. fontSize: 8,
  42. fillColor: 255, // Color value or 'inherit' to use css background-color from html table
  43. textColor: 50, // Color value or 'inherit' to use css color from html table
  44. fontStyle: 'normal', // 'normal', 'bold', 'italic', 'bolditalic' or 'inherit' to use css font-weight and font-style from html table
  45. overflow: 'ellipsize', // 'visible', 'hidden', 'ellipsize' or 'linebreak'
  46. halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal cell alignment from html table
  47. valign: 'middle' // 'top', 'middle', or 'bottom'
  48. },
  49. headerStyles: {
  50. fillColor: [52, 73, 94],
  51. textColor: 255,
  52. fontStyle: 'bold',
  53. halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal header cell alignment from html table
  54. valign: 'middle' // 'top', 'middle', or 'bottom'
  55. },
  56. alternateRowStyles: {
  57. fillColor: 245
  58. },
  59. tableExport: {
  60. doc: null, // jsPDF doc object. If set, an already created doc object will be used to export to
  61. onAfterAutotable: null,
  62. onBeforeAutotable: null,
  63. onAutotableText: null,
  64. onTable: null,
  65. outputImages: true
  66. }
  67. }
  68. },
  69. mso: { // MS Excel and MS Word related options
  70. fileFormat: 'xlshtml', // 'xlshtml' = Excel 2000 html format
  71. // 'xmlss' = XML Spreadsheet 2003 file format (XMLSS)
  72. // 'xlsx' = Excel 2007 Office Open XML format
  73. onMsoNumberFormat: null, // Excel 2000 html format only. See readme.md for more information about msonumberformat
  74. pageFormat: 'a4', // Page format used for page orientation
  75. pageOrientation: 'portrait', // portrait, landscape (xlshtml format only)
  76. rtl: false, // true = Set worksheet option 'DisplayRightToLeft'
  77. styles: [], // E.g. ['border-bottom', 'border-top', 'border-left', 'border-right']
  78. worksheetName: '',
  79. xslx: { // Specific Excel 2007 XML format settings:
  80. formatId: { // XLSX format (id) used to format excel cells. See readme.md: data-tableexport-xlsxformatid
  81. date: 14, // formatId or format string (e.g. 'm/d/yy') or function(cell, row, col) {return formatId}
  82. numbers: 2 // formatId or format string (e.g. '\"T\"\ #0.00') or function(cell, row, col) {return formatId}
  83. }
  84. }
  85. },
  86. numbers: {
  87. html: {
  88. decimalMark: '.', // Decimal mark in html source
  89. thousandsSeparator: ',' // Thousands separator in html source
  90. },
  91. output: { // Set 'output: false' to keep number format of html source in resulting output
  92. decimalMark: '.', // Decimal mark in resulting output
  93. thousandsSeparator: ',' // Thousands separator in resulting output
  94. }
  95. },
  96. onAfterSaveToFile: null, // function(data, fileName)
  97. onBeforeSaveToFile: null, // saveIt = function(data, fileName, type, charset, encoding): Return false to abort save process
  98. onCellData: null, // Text to export = function($cell, row, col, href, cellText, cellType)
  99. onCellHtmlData: null, // Text to export = function($cell, row, col, htmlContent)
  100. onCellHtmlHyperlink: null, // Text to export = function($cell, row, col, href, cellText)
  101. onIgnoreRow: null, // ignoreRow = function($tr, row): Return true to prevent export of the row
  102. onTableExportBegin: null, // function() - called when export starts
  103. onTableExportEnd: null, // function() - called when export ends
  104. outputMode: 'file', // 'file', 'string', 'base64' or 'window' (experimental)
  105. pdfmake: {
  106. enabled: false, // true: use pdfmake instead of jspdf and jspdf-autotable (experimental)
  107. docDefinition: {
  108. pageOrientation: 'portrait', // 'portrait' or 'landscape'
  109. defaultStyle: {
  110. font: 'Roboto' // Default font is 'Roboto' (contained in vfs_fonts.js)
  111. } // For an arabic font include mirza_fonts.js instead of vfs_fonts.js
  112. }, // For a chinese font include either gbsn00lp_fonts.js or ZCOOLXiaoWei_fonts.js instead instead of vfs_fonts.js
  113. fonts: {}
  114. },
  115. preserve: {
  116. leadingWS: false, // preserve leading white spaces
  117. trailingWS: false // preserve trailing white spaces
  118. },
  119. preventInjection: true, // Prepend a single quote to cell strings that start with =,+,- or @ to prevent formula injection
  120. sql: {
  121. tableEnclosure: '`', // If table name or column names contain any characters except letters, numbers, and
  122. columnEnclosure: '`' // underscores, usually the name must be delimited by enclosing it in back quotes (`)
  123. },
  124. tbodySelector: 'tr',
  125. tfootSelector: 'tr', // Set empty ('') to prevent export of tfoot rows
  126. theadSelector: 'tr',
  127. tableName: 'Table',
  128. type: 'csv' // Export format: 'csv', 'tsv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf'
  129. };
  130. var pageFormats = { // Size in pt of various paper formats. Adopted from jsPDF.
  131. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94], 'a2': [1190.55, 1683.78],
  132. 'a3': [841.89, 1190.55], 'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
  133. 'a6': [297.64, 419.53], 'a7': [209.76, 297.64], 'a8': [147.40, 209.76],
  134. 'a9': [104.88, 147.40], 'a10': [73.70, 104.88],
  135. 'b0': [2834.65, 4008.19], 'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
  136. 'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63], 'b5': [498.90, 708.66],
  137. 'b6': [354.33, 498.90], 'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
  138. 'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
  139. 'c0': [2599.37, 3676.54],
  140. 'c1': [1836.85, 2599.37], 'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
  141. 'c4': [649.13, 918.43], 'c5': [459.21, 649.13], 'c6': [323.15, 459.21],
  142. 'c7': [229.61, 323.15], 'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
  143. 'c10': [79.37, 113.39],
  144. 'dl': [311.81, 623.62],
  145. 'letter': [612, 792], 'government-letter': [576, 756], 'legal': [612, 1008],
  146. 'junior-legal': [576, 360], 'ledger': [1224, 792], 'tabloid': [792, 1224],
  147. 'credit-card': [153, 243]
  148. };
  149. var FONT_ROW_RATIO = 1.15;
  150. var el = this;
  151. var DownloadEvt = null;
  152. var $hrows = [];
  153. var $rows = [];
  154. var rowIndex = 0;
  155. var trData = '';
  156. var colNames = [];
  157. var ranges = [];
  158. var blob;
  159. var $hiddenTableElements = [];
  160. var checkCellVisibilty = false;
  161. $.extend(true, defaults, options);
  162. // Adopt deprecated options
  163. if (defaults.type === 'xlsx') {
  164. defaults.mso.fileFormat = defaults.type;
  165. defaults.type = 'excel';
  166. }
  167. if (typeof defaults.excelFileFormat !== 'undefined' && defaults.mso.fileFormat === 'undefined')
  168. defaults.mso.fileFormat = defaults.excelFileFormat;
  169. if (typeof defaults.excelPageFormat !== 'undefined' && defaults.mso.pageFormat === 'undefined')
  170. defaults.mso.pageFormat = defaults.excelPageFormat;
  171. if (typeof defaults.excelPageOrientation !== 'undefined' && defaults.mso.pageOrientation === 'undefined')
  172. defaults.mso.pageOrientation = defaults.excelPageOrientation;
  173. if (typeof defaults.excelRTL !== 'undefined' && defaults.mso.rtl === 'undefined')
  174. defaults.mso.rtl = defaults.excelRTL;
  175. if (typeof defaults.excelstyles !== 'undefined' && defaults.mso.styles === 'undefined')
  176. defaults.mso.styles = defaults.excelstyles;
  177. if (typeof defaults.onMsoNumberFormat !== 'undefined' && defaults.mso.onMsoNumberFormat === 'undefined')
  178. defaults.mso.onMsoNumberFormat = defaults.onMsoNumberFormat;
  179. if (typeof defaults.worksheetName !== 'undefined' && defaults.mso.worksheetName === '')
  180. defaults.mso.worksheetName = defaults.worksheetName;
  181. // Check values of some options
  182. defaults.mso.pageOrientation = (defaults.mso.pageOrientation.substr(0, 1) === 'l') ? 'landscape' : 'portrait';
  183. defaults.date.html = defaults.date.html || '';
  184. if (defaults.date.html.length) {
  185. var patt = [];
  186. patt['dd'] = '(3[01]|[12][0-9]|0?[1-9])';
  187. patt['mm'] = '(1[012]|0?[1-9])';
  188. patt['yyyy'] = '((?:1[6-9]|2[0-2])\\d{2})';
  189. patt['yy'] = '(\\d{2})';
  190. var separator = defaults.date.html.match(/[^a-zA-Z0-9]/)[0];
  191. var formatItems = defaults.date.html.toLowerCase().split(separator);
  192. defaults.date.regex = '^\\s*';
  193. defaults.date.regex += patt[formatItems[0]];
  194. defaults.date.regex += '(.)'; // separator group
  195. defaults.date.regex += patt[formatItems[1]];
  196. defaults.date.regex += '\\2'; // identical separator group
  197. defaults.date.regex += patt[formatItems[2]];
  198. defaults.date.regex += '\\s*$';
  199. // e.g. '^\\s*(3[01]|[12][0-9]|0?[1-9])(.)(1[012]|0?[1-9])\\2((?:1[6-9]|2[0-2])\\d{2})\\s*$'
  200. defaults.date.pattern = new RegExp(defaults.date.regex, 'g');
  201. var f = formatItems.indexOf('dd') + 1;
  202. defaults.date.match_d = f + (f > 1 ? 1 : 0);
  203. f = formatItems.indexOf('mm') + 1;
  204. defaults.date.match_m = f + (f > 1 ? 1 : 0);
  205. f = (formatItems.indexOf('yyyy') >= 0 ? formatItems.indexOf('yyyy') : formatItems.indexOf('yy')) + 1;
  206. defaults.date.match_y = f + (f > 1 ? 1 : 0);
  207. }
  208. colNames = GetColumnNames(el);
  209. if (typeof defaults.onTableExportBegin === 'function')
  210. defaults.onTableExportBegin();
  211. if (defaults.type === 'csv' || defaults.type === 'tsv' || defaults.type === 'txt') {
  212. var csvData = '';
  213. var rowlength = 0;
  214. ranges = [];
  215. rowIndex = 0;
  216. var csvString = function (cell, rowIndex, colIndex) {
  217. var result = '';
  218. if (cell !== null) {
  219. var dataString = parseString(cell, rowIndex, colIndex);
  220. var csvValue = (dataString === null || dataString === '') ? '' : dataString.toString();
  221. if (defaults.type === 'tsv') {
  222. if (dataString instanceof Date)
  223. dataString.toLocaleString();
  224. // According to http://www.iana.org/assignments/media-types/text/tab-separated-values
  225. // are fields that contain tabs not allowable in tsv encoding
  226. result = replaceAll(csvValue, '\t', ' ');
  227. } else {
  228. // Takes a string and encapsulates it (by default in double-quotes) if it
  229. // contains the csv field separator, spaces, or linebreaks.
  230. if (dataString instanceof Date)
  231. result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure;
  232. else {
  233. result = preventInjection(csvValue);
  234. result = replaceAll(result, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure);
  235. if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result))
  236. result = defaults.csvEnclosure + result + defaults.csvEnclosure;
  237. }
  238. }
  239. }
  240. return result;
  241. };
  242. var CollectCsvData = function ($rows, rowselector, length) {
  243. $rows.each(function () {
  244. trData = '';
  245. ForEachVisibleCell(this, rowselector, rowIndex, length + $rows.length,
  246. function (cell, row, col) {
  247. trData += csvString(cell, row, col) + (defaults.type === 'tsv' ? '\t' : defaults.csvSeparator);
  248. });
  249. trData = $.trim(trData).substring(0, trData.length - 1);
  250. if (trData.length > 0) {
  251. if (csvData.length > 0)
  252. csvData += '\n';
  253. csvData += trData;
  254. }
  255. rowIndex++;
  256. });
  257. return $rows.length;
  258. };
  259. rowlength += CollectCsvData($(el).find('thead').first().find(defaults.theadSelector), 'th,td', rowlength);
  260. findTableElements($(el), 'tbody').each(function () {
  261. rowlength += CollectCsvData(findTableElements($(this), defaults.tbodySelector), 'td,th', rowlength);
  262. });
  263. if (defaults.tfootSelector.length)
  264. CollectCsvData($(el).find('tfoot').first().find(defaults.tfootSelector), 'td,th', rowlength);
  265. csvData += '\n';
  266. //output
  267. if (defaults.outputMode === 'string')
  268. return csvData;
  269. if (defaults.outputMode === 'base64')
  270. return base64encode(csvData);
  271. if (defaults.outputMode === 'window') {
  272. downloadFile(false, 'data:text/' + (defaults.type === 'csv' ? 'csv' : 'plain') + ';charset=utf-8,', csvData);
  273. return;
  274. }
  275. saveToFile(csvData,
  276. defaults.fileName + '.' + defaults.type,
  277. 'text/' + (defaults.type === 'csv' ? 'csv' : 'plain'),
  278. 'utf-8',
  279. '',
  280. (defaults.type === 'csv' && defaults.csvUseBOM));
  281. } else if (defaults.type === 'sql') {
  282. // Header
  283. rowIndex = 0;
  284. ranges = [];
  285. var tdData = 'INSERT INTO ' + defaults.sql.tableEnclosure + defaults.tableName + defaults.sql.tableEnclosure + ' (';
  286. $hrows = collectHeadRows($(el));
  287. $($hrows).each(function () {
  288. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  289. function (cell, row, col) {
  290. var colName = parseString(cell, row, col) || '';
  291. if (colName.indexOf(defaults.sql.columnEnclosure) > -1)
  292. colName = replaceAll(colName.toString(), defaults.sql.columnEnclosure, defaults.sql.columnEnclosure + defaults.sql.columnEnclosure);
  293. tdData += defaults.sql.columnEnclosure + colName + defaults.sql.columnEnclosure + ',';
  294. });
  295. rowIndex++;
  296. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  297. });
  298. tdData += ') VALUES ';
  299. // Data
  300. $rows = collectRows($(el));
  301. $($rows).each(function () {
  302. trData = '';
  303. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  304. function (cell, row, col) {
  305. var dataString = parseString(cell, row, col) || '';
  306. if (dataString.indexOf('\'') > -1)
  307. dataString = replaceAll(dataString.toString(), '\'', '\'\'');
  308. trData += '\'' + dataString + '\',';
  309. });
  310. if (trData.length > 3) {
  311. tdData += '(' + trData;
  312. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  313. tdData += '),';
  314. }
  315. rowIndex++;
  316. });
  317. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  318. tdData += ';';
  319. // Output
  320. if (defaults.outputMode === 'string')
  321. return tdData;
  322. if (defaults.outputMode === 'base64')
  323. return base64encode(tdData);
  324. saveToFile(tdData, defaults.fileName + '.sql', 'application/sql', 'utf-8', '', false);
  325. } else if (defaults.type === 'json') {
  326. var jsonHeaderArray = [];
  327. ranges = [];
  328. $hrows = collectHeadRows($(el));
  329. $($hrows).each(function () {
  330. var jsonArrayTd = [];
  331. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  332. function (cell, row, col) {
  333. jsonArrayTd.push(parseString(cell, row, col));
  334. });
  335. jsonHeaderArray.push(jsonArrayTd);
  336. });
  337. // Data
  338. var jsonArray = [];
  339. $rows = collectRows($(el));
  340. $($rows).each(function () {
  341. var jsonObjectTd = {};
  342. var colIndex = 0;
  343. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  344. function (cell, row, col) {
  345. if (jsonHeaderArray.length) {
  346. jsonObjectTd[jsonHeaderArray[jsonHeaderArray.length - 1][colIndex]] = parseString(cell, row, col);
  347. } else {
  348. jsonObjectTd[colIndex] = parseString(cell, row, col);
  349. }
  350. colIndex++;
  351. });
  352. if ($.isEmptyObject(jsonObjectTd) === false)
  353. jsonArray.push(jsonObjectTd);
  354. rowIndex++;
  355. });
  356. var sdata;
  357. if (defaults.jsonScope === 'head')
  358. sdata = JSON.stringify(jsonHeaderArray);
  359. else if (defaults.jsonScope === 'data')
  360. sdata = JSON.stringify(jsonArray);
  361. else // all
  362. sdata = JSON.stringify({header: jsonHeaderArray, data: jsonArray});
  363. if (defaults.outputMode === 'string')
  364. return sdata;
  365. if (defaults.outputMode === 'base64')
  366. return base64encode(sdata);
  367. saveToFile(sdata, defaults.fileName + '.json', 'application/json', 'utf-8', 'base64', false);
  368. } else if (defaults.type === 'xml') {
  369. rowIndex = 0;
  370. ranges = [];
  371. var xml = '<?xml version="1.0" encoding="utf-8"?>';
  372. xml += '<tabledata><fields>';
  373. // Header
  374. $hrows = collectHeadRows($(el));
  375. $($hrows).each(function () {
  376. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  377. function (cell, row, col) {
  378. xml += '<field>' + parseString(cell, row, col) + '</field>';
  379. });
  380. rowIndex++;
  381. });
  382. xml += '</fields><data>';
  383. // Data
  384. var rowCount = 1;
  385. $rows = collectRows($(el));
  386. $($rows).each(function () {
  387. var colCount = 1;
  388. trData = '';
  389. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  390. function (cell, row, col) {
  391. trData += '<column-' + colCount + '>' + parseString(cell, row, col) + '</column-' + colCount + '>';
  392. colCount++;
  393. });
  394. if (trData.length > 0 && trData !== '<column-1></column-1>') {
  395. xml += '<row id="' + rowCount + '">' + trData + '</row>';
  396. rowCount++;
  397. }
  398. rowIndex++;
  399. });
  400. xml += '</data></tabledata>';
  401. // Output
  402. if (defaults.outputMode === 'string')
  403. return xml;
  404. if (defaults.outputMode === 'base64')
  405. return base64encode(xml);
  406. saveToFile(xml, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false);
  407. } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xmlss') {
  408. var docDatas = [];
  409. var docNames = [];
  410. $(el).filter(function () {
  411. return isVisible($(this));
  412. }).each(function () {
  413. var $table = $(this);
  414. var ssName = '';
  415. if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length)
  416. ssName = defaults.mso.worksheetName + ' ' + (docNames.length + 1);
  417. else if (typeof defaults.mso.worksheetName[docNames.length] !== 'undefined')
  418. ssName = defaults.mso.worksheetName[docNames.length];
  419. if (!ssName.length)
  420. ssName = $table.find('caption').text() || '';
  421. if (!ssName.length)
  422. ssName = 'Table ' + (docNames.length + 1);
  423. ssName = $.trim(ssName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  424. docNames.push($('<div />').text(ssName).html());
  425. if (defaults.exportHiddenCells === false) {
  426. $hiddenTableElements = $table.find('tr, th, td').filter(':hidden');
  427. checkCellVisibilty = $hiddenTableElements.length > 0;
  428. }
  429. rowIndex = 0;
  430. colNames = GetColumnNames(this);
  431. docData = '<Table>\r';
  432. function CollectXmlssData ($rows, rowselector, length) {
  433. var spans = [];
  434. $($rows).each(function () {
  435. var ssIndex = 0;
  436. var nCols = 0;
  437. trData = '';
  438. ForEachVisibleCell(this, 'td,th', rowIndex, length + $rows.length,
  439. function (cell, row, col) {
  440. if (cell !== null) {
  441. var style = '';
  442. var data = parseString(cell, row, col);
  443. var type = 'String';
  444. if (jQuery.isNumeric(data) !== false) {
  445. type = 'Number';
  446. } else {
  447. var number = parsePercent(data);
  448. if (number !== false) {
  449. data = number;
  450. type = 'Number';
  451. style += ' ss:StyleID="pct1"';
  452. }
  453. }
  454. if (type !== 'Number')
  455. data = data.replace(/\n/g, '<br>');
  456. var colspan = getColspan(cell);
  457. var rowspan = getRowspan(cell);
  458. // Skip spans
  459. $.each(spans, function () {
  460. var range = this;
  461. if (rowIndex >= range.s.r && rowIndex <= range.e.r && nCols >= range.s.c && nCols <= range.e.c) {
  462. for (var i = 0; i <= range.e.c - range.s.c; ++i) {
  463. nCols++;
  464. ssIndex++;
  465. }
  466. }
  467. });
  468. // Handle Row Span
  469. if (rowspan || colspan) {
  470. rowspan = rowspan || 1;
  471. colspan = colspan || 1;
  472. spans.push({
  473. s: {r: rowIndex, c: nCols},
  474. e: {r: rowIndex + rowspan - 1, c: nCols + colspan - 1}
  475. });
  476. }
  477. // Handle Colspan
  478. if (colspan > 1) {
  479. style += ' ss:MergeAcross="' + (colspan - 1) + '"';
  480. nCols += (colspan - 1);
  481. }
  482. if (rowspan > 1) {
  483. style += ' ss:MergeDown="' + (rowspan - 1) + '" ss:StyleID="rsp1"';
  484. }
  485. if (ssIndex > 0) {
  486. style += ' ss:Index="' + (nCols + 1) + '"';
  487. ssIndex = 0;
  488. }
  489. trData += '<Cell' + style + '><Data ss:Type="' + type + '">' +
  490. $('<div />').text(data).html() +
  491. '</Data></Cell>\r';
  492. nCols++;
  493. }
  494. });
  495. if (trData.length > 0)
  496. docData += '<Row ss:AutoFitHeight="0">\r' + trData + '</Row>\r';
  497. rowIndex++;
  498. });
  499. return $rows.length;
  500. }
  501. var rowLength = CollectXmlssData(collectHeadRows($table), 'th,td', 0);
  502. CollectXmlssData(collectRows($table), 'td,th', rowLength);
  503. docData += '</Table>\r';
  504. docDatas.push(docData);
  505. });
  506. var count = {};
  507. var firstOccurences = {};
  508. var item, itemCount;
  509. for (var n = 0, c = docNames.length; n < c; n++) {
  510. item = docNames[n];
  511. itemCount = count[item];
  512. itemCount = count[item] = (itemCount == null ? 1 : itemCount + 1);
  513. if (itemCount === 2)
  514. docNames[firstOccurences[item]] = docNames[firstOccurences[item]].substring(0, 29) + '-1';
  515. if (count[item] > 1)
  516. docNames[n] = docNames[n].substring(0, 29) + '-' + count[item];
  517. else
  518. firstOccurences[item] = n;
  519. }
  520. var CreationDate = new Date().toISOString();
  521. var xmlssDocFile = '<?xml version="1.0" encoding="UTF-8"?>\r' +
  522. '<?mso-application progid="Excel.Sheet"?>\r' +
  523. '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\r' +
  524. ' xmlns:o="urn:schemas-microsoft-com:office:office"\r' +
  525. ' xmlns:x="urn:schemas-microsoft-com:office:excel"\r' +
  526. ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"\r' +
  527. ' xmlns:html="http://www.w3.org/TR/REC-html40">\r' +
  528. '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">\r' +
  529. ' <Created>' + CreationDate + '</Created>\r' +
  530. '</DocumentProperties>\r' +
  531. '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">\r' +
  532. ' <AllowPNG/>\r' +
  533. '</OfficeDocumentSettings>\r' +
  534. '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">\r' +
  535. ' <WindowHeight>9000</WindowHeight>\r' +
  536. ' <WindowWidth>13860</WindowWidth>\r' +
  537. ' <WindowTopX>0</WindowTopX>\r' +
  538. ' <WindowTopY>0</WindowTopY>\r' +
  539. ' <ProtectStructure>False</ProtectStructure>\r' +
  540. ' <ProtectWindows>False</ProtectWindows>\r' +
  541. '</ExcelWorkbook>\r' +
  542. '<Styles>\r' +
  543. ' <Style ss:ID="Default" ss:Name="Normal">\r' +
  544. ' <Alignment ss:Vertical="Bottom"/>\r' +
  545. ' <Borders/>\r' +
  546. ' <Font/>\r' +
  547. ' <Interior/>\r' +
  548. ' <NumberFormat/>\r' +
  549. ' <Protection/>\r' +
  550. ' </Style>\r' +
  551. ' <Style ss:ID="rsp1">\r' +
  552. ' <Alignment ss:Vertical="Center"/>\r' +
  553. ' </Style>\r' +
  554. ' <Style ss:ID="pct1">\r' +
  555. ' <NumberFormat ss:Format="Percent"/>\r' +
  556. ' </Style>\r' +
  557. '</Styles>\r';
  558. for (var j = 0; j < docDatas.length; j++) {
  559. xmlssDocFile += '<Worksheet ss:Name="' + docNames[j] + '" ss:RightToLeft="' + (defaults.mso.rtl ? '1' : '0') + '">\r' +
  560. docDatas[j];
  561. if (defaults.mso.rtl) {
  562. xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">\r' +
  563. '<DisplayRightToLeft/>\r' +
  564. '</WorksheetOptions>\r';
  565. } else
  566. xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"/>\r';
  567. xmlssDocFile += '</Worksheet>\r';
  568. }
  569. xmlssDocFile += '</Workbook>\r';
  570. if (defaults.outputMode === 'string')
  571. return xmlssDocFile;
  572. if (defaults.outputMode === 'base64')
  573. return base64encode(xmlssDocFile);
  574. saveToFile(xmlssDocFile, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false);
  575. } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xlsx') {
  576. var sheetNames = [];
  577. var workbook = XLSX.utils.book_new();
  578. // Multiple worksheets and .xlsx file extension #202
  579. $(el).filter(function () {
  580. return isVisible($(this));
  581. }).each(function () {
  582. var $table = $(this);
  583. var ws = xlsxTableToSheet(this);
  584. var sheetName = '';
  585. if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length)
  586. sheetName = defaults.mso.worksheetName + ' ' + (sheetNames.length + 1);
  587. else if (typeof defaults.mso.worksheetName[sheetNames.length] !== 'undefined')
  588. sheetName = defaults.mso.worksheetName[sheetNames.length];
  589. if (!sheetName.length)
  590. sheetName = $table.find('caption').text() || '';
  591. if (!sheetName.length)
  592. sheetName = 'Table ' + (sheetNames.length + 1);
  593. sheetName = $.trim(sheetName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  594. sheetNames.push(sheetName);
  595. XLSX.utils.book_append_sheet(workbook, ws, sheetName);
  596. });
  597. // add worksheet to workbook
  598. var wbout = XLSX.write(workbook, {type: 'binary', bookType: defaults.mso.fileFormat, bookSST: false});
  599. saveToFile(xlsxWorkbookToArrayBuffer(wbout),
  600. defaults.fileName + '.' + defaults.mso.fileFormat,
  601. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  602. 'UTF-8', '', false);
  603. } else if (defaults.type === 'excel' || defaults.type === 'xls' || defaults.type === 'word' || defaults.type === 'doc') {
  604. var MSDocType = (defaults.type === 'excel' || defaults.type === 'xls') ? 'excel' : 'word';
  605. var MSDocExt = (MSDocType === 'excel') ? 'xls' : 'doc';
  606. var MSDocSchema = 'xmlns:x="urn:schemas-microsoft-com:office:' + MSDocType + '"';
  607. var docData = '';
  608. var docName = '';
  609. $(el).filter(function () {
  610. return isVisible($(this));
  611. }).each(function () {
  612. var $table = $(this);
  613. if (docName === '') {
  614. docName = defaults.mso.worksheetName || $table.find('caption').text() || 'Table';
  615. docName = $.trim(docName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  616. }
  617. if (defaults.exportHiddenCells === false) {
  618. $hiddenTableElements = $table.find('tr, th, td').filter(':hidden');
  619. checkCellVisibilty = $hiddenTableElements.length > 0;
  620. }
  621. rowIndex = 0;
  622. ranges = [];
  623. colNames = GetColumnNames(this);
  624. // Header
  625. docData += '<table><thead>';
  626. $hrows = collectHeadRows($table);
  627. $($hrows).each(function () {
  628. var $row = $(this);
  629. trData = '';
  630. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  631. function (cell, row, col) {
  632. if (cell !== null) {
  633. var thstyle = '';
  634. trData += '<th';
  635. if (defaults.mso.styles.length) {
  636. var cellstyles = document.defaultView.getComputedStyle(cell, null);
  637. var rowstyles = document.defaultView.getComputedStyle($row[0], null);
  638. for (var cssStyle in defaults.mso.styles) {
  639. var thcss = cellstyles[defaults.mso.styles[cssStyle]];
  640. if (thcss === '')
  641. thcss = rowstyles[defaults.mso.styles[cssStyle]];
  642. if (thcss !== '' && thcss !== '0px none rgb(0, 0, 0)' && thcss !== 'rgba(0, 0, 0, 0)') {
  643. thstyle += (thstyle === '') ? 'style="' : ';';
  644. thstyle += defaults.mso.styles[cssStyle] + ':' + thcss;
  645. }
  646. }
  647. }
  648. if (thstyle !== '')
  649. trData += ' ' + thstyle + '"';
  650. var tdcolspan = getColspan(cell);
  651. if (tdcolspan > 0)
  652. trData += ' colspan="' + tdcolspan + '"';
  653. var tdrowspan = getRowspan(cell);
  654. if (tdrowspan > 0)
  655. trData += ' rowspan="' + tdrowspan + '"';
  656. trData += '>' + parseString(cell, row, col) + '</th>';
  657. }
  658. });
  659. if (trData.length > 0)
  660. docData += '<tr>' + trData + '</tr>';
  661. rowIndex++;
  662. });
  663. docData += '</thead><tbody>';
  664. // Data
  665. $rows = collectRows($table);
  666. $($rows).each(function () {
  667. var $row = $(this);
  668. trData = '';
  669. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  670. function (cell, row, col) {
  671. if (cell !== null) {
  672. var tdvalue = parseString(cell, row, col);
  673. var tdstyle = '';
  674. var tdcss = $(cell).attr('data-tableexport-msonumberformat');
  675. if (typeof tdcss === 'undefined' && typeof defaults.mso.onMsoNumberFormat === 'function')
  676. tdcss = defaults.mso.onMsoNumberFormat(cell, row, col);
  677. if (typeof tdcss !== 'undefined' && tdcss !== '')
  678. tdstyle = 'style="mso-number-format:\'' + tdcss + '\'';
  679. if (defaults.mso.styles.length) {
  680. var cellstyles = document.defaultView.getComputedStyle(cell, null);
  681. var rowstyles = document.defaultView.getComputedStyle($row[0], null);
  682. for (var cssStyle in defaults.mso.styles) {
  683. tdcss = cellstyles[defaults.mso.styles[cssStyle]];
  684. if (tdcss === '')
  685. tdcss = rowstyles[defaults.mso.styles[cssStyle]];
  686. if (tdcss !== '' && tdcss !== '0px none rgb(0, 0, 0)' && tdcss !== 'rgba(0, 0, 0, 0)') {
  687. tdstyle += (tdstyle === '') ? 'style="' : ';';
  688. tdstyle += defaults.mso.styles[cssStyle] + ':' + tdcss;
  689. }
  690. }
  691. }
  692. trData += '<td';
  693. if (tdstyle !== '')
  694. trData += ' ' + tdstyle + '"';
  695. var tdcolspan = getColspan(cell);
  696. if (tdcolspan > 0)
  697. trData += ' colspan="' + tdcolspan + '"';
  698. var tdrowspan = getRowspan(cell);
  699. if (tdrowspan > 0)
  700. trData += ' rowspan="' + tdrowspan + '"';
  701. if (typeof tdvalue === 'string' && tdvalue !== '') {
  702. tdvalue = preventInjection(tdvalue);
  703. tdvalue = tdvalue.replace(/\n/g, '<br>');
  704. }
  705. trData += '>' + tdvalue + '</td>';
  706. }
  707. });
  708. if (trData.length > 0)
  709. docData += '<tr>' + trData + '</tr>';
  710. rowIndex++;
  711. });
  712. if (defaults.displayTableName)
  713. docData += '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>' + defaults.tableName + '</p>')) + '</td></tr>';
  714. docData += '</tbody></table>';
  715. });
  716. //noinspection XmlUnusedNamespaceDeclaration
  717. var docFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + MSDocSchema + ' xmlns="http://www.w3.org/TR/REC-html40">';
  718. docFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + MSDocType + '; charset=UTF-8">';
  719. docFile += '<head>';
  720. if (MSDocType === 'excel') {
  721. docFile += '<!--[if gte mso 9]>';
  722. docFile += '<xml>';
  723. docFile += '<x:ExcelWorkbook>';
  724. docFile += '<x:ExcelWorksheets>';
  725. docFile += '<x:ExcelWorksheet>';
  726. docFile += '<x:Name>';
  727. docFile += docName;
  728. docFile += '</x:Name>';
  729. docFile += '<x:WorksheetOptions>';
  730. docFile += '<x:DisplayGridlines/>';
  731. if (defaults.mso.rtl)
  732. docFile += '<x:DisplayRightToLeft/>';
  733. docFile += '</x:WorksheetOptions>';
  734. docFile += '</x:ExcelWorksheet>';
  735. docFile += '</x:ExcelWorksheets>';
  736. docFile += '</x:ExcelWorkbook>';
  737. docFile += '</xml>';
  738. docFile += '<![endif]-->';
  739. }
  740. docFile += '<style>';
  741. docFile += '@page { size:' + defaults.mso.pageOrientation + '; mso-page-orientation:' + defaults.mso.pageOrientation + '; }';
  742. docFile += '@page Section1 {size:' + pageFormats[defaults.mso.pageFormat][0] + 'pt ' + pageFormats[defaults.mso.pageFormat][1] + 'pt';
  743. docFile += '; margin:1.0in 1.25in 1.0in 1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}';
  744. docFile += 'div.Section1 {page:Section1;}';
  745. docFile += '@page Section2 {size:' + pageFormats[defaults.mso.pageFormat][1] + 'pt ' + pageFormats[defaults.mso.pageFormat][0] + 'pt';
  746. docFile += ';mso-page-orientation:' + defaults.mso.pageOrientation + ';margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}';
  747. docFile += 'div.Section2 {page:Section2;}';
  748. docFile += 'br {mso-data-placement:same-cell;}';
  749. docFile += '</style>';
  750. docFile += '</head>';
  751. docFile += '<body>';
  752. docFile += '<div class="Section' + ((defaults.mso.pageOrientation === 'landscape') ? '2' : '1') + '">';
  753. docFile += docData;
  754. docFile += '</div>';
  755. docFile += '</body>';
  756. docFile += '</html>';
  757. if (defaults.outputMode === 'string')
  758. return docFile;
  759. if (defaults.outputMode === 'base64')
  760. return base64encode(docFile);
  761. saveToFile(docFile, defaults.fileName + '.' + MSDocExt, 'application/vnd.ms-' + MSDocType, '', 'base64', false);
  762. } else if (defaults.type === 'png') {
  763. html2canvas($(el)[0]).then(
  764. function (canvas) {
  765. var image = canvas.toDataURL();
  766. var byteString = atob(image.substring(22)); // remove data stuff
  767. var buffer = new ArrayBuffer(byteString.length);
  768. var intArray = new Uint8Array(buffer);
  769. for (var i = 0; i < byteString.length; i++)
  770. intArray[i] = byteString.charCodeAt(i);
  771. if (defaults.outputMode === 'string')
  772. return byteString;
  773. if (defaults.outputMode === 'base64')
  774. return base64encode(image);
  775. if (defaults.outputMode === 'window') {
  776. window.open(image);
  777. return;
  778. }
  779. saveToFile(buffer, defaults.fileName + '.png', 'image/png', '', '', false);
  780. });
  781. } else if (defaults.type === 'pdf') {
  782. if (defaults.pdfmake.enabled === true) {
  783. // pdf output using pdfmake
  784. // https://github.com/bpampuch/pdfmake
  785. var docDefinition = {
  786. content: []
  787. };
  788. $.extend(true, docDefinition, defaults.pdfmake.docDefinition);
  789. ranges = [];
  790. $(el).filter(function () {
  791. return isVisible($(this));
  792. }).each(function () {
  793. var $table = $(this);
  794. var widths = [];
  795. var body = [];
  796. rowIndex = 0;
  797. /**
  798. * @return {number}
  799. */
  800. var CollectPdfmakeData = function ($rows, colselector, length) {
  801. var rlength = 0;
  802. $($rows).each(function () {
  803. var r = [];
  804. ForEachVisibleCell(this, colselector, rowIndex, length,
  805. function (cell, row, col) {
  806. if (typeof cell !== 'undefined' && cell !== null) {
  807. var colspan = getColspan(cell);
  808. var rowspan = getRowspan(cell);
  809. var cellValue = parseString(cell, row, col) || ' ';
  810. if (colspan > 1 || rowspan > 1) {
  811. colspan = colspan || 1;
  812. rowspan = rowspan || 1;
  813. r.push({colSpan: colspan, rowSpan: rowspan, text: cellValue});
  814. } else
  815. r.push(cellValue);
  816. } else
  817. r.push(' ');
  818. });
  819. if (r.length)
  820. body.push(r);
  821. if (rlength < r.length)
  822. rlength = r.length;
  823. rowIndex++;
  824. });
  825. return rlength;
  826. };
  827. $hrows = collectHeadRows($table);
  828. var colcount = CollectPdfmakeData($hrows, 'th,td', $hrows.length);
  829. for (var i = widths.length; i < colcount; i++)
  830. widths.push('*');
  831. // Data
  832. $rows = collectRows($table);
  833. CollectPdfmakeData($rows, 'th,td', $hrows.length + $rows.length);
  834. docDefinition.content.push({ table: {
  835. headerRows: $hrows.length,
  836. widths: widths,
  837. body: body
  838. },
  839. pageBreak: docDefinition.content.length ? "before" : undefined
  840. });
  841. }); // ...for each table
  842. if (typeof pdfMake !== 'undefined') {
  843. pdfMake.fonts = {
  844. Roboto: {
  845. normal: 'Roboto-Regular.ttf',
  846. bold: 'Roboto-Medium.ttf',
  847. italics: 'Roboto-Italic.ttf',
  848. bolditalics: 'Roboto-MediumItalic.ttf'
  849. }
  850. };
  851. if (pdfMake.vfs.hasOwnProperty ('Mirza-Regular.ttf')) {
  852. defaults.pdfmake.docDefinition.defaultStyle.font = 'Mirza';
  853. $.extend(true, pdfMake.fonts, {Mirza: {normal: 'Mirza-Regular.ttf',
  854. bold: 'Mirza-Bold.ttf',
  855. italics: 'Mirza-Medium.ttf',
  856. bolditalics: 'Mirza-SemiBold.ttf'
  857. }});
  858. }
  859. else if (pdfMake.vfs.hasOwnProperty ('gbsn00lp.ttf')) {
  860. defaults.pdfmake.docDefinition.defaultStyle.font = 'gbsn00lp';
  861. $.extend(true, pdfMake.fonts, {gbsn00lp: {normal: 'gbsn00lp.ttf',
  862. bold: 'gbsn00lp.ttf',
  863. italics: 'gbsn00lp.ttf',
  864. bolditalics: 'gbsn00lp.ttf'
  865. }});
  866. }
  867. else if (pdfMake.vfs.hasOwnProperty ('ZCOOLXiaoWei-Regular.ttf')) {
  868. defaults.pdfmake.docDefinition.defaultStyle.font = 'ZCOOLXiaoWei';
  869. $.extend(true, pdfMake.fonts, {ZCOOLXiaoWei: {normal: 'ZCOOLXiaoWei-Regular.ttf',
  870. bold: 'ZCOOLXiaoWei-Regular.ttf',
  871. italics: 'ZCOOLXiaoWei-Regular.ttf',
  872. bolditalics: 'ZCOOLXiaoWei-Regular.ttf'
  873. }});
  874. }
  875. $.extend(true, pdfMake.fonts, defaults.pdfmake.fonts);
  876. if (typeof pdfMake.createPdf !== 'undefined') {
  877. pdfMake.createPdf(docDefinition).getBuffer(function (buffer) {
  878. saveToFile(buffer, defaults.fileName + '.pdf', 'application/pdf', '', '', false);
  879. });
  880. }
  881. }
  882. } else if (defaults.jspdf.autotable === false) {
  883. // pdf output using jsPDF's core html support
  884. var addHtmlOptions = {
  885. dim: {
  886. w: getPropertyUnitValue($(el).first().get(0), 'width', 'mm'),
  887. h: getPropertyUnitValue($(el).first().get(0), 'height', 'mm')
  888. },
  889. pagesplit: false
  890. };
  891. var doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format);
  892. doc.addHTML($(el).first(),
  893. defaults.jspdf.margins.left,
  894. defaults.jspdf.margins.top,
  895. addHtmlOptions,
  896. function () {
  897. jsPdfOutput(doc, false);
  898. });
  899. //delete doc;
  900. } else {
  901. // pdf output using jsPDF AutoTable plugin
  902. // https://github.com/simonbengtsson/jsPDF-AutoTable
  903. var teOptions = defaults.jspdf.autotable.tableExport;
  904. // When setting jspdf.format to 'bestfit' tableExport tries to choose
  905. // the minimum required paper format and orientation in which the table
  906. // (or tables in multitable mode) completely fits without column adjustment
  907. if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') {
  908. var rk = '', ro = '';
  909. var mw = 0;
  910. $(el).each(function () {
  911. if (isVisible($(this))) {
  912. var w = getPropertyUnitValue($(this).get(0), 'width', 'pt');
  913. if (w > mw) {
  914. if (w > pageFormats.a0[0]) {
  915. rk = 'a0';
  916. ro = 'l';
  917. }
  918. for (var key in pageFormats) {
  919. if (pageFormats.hasOwnProperty(key)) {
  920. if (pageFormats[key][1] > w) {
  921. rk = key;
  922. ro = 'l';
  923. if (pageFormats[key][0] > w)
  924. ro = 'p';
  925. }
  926. }
  927. }
  928. mw = w;
  929. }
  930. }
  931. });
  932. defaults.jspdf.format = (rk === '' ? 'a4' : rk);
  933. defaults.jspdf.orientation = (ro === '' ? 'w' : ro);
  934. }
  935. // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport,
  936. // thus it can be accessed from any callback function
  937. if (teOptions.doc == null) {
  938. teOptions.doc = new jsPDF(defaults.jspdf.orientation,
  939. defaults.jspdf.unit,
  940. defaults.jspdf.format);
  941. teOptions.wScaleFactor = 1;
  942. teOptions.hScaleFactor = 1;
  943. if (typeof defaults.jspdf.onDocCreated === 'function')
  944. defaults.jspdf.onDocCreated(teOptions.doc);
  945. }
  946. if (teOptions.outputImages === true)
  947. teOptions.images = {};
  948. if (typeof teOptions.images !== 'undefined') {
  949. $(el).filter(function () {
  950. return isVisible($(this));
  951. }).each(function () {
  952. var rowCount = 0;
  953. ranges = [];
  954. if (defaults.exportHiddenCells === false) {
  955. $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden');
  956. checkCellVisibilty = $hiddenTableElements.length > 0;
  957. }
  958. $hrows = collectHeadRows($(this));
  959. $rows = collectRows($(this));
  960. $($rows).each(function () {
  961. ForEachVisibleCell(this, 'td,th', $hrows.length + rowCount, $hrows.length + $rows.length,
  962. function (cell) {
  963. collectImages(cell, $(cell).children(), teOptions);
  964. });
  965. rowCount++;
  966. });
  967. });
  968. $hrows = [];
  969. $rows = [];
  970. }
  971. loadImages(teOptions, function () {
  972. $(el).filter(function () {
  973. return isVisible($(this));
  974. }).each(function () {
  975. var colKey;
  976. rowIndex = 0;
  977. ranges = [];
  978. if (defaults.exportHiddenCells === false) {
  979. $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden');
  980. checkCellVisibilty = $hiddenTableElements.length > 0;
  981. }
  982. colNames = GetColumnNames(this);
  983. teOptions.columns = [];
  984. teOptions.rows = [];
  985. teOptions.teCells = {};
  986. // onTable: optional callback function for every matching table that can be used
  987. // to modify the tableExport options or to skip the output of a particular table
  988. // if the table selector targets multiple tables
  989. if (typeof teOptions.onTable === 'function')
  990. if (teOptions.onTable($(this), defaults) === false)
  991. return true; // continue to next iteration step (table)
  992. // each table works with an own copy of AutoTable options
  993. defaults.jspdf.autotable.tableExport = null; // avoid deep recursion error
  994. var atOptions = $.extend(true, {}, defaults.jspdf.autotable);
  995. defaults.jspdf.autotable.tableExport = teOptions;
  996. atOptions.margin = {};
  997. $.extend(true, atOptions.margin, defaults.jspdf.margins);
  998. atOptions.tableExport = teOptions;
  999. // Fix jsPDF Autotable's row height calculation
  1000. if (typeof atOptions.beforePageContent !== 'function') {
  1001. atOptions.beforePageContent = function (data) {
  1002. if (data.pageCount === 1) {
  1003. var all = data.table.rows.concat(data.table.headerRow);
  1004. $.each(all, function () {
  1005. var row = this;
  1006. if (row.height > 0) {
  1007. row.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  1008. data.table.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  1009. }
  1010. });
  1011. }
  1012. };
  1013. }
  1014. if (typeof atOptions.createdHeaderCell !== 'function') {
  1015. // apply some original css styles to pdf header cells
  1016. atOptions.createdHeaderCell = function (cell, data) {
  1017. // jsPDF AutoTable plugin v2.0.14 fix: each cell needs its own styles object
  1018. cell.styles = $.extend({}, data.row.styles);
  1019. if (typeof teOptions.columns [data.column.dataKey] !== 'undefined') {
  1020. var col = teOptions.columns [data.column.dataKey];
  1021. if (typeof col.rect !== 'undefined') {
  1022. var rh;
  1023. cell.contentWidth = col.rect.width;
  1024. if (typeof teOptions.heightRatio === 'undefined' || teOptions.heightRatio === 0) {
  1025. if (data.row.raw [data.column.dataKey].rowspan)
  1026. rh = data.row.raw [data.column.dataKey].rect.height / data.row.raw [data.column.dataKey].rowspan;
  1027. else
  1028. rh = data.row.raw [data.column.dataKey].rect.height;
  1029. teOptions.heightRatio = cell.styles.rowHeight / rh;
  1030. }
  1031. rh = data.row.raw [data.column.dataKey].rect.height * teOptions.heightRatio;
  1032. if (rh > cell.styles.rowHeight)
  1033. cell.styles.rowHeight = rh;
  1034. }
  1035. cell.styles.halign = (atOptions.headerStyles.halign === 'inherit') ? 'center' : atOptions.headerStyles.halign;
  1036. cell.styles.valign = atOptions.headerStyles.valign;
  1037. if (typeof col.style !== 'undefined' && col.style.hidden !== true) {
  1038. if (atOptions.headerStyles.halign === 'inherit')
  1039. cell.styles.halign = col.style.align;
  1040. if (atOptions.styles.fillColor === 'inherit')
  1041. cell.styles.fillColor = col.style.bcolor;
  1042. if (atOptions.styles.textColor === 'inherit')
  1043. cell.styles.textColor = col.style.color;
  1044. if (atOptions.styles.fontStyle === 'inherit')
  1045. cell.styles.fontStyle = col.style.fstyle;
  1046. }
  1047. }
  1048. };
  1049. }
  1050. if (typeof atOptions.createdCell !== 'function') {
  1051. // apply some original css styles to pdf table cells
  1052. atOptions.createdCell = function (cell, data) {
  1053. var tecell = teOptions.teCells [data.row.index + ':' + data.column.dataKey];
  1054. cell.styles.halign = (atOptions.styles.halign === 'inherit') ? 'center' : atOptions.styles.halign;
  1055. cell.styles.valign = atOptions.styles.valign;
  1056. if (typeof tecell !== 'undefined' && typeof tecell.style !== 'undefined' && tecell.style.hidden !== true) {
  1057. if (atOptions.styles.halign === 'inherit')
  1058. cell.styles.halign = tecell.style.align;
  1059. if (atOptions.styles.fillColor === 'inherit')
  1060. cell.styles.fillColor = tecell.style.bcolor;
  1061. if (atOptions.styles.textColor === 'inherit')
  1062. cell.styles.textColor = tecell.style.color;
  1063. if (atOptions.styles.fontStyle === 'inherit')
  1064. cell.styles.fontStyle = tecell.style.fstyle;
  1065. }
  1066. };
  1067. }
  1068. if (typeof atOptions.drawHeaderCell !== 'function') {
  1069. atOptions.drawHeaderCell = function (cell, data) {
  1070. var colopt = teOptions.columns [data.column.dataKey];
  1071. if ((colopt.style.hasOwnProperty('hidden') !== true || colopt.style.hidden !== true) &&
  1072. colopt.rowIndex >= 0)
  1073. return prepareAutoTableText(cell, data, colopt);
  1074. else
  1075. return false; // cell is hidden
  1076. };
  1077. }
  1078. if (typeof atOptions.drawCell !== 'function') {
  1079. atOptions.drawCell = function (cell, data) {
  1080. var tecell = teOptions.teCells [data.row.index + ':' + data.column.dataKey];
  1081. var draw2canvas = (typeof tecell !== 'undefined' && tecell.isCanvas);
  1082. if (draw2canvas !== true) {
  1083. if (prepareAutoTableText(cell, data, tecell)) {
  1084. teOptions.doc.rect(cell.x, cell.y, cell.width, cell.height, cell.styles.fillStyle);
  1085. if (typeof tecell !== 'undefined' &&
  1086. (typeof tecell.hasUserDefText === 'undefined' || tecell.hasUserDefText !== true) &&
  1087. typeof tecell.elements !== 'undefined' && tecell.elements.length) {
  1088. var hScale = cell.height / tecell.rect.height;
  1089. if (hScale > teOptions.hScaleFactor)
  1090. teOptions.hScaleFactor = hScale;
  1091. teOptions.wScaleFactor = cell.width / tecell.rect.width;
  1092. var ySave = cell.textPos.y;
  1093. drawAutotableElements(cell, tecell.elements, teOptions);
  1094. cell.textPos.y = ySave;
  1095. drawAutotableText(cell, tecell.elements, teOptions);
  1096. } else
  1097. drawAutotableText(cell, {}, teOptions);
  1098. }
  1099. } else {
  1100. var container = tecell.elements[0];
  1101. var imgId = $(container).attr('data-tableexport-canvas');
  1102. var r = container.getBoundingClientRect();
  1103. cell.width = r.width * teOptions.wScaleFactor;
  1104. cell.height = r.height * teOptions.hScaleFactor;
  1105. data.row.height = cell.height;
  1106. jsPdfDrawImage(cell, container, imgId, teOptions);
  1107. }
  1108. return false;
  1109. };
  1110. }
  1111. // collect header and data rows
  1112. teOptions.headerrows = [];
  1113. $hrows = collectHeadRows($(this));
  1114. $($hrows).each(function () {
  1115. colKey = 0;
  1116. teOptions.headerrows[rowIndex] = [];
  1117. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  1118. function (cell, row, col) {
  1119. var obj = getCellStyles(cell);
  1120. obj.title = parseString(cell, row, col);
  1121. obj.key = colKey++;
  1122. obj.rowIndex = rowIndex;
  1123. teOptions.headerrows[rowIndex].push(obj);
  1124. });
  1125. rowIndex++;
  1126. });
  1127. if (rowIndex > 0) {
  1128. // iterate through last row
  1129. var lastrow = rowIndex - 1;
  1130. while (lastrow >= 0) {
  1131. $.each(teOptions.headerrows[lastrow], function () {
  1132. var obj = this;
  1133. if (lastrow > 0 && this.rect === null)
  1134. obj = teOptions.headerrows[lastrow - 1][this.key];
  1135. if (obj !== null && obj.rowIndex >= 0 &&
  1136. (obj.style.hasOwnProperty('hidden') !== true || obj.style.hidden !== true))
  1137. teOptions.columns.push(obj);
  1138. });
  1139. lastrow = (teOptions.columns.length > 0) ? -1 : lastrow - 1;
  1140. }
  1141. }
  1142. var rowCount = 0;
  1143. $rows = [];
  1144. $rows = collectRows($(this));
  1145. $($rows).each(function () {
  1146. var rowData = [];
  1147. colKey = 0;
  1148. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  1149. function (cell, row, col) {
  1150. var obj;
  1151. if (typeof teOptions.columns[colKey] === 'undefined') {
  1152. // jsPDF-Autotable needs columns. Thus define hidden ones for tables without thead
  1153. obj = {
  1154. title: '',
  1155. key: colKey,
  1156. style: {
  1157. hidden: true
  1158. }
  1159. };
  1160. teOptions.columns.push(obj);
  1161. }
  1162. rowData.push(parseString(cell, row, col));
  1163. if (typeof cell !== 'undefined' && cell !== null) {
  1164. obj = getCellStyles(cell);
  1165. obj.isCanvas = cell.hasAttribute('data-tableexport-canvas');
  1166. obj.elements = obj.isCanvas ? $(cell) : $(cell).children();
  1167. if(typeof $(cell).data('teUserDefText') !== 'undefined')
  1168. obj.hasUserDefText = true;
  1169. teOptions.teCells [rowCount + ':' + colKey++] = obj;
  1170. } else {
  1171. obj = $.extend(true, {}, teOptions.teCells [rowCount + ':' + (colKey - 1)]);
  1172. obj.colspan = -1;
  1173. teOptions.teCells [rowCount + ':' + colKey++] = obj;
  1174. }
  1175. });
  1176. if (rowData.length) {
  1177. teOptions.rows.push(rowData);
  1178. rowCount++;
  1179. }
  1180. rowIndex++;
  1181. });
  1182. // onBeforeAutotable: optional callback function before calling
  1183. // jsPDF AutoTable that can be used to modify the AutoTable options
  1184. if (typeof teOptions.onBeforeAutotable === 'function')
  1185. teOptions.onBeforeAutotable($(this), teOptions.columns, teOptions.rows, atOptions);
  1186. teOptions.doc.autoTable(teOptions.columns, teOptions.rows, atOptions);
  1187. // onAfterAutotable: optional callback function after returning
  1188. // from jsPDF AutoTable that can be used to modify the AutoTable options
  1189. if (typeof teOptions.onAfterAutotable === 'function')
  1190. teOptions.onAfterAutotable($(this), atOptions);
  1191. // set the start position for the next table (in case there is one)
  1192. defaults.jspdf.autotable.startY = teOptions.doc.autoTableEndPosY() + atOptions.margin.top;
  1193. });
  1194. jsPdfOutput(teOptions.doc, (typeof teOptions.images !== 'undefined' && jQuery.isEmptyObject(teOptions.images) === false));
  1195. if (typeof teOptions.headerrows !== 'undefined')
  1196. teOptions.headerrows.length = 0;
  1197. if (typeof teOptions.columns !== 'undefined')
  1198. teOptions.columns.length = 0;
  1199. if (typeof teOptions.rows !== 'undefined')
  1200. teOptions.rows.length = 0;
  1201. delete teOptions.doc;
  1202. teOptions.doc = null;
  1203. });
  1204. }
  1205. }
  1206. function collectHeadRows ($table) {
  1207. var result = [];
  1208. findTableElements($table, 'thead').each(function () {
  1209. result.push.apply(result, findTableElements($(this), defaults.theadSelector).toArray());
  1210. });
  1211. return result;
  1212. }
  1213. function collectRows ($table) {
  1214. var result = [];
  1215. findTableElements($table, 'tbody').each(function () {
  1216. result.push.apply(result, findTableElements($(this), defaults.tbodySelector).toArray());
  1217. });
  1218. if (defaults.tfootSelector.length) {
  1219. findTableElements($table, 'tfoot').each(function () {
  1220. result.push.apply(result, findTableElements($(this), defaults.tfootSelector).toArray());
  1221. });
  1222. }
  1223. return result;
  1224. }
  1225. function findTableElements ($parent, selector) {
  1226. var parentSelector = $parent[0].tagName;
  1227. var parentLevel = $parent.parents(parentSelector).length;
  1228. return $parent.find(selector).filter(function () {
  1229. return parentLevel === $(this).closest(parentSelector).parents(parentSelector).length;
  1230. });
  1231. }
  1232. function GetColumnNames (table) {
  1233. var result = [];
  1234. $(table).find('thead').first().find('th').each(function (index, el) {
  1235. if ($(el).attr('data-field') !== undefined)
  1236. result[index] = $(el).attr('data-field');
  1237. else
  1238. result[index] = index.toString();
  1239. });
  1240. return result;
  1241. }
  1242. function isVisible ($element) {
  1243. var isRow = typeof $element[0].rowIndex !== 'undefined';
  1244. var isCell = isRow === false && typeof $element[0].cellIndex !== 'undefined';
  1245. var isElementVisible = (isCell || isRow) ? isTableElementVisible($element) : $element.is(':visible');
  1246. var tableexportDisplay = $element.attr('data-tableexport-display');
  1247. if (isCell && tableexportDisplay !== 'none' && tableexportDisplay !== 'always') {
  1248. $element = $($element[0].parentNode);
  1249. isRow = typeof $element[0].rowIndex !== 'undefined';
  1250. tableexportDisplay = $element.attr('data-tableexport-display');
  1251. }
  1252. if (isRow && tableexportDisplay !== 'none' && tableexportDisplay !== 'always') {
  1253. tableexportDisplay = $element.closest('table').attr('data-tableexport-display');
  1254. }
  1255. return tableexportDisplay !== 'none' && (isElementVisible === true || tableexportDisplay === 'always');
  1256. }
  1257. function isTableElementVisible ($element) {
  1258. var hiddenEls = [];
  1259. if (checkCellVisibilty) {
  1260. hiddenEls = $hiddenTableElements.filter(function () {
  1261. var found = false;
  1262. if (this.nodeType === $element[0].nodeType) {
  1263. if (typeof this.rowIndex !== 'undefined' && this.rowIndex === $element[0].rowIndex)
  1264. found = true;
  1265. else if (typeof this.cellIndex !== 'undefined' && this.cellIndex === $element[0].cellIndex &&
  1266. typeof this.parentNode.rowIndex !== 'undefined' &&
  1267. typeof $element[0].parentNode.rowIndex !== 'undefined' &&
  1268. this.parentNode.rowIndex === $element[0].parentNode.rowIndex)
  1269. found = true;
  1270. }
  1271. return found;
  1272. });
  1273. }
  1274. return (checkCellVisibilty === false || hiddenEls.length === 0);
  1275. }
  1276. function isColumnIgnored ($cell, rowLength, colIndex) {
  1277. var result = false;
  1278. if (isVisible($cell)) {
  1279. if (defaults.ignoreColumn.length > 0) {
  1280. if ($.inArray(colIndex, defaults.ignoreColumn) !== -1 ||
  1281. $.inArray(colIndex - rowLength, defaults.ignoreColumn) !== -1 ||
  1282. (colNames.length > colIndex && typeof colNames[colIndex] !== 'undefined' &&
  1283. $.inArray(colNames[colIndex], defaults.ignoreColumn) !== -1))
  1284. result = true;
  1285. }
  1286. } else
  1287. result = true;
  1288. return result;
  1289. }
  1290. function ForEachVisibleCell (tableRow, selector, rowIndex, rowCount, cellcallback) {
  1291. if (typeof (cellcallback) === 'function') {
  1292. var ignoreRow = false;
  1293. if (typeof defaults.onIgnoreRow === 'function')
  1294. ignoreRow = defaults.onIgnoreRow($(tableRow), rowIndex);
  1295. if (ignoreRow === false &&
  1296. (defaults.ignoreRow.length === 0 ||
  1297. ($.inArray(rowIndex, defaults.ignoreRow) === -1 &&
  1298. $.inArray(rowIndex - rowCount, defaults.ignoreRow) === -1)) &&
  1299. isVisible($(tableRow))) {
  1300. var $cells = findTableElements($(tableRow), selector);
  1301. var cellCount = 0;
  1302. $cells.each(function (colIndex) {
  1303. var $cell = $(this);
  1304. var c;
  1305. var colspan = getColspan(this);
  1306. var rowspan = getRowspan(this);
  1307. // Skip ranges
  1308. $.each(ranges, function () {
  1309. var range = this;
  1310. if (rowIndex >= range.s.r && rowIndex <= range.e.r && cellCount >= range.s.c && cellCount <= range.e.c) {
  1311. for (c = 0; c <= range.e.c - range.s.c; ++c)
  1312. cellcallback(null, rowIndex, cellCount++);
  1313. }
  1314. });
  1315. if (isColumnIgnored($cell, $cells.length, colIndex) === false) {
  1316. // Handle Row Span
  1317. if (rowspan || colspan) {
  1318. rowspan = rowspan || 1;
  1319. colspan = colspan || 1;
  1320. ranges.push({
  1321. s: {r: rowIndex, c: cellCount},
  1322. e: {r: rowIndex + rowspan - 1, c: cellCount + colspan - 1}
  1323. });
  1324. }
  1325. // Handle Value
  1326. cellcallback(this, rowIndex, cellCount++);
  1327. }
  1328. // Handle Colspan
  1329. if (colspan)
  1330. for (c = 0; c < colspan - 1; ++c)
  1331. cellcallback(null, rowIndex, cellCount++);
  1332. });
  1333. // Skip ranges
  1334. $.each(ranges, function () {
  1335. var range = this;
  1336. if (rowIndex >= range.s.r && rowIndex <= range.e.r && cellCount >= range.s.c && cellCount <= range.e.c) {
  1337. for (c = 0; c <= range.e.c - range.s.c; ++c)
  1338. cellcallback(null, rowIndex, cellCount++);
  1339. }
  1340. });
  1341. }
  1342. }
  1343. }
  1344. function jsPdfDrawImage (cell, container, imgId, teOptions) {
  1345. if (typeof teOptions.images !== 'undefined') {
  1346. var image = teOptions.images[imgId];
  1347. if (typeof image !== 'undefined') {
  1348. var r = container.getBoundingClientRect();
  1349. var arCell = cell.width / cell.height;
  1350. var arImg = r.width / r.height;
  1351. var imgWidth = cell.width;
  1352. var imgHeight = cell.height;
  1353. var px2pt = 0.264583 * 72 / 25.4;
  1354. var uy = 0;
  1355. if (arImg <= arCell) {
  1356. imgHeight = Math.min(cell.height, r.height);
  1357. imgWidth = r.width * imgHeight / r.height;
  1358. } else if (arImg > arCell) {
  1359. imgWidth = Math.min(cell.width, r.width);
  1360. imgHeight = r.height * imgWidth / r.width;
  1361. }
  1362. imgWidth *= px2pt;
  1363. imgHeight *= px2pt;
  1364. if (imgHeight < cell.height)
  1365. uy = (cell.height - imgHeight) / 2;
  1366. try {
  1367. teOptions.doc.addImage(image.src, cell.textPos.x, cell.y + uy, imgWidth, imgHeight);
  1368. } catch (e) {
  1369. // TODO: IE -> convert png to jpeg
  1370. }
  1371. cell.textPos.x += imgWidth;
  1372. }
  1373. }
  1374. }
  1375. function jsPdfOutput (doc, hasimages) {
  1376. if (defaults.outputMode === 'string')
  1377. return doc.output();
  1378. if (defaults.outputMode === 'base64')
  1379. return base64encode(doc.output());
  1380. if (defaults.outputMode === 'window') {
  1381. window.URL = window.URL || window.webkitURL;
  1382. window.open(window.URL.createObjectURL(doc.output('blob')));
  1383. return;
  1384. }
  1385. try {
  1386. var blob = doc.output('blob');
  1387. saveAs(blob, defaults.fileName + '.pdf');
  1388. } catch (e) {
  1389. downloadFile(defaults.fileName + '.pdf',
  1390. 'data:application/pdf' + (hasimages ? '' : ';base64') + ',',
  1391. hasimages ? doc.output('blob') : doc.output());
  1392. }
  1393. }
  1394. function prepareAutoTableText (cell, data, cellopt) {
  1395. var cs = 0;
  1396. if (typeof cellopt !== 'undefined')
  1397. cs = cellopt.colspan;
  1398. if (cs >= 0) {
  1399. // colspan handling
  1400. var cellWidth = cell.width;
  1401. var textPosX = cell.textPos.x;
  1402. var i = data.table.columns.indexOf(data.column);
  1403. for (var c = 1; c < cs; c++) {
  1404. var column = data.table.columns[i + c];
  1405. cellWidth += column.width;
  1406. }
  1407. if (cs > 1) {
  1408. if (cell.styles.halign === 'right')
  1409. textPosX = cell.textPos.x + cellWidth - cell.width;
  1410. else if (cell.styles.halign === 'center')
  1411. textPosX = cell.textPos.x + (cellWidth - cell.width) / 2;
  1412. }
  1413. cell.width = cellWidth;
  1414. cell.textPos.x = textPosX;
  1415. if (typeof cellopt !== 'undefined' && cellopt.rowspan > 1)
  1416. cell.height = cell.height * cellopt.rowspan;
  1417. // fix jsPDF's calculation of text position
  1418. if (cell.styles.valign === 'middle' || cell.styles.valign === 'bottom') {
  1419. var splittedText = typeof cell.text === 'string' ? cell.text.split(/\r\n|\r|\n/g) : cell.text;
  1420. var lineCount = splittedText.length || 1;
  1421. if (lineCount > 2)
  1422. cell.textPos.y -= ((2 - FONT_ROW_RATIO) / 2 * data.row.styles.fontSize) * (lineCount - 2) / 3;
  1423. }
  1424. return true;
  1425. } else
  1426. return false; // cell is hidden (colspan = -1), don't draw it
  1427. }
  1428. function collectImages (cell, elements, teOptions) {
  1429. if (typeof cell !== 'undefined' && cell !== null) {
  1430. if (cell.hasAttribute('data-tableexport-canvas')) {
  1431. var imgId = new Date().getTime();
  1432. $(cell).attr('data-tableexport-canvas', imgId);
  1433. teOptions.images[imgId] = {
  1434. url: '[data-tableexport-canvas="' + imgId + '"]',
  1435. src: null
  1436. };
  1437. } else if (elements !== 'undefined' && elements != null) {
  1438. elements.each(function () {
  1439. if ($(this).is('img')) {
  1440. var imgId = strHashCode(this.src);
  1441. teOptions.images[imgId] = {
  1442. url: this.src,
  1443. src: this.src
  1444. };
  1445. }
  1446. collectImages(cell, $(this).children(), teOptions);
  1447. });
  1448. }
  1449. }
  1450. }
  1451. function loadImages (teOptions, callback) {
  1452. var imageCount = 0;
  1453. var pendingCount = 0;
  1454. function done () {
  1455. callback(imageCount);
  1456. }
  1457. function loadImage (image) {
  1458. if (image.url) {
  1459. if (!image.src) {
  1460. var $imgContainer = $(image.url);
  1461. if ($imgContainer.length) {
  1462. imageCount = ++pendingCount;
  1463. html2canvas($imgContainer[0]).then(function (canvas) {
  1464. image.src = canvas.toDataURL('image/png');
  1465. if (!--pendingCount)
  1466. done();
  1467. });
  1468. }
  1469. } else {
  1470. var img = new Image();
  1471. imageCount = ++pendingCount;
  1472. img.crossOrigin = 'Anonymous';
  1473. img.onerror = img.onload = function () {
  1474. if (img.complete) {
  1475. if (img.src.indexOf('data:image/') === 0) {
  1476. img.width = image.width || img.width || 0;
  1477. img.height = image.height || img.height || 0;
  1478. }
  1479. if (img.width + img.height) {
  1480. var canvas = document.createElement('canvas');
  1481. var ctx = canvas.getContext('2d');
  1482. canvas.width = img.width;
  1483. canvas.height = img.height;
  1484. ctx.drawImage(img, 0, 0);
  1485. image.src = canvas.toDataURL('image/png');
  1486. }
  1487. }
  1488. if (!--pendingCount)
  1489. done();
  1490. };
  1491. img.src = image.url;
  1492. }
  1493. }
  1494. }
  1495. if (typeof teOptions.images !== 'undefined') {
  1496. for (var i in teOptions.images)
  1497. if (teOptions.images.hasOwnProperty(i))
  1498. loadImage(teOptions.images[i]);
  1499. }
  1500. return pendingCount || done();
  1501. }
  1502. function drawAutotableElements (cell, elements, teOptions) {
  1503. elements.each(function () {
  1504. if ($(this).is('div')) {
  1505. var bcolor = rgb2array(getStyle(this, 'background-color'), [255, 255, 255]);
  1506. var lcolor = rgb2array(getStyle(this, 'border-top-color'), [0, 0, 0]);
  1507. var lwidth = getPropertyUnitValue(this, 'border-top-width', defaults.jspdf.unit);
  1508. var r = this.getBoundingClientRect();
  1509. var ux = this.offsetLeft * teOptions.wScaleFactor;
  1510. var uy = this.offsetTop * teOptions.hScaleFactor;
  1511. var uw = r.width * teOptions.wScaleFactor;
  1512. var uh = r.height * teOptions.hScaleFactor;
  1513. teOptions.doc.setDrawColor.apply(undefined, lcolor);
  1514. teOptions.doc.setFillColor.apply(undefined, bcolor);
  1515. teOptions.doc.setLineWidth(lwidth);
  1516. teOptions.doc.rect(cell.x + ux, cell.y + uy, uw, uh, lwidth ? 'FD' : 'F');
  1517. } else if ($(this).is('img')) {
  1518. var imgId = strHashCode(this.src);
  1519. jsPdfDrawImage(cell, this, imgId, teOptions);
  1520. }
  1521. drawAutotableElements(cell, $(this).children(), teOptions);
  1522. });
  1523. }
  1524. function drawAutotableText (cell, texttags, teOptions) {
  1525. if (typeof teOptions.onAutotableText === 'function') {
  1526. teOptions.onAutotableText(teOptions.doc, cell, texttags);
  1527. } else {
  1528. var x = cell.textPos.x;
  1529. var y = cell.textPos.y;
  1530. var style = {halign: cell.styles.halign, valign: cell.styles.valign};
  1531. if (texttags.length) {
  1532. var tag = texttags[0];
  1533. while (tag.previousSibling)
  1534. tag = tag.previousSibling;
  1535. var b = false, i = false;
  1536. while (tag) {
  1537. var txt = tag.innerText || tag.textContent || '';
  1538. var leadingspace = (txt.length && txt[0] === ' ') ? ' ' : '';
  1539. var trailingspace = (txt.length > 1 && txt[txt.length - 1] === ' ') ? ' ' : '';
  1540. if (defaults.preserve.leadingWS !== true)
  1541. txt = leadingspace + trimLeft(txt);
  1542. if (defaults.preserve.trailingWS !== true)
  1543. txt = trimRight(txt) + trailingspace;
  1544. if ($(tag).is('br')) {
  1545. x = cell.textPos.x;
  1546. y += teOptions.doc.internal.getFontSize();
  1547. }
  1548. if ($(tag).is('b'))
  1549. b = true;
  1550. else if ($(tag).is('i'))
  1551. i = true;
  1552. if (b || i)
  1553. teOptions.doc.setFontType((b && i) ? 'bolditalic' : b ? 'bold' : 'italic');
  1554. var w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1555. if (w) {
  1556. if (cell.styles.overflow === 'linebreak' &&
  1557. x > cell.textPos.x && (x + w) > (cell.textPos.x + cell.width)) {
  1558. var chars = '.,!%*;:=-';
  1559. if (chars.indexOf(txt.charAt(0)) >= 0) {
  1560. var s = txt.charAt(0);
  1561. w = teOptions.doc.getStringUnitWidth(s) * teOptions.doc.internal.getFontSize();
  1562. if ((x + w) <= (cell.textPos.x + cell.width)) {
  1563. teOptions.doc.autoTableText(s, x, y, style);
  1564. txt = txt.substring(1, txt.length);
  1565. }
  1566. w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1567. }
  1568. x = cell.textPos.x;
  1569. y += teOptions.doc.internal.getFontSize();
  1570. }
  1571. if (cell.styles.overflow !== 'visible') {
  1572. while (txt.length && (x + w) > (cell.textPos.x + cell.width)) {
  1573. txt = txt.substring(0, txt.length - 1);
  1574. w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1575. }
  1576. }
  1577. teOptions.doc.autoTableText(txt, x, y, style);
  1578. x += w;
  1579. }
  1580. if (b || i) {
  1581. if ($(tag).is('b'))
  1582. b = false;
  1583. else if ($(tag).is('i'))
  1584. i = false;
  1585. teOptions.doc.setFontType((!b && !i) ? 'normal' : b ? 'bold' : 'italic');
  1586. }
  1587. tag = tag.nextSibling;
  1588. }
  1589. cell.textPos.x = x;
  1590. cell.textPos.y = y;
  1591. } else {
  1592. teOptions.doc.autoTableText(cell.text, cell.textPos.x, cell.textPos.y, style);
  1593. }
  1594. }
  1595. }
  1596. function escapeRegExp (string) {
  1597. return string == null ? '' : string.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
  1598. }
  1599. function replaceAll (string, find, replace) {
  1600. return string == null ? '' : string.toString().replace(new RegExp(escapeRegExp(find), 'g'), replace);
  1601. }
  1602. function trimLeft (string) {
  1603. return string == null ? '' : string.toString().replace(/^\s+/, '');
  1604. }
  1605. function trimRight (string) {
  1606. return string == null ? '' : string.toString().replace(/\s+$/, '');
  1607. }
  1608. function parseDateUTC (s) {
  1609. if (defaults.date.html.length === 0)
  1610. return false;
  1611. defaults.date.pattern.lastIndex = 0;
  1612. var match = defaults.date.pattern.exec(s);
  1613. if (match == null)
  1614. return false;
  1615. var y = +match[defaults.date.match_y];
  1616. if (y < 0 || y > 8099) return false;
  1617. var m = match[defaults.date.match_m] * 1;
  1618. var d = match[defaults.date.match_d] * 1;
  1619. if (!isFinite(d)) return false;
  1620. var o = new Date(y, m - 1, d, 0, 0, 0);
  1621. if (o.getFullYear() === y && o.getMonth() === (m - 1) && o.getDate() === d)
  1622. return new Date(Date.UTC(y, m - 1, d, 0, 0, 0));
  1623. else
  1624. return false;
  1625. }
  1626. function parseNumber (value) {
  1627. value = value || '0';
  1628. if ('' !== defaults.numbers.html.thousandsSeparator)
  1629. value = replaceAll(value, defaults.numbers.html.thousandsSeparator, '');
  1630. if ('.' !== defaults.numbers.html.decimalMark)
  1631. value = replaceAll(value, defaults.numbers.html.decimalMark, '.');
  1632. return typeof value === 'number' || jQuery.isNumeric(value) !== false ? value : false;
  1633. }
  1634. function parsePercent (value) {
  1635. if (value.indexOf('%') > -1) {
  1636. value = parseNumber(value.replace(/%/g, ''));
  1637. if (value !== false)
  1638. value = value / 100;
  1639. } else
  1640. value = false;
  1641. return value;
  1642. }
  1643. function parseString (cell, rowIndex, colIndex, cellInfo) {
  1644. var result = '';
  1645. var cellType = 'text';
  1646. if (cell !== null) {
  1647. var $cell = $(cell);
  1648. var htmlData;
  1649. $cell.removeData('teUserDefText');
  1650. if ($cell[0].hasAttribute('data-tableexport-canvas')) {
  1651. htmlData = '';
  1652. } else if ($cell[0].hasAttribute('data-tableexport-value')) {
  1653. htmlData = $cell.attr('data-tableexport-value');
  1654. htmlData = htmlData ? htmlData + '' : '';
  1655. $cell.data('teUserDefText', 1);
  1656. } else {
  1657. htmlData = $cell.html();
  1658. if (typeof defaults.onCellHtmlData === 'function') {
  1659. htmlData = defaults.onCellHtmlData($cell, rowIndex, colIndex, htmlData);
  1660. $cell.data('teUserDefText', 1);
  1661. }
  1662. else if (htmlData !== '') {
  1663. var html = $.parseHTML(htmlData);
  1664. var inputidx = 0;
  1665. var selectidx = 0;
  1666. htmlData = '';
  1667. $.each(html, function () {
  1668. if ($(this).is('input')) {
  1669. htmlData += $cell.find('input').eq(inputidx++).val();
  1670. }
  1671. else if ($(this).is('select')) {
  1672. htmlData += $cell.find('select option:selected').eq(selectidx++).text();
  1673. }
  1674. else if ($(this).is('br')) {
  1675. htmlData += '<br>';
  1676. }
  1677. else {
  1678. if (typeof $(this).html() === 'undefined')
  1679. htmlData += $(this).text();
  1680. else if (jQuery().bootstrapTable === undefined ||
  1681. ($(this).hasClass('fht-cell') === false && // BT 4
  1682. $(this).hasClass('filterControl') === false &&
  1683. $cell.parents('.detail-view').length === 0))
  1684. htmlData += $(this).html();
  1685. if ($(this).is('a')) {
  1686. var href = $cell.find('a').attr('href') || '';
  1687. if (typeof defaults.onCellHtmlHyperlink === 'function')
  1688. result += defaults.onCellHtmlHyperlink($cell, rowIndex, colIndex, href, htmlData);
  1689. else if (defaults.htmlHyperlink === 'href')
  1690. result += href;
  1691. else // 'content'
  1692. result += htmlData;
  1693. htmlData = '';
  1694. }
  1695. }
  1696. });
  1697. }
  1698. }
  1699. if (htmlData && htmlData !== '' && defaults.htmlContent === true) {
  1700. result = $.trim(htmlData);
  1701. } else if (htmlData && htmlData !== '') {
  1702. var cellFormat = $cell.attr('data-tableexport-cellformat');
  1703. if (cellFormat !== '') {
  1704. var text = htmlData.replace(/\n/g, '\u2028').replace(/(<\s*br([^>]*)>)/gi, '\u2060');
  1705. var obj = $('<div/>').html(text).contents();
  1706. var number = false;
  1707. text = '';
  1708. $.each(obj.text().split('\u2028'), function (i, v) {
  1709. if (i > 0)
  1710. text += ' ';
  1711. if (defaults.preserve.leadingWS !== true)
  1712. v = trimLeft(v);
  1713. text += (defaults.preserve.trailingWS !== true) ? trimRight(v) : v;
  1714. });
  1715. $.each(text.split('\u2060'), function (i, v) {
  1716. if (i > 0)
  1717. result += '\n';
  1718. if (defaults.preserve.leadingWS !== true)
  1719. v = trimLeft(v);
  1720. if (defaults.preserve.trailingWS !== true)
  1721. v = trimRight(v);
  1722. result += v.replace(/\u00AD/g, ''); // remove soft hyphens
  1723. });
  1724. result = result.replace(/\u00A0/g, ' '); // replace nbsp's with spaces
  1725. if (defaults.type === 'json' ||
  1726. (defaults.type === 'excel' && defaults.mso.fileFormat === 'xmlss') ||
  1727. defaults.numbers.output === false) {
  1728. number = parseNumber(result);
  1729. if (number !== false) {
  1730. cellType = 'number';
  1731. result = Number(number);
  1732. }
  1733. } else if (defaults.numbers.html.decimalMark !== defaults.numbers.output.decimalMark ||
  1734. defaults.numbers.html.thousandsSeparator !== defaults.numbers.output.thousandsSeparator) {
  1735. number = parseNumber(result);
  1736. if (number !== false) {
  1737. var frac = ('' + number.substr(number < 0 ? 1 : 0)).split('.');
  1738. if (frac.length === 1)
  1739. frac[1] = '';
  1740. var mod = frac[0].length > 3 ? frac[0].length % 3 : 0;
  1741. cellType = 'number';
  1742. result = (number < 0 ? '-' : '') +
  1743. (defaults.numbers.output.thousandsSeparator ? ((mod ? frac[0].substr(0, mod) + defaults.numbers.output.thousandsSeparator : '') + frac[0].substr(mod).replace(/(\d{3})(?=\d)/g, '$1' + defaults.numbers.output.thousandsSeparator)) : frac[0]) +
  1744. (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : '');
  1745. }
  1746. }
  1747. } else
  1748. result = htmlData;
  1749. }
  1750. if (defaults.escape === true) {
  1751. //noinspection JSDeprecatedSymbols
  1752. result = escape(result);
  1753. }
  1754. if (typeof defaults.onCellData === 'function') {
  1755. result = defaults.onCellData($cell, rowIndex, colIndex, result, cellType);
  1756. $cell.data('teUserDefText', 1);
  1757. }
  1758. }
  1759. if (cellInfo !== undefined)
  1760. cellInfo.type = cellType;
  1761. return result;
  1762. }
  1763. function preventInjection (str) {
  1764. if (str.length > 0 && defaults.preventInjection === true) {
  1765. var chars = '=+-@';
  1766. if (chars.indexOf(str.charAt(0)) >= 0)
  1767. return ('\'' + str);
  1768. }
  1769. return str;
  1770. }
  1771. //noinspection JSUnusedLocalSymbols
  1772. function hyphenate (a, b, c) {
  1773. return b + '-' + c.toLowerCase();
  1774. }
  1775. function rgb2array (rgb_string, default_result) {
  1776. var re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
  1777. var bits = re.exec(rgb_string);
  1778. var result = default_result;
  1779. if (bits)
  1780. result = [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])];
  1781. return result;
  1782. }
  1783. function getCellStyles (cell) {
  1784. var a = getStyle(cell, 'text-align');
  1785. var fw = getStyle(cell, 'font-weight');
  1786. var fs = getStyle(cell, 'font-style');
  1787. var f = '';
  1788. if (a === 'start')
  1789. a = getStyle(cell, 'direction') === 'rtl' ? 'right' : 'left';
  1790. if (fw >= 700)
  1791. f = 'bold';
  1792. if (fs === 'italic')
  1793. f += fs;
  1794. if (f === '')
  1795. f = 'normal';
  1796. var result = {
  1797. style: {
  1798. align: a,
  1799. bcolor: rgb2array(getStyle(cell, 'background-color'), [255, 255, 255]),
  1800. color: rgb2array(getStyle(cell, 'color'), [0, 0, 0]),
  1801. fstyle: f
  1802. },
  1803. colspan: getColspan(cell),
  1804. rowspan: getRowspan(cell)
  1805. };
  1806. if (cell !== null) {
  1807. var r = cell.getBoundingClientRect();
  1808. result.rect = {
  1809. width: r.width,
  1810. height: r.height
  1811. };
  1812. }
  1813. return result;
  1814. }
  1815. function getColspan (cell) {
  1816. var result = $(cell).attr('data-tableexport-colspan');
  1817. if (typeof result === 'undefined' && $(cell).is('[colspan]'))
  1818. result = $(cell).attr('colspan');
  1819. return (parseInt(result) || 0);
  1820. }
  1821. function getRowspan (cell) {
  1822. var result = $(cell).attr('data-tableexport-rowspan');
  1823. if (typeof result === 'undefined' && $(cell).is('[rowspan]'))
  1824. result = $(cell).attr('rowspan');
  1825. return (parseInt(result) || 0);
  1826. }
  1827. // get computed style property
  1828. function getStyle (target, prop) {
  1829. try {
  1830. if (window.getComputedStyle) { // gecko and webkit
  1831. prop = prop.replace(/([a-z])([A-Z])/, hyphenate); // requires hyphenated, not camel
  1832. return window.getComputedStyle(target, null).getPropertyValue(prop);
  1833. }
  1834. if (target.currentStyle) { // ie
  1835. return target.currentStyle[prop];
  1836. }
  1837. return target.style[prop];
  1838. } catch (e) {
  1839. }
  1840. return '';
  1841. }
  1842. function getUnitValue (parent, value, unit) {
  1843. var baseline = 100; // any number serves
  1844. var temp = document.createElement('div'); // create temporary element
  1845. temp.style.overflow = 'hidden'; // in case baseline is set too low
  1846. temp.style.visibility = 'hidden'; // no need to show it
  1847. parent.appendChild(temp); // insert it into the parent for em, ex and %
  1848. temp.style.width = baseline + unit;
  1849. var factor = baseline / temp.offsetWidth;
  1850. parent.removeChild(temp); // clean up
  1851. return (value * factor);
  1852. }
  1853. function getPropertyUnitValue (target, prop, unit) {
  1854. var value = getStyle(target, prop); // get the computed style value
  1855. var numeric = value.match(/\d+/); // get the numeric component
  1856. if (numeric !== null) {
  1857. numeric = numeric[0]; // get the string
  1858. return getUnitValue(target.parentElement, numeric, unit);
  1859. }
  1860. return 0;
  1861. }
  1862. function xlsxWorkbookToArrayBuffer (s) {
  1863. var buf = new ArrayBuffer(s.length);
  1864. var view = new Uint8Array(buf);
  1865. for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  1866. return buf;
  1867. }
  1868. function xlsxTableToSheet (table) {
  1869. var ws = ({});
  1870. var rows = table.getElementsByTagName('tr');
  1871. var sheetRows = 10000000;
  1872. var range = {s: {r: 0, c: 0}, e: {r: 0, c: 0}};
  1873. var merges = [], midx = 0;
  1874. var rowinfo = [];
  1875. var _R = 0, R = 0, _C, C, RS, CS;
  1876. var elt;
  1877. var ssfTable = XLSX.SSF.get_table();
  1878. for (; _R < rows.length && R < sheetRows; ++_R) {
  1879. var row = rows[_R];
  1880. var ignoreRow = false;
  1881. if (typeof defaults.onIgnoreRow === 'function')
  1882. ignoreRow = defaults.onIgnoreRow($(row), _R);
  1883. if (ignoreRow === true ||
  1884. (defaults.ignoreRow.length !== 0 &&
  1885. ($.inArray(_R, defaults.ignoreRow) !== -1 ||
  1886. $.inArray(_R - rows.length, defaults.ignoreRow) !== -1)) ||
  1887. isVisible($(row)) === false) {
  1888. continue;
  1889. }
  1890. var elts = (row.children);
  1891. var _CLength = 0;
  1892. for (_C = 0; _C < elts.length; ++_C) {
  1893. elt = elts[_C];
  1894. CS = +getColspan(elt) || 1;
  1895. _CLength += CS;
  1896. }
  1897. var CSOffset = 0;
  1898. for (_C = C = 0; _C < elts.length; ++_C) {
  1899. elt = elts[_C];
  1900. CS = +getColspan(elt) || 1;
  1901. var col = _C + CSOffset;
  1902. if (isColumnIgnored($(elt), _CLength, col + (col < C ? C - col : 0)))
  1903. continue;
  1904. CSOffset += CS - 1;
  1905. for (midx = 0; midx < merges.length; ++midx) {
  1906. var m = merges[midx];
  1907. if (m.s.c == C && m.s.r <= R && R <= m.e.r) {
  1908. C = m.e.c + 1;
  1909. midx = -1;
  1910. }
  1911. }
  1912. if ((RS = +getRowspan(elt)) > 0 || CS > 1)
  1913. merges.push({s: {r: R, c: C}, e: {r: R + (RS || 1) - 1, c: C + CS - 1}});
  1914. var cellInfo = {type: ''};
  1915. var v = parseString(elt, _R, _C + CSOffset, cellInfo);
  1916. var o = {t: 's', v: v};
  1917. var _t = '';
  1918. var cellFormat = $(elt).attr('data-tableexport-cellformat');
  1919. if (cellFormat !== '') {
  1920. var ssfId = parseInt($(elt).attr('data-tableexport-xlsxformatid') || 0);
  1921. if (ssfId === 0 &&
  1922. typeof defaults.mso.xslx.formatId.numbers === 'function')
  1923. ssfId = defaults.mso.xslx.formatId.numbers($(elt), _R, _C + CSOffset);
  1924. if (ssfId === 0 &&
  1925. typeof defaults.mso.xslx.formatId.date === 'function')
  1926. ssfId = defaults.mso.xslx.formatId.date($(elt), _R, _C + CSOffset);
  1927. if (ssfId === 49 || ssfId === '@')
  1928. _t = 's';
  1929. else if (cellInfo.type === 'number' ||
  1930. (ssfId > 0 && ssfId < 14) || (ssfId > 36 && ssfId < 41) || ssfId === 48)
  1931. _t = 'n';
  1932. else if (cellInfo.type === 'date' ||
  1933. (ssfId > 13 && ssfId < 37) || (ssfId > 44 && ssfId < 48) || ssfId === 56)
  1934. _t = 'd';
  1935. } else
  1936. _t = 's';
  1937. if (v != null) {
  1938. var vd;
  1939. if (v.length === 0)
  1940. o.t = 'z';
  1941. else if (v.trim().length === 0 || _t === 's') {
  1942. }
  1943. else if (cellInfo.type === 'function')
  1944. o = {f: v};
  1945. else if (v === 'TRUE')
  1946. o = {t: 'b', v: true};
  1947. else if (v === 'FALSE')
  1948. o = {t: 'b', v: false};
  1949. else if (_t === '' && $(elt).find('a').length) {
  1950. v = defaults.htmlHyperlink !== 'href' ? v : '';
  1951. o = {f: '=HYPERLINK("' + $(elt).find('a').attr('href') + (v.length ? '","' + v : '') + '")'};
  1952. }
  1953. else if (_t === 'n' || isFinite(xlsxToNumber(v, defaults.numbers.output))) { // yes, defaults.numbers.output is right
  1954. var vn = xlsxToNumber(v, defaults.numbers.output);
  1955. if (ssfId === 0 && typeof defaults.mso.xslx.formatId.numbers !== 'function')
  1956. ssfId = defaults.mso.xslx.formatId.numbers;
  1957. if (isFinite(vn) || isFinite(v))
  1958. o = {
  1959. t: 'n',
  1960. v: (isFinite(vn) ? vn : v),
  1961. z: (typeof ssfId === 'string') ? ssfId : (ssfId in ssfTable ? ssfTable[ssfId] : '0.00')
  1962. };
  1963. }
  1964. else if ((vd = parseDateUTC(v)) !== false || _t === 'd') {
  1965. if (ssfId === 0 && typeof defaults.mso.xslx.formatId.date !== 'function')
  1966. ssfId = defaults.mso.xslx.formatId.date;
  1967. o = {
  1968. t: 'd',
  1969. v: (vd !== false ? vd : v),
  1970. z: (typeof ssfId === 'string') ? ssfId : (ssfId in ssfTable ? ssfTable[ssfId] : 'm/d/yy')
  1971. };
  1972. }
  1973. }
  1974. ws[xlsxEncodeCell({c: C, r: R})] = o;
  1975. if (range.e.c < C)
  1976. range.e.c = C;
  1977. C += CS;
  1978. }
  1979. ++R;
  1980. }
  1981. if (merges.length) ws['!merges'] = merges;
  1982. if (rowinfo.length) ws['!rows'] = rowinfo;
  1983. range.e.r = R - 1;
  1984. ws['!ref'] = xlsxEncodeRange(range);
  1985. if (R >= sheetRows)
  1986. ws['!fullref'] = xlsxEncodeRange((range.e.r = rows.length - _R + R - 1, range));
  1987. return ws;
  1988. }
  1989. function xlsxEncodeRow (row) { return '' + (row + 1); }
  1990. function xlsxEncodeCol (col) {
  1991. var s = '';
  1992. for (++col; col; col = Math.floor((col - 1) / 26)) s = String.fromCharCode(((col - 1) % 26) + 65) + s;
  1993. return s;
  1994. }
  1995. function xlsxEncodeCell (cell) { return xlsxEncodeCol(cell.c) + xlsxEncodeRow(cell.r); }
  1996. function xlsxEncodeRange (cs, ce) {
  1997. if (typeof ce === 'undefined' || typeof ce === 'number') {
  1998. return xlsxEncodeRange(cs.s, cs.e);
  1999. }
  2000. if (typeof cs !== 'string') cs = xlsxEncodeCell((cs));
  2001. if (typeof ce !== 'string') ce = xlsxEncodeCell((ce));
  2002. return cs === ce ? cs : cs + ':' + ce;
  2003. }
  2004. function xlsxToNumber (s, numbersFormat) {
  2005. var v = Number(s);
  2006. if (isFinite(v)) return v;
  2007. var wt = 1;
  2008. var ss = s;
  2009. if ('' !== numbersFormat.thousandsSeparator)
  2010. ss = ss.replace(new RegExp('([\\d])' + numbersFormat.thousandsSeparator + '([\\d])', 'g'), '$1$2');
  2011. if ('.' !== numbersFormat.decimalMark)
  2012. ss = ss.replace(new RegExp('([\\d])' + numbersFormat.decimalMark + '([\\d])', 'g'), '$1.$2');
  2013. ss = ss.replace(/[$]/g, '').replace(/[%]/g, function () {
  2014. wt *= 100;
  2015. return '';
  2016. });
  2017. if (isFinite(v = Number(ss))) return v / wt;
  2018. ss = ss.replace(/[(](.*)[)]/, function ($$, $1) {
  2019. wt = -wt;
  2020. return $1;
  2021. });
  2022. if (isFinite(v = Number(ss))) return v / wt;
  2023. return v;
  2024. }
  2025. function strHashCode (str) {
  2026. var hash = 0, i, chr, len;
  2027. if (str.length === 0) return hash;
  2028. for (i = 0, len = str.length; i < len; i++) {
  2029. chr = str.charCodeAt(i);
  2030. hash = ((hash << 5) - hash) + chr;
  2031. hash |= 0; // Convert to 32bit integer
  2032. }
  2033. return hash;
  2034. }
  2035. function saveToFile (data, fileName, type, charset, encoding, bom) {
  2036. var saveIt = true;
  2037. if (typeof defaults.onBeforeSaveToFile === 'function') {
  2038. saveIt = defaults.onBeforeSaveToFile(data, fileName, type, charset, encoding);
  2039. if (typeof saveIt !== 'boolean')
  2040. saveIt = true;
  2041. }
  2042. if (saveIt) {
  2043. try {
  2044. blob = new Blob([data], {type: type + ';charset=' + charset});
  2045. saveAs(blob, fileName, bom === false);
  2046. if (typeof defaults.onAfterSaveToFile === 'function')
  2047. defaults.onAfterSaveToFile(data, fileName);
  2048. } catch (e) {
  2049. downloadFile(fileName,
  2050. 'data:' + type +
  2051. (charset.length ? ';charset=' + charset : '') +
  2052. (encoding.length ? ';' + encoding : '') + ',',
  2053. (bom ? ('\ufeff' + data) : data));
  2054. }
  2055. }
  2056. }
  2057. function downloadFile (filename, header, data) {
  2058. var ua = window.navigator.userAgent;
  2059. if (filename !== false && window.navigator.msSaveOrOpenBlob) {
  2060. //noinspection JSUnresolvedFunction
  2061. window.navigator.msSaveOrOpenBlob(new Blob([data]), filename);
  2062. } else if (filename !== false && (ua.indexOf('MSIE ') > 0 || !!ua.match(/Trident.*rv\:11\./))) {
  2063. // Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin)
  2064. // based on sampopes answer on http://stackoverflow.com/questions/22317951
  2065. // ! Not working for json and pdf format !
  2066. var frame = document.createElement('iframe');
  2067. if (frame) {
  2068. document.body.appendChild(frame);
  2069. frame.setAttribute('style', 'display:none');
  2070. frame.contentDocument.open('txt/plain', 'replace');
  2071. frame.contentDocument.write(data);
  2072. frame.contentDocument.close();
  2073. frame.contentWindow.focus();
  2074. var extension = filename.substr((filename.lastIndexOf('.') + 1));
  2075. switch (extension) {
  2076. case 'doc':
  2077. case 'json':
  2078. case 'png':
  2079. case 'pdf':
  2080. case 'xls':
  2081. case 'xlsx':
  2082. filename += '.txt';
  2083. break;
  2084. }
  2085. frame.contentDocument.execCommand('SaveAs', true, filename);
  2086. document.body.removeChild(frame);
  2087. }
  2088. } else {
  2089. var DownloadLink = document.createElement('a');
  2090. if (DownloadLink) {
  2091. var blobUrl = null;
  2092. DownloadLink.style.display = 'none';
  2093. if (filename !== false)
  2094. DownloadLink.download = filename;
  2095. else
  2096. DownloadLink.target = '_blank';
  2097. if (typeof data === 'object') {
  2098. window.URL = window.URL || window.webkitURL;
  2099. var binaryData = [];
  2100. binaryData.push(data);
  2101. blobUrl = window.URL.createObjectURL(new Blob(binaryData, {type: header}));
  2102. DownloadLink.href = blobUrl;
  2103. } else if (header.toLowerCase().indexOf('base64,') >= 0)
  2104. DownloadLink.href = header + base64encode(data);
  2105. else
  2106. DownloadLink.href = header + encodeURIComponent(data);
  2107. document.body.appendChild(DownloadLink);
  2108. if (document.createEvent) {
  2109. if (DownloadEvt === null)
  2110. DownloadEvt = document.createEvent('MouseEvents');
  2111. DownloadEvt.initEvent('click', true, false);
  2112. DownloadLink.dispatchEvent(DownloadEvt);
  2113. } else if (document.createEventObject)
  2114. DownloadLink.fireEvent('onclick');
  2115. else if (typeof DownloadLink.onclick === 'function')
  2116. DownloadLink.onclick();
  2117. setTimeout(function () {
  2118. if (blobUrl)
  2119. window.URL.revokeObjectURL(blobUrl);
  2120. document.body.removeChild(DownloadLink);
  2121. if (typeof defaults.onAfterSaveToFile === 'function')
  2122. defaults.onAfterSaveToFile(data, filename);
  2123. }, 100);
  2124. }
  2125. }
  2126. }
  2127. function utf8Encode (text) {
  2128. if (typeof text === 'string') {
  2129. text = text.replace(/\x0d\x0a/g, '\x0a');
  2130. var utftext = '';
  2131. for (var n = 0; n < text.length; n++) {
  2132. var c = text.charCodeAt(n);
  2133. if (c < 128) {
  2134. utftext += String.fromCharCode(c);
  2135. } else if ((c > 127) && (c < 2048)) {
  2136. utftext += String.fromCharCode((c >> 6) | 192);
  2137. utftext += String.fromCharCode((c & 63) | 128);
  2138. } else {
  2139. utftext += String.fromCharCode((c >> 12) | 224);
  2140. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  2141. utftext += String.fromCharCode((c & 63) | 128);
  2142. }
  2143. }
  2144. return utftext;
  2145. }
  2146. return text;
  2147. }
  2148. function base64encode (input) {
  2149. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  2150. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  2151. var output = '';
  2152. var i = 0;
  2153. input = utf8Encode(input);
  2154. while (i < input.length) {
  2155. chr1 = input.charCodeAt(i++);
  2156. chr2 = input.charCodeAt(i++);
  2157. chr3 = input.charCodeAt(i++);
  2158. enc1 = chr1 >> 2;
  2159. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2160. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  2161. enc4 = chr3 & 63;
  2162. if (isNaN(chr2)) {
  2163. enc3 = enc4 = 64;
  2164. } else if (isNaN(chr3)) {
  2165. enc4 = 64;
  2166. }
  2167. output = output +
  2168. keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  2169. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  2170. }
  2171. return output;
  2172. }
  2173. if (typeof defaults.onTableExportEnd === 'function')
  2174. defaults.onTableExportEnd();
  2175. return this;
  2176. };
  2177. })(jQuery);