tableExport.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /*
  2. tableExport.jquery.plugin
  3. Copyright (c) 2015 hhurz, https://github.com/hhurz/tableExport.jquery.plugin
  4. Original work Copyright (c) 2014 Giri Raj, https://github.com/kayalshri/
  5. Licensed under the MIT License, http://opensource.org/licenses/mit-license
  6. */
  7. (function ($) {
  8. $.fn.extend({
  9. tableExport: function (options) {
  10. var defaults = {
  11. consoleLog: false,
  12. csvEnclosure: '"',
  13. csvSeparator: ',',
  14. csvUseBOM: true,
  15. displayTableName: false,
  16. escape: false,
  17. excelstyles: ['border-bottom', 'border-top', 'border-left', 'border-right'],
  18. fileName: 'tableExport',
  19. htmlContent: false,
  20. ignoreColumn: [],
  21. ignoreRow:[],
  22. jspdf: {orientation: 'p',
  23. unit: 'pt',
  24. format: 'a4', // jspdf page format or 'bestfit' for autmatic paper format selection
  25. margins: {left: 20, right: 10, top: 10, bottom: 10},
  26. autotable: {styles: {cellPadding: 2,
  27. rowHeight: 12,
  28. fontSize: 8,
  29. fillColor: 255, // color value or 'inherit' to use css background-color from html table
  30. textColor: 50, // color value or 'inherit' to use css color from html table
  31. fontStyle: 'normal', // normal, bold, italic, bolditalic or 'inherit' to use css font-weight and fonst-style from html table
  32. overflow: 'ellipsize', // visible, hidden, ellipsize or linebreak
  33. halign: 'left', // left, center, right
  34. valign: 'middle' // top, middle, bottom
  35. },
  36. headerStyles: {fillColor: [52, 73, 94],
  37. textColor: 255,
  38. fontStyle: 'bold',
  39. halign: 'center'
  40. },
  41. alternateRowStyles: {fillColor: 245
  42. },
  43. tableExport: {onAfterAutotable: null,
  44. onBeforeAutotable: null,
  45. onTable: null
  46. }
  47. }
  48. },
  49. numbers: {html: {decimalMark: '.',
  50. thousandsSeparator: ','
  51. },
  52. output: {decimalMark: '.',
  53. thousandsSeparator: ','
  54. }
  55. },
  56. onCellData: null,
  57. onCellHtmlData: null,
  58. outputMode: 'file', // 'file', 'string' or 'base64'
  59. tbodySelector: 'tr',
  60. theadSelector: 'tr',
  61. tableName: 'myTableName',
  62. type: 'csv', // 'csv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf'
  63. worksheetName: 'xlsWorksheetName'
  64. };
  65. var FONT_ROW_RATIO = 1.15;
  66. var el = this;
  67. var DownloadEvt = null;
  68. var $hrows = [];
  69. var $rows = [];
  70. var rowIndex = 0;
  71. var rowspans = [];
  72. var trData = '';
  73. $.extend(true, defaults, options);
  74. if (defaults.type == 'csv' || defaults.type == 'txt') {
  75. var csvData = "";
  76. var rowlength = 0;
  77. rowIndex = 0;
  78. function CollectCsvData (tgroup, tselector, rowselector, length) {
  79. $rows = $(el).find(tgroup).first().find(tselector);
  80. $rows.each(function () {
  81. trData = "";
  82. ForEachVisibleCell(this, rowselector, rowIndex, length + $rows.length,
  83. function (cell, row, col) {
  84. trData += csvString(cell, row, col) + defaults.csvSeparator;
  85. });
  86. trData = $.trim(trData).substring(0, trData.length - 1);
  87. if (trData.length > 0) {
  88. if (csvData.length > 0)
  89. csvData += "\n";
  90. csvData += trData;
  91. }
  92. rowIndex++;
  93. });
  94. return $rows.length;
  95. }
  96. rowlength += CollectCsvData ('thead', defaults.theadSelector, 'th,td', rowlength);
  97. rowlength += CollectCsvData ('tbody', defaults.tbodySelector, 'td', rowlength);
  98. CollectCsvData ('tfoot', defaults.tbodySelector, 'td', rowlength);
  99. csvData += "\n";
  100. //output
  101. if (defaults.consoleLog === true)
  102. console.log(csvData);
  103. if (defaults.outputMode === 'string')
  104. return csvData;
  105. if (defaults.outputMode === 'base64')
  106. return base64encode(csvData);
  107. try {
  108. var blob = new Blob([csvData], {type: "text/" + (defaults.type == 'csv' ? 'csv' : 'plain') + ";charset=utf-8"});
  109. saveAs(blob, defaults.fileName + '.' + defaults.type, (defaults.type != 'csv' || defaults.csvUseBOM === false));
  110. }
  111. catch (e) {
  112. downloadFile(defaults.fileName + '.' + defaults.type,
  113. 'data:text/' + (defaults.type == 'csv' ? 'csv' : 'plain') + ';charset=utf-8,' + ((defaults.type == 'csv' && defaults.csvUseBOM)? '\ufeff' : ''),
  114. csvData);
  115. }
  116. } else if (defaults.type == 'sql') {
  117. // Header
  118. rowIndex = 0;
  119. var tdData = "INSERT INTO `" + defaults.tableName + "` (";
  120. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  121. $hrows.each(function () {
  122. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  123. function (cell, row, col) {
  124. tdData += "'" + parseString(cell, row, col) + "',";
  125. });
  126. rowIndex++;
  127. tdData = $.trim(tdData);
  128. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  129. });
  130. tdData += ") VALUES ";
  131. // Row vs Column
  132. $rows = $(el).find('tbody').first().find(defaults.tbodySelector);
  133. $rows.each(function () {
  134. trData = "";
  135. ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length,
  136. function (cell, row, col) {
  137. trData += "'" + parseString(cell, row, col) + "',";
  138. });
  139. if (trData.length > 3) {
  140. tdData += "(" + trData;
  141. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  142. tdData += "),";
  143. }
  144. rowIndex++;
  145. });
  146. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  147. tdData += ";";
  148. //output
  149. if (defaults.consoleLog === true)
  150. console.log(tdData);
  151. if (defaults.outputMode === 'string')
  152. return tdData;
  153. if (defaults.outputMode === 'base64')
  154. return base64encode(tdData);
  155. try {
  156. var blob = new Blob([tdData], {type: "text/plain;charset=utf-8"});
  157. saveAs(blob, defaults.fileName + '.sql');
  158. }
  159. catch (e) {
  160. downloadFile(defaults.fileName + '.sql',
  161. 'data:application/sql;charset=utf-8,',
  162. tdData);
  163. }
  164. } else if (defaults.type == 'json') {
  165. var jsonHeaderArray = [];
  166. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  167. $hrows.each(function () {
  168. var jsonArrayTd = [];
  169. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  170. function (cell, row, col) {
  171. jsonArrayTd.push(parseString(cell, row, col));
  172. });
  173. jsonHeaderArray.push(jsonArrayTd);
  174. });
  175. var jsonArray = [];
  176. $rows = $(el).find('tbody').first().find(defaults.tbodySelector);
  177. $rows.each(function () {
  178. var jsonArrayTd = [];
  179. ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length,
  180. function (cell, row, col) {
  181. jsonArrayTd.push(parseString(cell, row, col));
  182. });
  183. if (jsonArrayTd.length > 0 && (jsonArrayTd.length != 1 || jsonArrayTd[0] != ""))
  184. jsonArray.push(jsonArrayTd);
  185. rowIndex++;
  186. });
  187. var jsonExportArray = [];
  188. jsonExportArray.push({header: jsonHeaderArray, data: jsonArray});
  189. var sdata = JSON.stringify(jsonExportArray);
  190. if (defaults.consoleLog === true)
  191. console.log(sdata);
  192. if (defaults.outputMode === 'string')
  193. return sdata;
  194. if (defaults.outputMode === 'base64')
  195. return base64encode(sdata);
  196. try {
  197. var blob = new Blob([sdata], {type: "application/json;charset=utf-8"});
  198. saveAs(blob, defaults.fileName + '.json');
  199. }
  200. catch (e) {
  201. downloadFile(defaults.fileName + '.json',
  202. 'data:application/json;charset=utf-8;base64,',
  203. sdata);
  204. }
  205. } else if (defaults.type === 'xml') {
  206. rowIndex = 0;
  207. var xml = '<?xml version="1.0" encoding="utf-8"?>';
  208. xml += '<tabledata><fields>';
  209. // Header
  210. $hrows = $(el).find('thead').first().find(defaults.theadSelector);
  211. $hrows.each(function () {
  212. ForEachVisibleCell(this, 'th,td', rowIndex, $rows.length,
  213. function (cell, row, col) {
  214. xml += "<field>" + parseString(cell, row, col) + "</field>";
  215. });
  216. rowIndex++;
  217. });
  218. xml += '</fields><data>';
  219. // Row Vs Column
  220. var rowCount = 1;
  221. $rows = $(el).find('tbody').first().find(defaults.tbodySelector);
  222. $rows.each(function () {
  223. var colCount = 1;
  224. trData = "";
  225. ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length,
  226. function (cell, row, col) {
  227. trData += "<column-" + colCount + ">" + parseString(cell, row, col) + "</column-" + colCount + ">";
  228. colCount++;
  229. });
  230. if (trData.length > 0 && trData != "<column-1></column-1>") {
  231. xml += '<row id="' + rowCount + '">' + trData + '</row>';
  232. rowCount++;
  233. }
  234. rowIndex++;
  235. });
  236. xml += '</data></tabledata>';
  237. //output
  238. if (defaults.consoleLog === true)
  239. console.log(xml);
  240. if (defaults.outputMode === 'string')
  241. return xml;
  242. if (defaults.outputMode === 'base64')
  243. return base64encode(xml);
  244. try {
  245. var blob = new Blob([xml], {type: "application/xml;charset=utf-8"});
  246. saveAs(blob, defaults.fileName + '.xml');
  247. }
  248. catch (e) {
  249. downloadFile(defaults.fileName + '.xml',
  250. 'data:application/xml;charset=utf-8;base64,',
  251. xml);
  252. }
  253. } else if (defaults.type == 'excel' || defaults.type == 'xls' || defaults.type == 'word' || defaults.type == 'doc') {
  254. var MSDocType = (defaults.type == 'excel' || defaults.type == 'xls') ? 'excel' : 'word';
  255. var MSDocExt = (MSDocType == 'excel') ? 'xls' : 'doc';
  256. var MSDocSchema = (MSDocExt == 'xls') ? 'xmlns:x="urn:schemas-microsoft-com:office:excel"' : 'xmlns:w="urn:schemas-microsoft-com:office:word"';
  257. var $tables = $(el).filter(function() {
  258. return $(this).data("tableexport-display") != 'none' &&
  259. ($(this).is(':visible') ||
  260. $(this).data("tableexport-display") == 'always');
  261. });
  262. var docData = '';
  263. $tables.each(function(){
  264. rowIndex = 0;
  265. docData += '<table><thead>';
  266. // Header
  267. $hrows = $(this).find('thead').first().find(defaults.theadSelector);
  268. $hrows.each(function() {
  269. trData = "";
  270. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  271. function(cell, row, col) {
  272. if (cell != null) {
  273. trData += '<th style="';
  274. for (var styles in defaults.excelstyles) {
  275. if (defaults.excelstyles.hasOwnProperty(styles)) {
  276. trData += defaults.excelstyles[styles] + ': ' + $(cell).css(defaults.excelstyles[styles]) + ';';
  277. }
  278. }
  279. if ($(cell).is("[colspan]"))
  280. trData += '" colspan="' + $(cell).attr('colspan');
  281. if ($(cell).is("[rowspan]"))
  282. trData += '" rowspan="' + $(cell).attr('rowspan');
  283. trData += '">' + parseString(cell, row, col) + '</th>';
  284. }
  285. });
  286. if (trData.length > 0)
  287. docData += '<tr>' + trData + '</tr>';
  288. rowIndex++;
  289. });
  290. docData += '</thead><tbody>';
  291. // Row Vs Column
  292. $rows = $(this).find('tbody').first().find(defaults.tbodySelector);
  293. $rows.each(function() {
  294. trData = "";
  295. ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length,
  296. function(cell, row, col) {
  297. if (cell != null) {
  298. trData += '<td style="';
  299. for (var styles in defaults.excelstyles) {
  300. if (defaults.excelstyles.hasOwnProperty(styles)) {
  301. trData += defaults.excelstyles[styles] + ': ' + $(cell).css(defaults.excelstyles[styles]) + ';';
  302. }
  303. }
  304. if ($(cell).is("[colspan]"))
  305. trData += '" colspan="' + $(cell).attr('colspan');
  306. if ($(cell).is("[rowspan]"))
  307. trData += '" rowspan="' + $(cell).attr('rowspan');
  308. trData += '">' + parseString(cell, row, col) + '</td>';
  309. }
  310. });
  311. if (trData.length > 0)
  312. docData += '<tr>' + trData + '</tr>';
  313. rowIndex++;
  314. });
  315. if (defaults.displayTableName)
  316. docData += '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>' + defaults.tableName + '</p>')) + '</td></tr>';
  317. docData += '</tbody></table>';
  318. if (defaults.consoleLog === true)
  319. console.log(docData);
  320. });
  321. var docFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + MSDocSchema + ' xmlns="http://www.w3.org/TR/REC-html40">';
  322. docFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + MSDocType + '; charset=UTF-8">';
  323. docFile += "<head>";
  324. if (MSDocType === 'excel') {
  325. docFile += "<!--[if gte mso 9]>";
  326. docFile += "<xml>";
  327. docFile += "<x:ExcelWorkbook>";
  328. docFile += "<x:ExcelWorksheets>";
  329. docFile += "<x:ExcelWorksheet>";
  330. docFile += "<x:Name>";
  331. docFile += defaults.worksheetName;
  332. docFile += "</x:Name>";
  333. docFile += "<x:WorksheetOptions>";
  334. docFile += "<x:DisplayGridlines/>";
  335. docFile += "</x:WorksheetOptions>";
  336. docFile += "</x:ExcelWorksheet>";
  337. docFile += "</x:ExcelWorksheets>";
  338. docFile += "</x:ExcelWorkbook>";
  339. docFile += "</xml>";
  340. docFile += "<![endif]-->";
  341. }
  342. docFile += "</head>";
  343. docFile += "<body>";
  344. docFile += docData;
  345. docFile += "</body>";
  346. docFile += "</html>";
  347. if (defaults.consoleLog === true)
  348. console.log(docFile);
  349. if (defaults.outputMode === 'string')
  350. return docFile;
  351. if (defaults.outputMode === 'base64')
  352. return base64encode(docFile);
  353. try {
  354. var blob = new Blob([docFile], {type: 'application/vnd.ms-' + defaults.type});
  355. saveAs(blob, defaults.fileName + '.' + MSDocExt);
  356. }
  357. catch (e) {
  358. downloadFile(defaults.fileName + '.' + MSDocExt,
  359. 'data:application/vnd.ms-' + MSDocType + ';base64,',
  360. docFile);
  361. }
  362. } else if (defaults.type == 'png') {
  363. html2canvas($(el)[0], {
  364. allowTaint: true,
  365. background: '#fff',
  366. onrendered: function (canvas) {
  367. var image = canvas.toDataURL();
  368. image = image.substring(22); // remove data stuff
  369. var byteString = atob(image);
  370. var buffer = new ArrayBuffer(byteString.length);
  371. var intArray = new Uint8Array(buffer);
  372. for (var i = 0; i < byteString.length; i++)
  373. intArray[i] = byteString.charCodeAt(i);
  374. if (defaults.consoleLog === true)
  375. console.log(byteString);
  376. if (defaults.outputMode === 'string')
  377. return byteString;
  378. if (defaults.outputMode === 'base64')
  379. return base64encode(image);
  380. try {
  381. var blob = new Blob([buffer], {type: "image/png"});
  382. saveAs(blob, defaults.fileName + '.png');
  383. }
  384. catch (e) {
  385. downloadFile(defaults.fileName + '.png',
  386. 'data:image/png;base64,',
  387. image);
  388. }
  389. }
  390. });
  391. } else if (defaults.type == 'pdf') {
  392. if (defaults.jspdf.autotable === false) {
  393. var addHtmlOptions = {
  394. dim: {
  395. w: getPropertyUnitValue($(el).first().get(0), 'width', 'mm'),
  396. h: getPropertyUnitValue($(el).first().get(0), 'height', 'mm')
  397. },
  398. pagesplit: false
  399. };
  400. var doc = new jsPDF(defaults.jspdf.orientation, defaults.jspdf.unit, defaults.jspdf.format);
  401. doc.addHTML($(el).first(),
  402. defaults.jspdf.margins.left,
  403. defaults.jspdf.margins.top,
  404. addHtmlOptions,
  405. function () {
  406. jsPdfOutput(doc);
  407. });
  408. //delete doc;
  409. }
  410. else {
  411. // pdf output using jsPDF AutoTable plugin
  412. // https://github.com/simonbengtsson/jsPDF-AutoTable
  413. var teOptions = defaults.jspdf.autotable.tableExport;
  414. // When setting jspdf.format to 'bestfit' tableExport tries to choose
  415. // the minimum required paper format and orientation in which the table
  416. // (or tables in multitable mode) completely fits without column adjustment
  417. if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') {
  418. var pageFormats = {
  419. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
  420. 'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
  421. 'a4': [595.28, 841.89]
  422. };
  423. var rk = '', ro = '';
  424. var mw = 0;
  425. $(el).filter(':visible').each(function () {
  426. if ($(this).css('display') != 'none') {
  427. var w = getPropertyUnitValue($(this).get(0), 'width', 'pt');
  428. if (w > mw) {
  429. if (w > pageFormats['a0'][0]) {
  430. rk = 'a0';
  431. ro = 'l';
  432. }
  433. for (var key in pageFormats) {
  434. if (pageFormats.hasOwnProperty(key)) {
  435. if (pageFormats[key][1] > w) {
  436. rk = key;
  437. ro = 'l';
  438. if (pageFormats[key][0] > w)
  439. ro = 'p';
  440. }
  441. }
  442. }
  443. mw = w;
  444. }
  445. }
  446. });
  447. defaults.jspdf.format = (rk == '' ? 'a4' : rk);
  448. defaults.jspdf.orientation = (ro == '' ? 'w' : ro);
  449. }
  450. // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport,
  451. // thus it can be accessed from any callback function
  452. teOptions.doc = new jsPDF(defaults.jspdf.orientation,
  453. defaults.jspdf.unit,
  454. defaults.jspdf.format);
  455. $(el).filter(function() {
  456. return $(this).data("tableexport-display") != 'none' &&
  457. ($(this).is(':visible') ||
  458. $(this).data("tableexport-display") == 'always');
  459. }).each(function () {
  460. var colKey;
  461. var rowIndex = 0;
  462. teOptions.columns = [];
  463. teOptions.rows = [];
  464. teOptions.rowoptions = {};
  465. // onTable: optional callback function for every matching table that can be used
  466. // to modify the tableExport options or to skip the output of a particular table
  467. // if the table selector targets multiple tables
  468. if (typeof teOptions.onTable === 'function')
  469. if (teOptions.onTable($(this), defaults) === false)
  470. return true; // continue to next iteration step (table)
  471. // each table works with an own copy of AutoTable options
  472. defaults.jspdf.autotable.tableExport = null; // avoid deep recursion error
  473. var atOptions = $.extend(true, {}, defaults.jspdf.autotable);
  474. defaults.jspdf.autotable.tableExport = teOptions;
  475. atOptions.margin = {};
  476. $.extend(true, atOptions.margin, defaults.jspdf.margins);
  477. atOptions.tableExport = teOptions;
  478. // Fix jsPDF Autotable's row height calculation
  479. if (typeof atOptions.beforePageContent !== 'function') {
  480. atOptions.beforePageContent = function (data) {
  481. if (data.pageCount == 1) {
  482. var all = data.table.rows.concat(data.table.headerRow);
  483. all.forEach(function (row) {
  484. if ( row.height > 0 ) {
  485. row.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  486. data.table.height += (2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize;
  487. }
  488. });
  489. }
  490. }
  491. }
  492. if (typeof atOptions.createdHeaderCell !== 'function') {
  493. // apply some original css styles to pdf header cells
  494. atOptions.createdHeaderCell = function (cell, data) {
  495. if (typeof teOptions.columns [data.column.dataKey] != 'undefined') {
  496. var col = teOptions.columns [data.column.dataKey];
  497. cell.styles.halign = col.style.align;
  498. if (atOptions.styles.fillColor === 'inherit')
  499. cell.styles.fillColor = col.style.bcolor;
  500. if (atOptions.styles.textColor === 'inherit')
  501. cell.styles.textColor = col.style.color;
  502. if (atOptions.styles.fontStyle === 'inherit')
  503. cell.styles.fontStyle = col.style.fstyle;
  504. }
  505. }
  506. }
  507. if (typeof atOptions.createdCell !== 'function') {
  508. // apply some original css styles to pdf table cells
  509. atOptions.createdCell = function (cell, data) {
  510. var rowopt = teOptions.rowoptions [data.row.index + ":" + data.column.dataKey];
  511. if ( typeof rowopt != 'undefined' && typeof rowopt.style != 'undefined' ) {
  512. cell.styles.halign = rowopt.style.align;
  513. if (atOptions.styles.fillColor === 'inherit')
  514. cell.styles.fillColor = rowopt.style.bcolor;
  515. if (atOptions.styles.textColor === 'inherit')
  516. cell.styles.textColor = rowopt.style.color;
  517. if (atOptions.styles.fontStyle === 'inherit')
  518. cell.styles.fontStyle = rowopt.style.fstyle;
  519. }
  520. }
  521. }
  522. if (typeof atOptions.drawHeaderCell !== 'function') {
  523. atOptions.drawHeaderCell = function (cell, data) {
  524. var colopt = teOptions.columns [data.column.dataKey];
  525. if (colopt.style.hasOwnProperty("hidden") != true || colopt.style.hidden !== true)
  526. return prepareAutoTableText (cell, data, colopt);
  527. else
  528. return false; // cell is hidden
  529. }
  530. }
  531. if (typeof atOptions.drawCell !== 'function') {
  532. atOptions.drawCell = function (cell, data) {
  533. var rowopt = teOptions.rowoptions [data.row.index + ":" + data.column.dataKey];
  534. return prepareAutoTableText (cell, data, rowopt);
  535. }
  536. }
  537. // collect header and data rows
  538. $hrows = $(this).find('thead').find(defaults.theadSelector);
  539. $hrows.each(function () {
  540. colKey = 0;
  541. ForEachVisibleCell(this, 'th,td', rowIndex, $hrows.length,
  542. function (cell, row, col) {
  543. var obj = getCellStyles (cell);
  544. obj.title = parseString(cell, row, col);
  545. obj.key = colKey++;
  546. teOptions.columns.push(obj);
  547. });
  548. rowIndex++;
  549. });
  550. var rowCount = 0;
  551. $rows = $(this).find('tbody').find(defaults.tbodySelector);
  552. $rows.each(function () {
  553. var rowData = [];
  554. colKey = 0;
  555. ForEachVisibleCell(this, 'td', rowIndex, $hrows.length + $rows.length,
  556. function (cell, row, col) {
  557. if (typeof teOptions.columns[colKey] === 'undefined') {
  558. // jsPDF-Autotable needs columns. Thus define hidden ones for tables without thead
  559. var obj = {
  560. title: '',
  561. key: colKey,
  562. style: {
  563. hidden: true
  564. }
  565. };
  566. teOptions.columns.push(obj);
  567. }
  568. if (cell !== null) {
  569. teOptions.rowoptions [rowCount + ":" + colKey++] = getCellStyles (cell);
  570. }
  571. else {
  572. var obj = $.extend(true, {}, teOptions.rowoptions [rowCount + ":" + (colKey-1)]);
  573. obj.colspan = -1;
  574. teOptions.rowoptions [rowCount + ":" + colKey++] = obj;
  575. }
  576. rowData.push(parseString(cell, row, col));
  577. });
  578. if (rowData.length) {
  579. teOptions.rows.push(rowData);
  580. rowCount++
  581. }
  582. rowIndex++;
  583. });
  584. // onBeforeAutotable: optional callback function before calling
  585. // jsPDF AutoTable that can be used to modify the AutoTable options
  586. if (typeof teOptions.onBeforeAutotable === 'function')
  587. teOptions.onBeforeAutotable($(this), teOptions.columns, teOptions.rows, atOptions);
  588. teOptions.doc.autoTable(teOptions.columns, teOptions.rows, atOptions);
  589. // onAfterAutotable: optional callback function after returning
  590. // from jsPDF AutoTable that can be used to modify the AutoTable options
  591. if (typeof teOptions.onAfterAutotable === 'function')
  592. teOptions.onAfterAutotable($(this), atOptions);
  593. // set the start position for the next table (in case there is one)
  594. defaults.jspdf.autotable.startY = teOptions.doc.autoTableEndPosY() + atOptions.margin.top;
  595. });
  596. jsPdfOutput(teOptions.doc);
  597. teOptions.columns.length = 0;
  598. teOptions.rows.length = 0;
  599. delete teOptions.doc;
  600. teOptions.doc = null;
  601. }
  602. }
  603. function ForEachVisibleCell(tableRow, selector, rowIndex, rowCount, cellcallback) {
  604. if ($.inArray(rowIndex, defaults.ignoreRow) == -1 &&
  605. $.inArray(rowIndex-rowCount, defaults.ignoreRow) == -1) {
  606. var $row = $(tableRow).filter(function() {
  607. return $(this).data("tableexport-display") != 'none' &&
  608. ($(this).is(':visible') ||
  609. $(this).data("tableexport-display") == 'always' ||
  610. $(this).closest('table').data("tableexport-display") == 'always');
  611. }).find(selector);
  612. var rowColspan = 0;
  613. $row.each(function (colIndex) {
  614. if ($(this).data("tableexport-display") == 'always' ||
  615. ($(this).css('display') != 'none' &&
  616. $(this).css('visibility') != 'hidden' &&
  617. $(this).data("tableexport-display") != 'none')) {
  618. if ($.inArray(colIndex, defaults.ignoreColumn) == -1 &&
  619. $.inArray(colIndex-$row.length, defaults.ignoreColumn) == -1) {
  620. if (typeof (cellcallback) === "function") {
  621. var c, Colspan = 0;
  622. var r, Rowspan = 0;
  623. // handle rowspans from previous rows
  624. if (typeof rowspans[rowIndex] != 'undefined' && rowspans[rowIndex].length > 0) {
  625. for (c = 0; c <= colIndex; c++) {
  626. if (typeof rowspans[rowIndex][c] != 'undefined') {
  627. cellcallback(null, rowIndex, c);
  628. delete rowspans[rowIndex][c];
  629. colIndex++;
  630. }
  631. }
  632. }
  633. if ($(this).is("[colspan]")) {
  634. Colspan = parseInt($(this).attr('colspan'));
  635. rowColspan += Colspan > 0 ? Colspan - 1 : 0;
  636. }
  637. if ($(this).is("[rowspan]"))
  638. Rowspan = parseInt($(this).attr('rowspan'));
  639. // output content of current cell
  640. cellcallback(this, rowIndex, colIndex);
  641. // handle colspan of current cell
  642. for (c = 0; c < Colspan - 1; c++)
  643. cellcallback(null, rowIndex, colIndex + c);
  644. // store rowspan for following rows
  645. if (Rowspan) {
  646. for (r = 1; r < Rowspan; r++) {
  647. if (typeof rowspans[rowIndex + r] == 'undefined')
  648. rowspans[rowIndex + r] = [];
  649. rowspans[rowIndex + r][colIndex + rowColspan] = "";
  650. for (c = 1; c < Colspan; c++)
  651. rowspans[rowIndex + r][colIndex + rowColspan - c] = "";
  652. }
  653. }
  654. }
  655. }
  656. }
  657. });
  658. }
  659. }
  660. function jsPdfOutput(doc) {
  661. if (defaults.consoleLog === true)
  662. console.log(doc.output());
  663. if (defaults.outputMode === 'string')
  664. return doc.output();
  665. if (defaults.outputMode === 'base64')
  666. return base64encode(doc.output());
  667. try {
  668. var blob = doc.output('blob');
  669. saveAs(blob, defaults.fileName + '.pdf');
  670. }
  671. catch (e) {
  672. downloadFile(defaults.fileName + '.pdf',
  673. 'data:application/pdf;base64,',
  674. doc.output());
  675. }
  676. }
  677. function prepareAutoTableText (cell, data, cellopt) {
  678. var cs = 0;
  679. if ( typeof cellopt != 'undefined' )
  680. cs = cellopt.colspan;
  681. if ( cs >= 0 ) {
  682. // colspan handling
  683. var cellWidth = cell.width;
  684. var textPosX = cell.textPos.x;
  685. var i = data.table.columns.indexOf(data.column);
  686. for (var c = 1; c < cs; c++) {
  687. var column = data.table.columns[i+c];
  688. cellWidth += column.width;
  689. }
  690. if ( cs > 1 ) {
  691. if ( cell.styles.halign === 'right' )
  692. textPosX = cell.textPos.x + cellWidth - cell.width;
  693. else if ( cell.styles.halign === 'center' )
  694. textPosX = cell.textPos.x + (cellWidth - cell.width) / 2;
  695. }
  696. cell.width = cellWidth;
  697. cell.textPos.x = textPosX;
  698. if ( typeof cellopt != 'undefined' && cellopt.rowspan > 1 )
  699. {
  700. if ( cell.styles.valign === 'middle' )
  701. cell.textPos.y = cell.textPos.y + (cell.height * (cellopt.rowspan - 1)) / 2;
  702. else if ( cell.styles.valign === 'bottom' )
  703. cell.textPos.y += (cellopt.rowspan - 1) * cell.height;
  704. cell.height = cell.height * cellopt.rowspan;
  705. }
  706. // fix jsPDF's calculation of text position
  707. if ( cell.styles.valign === 'middle' || cell.styles.valign === 'bottom' ) {
  708. var splittedText = typeof cell.text === 'string' ? cell.text.split(/\r\n|\r|\n/g) : cell.text;
  709. var lineCount = splittedText.length || 1;
  710. if (lineCount > 2)
  711. cell.textPos.y -= ((2 - FONT_ROW_RATIO) / 2 * data.row.styles.fontSize) * (lineCount-2) / 3 ;
  712. }
  713. return true;
  714. }
  715. else
  716. return false; // cell is hidden (colspan = -1), don't draw it
  717. }
  718. function escapeRegExp(string) {
  719. return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  720. }
  721. function replaceAll(string, find, replace) {
  722. return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
  723. }
  724. // Takes a string and encapsulates it (by default in double-quotes) if it
  725. // contains the csv field separator, spaces, or linebreaks.
  726. function csvString(cell, rowIndex, colIndex) {
  727. var result = '';
  728. if (cell != null) {
  729. var dataString = parseString(cell, rowIndex, colIndex);
  730. var csvValue = (dataString === null || dataString == '') ? '' : dataString.toString();
  731. if (dataString instanceof Date)
  732. result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure;
  733. else {
  734. result = replaceAll(csvValue, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure);
  735. if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result))
  736. result = defaults.csvEnclosure + result + defaults.csvEnclosure;
  737. }
  738. }
  739. return result;
  740. }
  741. function parseNumber(value) {
  742. value = value || "0";
  743. value = replaceAll(value, defaults.numbers.html.decimalMark, '.');
  744. value = replaceAll(value, defaults.numbers.html.thousandsSeparator, '');
  745. return typeof value === "number" || jQuery.isNumeric(value) !== false ? value : false;
  746. }
  747. function parseString(cell, rowIndex, colIndex) {
  748. var result = '';
  749. if (cell != null) {
  750. var $cell = $(cell);
  751. var htmlData;
  752. if ($cell[0].hasAttribute("data-tableexport-value"))
  753. htmlData = $cell.data("tableexport-value");
  754. else
  755. htmlData = $cell.html();
  756. if (typeof defaults.onCellHtmlData === 'function')
  757. htmlData = defaults.onCellHtmlData($cell, rowIndex, colIndex, htmlData);
  758. if (defaults.htmlContent === true) {
  759. result = $.trim(htmlData);
  760. }
  761. else {
  762. var text = htmlData.replace(/\n/g,'\u2028').replace(/<br\s*[\/]?>/gi, '\u2060');
  763. var obj = $('<div/>').html(text).contents();
  764. text = '';
  765. $.each(obj.text().split("\u2028"), function(i, v) {
  766. if (i > 0)
  767. text += " ";
  768. text += $.trim(v);
  769. });
  770. $.each(text.split("\u2060"), function(i, v) {
  771. if (i > 0)
  772. result += "\n";
  773. result += $.trim(v).replace(/\u00AD/g, ""); // remove soft hyphens
  774. });
  775. if (defaults.numbers.html.decimalMark != defaults.numbers.output.decimalMark ||
  776. defaults.numbers.html.thousandsSeparator != defaults.numbers.output.thousandsSeparator) {
  777. var number = parseNumber (result);
  778. if ( number !== false ) {
  779. var frac = ("" + number).split('.');
  780. if ( frac.length == 1 )
  781. frac[1] = "";
  782. var mod = frac[0].length > 3 ? frac[0].length % 3 : 0;
  783. result = (number < 0 ? "-" : "") +
  784. (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]) +
  785. (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : "");
  786. }
  787. }
  788. }
  789. if (defaults.escape === true) {
  790. result = escape(result);
  791. }
  792. if (typeof defaults.onCellData === 'function') {
  793. result = defaults.onCellData($cell, rowIndex, colIndex, result);
  794. }
  795. }
  796. return result;
  797. }
  798. function hyphenate(a, b, c) {
  799. return b + "-" + c.toLowerCase();
  800. }
  801. function rgb2array(rgb_string, default_result) {
  802. var re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
  803. var bits = re.exec(rgb_string);
  804. var result = default_result;
  805. if (bits)
  806. result = [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ];
  807. return result;
  808. }
  809. function getCellStyles (cell) {
  810. var a = getStyle(cell, 'text-align');
  811. var fw = getStyle(cell, 'font-weight');
  812. var fs = getStyle(cell, 'font-style');
  813. var f = '';
  814. if (a == 'start')
  815. a = getStyle(cell, 'direction') == 'rtl' ? 'right' : 'left';
  816. if (fw >= 700)
  817. f = 'bold';
  818. if (fs == 'italic')
  819. f += fs;
  820. if (f == '')
  821. f = 'normal';
  822. return {
  823. style: {
  824. align: a,
  825. bcolor: rgb2array(getStyle(cell, 'background-color'), [255, 255, 255]),
  826. color: rgb2array(getStyle(cell, 'color'), [0, 0, 0]),
  827. fstyle: f
  828. },
  829. colspan: (parseInt($(cell).attr('colspan')) || 0),
  830. rowspan: (parseInt($(cell).attr('rowspan')) || 0)
  831. };
  832. }
  833. // get computed style property
  834. function getStyle(target, prop) {
  835. try {
  836. if (window.getComputedStyle) { // gecko and webkit
  837. prop = prop.replace(/([a-z])([A-Z])/, hyphenate); // requires hyphenated, not camel
  838. return window.getComputedStyle(target, null).getPropertyValue(prop);
  839. }
  840. if (target.currentStyle) { // ie
  841. return target.currentStyle[prop];
  842. }
  843. return target.style[prop];
  844. }
  845. catch (e) {
  846. }
  847. return "";
  848. }
  849. function getPropertyUnitValue(target, prop, unit) {
  850. var baseline = 100; // any number serves
  851. var value = getStyle(target, prop); // get the computed style value
  852. var numeric = value.match(/\d+/); // get the numeric component
  853. if (numeric !== null) {
  854. numeric = numeric[0]; // get the string
  855. var temp = document.createElement("div"); // create temporary element
  856. temp.style.overflow = "hidden"; // in case baseline is set too low
  857. temp.style.visibility = "hidden"; // no need to show it
  858. target.parentElement.appendChild(temp); // insert it into the parent for em, ex and %
  859. temp.style.width = baseline + unit;
  860. var factor = baseline / temp.offsetWidth;
  861. target.parentElement.removeChild(temp); // clean up
  862. return (numeric * factor);
  863. }
  864. return 0;
  865. }
  866. function downloadFile(filename, header, data) {
  867. var ua = window.navigator.userAgent;
  868. if (ua.indexOf("MSIE ") > 0 || !!ua.match(/Trident.*rv\:11\./)) {
  869. // Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin)
  870. // based on sampopes answer on http://stackoverflow.com/questions/22317951
  871. // ! Not working for json and pdf format !
  872. var frame = document.createElement("iframe");
  873. if (frame) {
  874. document.body.appendChild(frame);
  875. frame.setAttribute("style", "display:none");
  876. frame.contentDocument.open("txt/html", "replace");
  877. frame.contentDocument.write(data);
  878. frame.contentDocument.close();
  879. frame.focus();
  880. frame.contentDocument.execCommand("SaveAs", true, filename);
  881. document.body.removeChild(frame);
  882. }
  883. }
  884. else {
  885. var DownloadLink = document.createElement('a');
  886. if (DownloadLink) {
  887. DownloadLink.style.display = 'none';
  888. DownloadLink.download = filename;
  889. if (header.toLowerCase().indexOf("base64,") >= 0)
  890. DownloadLink.href = header + base64encode(data);
  891. else
  892. DownloadLink.href = header + encodeURIComponent(data);
  893. document.body.appendChild(DownloadLink);
  894. if (document.createEvent) {
  895. if (DownloadEvt == null)
  896. DownloadEvt = document.createEvent('MouseEvents');
  897. DownloadEvt.initEvent('click', true, false);
  898. DownloadLink.dispatchEvent(DownloadEvt);
  899. }
  900. else if (document.createEventObject)
  901. DownloadLink.fireEvent('onclick');
  902. else if (typeof DownloadLink.onclick == 'function')
  903. DownloadLink.onclick();
  904. document.body.removeChild(DownloadLink);
  905. }
  906. }
  907. }
  908. function utf8Encode(string) {
  909. string = string.replace(/\x0d\x0a/g, "\x0a");
  910. var utftext = "";
  911. for (var n = 0; n < string.length; n++) {
  912. var c = string.charCodeAt(n);
  913. if (c < 128) {
  914. utftext += String.fromCharCode(c);
  915. }
  916. else if ((c > 127) && (c < 2048)) {
  917. utftext += String.fromCharCode((c >> 6) | 192);
  918. utftext += String.fromCharCode((c & 63) | 128);
  919. }
  920. else {
  921. utftext += String.fromCharCode((c >> 12) | 224);
  922. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  923. utftext += String.fromCharCode((c & 63) | 128);
  924. }
  925. }
  926. return utftext;
  927. }
  928. function base64encode(input) {
  929. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  930. var output = "";
  931. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  932. var i = 0;
  933. input = utf8Encode(input);
  934. while (i < input.length) {
  935. chr1 = input.charCodeAt(i++);
  936. chr2 = input.charCodeAt(i++);
  937. chr3 = input.charCodeAt(i++);
  938. enc1 = chr1 >> 2;
  939. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  940. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  941. enc4 = chr3 & 63;
  942. if (isNaN(chr2)) {
  943. enc3 = enc4 = 64;
  944. } else if (isNaN(chr3)) {
  945. enc4 = 64;
  946. }
  947. output = output +
  948. keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  949. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  950. }
  951. return output;
  952. }
  953. return this;
  954. }
  955. });
  956. })(jQuery);