tableExport.js 100 KB

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