tableExport.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  1. /**
  2. * @preserve tableExport.jquery.plugin
  3. *
  4. * Copyright (c) 2015,2016 hhurz, https://github.com/hhurz/tableExport.jquery.plugin
  5. * Original work Copyright (c) 2014 Giri Raj, https://github.com/kayalshri/
  6. *
  7. * Licensed under the MIT License, http://opensource.org/licenses/mit-license
  8. */
  9. (function ($) {
  10. $.fn.extend({
  11. tableExport: function (options) {
  12. var defaults = {
  13. consoleLog: false,
  14. csvEnclosure: '"',
  15. csvSeparator: ',',
  16. csvUseBOM: true,
  17. displayTableName: false,
  18. escape: false,
  19. excelstyles: [], // e.g. ['border-bottom', 'border-top', 'border-left', 'border-right']
  20. fileName: 'tableExport',
  21. htmlContent: false,
  22. ignoreColumn: [],
  23. ignoreRow:[],
  24. jsonScope: 'all', // head, data, all
  25. jspdf: {orientation: 'p',
  26. unit: 'pt',
  27. format: 'a4', // jspdf page format or 'bestfit' for autmatic paper format selection
  28. margins: {left: 20, right: 10, top: 10, bottom: 10},
  29. autotable: {styles: {cellPadding: 2,
  30. rowHeight: 12,
  31. fontSize: 8,
  32. fillColor: 255, // color value or 'inherit' to use css background-color from html table
  33. textColor: 50, // color value or 'inherit' to use css color from html table
  34. fontStyle: 'normal', // normal, bold, italic, bolditalic or 'inherit' to use css font-weight and fonst-style from html table
  35. overflow: 'ellipsize', // visible, hidden, ellipsize or linebreak
  36. halign: 'left', // left, center, right
  37. valign: 'middle' // top, middle, bottom
  38. },
  39. headerStyles: {fillColor: [52, 73, 94],
  40. textColor: 255,
  41. fontStyle: 'bold',
  42. halign: 'center'
  43. },
  44. alternateRowStyles: {fillColor: 245
  45. },
  46. tableExport: {onAfterAutotable: null,
  47. onBeforeAutotable: null,
  48. onTable: null,
  49. outputImages: true
  50. }
  51. }
  52. },
  53. numbers: {html: {decimalMark: '.',
  54. thousandsSeparator: ','
  55. },
  56. output: {decimalMark: '.',
  57. thousandsSeparator: ','
  58. }
  59. },
  60. onCellData: null,
  61. onCellHtmlData: null,
  62. outputMode: 'file', // 'file', 'string', 'base64' or 'window' (experimental)
  63. pdfmake: {enabled: false}, // true: use pdfmake instead of jspdf(-autotable)
  64. tbodySelector: 'tr',
  65. tfootSelector: 'tr', // set empty ('') to prevent export of tfoot rows
  66. theadSelector: 'tr',
  67. tableName: 'myTableName',
  68. type: 'csv', // 'csv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf'
  69. worksheetName: 'xlsWorksheetName'
  70. };
  71. var FONT_ROW_RATIO = 1.15;
  72. var el = this;
  73. var DownloadEvt = null;
  74. var $hrows = [];
  75. var $rows = [];
  76. var rowIndex = 0;
  77. var rowspans = [];
  78. var trData = '';
  79. var colNames = [];
  80. var blob;
  81. $.extend(true, defaults, options);
  82. colNames = GetColumnNames (el);
  83. if (defaults.type == 'csv' || defaults.type == 'txt') {
  84. var csvData = "";
  85. var rowlength = 0;
  86. rowIndex = 0;
  87. var CollectCsvData = function ($rows, rowselector, length) {
  88. $rows.each(function () {
  89. trData = "";
  90. ForEachVisibleCell(this, rowselector, rowIndex, length + $rows.length,
  91. function (cell, row, col) {
  92. trData += csvString(cell, row, col) + defaults.csvSeparator;
  93. });
  94. trData = $.trim(trData).substring(0, trData.length - 1);
  95. if (trData.length > 0) {
  96. if (csvData.length > 0)
  97. csvData += "\n";
  98. csvData += trData;
  99. }
  100. rowIndex++;
  101. });
  102. return $rows.length;
  103. };
  104. rowlength += CollectCsvData ($(el).find('thead').first().find(defaults.theadSelector), 'th,td', rowlength);
  105. $(el).find('tbody').each(function() {
  106. rowlength += CollectCsvData ($(this).find(defaults.tbodySelector), 'td,th', rowlength);
  107. });
  108. if (defaults.tfootSelector.length)
  109. CollectCsvData ($(el).find('tfoot').first().find(defaults.tfootSelector), 'td,th', rowlength);
  110. csvData += "\n";
  111. //output
  112. if (defaults.consoleLog === true)
  113. console.log(csvData);
  114. if (defaults.outputMode === 'string')
  115. return csvData;
  116. if (defaults.outputMode === 'base64')
  117. return base64encode(csvData);
  118. if (defaults.outputMode === 'window') {
  119. downloadFile(false, 'data:text/' + (defaults.type == 'csv' ? 'csv' : 'plain') + ';charset=utf-8,', csvData);
  120. return;
  121. }
  122. try {
  123. blob = new Blob([csvData], {type: "text/" + (defaults.type == 'csv' ? 'csv' : 'plain') + ";charset=utf-8"});
  124. saveAs(blob, defaults.fileName + '.' + defaults.type, (defaults.type != 'csv' || defaults.csvUseBOM === false));
  125. }
  126. catch (e) {
  127. downloadFile(defaults.fileName + '.' + defaults.type,
  128. 'data:text/' + (defaults.type == 'csv' ? 'csv' : 'plain') + ';charset=utf-8,' + ((defaults.type == 'csv' && defaults.csvUseBOM)? '\ufeff' : ''),
  129. csvData);
  130. }
  131. } else if (defaults.type == 'sql') {
  132. // Header
  133. rowIndex = 0;
  134. var tdData = "INSERT INTO `" + defaults.tableName + "` (";
  135. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  136. $hrows.each(function () {
  137. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  138. function (cell, row, col) {
  139. tdData += "'" + parseString(cell, row, col) + "',";
  140. });
  141. rowIndex++;
  142. tdData = $.trim(tdData);
  143. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  144. });
  145. tdData += ") VALUES ";
  146. // Row vs Column
  147. $(el).find('tbody').each(function() {
  148. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  149. });
  150. if (defaults.tfootSelector.length)
  151. $rows.push.apply ($rows, $(el).find('tfoot').find(defaults.tfootSelector));
  152. $($rows).each(function () {
  153. trData = "";
  154. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  155. function (cell, row, col) {
  156. trData += "'" + parseString(cell, row, col) + "',";
  157. });
  158. if (trData.length > 3) {
  159. tdData += "(" + trData;
  160. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  161. tdData += "),";
  162. }
  163. rowIndex++;
  164. });
  165. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  166. tdData += ";";
  167. //output
  168. if (defaults.consoleLog === true)
  169. console.log(tdData);
  170. if (defaults.outputMode === 'string')
  171. return tdData;
  172. if (defaults.outputMode === 'base64')
  173. return base64encode(tdData);
  174. try {
  175. blob = new Blob([tdData], {type: "text/plain;charset=utf-8"});
  176. saveAs(blob, defaults.fileName + '.sql');
  177. }
  178. catch (e) {
  179. downloadFile(defaults.fileName + '.sql',
  180. 'data:application/sql;charset=utf-8,',
  181. tdData);
  182. }
  183. } else if (defaults.type == 'json') {
  184. var jsonHeaderArray = [];
  185. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  186. $hrows.each(function () {
  187. var jsonArrayTd = [];
  188. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  189. function (cell, row, col) {
  190. jsonArrayTd.push(parseString(cell, row, col));
  191. });
  192. jsonHeaderArray.push(jsonArrayTd);
  193. });
  194. var jsonArray = [];
  195. $(el).find('tbody').each(function() {
  196. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  197. });
  198. if (defaults.tfootSelector.length)
  199. $rows.push.apply ($rows, $(el).find('tfoot').find(defaults.tfootSelector));
  200. $($rows).each(function () {
  201. var jsonObjectTd = {};
  202. var colIndex = 0;
  203. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  204. function (cell, row, col) {
  205. if (jsonHeaderArray.length) {
  206. jsonObjectTd[jsonHeaderArray[jsonHeaderArray.length-1][colIndex]] = parseString(cell, row, col);
  207. } else {
  208. jsonObjectTd[colIndex] = parseString(cell, row, col);
  209. }
  210. colIndex++;
  211. });
  212. if ($.isEmptyObject(jsonObjectTd) === false)
  213. jsonArray.push(jsonObjectTd);
  214. rowIndex++;
  215. });
  216. var sdata = "";
  217. if (defaults.jsonScope == 'head')
  218. sdata = JSON.stringify(jsonHeaderArray);
  219. else if (defaults.jsonScope == 'data')
  220. sdata = JSON.stringify(jsonArray);
  221. else // all
  222. sdata = JSON.stringify({header: jsonHeaderArray, data: jsonArray});
  223. if (defaults.consoleLog === true)
  224. console.log(sdata);
  225. if (defaults.outputMode === 'string')
  226. return sdata;
  227. if (defaults.outputMode === 'base64')
  228. return base64encode(sdata);
  229. try {
  230. blob = new Blob([sdata], {type: "application/json;charset=utf-8"});
  231. saveAs(blob, defaults.fileName + '.json');
  232. }
  233. catch (e) {
  234. downloadFile(defaults.fileName + '.json',
  235. 'data:application/json;charset=utf-8;base64,',
  236. sdata);
  237. }
  238. } else if (defaults.type === 'xml') {
  239. rowIndex = 0;
  240. var xml = '<?xml version="1.0" encoding="utf-8"?>';
  241. xml += '<tabledata><fields>';
  242. // Header
  243. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  244. $hrows.each(function () {
  245. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  246. function (cell, row, col) {
  247. xml += "<field>" + parseString(cell, row, col) + "</field>";
  248. });
  249. rowIndex++;
  250. });
  251. xml += '</fields><data>';
  252. // Row Vs Column
  253. var rowCount = 1;
  254. $(el).find('tbody').each(function() {
  255. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  256. });
  257. if (defaults.tfootSelector.length)
  258. $rows.push.apply ($rows, $(el).find('tfoot').find(defaults.tfootSelector));
  259. $($rows).each(function () {
  260. var colCount = 1;
  261. trData = "";
  262. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  263. function (cell, row, col) {
  264. trData += "<column-" + colCount + ">" + parseString(cell, row, col) + "</column-" + colCount + ">";
  265. colCount++;
  266. });
  267. if (trData.length > 0 && trData != "<column-1></column-1>") {
  268. xml += '<row id="' + rowCount + '">' + trData + '</row>';
  269. rowCount++;
  270. }
  271. rowIndex++;
  272. });
  273. xml += '</data></tabledata>';
  274. //output
  275. if (defaults.consoleLog === true)
  276. console.log(xml);
  277. if (defaults.outputMode === 'string')
  278. return xml;
  279. if (defaults.outputMode === 'base64')
  280. return base64encode(xml);
  281. try {
  282. blob = new Blob([xml], {type: "application/xml;charset=utf-8"});
  283. saveAs(blob, defaults.fileName + '.xml');
  284. }
  285. catch (e) {
  286. downloadFile(defaults.fileName + '.xml',
  287. 'data:application/xml;charset=utf-8;base64,',
  288. xml);
  289. }
  290. } else if (defaults.type == 'excel' || defaults.type == 'xls' || defaults.type == 'word' || defaults.type == 'doc') {
  291. var MSDocType = (defaults.type == 'excel' || defaults.type == 'xls') ? 'excel' : 'word';
  292. var MSDocExt = (MSDocType == 'excel') ? 'xls' : 'doc';
  293. var MSDocSchema = 'xmlns:x="urn:schemas-microsoft-com:office:' + MSDocType + '"';
  294. var $tables = $(el).filter(function() {
  295. return $(this).data("tableexport-display") != 'none' &&
  296. ($(this).is(':visible') ||
  297. $(this).data("tableexport-display") == 'always');
  298. });
  299. var docData = '';
  300. $tables.each(function(){
  301. var $table = $(this);
  302. rowIndex = 0;
  303. colNames = GetColumnNames (this);
  304. docData += '<table><thead>';
  305. // Header
  306. $hrows = $table.find('thead').first().find(defaults.theadSelector);
  307. $hrows.each(function() {
  308. trData = "";
  309. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  310. function(cell, row, col) {
  311. if (cell !== null) {
  312. var thstyle = '';
  313. trData += '<th';
  314. for (var styles in defaults.excelstyles) {
  315. if (defaults.excelstyles.hasOwnProperty(styles)) {
  316. var thcss = $(cell).css(defaults.excelstyles[styles]);
  317. if (thcss !== '' && thcss !='0px none rgb(0, 0, 0)' && thcss != 'rgba(0, 0, 0, 0)') {
  318. thstyle += (thstyle === '') ? 'style="' : ';';
  319. thstyle += defaults.excelstyles[styles] + ':' + thcss;
  320. }
  321. }
  322. }
  323. if (thstyle !== '' )
  324. trData += ' ' + thstyle + '"';
  325. if ($(cell).is("[colspan]"))
  326. trData += ' colspan="' + $(cell).attr('colspan') + '"';
  327. if ($(cell).is("[rowspan]"))
  328. trData += ' rowspan="' + $(cell).attr('rowspan') + '"';
  329. trData += '>' + parseString(cell, row, col) + '</th>';
  330. }
  331. });
  332. if (trData.length > 0)
  333. docData += '<tr>' + trData + '</tr>';
  334. rowIndex++;
  335. });
  336. docData += '</thead><tbody>';
  337. // Row Vs Column, support multiple tbodys
  338. $table.find('tbody').each(function() {
  339. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  340. });
  341. if (defaults.tfootSelector.length)
  342. $rows.push.apply ($rows, $table.find('tfoot').find(defaults.tfootSelector));
  343. $($rows).each(function() {
  344. var $row = $(this);
  345. trData = "";
  346. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  347. function(cell, row, col) {
  348. if (cell !== null) {
  349. var tdstyle = '';
  350. var tdcss = $(cell).data("tableexport-msonumberformat");
  351. if (typeof tdcss == 'undefined' && typeof defaults.onMsoNumberFormat === 'function')
  352. tdcss = defaults.onMsoNumberFormat(cell, row, col);
  353. if (typeof tdcss != 'undefined' && tdcss !== '')
  354. tdstyle = 'style="mso-number-format:\'' + tdcss + '\'';
  355. for (var cssStyle in defaults.excelstyles) {
  356. if (defaults.excelstyles.hasOwnProperty(cssStyle)) {
  357. tdcss = $(cell).css(defaults.excelstyles[cssStyle]);
  358. if (tdcss === '')
  359. tdcss = $row.css(defaults.excelstyles[cssStyle]);
  360. if (tdcss !== '' && tdcss !='0px none rgb(0, 0, 0)' && tdcss != 'rgba(0, 0, 0, 0)') {
  361. tdstyle += (tdstyle === '') ? 'style="' : ';';
  362. tdstyle += defaults.excelstyles[cssStyle] + ':' + tdcss;
  363. }
  364. }
  365. }
  366. trData += '<td';
  367. if (tdstyle !== '' )
  368. trData += ' ' + tdstyle + '"';
  369. if ($(cell).is("[colspan]"))
  370. trData += ' colspan="' + $(cell).attr('colspan') + '"';
  371. if ($(cell).is("[rowspan]"))
  372. trData += ' rowspan="' + $(cell).attr('rowspan') + '"';
  373. trData += '>' + parseString(cell, row, col).replace(/\n/g,'<br>') + '</td>';
  374. }
  375. });
  376. if (trData.length > 0)
  377. docData += '<tr>' + trData + '</tr>';
  378. rowIndex++;
  379. });
  380. if (defaults.displayTableName)
  381. docData += '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>' + defaults.tableName + '</p>')) + '</td></tr>';
  382. docData += '</tbody></table>';
  383. if (defaults.consoleLog === true)
  384. console.log(docData);
  385. });
  386. var docFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + MSDocSchema + ' xmlns="http://www.w3.org/TR/REC-html40">';
  387. docFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + MSDocType + '; charset=UTF-8">';
  388. docFile += "<head>";
  389. if (MSDocType === 'excel') {
  390. docFile += "<!--[if gte mso 9]>";
  391. docFile += "<xml>";
  392. docFile += "<x:ExcelWorkbook>";
  393. docFile += "<x:ExcelWorksheets>";
  394. docFile += "<x:ExcelWorksheet>";
  395. docFile += "<x:Name>";
  396. docFile += defaults.worksheetName;
  397. docFile += "</x:Name>";
  398. docFile += "<x:WorksheetOptions>";
  399. docFile += "<x:DisplayGridlines/>";
  400. docFile += "</x:WorksheetOptions>";
  401. docFile += "</x:ExcelWorksheet>";
  402. docFile += "</x:ExcelWorksheets>";
  403. docFile += "</x:ExcelWorkbook>";
  404. docFile += "</xml>";
  405. docFile += "<![endif]-->";
  406. }
  407. docFile += "<style>br {mso-data-placement:same-cell;}</style>";
  408. docFile += "</head>";
  409. docFile += "<body>";
  410. docFile += docData;
  411. docFile += "</body>";
  412. docFile += "</html>";
  413. if (defaults.consoleLog === true)
  414. console.log(docFile);
  415. if (defaults.outputMode === 'string')
  416. return docFile;
  417. if (defaults.outputMode === 'base64')
  418. return base64encode(docFile);
  419. try {
  420. blob = new Blob([docFile], {type: 'application/vnd.ms-' + defaults.type});
  421. saveAs(blob, defaults.fileName + '.' + MSDocExt);
  422. }
  423. catch (e) {
  424. downloadFile(defaults.fileName + '.' + MSDocExt,
  425. 'data:application/vnd.ms-' + MSDocType + ';base64,',
  426. docFile);
  427. }
  428. } else if (defaults.type == 'xlsx') {
  429. var data = [];
  430. var ranges = [];
  431. rowIndex = 0;
  432. $rows = $(el).find('thead').first().find(defaults.theadSelector);
  433. $(el).find('tbody').each(function() {
  434. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  435. });
  436. if (defaults.tfootSelector.length)
  437. $rows.push.apply ($rows, $(el).find('tfoot').find(defaults.tfootSelector));
  438. $($rows).each(function () {
  439. var cols = [];
  440. ForEachVisibleCell(this, 'th,td', rowIndex, $rows.length,
  441. function (cell, row, col) {
  442. if (typeof cell !== 'undefined' && cell !== null) {
  443. var colspan = parseInt(cell.getAttribute('colspan'));
  444. var rowspan = parseInt(cell.getAttribute('rowspan'));
  445. var cellValue = parseString(cell, row, col);
  446. if(cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
  447. //Skip ranges
  448. ranges.forEach(function(range) {
  449. if(rowIndex >= range.s.r && rowIndex <= range.e.r && cols.length >= range.s.c && cols.length <= range.e.c) {
  450. for(var i = 0; i <= range.e.c - range.s.c; ++i) cols.push(null);
  451. }
  452. });
  453. //Handle Row Span
  454. if (rowspan || colspan) {
  455. rowspan = rowspan || 1;
  456. colspan = colspan || 1;
  457. ranges.push({s:{r:rowIndex, c:cols.length},e:{r:rowIndex+rowspan-1, c:cols.length+colspan-1}});
  458. }
  459. //Handle Value
  460. cols.push(cellValue !== "" ? cellValue : null);
  461. //Handle Colspan
  462. if (colspan) for (var k = 0; k < colspan - 1; ++k) cols.push(null);
  463. }
  464. });
  465. data.push(cols);
  466. rowIndex++;
  467. });
  468. var wb = new jx_Workbook(),
  469. ws = jx_createSheet(data);
  470. // add ranges to worksheet
  471. ws['!merges'] = ranges;
  472. // add worksheet to workbook
  473. wb.SheetNames.push(defaults.worksheetName);
  474. wb.Sheets[defaults.worksheetName] = ws;
  475. var wbout = XLSX.write(wb, {bookType: defaults.type, bookSST: false, type: 'binary'});
  476. try {
  477. blob = new Blob([jx_s2ab(wbout)], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'});
  478. saveAs(blob, defaults.fileName + '.' + defaults.type);
  479. }
  480. catch (e) {
  481. downloadFile(defaults.fileName + '.' + defaults.type,
  482. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8',
  483. data);
  484. }
  485. } else if (defaults.type == 'png') {
  486. //html2canvas($(el)[0], {
  487. // onrendered: function (canvas) {
  488. html2canvas($(el)[0]).then(
  489. function (canvas) {
  490. var image = canvas.toDataURL();
  491. var byteString = atob(image.substring(22)); // remove data stuff
  492. var buffer = new ArrayBuffer(byteString.length);
  493. var intArray = new Uint8Array(buffer);
  494. for (var i = 0; i < byteString.length; i++)
  495. intArray[i] = byteString.charCodeAt(i);
  496. if (defaults.consoleLog === true)
  497. console.log(byteString);
  498. if (defaults.outputMode === 'string')
  499. return byteString;
  500. if (defaults.outputMode === 'base64')
  501. return base64encode(image);
  502. if (defaults.outputMode === 'window') {
  503. window.open(image);
  504. return;
  505. }
  506. try {
  507. blob = new Blob([buffer], {type: "image/png"});
  508. saveAs(blob, defaults.fileName + '.png');
  509. }
  510. catch (e) {
  511. downloadFile(defaults.fileName + '.png',
  512. 'data:image/png,',
  513. image);
  514. }
  515. //}
  516. });
  517. } else if (defaults.type == 'pdf') {
  518. if (defaults.pdfmake.enabled === true) {
  519. // pdf output using pdfmake
  520. // https://github.com/bpampuch/pdfmake
  521. var widths = [];
  522. var body = [];
  523. rowIndex = 0;
  524. $hrows = $(this).find('thead').first().find(defaults.theadSelector);
  525. $hrows.each(function () {
  526. var h = [];
  527. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  528. function (cell, row, col) {
  529. h.push(parseString(cell, row, col));
  530. });
  531. if (h.length)
  532. body.push(h);
  533. for(var i = widths.length; i < h.length;i++)
  534. widths.push("*");
  535. rowIndex++;
  536. });
  537. $(this).find('tbody').each(function() {
  538. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  539. });
  540. if (defaults.tfootSelector.length)
  541. $rows.push.apply ($rows, $(this).find('tfoot').find(defaults.tfootSelector));
  542. $($rows).each(function () {
  543. var r = [];
  544. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  545. function (cell, row, col) {
  546. r.push(parseString(cell, row, col));
  547. });
  548. if (r.length)
  549. body.push(r);
  550. rowIndex++;
  551. });
  552. var docDefinition = {
  553. pageOrientation: 'landscape',
  554. content: [
  555. {
  556. table: {
  557. headerRows: $hrows.length,
  558. widths: widths,
  559. body: body
  560. }
  561. }
  562. ]
  563. };
  564. pdfMake.createPdf(docDefinition).getBuffer(function (buffer) {
  565. try {
  566. var blob = new Blob([buffer], {type: "application/pdf"});
  567. saveAs(blob, defaults.fileName + '.pdf');
  568. }
  569. catch (e) {
  570. downloadFile(defaults.fileName + '.pdf',
  571. 'data:application/pdf;base64,',
  572. buffer);
  573. }
  574. });
  575. }
  576. else if (defaults.jspdf.autotable === false) {
  577. // pdf output using jsPDF's core html support
  578. var addHtmlOptions = {
  579. dim: {
  580. w: getPropertyUnitValue($(el).first().get(0), 'width', 'mm'),
  581. h: getPropertyUnitValue($(el).first().get(0), 'height', 'mm')
  582. },
  583. pagesplit: false
  584. };
  585. var doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format);
  586. doc.addHTML($(el).first(),
  587. defaults.jspdf.margins.left,
  588. defaults.jspdf.margins.top,
  589. addHtmlOptions,
  590. function () {
  591. jsPdfOutput(doc);
  592. });
  593. //delete doc;
  594. }
  595. else {
  596. // pdf output using jsPDF AutoTable plugin
  597. // https://github.com/simonbengtsson/jsPDF-AutoTable
  598. var teOptions = defaults.jspdf.autotable.tableExport;
  599. // When setting jspdf.format to 'bestfit' tableExport tries to choose
  600. // the minimum required paper format and orientation in which the table
  601. // (or tables in multitable mode) completely fits without column adjustment
  602. if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') {
  603. var pageFormats = {
  604. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
  605. 'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
  606. 'a4': [595.28, 841.89]
  607. };
  608. var rk = '', ro = '';
  609. var mw = 0;
  610. $(el).filter(':visible').each(function () {
  611. if ($(this).css('display') != 'none') {
  612. var w = getPropertyUnitValue($(this).get(0), 'width', 'pt');
  613. if (w > mw) {
  614. if (w > pageFormats.a0[0]) {
  615. rk = 'a0';
  616. ro = 'l';
  617. }
  618. for (var key in pageFormats) {
  619. if (pageFormats.hasOwnProperty(key)) {
  620. if (pageFormats[key][1] > w) {
  621. rk = key;
  622. ro = 'l';
  623. if (pageFormats[key][0] > w)
  624. ro = 'p';
  625. }
  626. }
  627. }
  628. mw = w;
  629. }
  630. }
  631. });
  632. defaults.jspdf.format = (rk === '' ? 'a4' : rk);
  633. defaults.jspdf.orientation = (ro === '' ? 'w' : ro);
  634. }
  635. // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport,
  636. // thus it can be accessed from any callback function
  637. teOptions.doc = new jsPDF(defaults.jspdf.orientation,
  638. defaults.jspdf.unit,
  639. defaults.jspdf.format);
  640. if (teOptions.outputImages === true)
  641. teOptions.images = {};
  642. if (typeof teOptions.images != 'undefined') {
  643. $(el).filter(function() {
  644. return $(this).data("tableexport-display") != 'none' &&
  645. ($(this).is(':visible') ||
  646. $(this).data("tableexport-display") == 'always');
  647. }).each(function () {
  648. var rowCount = 0;
  649. $hrows = $(this).find('thead').find(defaults.theadSelector);
  650. $(this).find('tbody').each(function() {
  651. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  652. });
  653. if (defaults.tfootSelector.length)
  654. $rows.push.apply ($rows, $(this).find('tfoot').find(defaults.tfootSelector));
  655. $($rows).each(function () {
  656. ForEachVisibleCell(this, 'td,th', $hrows.length + rowCount, $hrows.length + $rows.length,
  657. function (cell, row, col) {
  658. if (typeof cell !== 'undefined' && cell !== null) {
  659. var kids = $(cell).children();
  660. if (typeof kids != 'undefined' && kids.length > 0)
  661. collectImages (cell, kids, teOptions);
  662. }
  663. });
  664. rowCount++;
  665. });
  666. });
  667. $hrows = [];
  668. $rows = [];
  669. }
  670. loadImages ( teOptions, function (imageCount) {
  671. $(el).filter(function() {
  672. return $(this).data("tableexport-display") != 'none' &&
  673. ($(this).is(':visible') ||
  674. $(this).data("tableexport-display") == 'always');
  675. }).each(function () {
  676. var colKey;
  677. var rowIndex = 0;
  678. colNames = GetColumnNames (this);
  679. teOptions.columns = [];
  680. teOptions.rows = [];
  681. teOptions.rowoptions = {};
  682. // onTable: optional callback function for every matching table that can be used
  683. // to modify the tableExport options or to skip the output of a particular table
  684. // if the table selector targets multiple tables
  685. if (typeof teOptions.onTable === 'function')
  686. if (teOptions.onTable($(this), defaults) === false)
  687. return true; // continue to next iteration step (table)
  688. // each table works with an own copy of AutoTable options
  689. defaults.jspdf.autotable.tableExport = null; // avoid deep recursion error
  690. var atOptions = $.extend(true, {}, defaults.jspdf.autotable);
  691. defaults.jspdf.autotable.tableExport = teOptions;
  692. atOptions.margin = {};
  693. $.extend(true, atOptions.margin, defaults.jspdf.margins);
  694. atOptions.tableExport = teOptions;
  695. // Fix jsPDF Autotable's row height calculation
  696. if (typeof atOptions.beforePageContent !== 'function') {
  697. atOptions.beforePageContent = function (data) {
  698. if (data.pageCount == 1) {
  699. var all = data.table.rows.concat(data.table.headerRow);
  700. all.forEach(function (row) {
  701. if ( row.height > 0 ) {
  702. row.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  703. data.table.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  704. }
  705. });
  706. }
  707. };
  708. }
  709. if (typeof atOptions.createdHeaderCell !== 'function') {
  710. // apply some original css styles to pdf header cells
  711. atOptions.createdHeaderCell = function (cell, data) {
  712. // jsPDF AutoTable plugin v2.0.14 fix: each cell needs its own styles object
  713. cell.styles = $.extend({}, data.row.styles);
  714. if (typeof teOptions.columns [data.column.dataKey] != 'undefined') {
  715. var col = teOptions.columns [data.column.dataKey];
  716. if (typeof col.rect != 'undefined') {
  717. var rh;
  718. cell.contentWidth = col.rect.width;
  719. if (typeof teOptions.heightRatio == 'undefined' || teOptions.heightRatio === 0) {
  720. if (data.row.raw [data.column.dataKey].rowspan)
  721. rh = data.row.raw [data.column.dataKey].rect.height / data.row.raw [data.column.dataKey].rowspan;
  722. else
  723. rh = data.row.raw [data.column.dataKey].rect.height;
  724. teOptions.heightRatio = cell.styles.rowHeight / rh;
  725. }
  726. rh = data.row.raw [data.column.dataKey].rect.height * teOptions.heightRatio;
  727. if (rh > cell.styles.rowHeight)
  728. cell.styles.rowHeight = rh;
  729. }
  730. if (typeof col.style != 'undefined' && col.style.hidden !== true) {
  731. cell.styles.halign = col.style.align;
  732. if (atOptions.styles.fillColor === 'inherit')
  733. cell.styles.fillColor = col.style.bcolor;
  734. if (atOptions.styles.textColor === 'inherit')
  735. cell.styles.textColor = col.style.color;
  736. if (atOptions.styles.fontStyle === 'inherit')
  737. cell.styles.fontStyle = col.style.fstyle;
  738. }
  739. }
  740. };
  741. }
  742. if (typeof atOptions.createdCell !== 'function') {
  743. // apply some original css styles to pdf table cells
  744. atOptions.createdCell = function (cell, data) {
  745. var rowopt = teOptions.rowoptions [data.row.index + ":" + data.column.dataKey];
  746. if (typeof rowopt != 'undefined' &&
  747. typeof rowopt.style != 'undefined' &&
  748. rowopt.style.hidden !== true) {
  749. cell.styles.halign = rowopt.style.align;
  750. if (atOptions.styles.fillColor === 'inherit')
  751. cell.styles.fillColor = rowopt.style.bcolor;
  752. if (atOptions.styles.textColor === 'inherit')
  753. cell.styles.textColor = rowopt.style.color;
  754. if (atOptions.styles.fontStyle === 'inherit')
  755. cell.styles.fontStyle = rowopt.style.fstyle;
  756. }
  757. };
  758. }
  759. if (typeof atOptions.drawHeaderCell !== 'function') {
  760. atOptions.drawHeaderCell = function (cell, data) {
  761. var colopt = teOptions.columns [data.column.dataKey];
  762. if ((colopt.style.hasOwnProperty("hidden") !== true || colopt.style.hidden !== true) &&
  763. colopt.rowIndex >= 0 )
  764. return prepareAutoTableText (cell, data, colopt);
  765. else
  766. return false; // cell is hidden
  767. };
  768. }
  769. if (typeof atOptions.drawCell !== 'function') {
  770. atOptions.drawCell = function (cell, data) {
  771. var rowopt = teOptions.rowoptions [data.row.index + ":" + data.column.dataKey];
  772. if ( prepareAutoTableText (cell, data, rowopt) ) {
  773. teOptions.doc.rect(cell.x, cell.y, cell.width, cell.height, cell.styles.fillStyle);
  774. if (typeof rowopt != 'undefined' && typeof rowopt.kids != 'undefined' && rowopt.kids.length > 0) {
  775. var dh = cell.height / rowopt.rect.height;
  776. if ( dh > teOptions.dh || typeof teOptions.dh == 'undefined' )
  777. teOptions.dh = dh;
  778. teOptions.dw = cell.width / rowopt.rect.width;
  779. drawCellElements (cell, rowopt.kids, teOptions);
  780. }
  781. teOptions.doc.autoTableText(cell.text, cell.textPos.x, cell.textPos.y, {
  782. halign: cell.styles.halign,
  783. valign: cell.styles.valign
  784. });
  785. }
  786. return false;
  787. };
  788. }
  789. // collect header and data rows
  790. teOptions.headerrows = [];
  791. $hrows = $(this).find('thead').find(defaults.theadSelector);
  792. $hrows.each(function () {
  793. colKey = 0;
  794. teOptions.headerrows[rowIndex] = [];
  795. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  796. function (cell, row, col) {
  797. var obj = getCellStyles (cell);
  798. obj.title = parseString(cell, row, col);
  799. obj.key = colKey++;
  800. obj.rowIndex = rowIndex;
  801. teOptions.headerrows[rowIndex].push(obj);
  802. });
  803. rowIndex++;
  804. });
  805. if (rowIndex > 0) {
  806. // iterate through last row
  807. $.each(teOptions.headerrows[rowIndex-1], function () {
  808. var obj = this;
  809. if (rowIndex > 1 && this.rect === null)
  810. obj = teOptions.headerrows[rowIndex-2][this.key];
  811. if (obj !== null)
  812. teOptions.columns.push(obj);
  813. });
  814. }
  815. var rowCount = 0;
  816. $rows = [];
  817. $(this).find('tbody').each(function() {
  818. $rows.push.apply ($rows, $(this).find(defaults.tbodySelector));
  819. });
  820. if (defaults.tfootSelector.length)
  821. $rows.push.apply ($rows, $(this).find('tfoot').find(defaults.tfootSelector));
  822. $($rows).each(function () {
  823. var rowData = [];
  824. colKey = 0;
  825. ForEachVisibleCell(this, 'td,th', rowIndex, $hrows.length + $rows.length,
  826. function (cell, row, col) {
  827. if (typeof teOptions.columns[colKey] === 'undefined') {
  828. // jsPDF-Autotable needs columns. Thus define hidden ones for tables without thead
  829. var obj = {
  830. title: '',
  831. key: colKey,
  832. style: {
  833. hidden: true
  834. }
  835. };
  836. teOptions.columns.push(obj);
  837. }
  838. if (typeof cell !== 'undefined' && cell !== null) {
  839. var obj = getCellStyles (cell);
  840. obj.kids = $(cell).children();
  841. teOptions.rowoptions [rowCount + ":" + colKey++] = obj;
  842. }
  843. else {
  844. var obj = $.extend(true, {}, teOptions.rowoptions [rowCount + ":" + (colKey-1)]);
  845. obj.colspan = -1;
  846. teOptions.rowoptions [rowCount + ":" + colKey++] = obj;
  847. }
  848. rowData.push(parseString(cell, row, col));
  849. });
  850. if (rowData.length) {
  851. teOptions.rows.push(rowData);
  852. rowCount++;
  853. }
  854. rowIndex++;
  855. });
  856. // onBeforeAutotable: optional callback function before calling
  857. // jsPDF AutoTable that can be used to modify the AutoTable options
  858. if (typeof teOptions.onBeforeAutotable === 'function')
  859. teOptions.onBeforeAutotable($(this), teOptions.columns, teOptions.rows, atOptions);
  860. teOptions.doc.autoTable(teOptions.columns, teOptions.rows, atOptions);
  861. // onAfterAutotable: optional callback function after returning
  862. // from jsPDF AutoTable that can be used to modify the AutoTable options
  863. if (typeof teOptions.onAfterAutotable === 'function')
  864. teOptions.onAfterAutotable($(this), atOptions);
  865. // set the start position for the next table (in case there is one)
  866. defaults.jspdf.autotable.startY = teOptions.doc.autoTableEndPosY() + atOptions.margin.top;
  867. });
  868. jsPdfOutput(teOptions.doc);
  869. if (typeof teOptions.headerrows != 'undefined')
  870. teOptions.headerrows.length = 0;
  871. if (typeof teOptions.columns != 'undefined')
  872. teOptions.columns.length = 0;
  873. if (typeof teOptions.rows != 'undefined')
  874. teOptions.rows.length = 0;
  875. delete teOptions.doc;
  876. teOptions.doc = null;
  877. });
  878. }
  879. }
  880. function FindColObject (objects, colIndex, rowIndex) {
  881. var result = null;
  882. $.each(objects, function () {
  883. if (this.rowIndex == rowIndex && this.key == colIndex) {
  884. result = this;
  885. return false;
  886. }
  887. });
  888. return result;
  889. }
  890. function GetColumnNames (table) {
  891. var result = [];
  892. $(table).find('thead').first().find('th').each(function(index, el) {
  893. if ($(el).attr("data-field") !== undefined)
  894. result[index] = $(el).attr("data-field");
  895. else
  896. result[index] = index.toString();
  897. });
  898. return result;
  899. }
  900. function isColumnIgnored($row, colIndex) {
  901. var result = false;
  902. if (defaults.ignoreColumn.length > 0) {
  903. if (typeof defaults.ignoreColumn[0] == 'string') {
  904. if (colNames.length > colIndex && typeof colNames[colIndex] != 'undefined')
  905. if ($.inArray(colNames[colIndex], defaults.ignoreColumn) != -1)
  906. result = true;
  907. }
  908. else if (typeof defaults.ignoreColumn[0] == 'number') {
  909. if ($.inArray(colIndex, defaults.ignoreColumn) != -1 ||
  910. $.inArray(colIndex-$row.length, defaults.ignoreColumn) != -1)
  911. result = true;
  912. }
  913. }
  914. return result;
  915. }
  916. function ForEachVisibleCell(tableRow, selector, rowIndex, rowCount, cellcallback) {
  917. if ($.inArray(rowIndex, defaults.ignoreRow) == -1 &&
  918. $.inArray(rowIndex-rowCount, defaults.ignoreRow) == -1) {
  919. var $row = $(tableRow).filter(function() {
  920. return $(this).data("tableexport-display") != 'none' &&
  921. ($(this).is(':visible') ||
  922. $(this).data("tableexport-display") == 'always' ||
  923. $(this).closest('table').data("tableexport-display") == 'always');
  924. }).find(selector);
  925. var rowColspan = 0;
  926. var rowColIndex = 0;
  927. $row.each(function (colIndex) {
  928. if ($(this).data("tableexport-display") == 'always' ||
  929. ($(this).css('display') != 'none' &&
  930. $(this).css('visibility') != 'hidden' &&
  931. $(this).data("tableexport-display") != 'none')) {
  932. if (isColumnIgnored($row, colIndex) === false) {
  933. if (typeof (cellcallback) === "function") {
  934. var c, Colspan = 0;
  935. var r, Rowspan = 0;
  936. // handle rowspans from previous rows
  937. if (typeof rowspans[rowIndex] != 'undefined' && rowspans[rowIndex].length > 0) {
  938. for (c = 0; c <= colIndex; c++) {
  939. if (typeof rowspans[rowIndex][c] != 'undefined') {
  940. cellcallback(null, rowIndex, c);
  941. delete rowspans[rowIndex][c];
  942. colIndex++;
  943. }
  944. }
  945. }
  946. rowColIndex = colIndex;
  947. if ($(this).is("[colspan]")) {
  948. Colspan = parseInt($(this).attr('colspan'));
  949. rowColspan += Colspan > 0 ? Colspan - 1 : 0;
  950. }
  951. if ($(this).is("[rowspan]"))
  952. Rowspan = parseInt($(this).attr('rowspan'));
  953. // output content of current cell
  954. cellcallback(this, rowIndex, colIndex);
  955. // handle colspan of current cell
  956. for (c = 0; c < Colspan - 1; c++)
  957. cellcallback(null, rowIndex, colIndex + c);
  958. // store rowspan for following rows
  959. if (Rowspan) {
  960. for (r = 1; r < Rowspan; r++) {
  961. if (typeof rowspans[rowIndex + r] == 'undefined')
  962. rowspans[rowIndex + r] = [];
  963. rowspans[rowIndex + r][colIndex + rowColspan] = "";
  964. for (c = 1; c < Colspan; c++)
  965. rowspans[rowIndex + r][colIndex + rowColspan - c] = "";
  966. }
  967. }
  968. }
  969. }
  970. }
  971. });
  972. // handle rowspans from previous rows
  973. if (typeof rowspans[rowIndex] != 'undefined' && rowspans[rowIndex].length > 0) {
  974. for (var c = 0; c <= rowspans[rowIndex].length; c++) {
  975. if (typeof rowspans[rowIndex][c] != 'undefined') {
  976. cellcallback(null, rowIndex, c);
  977. delete rowspans[rowIndex][c];
  978. }
  979. }
  980. }
  981. }
  982. }
  983. function jsPdfOutput(doc) {
  984. if (defaults.consoleLog === true)
  985. console.log(doc.output());
  986. if (defaults.outputMode === 'string')
  987. return doc.output();
  988. if (defaults.outputMode === 'base64')
  989. return base64encode(doc.output());
  990. if (defaults.outputMode === 'window') {
  991. window.open(URL.createObjectURL(doc.output("blob")));
  992. return;
  993. }
  994. try {
  995. var blob = doc.output('blob');
  996. saveAs(blob, defaults.fileName + '.pdf');
  997. }
  998. catch (e) {
  999. downloadFile(defaults.fileName + '.pdf',
  1000. 'data:application/pdf;base64,',
  1001. doc.output());
  1002. }
  1003. }
  1004. function prepareAutoTableText (cell, data, cellopt) {
  1005. var cs = 0;
  1006. if ( typeof cellopt != 'undefined' )
  1007. cs = cellopt.colspan;
  1008. if ( cs >= 0 ) {
  1009. // colspan handling
  1010. var cellWidth = cell.width;
  1011. var textPosX = cell.textPos.x;
  1012. var i = data.table.columns.indexOf(data.column);
  1013. for (var c = 1; c < cs; c++) {
  1014. var column = data.table.columns[i+c];
  1015. cellWidth += column.width;
  1016. }
  1017. if ( cs > 1 ) {
  1018. if ( cell.styles.halign === 'right' )
  1019. textPosX = cell.textPos.x + cellWidth - cell.width;
  1020. else if ( cell.styles.halign === 'center' )
  1021. textPosX = cell.textPos.x + (cellWidth - cell.width) / 2;
  1022. }
  1023. cell.width = cellWidth;
  1024. cell.textPos.x = textPosX;
  1025. if ( typeof cellopt != 'undefined' && cellopt.rowspan > 1 )
  1026. cell.height = cell.height * cellopt.rowspan;
  1027. // fix jsPDF's calculation of text position
  1028. if ( cell.styles.valign === 'middle' || cell.styles.valign === 'bottom' ) {
  1029. var splittedText = typeof cell.text === 'string' ? cell.text.split(/\r\n|\r|\n/g) : cell.text;
  1030. var lineCount = splittedText.length || 1;
  1031. if (lineCount > 2)
  1032. cell.textPos.y -= ((2 - FONT_ROW_RATIO) / 2 * data.row.styles.fontSize) * (lineCount-2) / 3 ;
  1033. }
  1034. return true;
  1035. }
  1036. else
  1037. return false; // cell is hidden (colspan = -1), don't draw it
  1038. }
  1039. function collectImages (cell, elements, teOptions) {
  1040. if (typeof teOptions.images != 'undefined') {
  1041. elements.each(function () {
  1042. var kids = $(this).children();
  1043. if ( $(this).is("img") ) {
  1044. var hash = strHashCode(this.src);
  1045. teOptions.images[hash] = { url: this.src,
  1046. src: this.src };
  1047. }
  1048. if (typeof kids != 'undefined' && kids.length > 0)
  1049. collectImages (cell, kids, teOptions);
  1050. });
  1051. }
  1052. }
  1053. function loadImages (teOptions, callback) {
  1054. var i;
  1055. var imageCount = 0;
  1056. var x = 0;
  1057. function done() {
  1058. callback(imageCount);
  1059. }
  1060. function loadImage(image) {
  1061. if (!image.url)
  1062. return;
  1063. var img = new Image();
  1064. imageCount = ++x;
  1065. img.crossOrigin = 'Anonymous';
  1066. img.onerror = img.onload = function () {
  1067. if(img.complete) {
  1068. if (img.src.indexOf('data:image/') === 0) {
  1069. img.width = image.width || img.width || 0;
  1070. img.height = image.height || img.height || 0;
  1071. }
  1072. if (img.width + img.height) {
  1073. var canvas = document.createElement("canvas");
  1074. var ctx = canvas.getContext("2d");
  1075. canvas.width = img.width;
  1076. canvas.height = img.height;
  1077. ctx.drawImage( img, 0, 0 );
  1078. image.src = canvas.toDataURL("image/jpeg");
  1079. }
  1080. }
  1081. if(!--x)
  1082. done();
  1083. };
  1084. img.src = image.url;
  1085. }
  1086. if (typeof teOptions.images != 'undefined') {
  1087. for (i in teOptions.images)
  1088. if (teOptions.images.hasOwnProperty(i))
  1089. loadImage(teOptions.images[i]);
  1090. }
  1091. return x || done();
  1092. }
  1093. function drawCellElements (cell, elements, teOptions) {
  1094. elements.each(function () {
  1095. var kids = $(this).children();
  1096. if ( $(this).is("div") ) {
  1097. var bcolor = rgb2array(getStyle(this, 'background-color'), [255, 255, 255]);
  1098. var lcolor = rgb2array(getStyle(this, 'border-top-color'), [0, 0, 0]);
  1099. var lwidth = getPropertyUnitValue(this, 'border-top-width', defaults.jspdf.unit);
  1100. var r = this.getBoundingClientRect();
  1101. var ux = this.offsetLeft * teOptions.dw;
  1102. var uy = this.offsetTop * teOptions.dh;
  1103. var uw = r.width * teOptions.dw;
  1104. var uh = r.height * teOptions.dh;
  1105. teOptions.doc.setDrawColor.apply (undefined, lcolor);
  1106. teOptions.doc.setFillColor.apply (undefined, bcolor);
  1107. teOptions.doc.setLineWidth (lwidth);
  1108. teOptions.doc.rect(cell.x + ux, cell.y + uy, uw, uh, lwidth ? "FD" : "F");
  1109. }
  1110. else if ( $(this).is("img") ) {
  1111. if (typeof teOptions.images != 'undefined') {
  1112. var hash = strHashCode(this.src);
  1113. var image = teOptions.images[hash];
  1114. if (typeof image != 'undefined') {
  1115. var arCell = cell.width / cell.height;
  1116. var arImg = this.width / this.height;
  1117. var imgWidth = cell.width;
  1118. var imgHeight = cell.height;
  1119. var uy = 0;
  1120. if (arImg < arCell) {
  1121. imgHeight = Math.min (cell.height, this.height);
  1122. imgWidth = this.width * imgHeight / this.height;
  1123. }
  1124. else if (arImg > arCell) {
  1125. imgWidth = Math.min (cell.width, this.width);
  1126. imgHeight = this.height * imgWidth / this.width;
  1127. }
  1128. if (imgHeight < cell.height)
  1129. uy = (cell.height - imgHeight) / 2;
  1130. teOptions.doc.addImage (image.src, cell.textPos.x, cell.y + uy, imgWidth, imgHeight);
  1131. cell.textPos.x += imgWidth;
  1132. }
  1133. }
  1134. }
  1135. if (typeof kids != 'undefined' && kids.length > 0)
  1136. drawCellElements (cell, kids, teOptions);
  1137. });
  1138. }
  1139. function escapeRegExp(string) {
  1140. return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  1141. }
  1142. function replaceAll(string, find, replace) {
  1143. return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
  1144. }
  1145. // Takes a string and encapsulates it (by default in double-quotes) if it
  1146. // contains the csv field separator, spaces, or linebreaks.
  1147. function csvString(cell, rowIndex, colIndex) {
  1148. var result = '';
  1149. if (cell !== null) {
  1150. var dataString = parseString(cell, rowIndex, colIndex);
  1151. var csvValue = (dataString === null || dataString === '') ? '' : dataString.toString();
  1152. if (dataString instanceof Date)
  1153. result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure;
  1154. else {
  1155. result = replaceAll(csvValue, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure);
  1156. if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result))
  1157. result = defaults.csvEnclosure + result + defaults.csvEnclosure;
  1158. }
  1159. }
  1160. return result;
  1161. }
  1162. function parseNumber(value) {
  1163. value = value || "0";
  1164. value = replaceAll(value, defaults.numbers.html.decimalMark, '.');
  1165. value = replaceAll(value, defaults.numbers.html.thousandsSeparator, '');
  1166. return typeof value === "number" || jQuery.isNumeric(value) !== false ? value : false;
  1167. }
  1168. function parseString(cell, rowIndex, colIndex) {
  1169. var result = '';
  1170. if (cell !== null) {
  1171. var $cell = $(cell);
  1172. var htmlData;
  1173. if ($cell[0].hasAttribute("data-tableexport-value"))
  1174. htmlData = $cell.data("tableexport-value");
  1175. else
  1176. htmlData = $cell.html();
  1177. if (htmlData != '') {
  1178. var html = $.parseHTML( htmlData );
  1179. htmlData = '';
  1180. $.each( html, function() {
  1181. if ( $(this).is("input") )
  1182. htmlData += $cell.find('input').val();
  1183. else if ( $(this).is("select") )
  1184. htmlData += $cell.find('select option:selected').text();
  1185. else {
  1186. htmlData += $cell.html();
  1187. return false;
  1188. }
  1189. });
  1190. }
  1191. if (typeof defaults.onCellHtmlData === 'function')
  1192. htmlData = defaults.onCellHtmlData($cell, rowIndex, colIndex, htmlData);
  1193. if (defaults.htmlContent === true) {
  1194. result = $.trim(htmlData);
  1195. }
  1196. else {
  1197. var text = htmlData.replace(/\n/g,'\u2028').replace(/<br\s*[\/]?>/gi, '\u2060');
  1198. var obj = $('<div/>').html(text).contents();
  1199. text = '';
  1200. $.each(obj.text().split("\u2028"), function(i, v) {
  1201. if (i > 0)
  1202. text += " ";
  1203. text += $.trim(v);
  1204. });
  1205. $.each(text.split("\u2060"), function(i, v) {
  1206. if (i > 0)
  1207. result += "\n";
  1208. result += $.trim(v).replace(/\u00AD/g, ""); // remove soft hyphens
  1209. });
  1210. if (defaults.numbers.html.decimalMark != defaults.numbers.output.decimalMark ||
  1211. defaults.numbers.html.thousandsSeparator != defaults.numbers.output.thousandsSeparator) {
  1212. var number = parseNumber (result);
  1213. if ( number !== false ) {
  1214. var frac = ("" + number).split('.');
  1215. if ( frac.length == 1 )
  1216. frac[1] = "";
  1217. var mod = frac[0].length > 3 ? frac[0].length % 3 : 0;
  1218. result = (number < 0 ? "-" : "") +
  1219. (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]) +
  1220. (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : "");
  1221. }
  1222. }
  1223. }
  1224. if (defaults.escape === true) {
  1225. result = escape(result);
  1226. }
  1227. if (typeof defaults.onCellData === 'function') {
  1228. result = defaults.onCellData($cell, rowIndex, colIndex, result);
  1229. }
  1230. }
  1231. return result;
  1232. }
  1233. function hyphenate(a, b, c) {
  1234. return b + "-" + c.toLowerCase();
  1235. }
  1236. function rgb2array(rgb_string, default_result) {
  1237. var re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
  1238. var bits = re.exec(rgb_string);
  1239. var result = default_result;
  1240. if (bits)
  1241. result = [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ];
  1242. return result;
  1243. }
  1244. function getCellStyles (cell) {
  1245. var a = getStyle(cell, 'text-align');
  1246. var fw = getStyle(cell, 'font-weight');
  1247. var fs = getStyle(cell, 'font-style');
  1248. var f = '';
  1249. if (a == 'start')
  1250. a = getStyle(cell, 'direction') == 'rtl' ? 'right' : 'left';
  1251. if (fw >= 700)
  1252. f = 'bold';
  1253. if (fs == 'italic')
  1254. f += fs;
  1255. if (f === '')
  1256. f = 'normal';
  1257. var result = {
  1258. style: {
  1259. align: a,
  1260. bcolor: rgb2array(getStyle(cell, 'background-color'), [255, 255, 255]),
  1261. color: rgb2array(getStyle(cell, 'color'), [0, 0, 0]),
  1262. fstyle: f
  1263. },
  1264. colspan: (parseInt($(cell).attr('colspan')) || 0),
  1265. rowspan: (parseInt($(cell).attr('rowspan')) || 0)
  1266. };
  1267. if (cell !== null) {
  1268. var r = cell.getBoundingClientRect();
  1269. result.rect = {
  1270. width: r.width,
  1271. height: r.height
  1272. };
  1273. }
  1274. return result;
  1275. }
  1276. // get computed style property
  1277. function getStyle(target, prop) {
  1278. try {
  1279. if (window.getComputedStyle) { // gecko and webkit
  1280. prop = prop.replace(/([a-z])([A-Z])/, hyphenate); // requires hyphenated, not camel
  1281. return window.getComputedStyle(target, null).getPropertyValue(prop);
  1282. }
  1283. if (target.currentStyle) { // ie
  1284. return target.currentStyle[prop];
  1285. }
  1286. return target.style[prop];
  1287. }
  1288. catch (e) {
  1289. }
  1290. return "";
  1291. }
  1292. function getUnitValue(parent, value, unit) {
  1293. var baseline = 100; // any number serves
  1294. var temp = document.createElement("div"); // create temporary element
  1295. temp.style.overflow = "hidden"; // in case baseline is set too low
  1296. temp.style.visibility = "hidden"; // no need to show it
  1297. parent.appendChild(temp); // insert it into the parent for em, ex and %
  1298. temp.style.width = baseline + unit;
  1299. var factor = baseline / temp.offsetWidth;
  1300. parent.removeChild(temp); // clean up
  1301. return (value * factor);
  1302. }
  1303. function getPropertyUnitValue(target, prop, unit) {
  1304. var value = getStyle(target, prop); // get the computed style value
  1305. var numeric = value.match(/\d+/); // get the numeric component
  1306. if (numeric !== null) {
  1307. numeric = numeric[0]; // get the string
  1308. return getUnitValue (target.parentElement, numeric, unit);
  1309. }
  1310. return 0;
  1311. }
  1312. function jx_Workbook() {
  1313. if(!(this instanceof jx_Workbook)) return new jx_Workbook();
  1314. this.SheetNames = [];
  1315. this.Sheets = {};
  1316. }
  1317. function jx_s2ab(s) {
  1318. var buf = new ArrayBuffer(s.length);
  1319. var view = new Uint8Array(buf);
  1320. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  1321. return buf;
  1322. }
  1323. function jx_datenum(v, date1904) {
  1324. if(date1904) v+=1462;
  1325. var epoch = Date.parse(v);
  1326. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  1327. }
  1328. function jx_createSheet(data) {
  1329. var ws = {};
  1330. var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
  1331. for(var R = 0; R != data.length; ++R) {
  1332. for(var C = 0; C != data[R].length; ++C) {
  1333. if(range.s.r > R) range.s.r = R;
  1334. if(range.s.c > C) range.s.c = C;
  1335. if(range.e.r < R) range.e.r = R;
  1336. if(range.e.c < C) range.e.c = C;
  1337. var cell = {v: data[R][C] };
  1338. if(cell.v === null) continue;
  1339. var cell_ref = XLSX.utils.encode_cell({c:C,r:R});
  1340. if(typeof cell.v === 'number') cell.t = 'n';
  1341. else if(typeof cell.v === 'boolean') cell.t = 'b';
  1342. else if(cell.v instanceof Date) {
  1343. cell.t = 'n'; cell.z = XLSX.SSF._table[14];
  1344. cell.v = jx_datenum(cell.v);
  1345. }
  1346. else cell.t = 's';
  1347. ws[cell_ref] = cell;
  1348. }
  1349. }
  1350. if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  1351. return ws;
  1352. }
  1353. function strHashCode (str) {
  1354. var hash = 0, i, chr, len;
  1355. if (str.length === 0) return hash;
  1356. for (i = 0, len = str.length; i < len; i++) {
  1357. chr = str.charCodeAt(i);
  1358. hash = ((hash << 5) - hash) + chr;
  1359. hash |= 0; // Convert to 32bit integer
  1360. }
  1361. return hash;
  1362. }
  1363. function downloadFile(filename, header, data) {
  1364. var ua = window.navigator.userAgent;
  1365. if (filename !== false && (ua.indexOf("MSIE ") > 0 || !!ua.match(/Trident.*rv\:11\./))) {
  1366. if (window.navigator.msSaveOrOpenBlob)
  1367. window.navigator.msSaveOrOpenBlob(new Blob([data]), filename);
  1368. else {
  1369. // Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin)
  1370. // based on sampopes answer on http://stackoverflow.com/questions/22317951
  1371. // ! Not working for json and pdf format !
  1372. var frame = document.createElement("iframe");
  1373. if (frame) {
  1374. document.body.appendChild(frame);
  1375. frame.setAttribute("style", "display:none");
  1376. frame.contentDocument.open("txt/html", "replace");
  1377. frame.contentDocument.write(data);
  1378. frame.contentDocument.close();
  1379. frame.focus();
  1380. frame.contentDocument.execCommand("SaveAs", true, filename);
  1381. document.body.removeChild(frame);
  1382. }
  1383. }
  1384. }
  1385. else {
  1386. var DownloadLink = document.createElement('a');
  1387. if (DownloadLink) {
  1388. DownloadLink.style.display = 'none';
  1389. if (filename !== false)
  1390. DownloadLink.download = filename;
  1391. else
  1392. DownloadLink.target = '_blank';
  1393. if (header.toLowerCase().indexOf("base64,") >= 0)
  1394. DownloadLink.href = header + base64encode(data);
  1395. else
  1396. DownloadLink.href = header + encodeURIComponent(data);
  1397. document.body.appendChild(DownloadLink);
  1398. if (document.createEvent) {
  1399. if (DownloadEvt === null)
  1400. DownloadEvt = document.createEvent('MouseEvents');
  1401. DownloadEvt.initEvent('click', true, false);
  1402. DownloadLink.dispatchEvent(DownloadEvt);
  1403. }
  1404. else if (document.createEventObject)
  1405. DownloadLink.fireEvent('onclick');
  1406. else if (typeof DownloadLink.onclick == 'function')
  1407. DownloadLink.onclick();
  1408. document.body.removeChild(DownloadLink);
  1409. }
  1410. }
  1411. }
  1412. function utf8Encode(string) {
  1413. string = string.replace(/\x0d\x0a/g, "\x0a");
  1414. var utftext = "";
  1415. for (var n = 0; n < string.length; n++) {
  1416. var c = string.charCodeAt(n);
  1417. if (c < 128) {
  1418. utftext += String.fromCharCode(c);
  1419. }
  1420. else if ((c > 127) && (c < 2048)) {
  1421. utftext += String.fromCharCode((c >> 6) | 192);
  1422. utftext += String.fromCharCode((c & 63) | 128);
  1423. }
  1424. else {
  1425. utftext += String.fromCharCode((c >> 12) | 224);
  1426. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  1427. utftext += String.fromCharCode((c & 63) | 128);
  1428. }
  1429. }
  1430. return utftext;
  1431. }
  1432. function base64encode(input) {
  1433. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1434. var output = "";
  1435. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1436. var i = 0;
  1437. input = utf8Encode(input);
  1438. while (i < input.length) {
  1439. chr1 = input.charCodeAt(i++);
  1440. chr2 = input.charCodeAt(i++);
  1441. chr3 = input.charCodeAt(i++);
  1442. enc1 = chr1 >> 2;
  1443. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1444. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1445. enc4 = chr3 & 63;
  1446. if (isNaN(chr2)) {
  1447. enc3 = enc4 = 64;
  1448. } else if (isNaN(chr3)) {
  1449. enc4 = 64;
  1450. }
  1451. output = output +
  1452. keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1453. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1454. }
  1455. return output;
  1456. }
  1457. return this;
  1458. }
  1459. });
  1460. })(jQuery);