tableExport.js 89 KB

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