酒店预订平台
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.
 
 
 
 
 
 

2629 lines
100 KiB

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