tableExport.js 97 KB

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