tableExport.js 89 KB

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