tableExport.js 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370
  1. /**
  2. * @preserve tableExport.jquery.plugin
  3. *
  4. * Version 1.28.0
  5. *
  6. * Copyright (c) 2015-2023 hhurz,
  7. * https://github.com/hhurz/tableExport.jquery.plugin
  8. *
  9. * Based on https://github.com/kayalshri/tableExport.jquery.plugin
  10. *
  11. * Licensed under the MIT License
  12. **/
  13. 'use strict';
  14. (function ($) {
  15. $.fn.tableExport = function (options) {
  16. let docData;
  17. const defaults = {
  18. csvEnclosure: '"',
  19. csvSeparator: ',',
  20. csvUseBOM: true,
  21. date: {
  22. html: 'dd/mm/yyyy' // Date format used in html source. Supported placeholders: dd, mm, yy, yyyy and a arbitrary single separator character
  23. },
  24. displayTableName: false, // Deprecated
  25. escape: false, // Deprecated
  26. exportHiddenCells: false, // true = speed up export of large tables with hidden cells (hidden cells will be exported !)
  27. fileName: 'tableExport',
  28. htmlContent: false,
  29. htmlHyperlink: 'content', // Export the 'content' or the 'href' link of <a> tags unless onCellHtmlHyperlink is not defined
  30. ignoreColumn: [],
  31. ignoreRow: [],
  32. jsonScope: 'all', // One of 'head', 'data', 'all'
  33. jspdf: { // jsPDF / jsPDF-AutoTable related options
  34. orientation: 'p',
  35. unit: 'pt',
  36. format: 'a4', // One of jsPDF page formats or 'bestfit' for automatic paper format selection
  37. margins: {left: 20, right: 10, top: 10, bottom: 10},
  38. onDocCreated: null,
  39. autotable: {
  40. styles: {
  41. cellPadding: 2,
  42. rowHeight: 12,
  43. fontSize: 8,
  44. fillColor: 255, // Color value or 'inherit' to use css background-color from html table
  45. textColor: 50, // Color value or 'inherit' to use css color from html table
  46. fontStyle: 'normal', // 'normal', 'bold', 'italic', 'bolditalic' or 'inherit' to use css font-weight and font-style from html table
  47. overflow: 'ellipsize', // 'visible', 'hidden', 'ellipsize' or 'linebreak'
  48. halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal cell alignment from html table
  49. valign: 'middle' // 'top', 'middle', or 'bottom'
  50. },
  51. headerStyles: {
  52. fillColor: [52, 73, 94],
  53. textColor: 255,
  54. fontStyle: 'bold',
  55. halign: 'inherit', // 'left', 'center', 'right' or 'inherit' to use css horizontal header cell alignment from html table
  56. valign: 'middle' // 'top', 'middle', or 'bottom'
  57. },
  58. alternateRowStyles: {
  59. fillColor: 245
  60. },
  61. tableExport: {
  62. doc: null, // jsPDF doc object. If set, an already created doc object will be used to export to
  63. onAfterAutotable: null,
  64. onBeforeAutotable: null,
  65. onAutotableText: null,
  66. onTable: null,
  67. outputImages: true
  68. }
  69. }
  70. },
  71. mso: { // MS Excel and MS Word related options
  72. fileFormat: 'xlshtml', // 'xlshtml' = Excel 2000 html format
  73. // 'xmlss' = XML Spreadsheet 2003 file format (XMLSS)
  74. // 'xlsx' = Excel 2007 Office Open XML format
  75. onMsoNumberFormat: null, // Excel 2000 html format only. See readme.md for more information about msonumberformat
  76. pageFormat: 'a4', // Page format used for page orientation
  77. pageOrientation: 'portrait', // portrait, landscape (xlshtml format only)
  78. rtl: false, // true = Set worksheet option 'DisplayRightToLeft'
  79. styles: [], // E.g. ['border-bottom', 'border-top', 'border-left', 'border-right']
  80. worksheetName: '',
  81. xlsx: { // Specific Excel 2007 XML format settings:
  82. formatId: { // XLSX format (id) used to format excel cells. See readme.md: data-tableexport-xlsxformatid
  83. date: 14, // The default format id, or a format string (e.g. 'm/d/yy'), or a function(cell, row, col)
  84. numbers: 2, // The default Format id, or a format string (e.g. '\"T\"\ #0.00'), or a function(cell, row, col)
  85. currency: 164 // This id is used by "data-tableexport-xlsxformatid" to allow you to export a cell in currency format (see below)
  86. },
  87. format: {
  88. currency: '$#,##0.00;[Red]-$#,##0.00' // The format string to be used for the export for the currency format
  89. // Euro format: '#,##0.00 €;[Red](#,##0.00) €'
  90. },
  91. onHyperlink: null // function($cell, row, col, href, content, hyperlink): Return what to export for hyperlinks
  92. }
  93. },
  94. numbers: {
  95. html: {
  96. decimalMark: '.', // Decimal mark in html source
  97. thousandsSeparator: ',' // Thousands separator in html source
  98. },
  99. output: { // Set 'output: false' to keep number format of html source in resulting output
  100. decimalMark: '.', // Decimal mark in resulting output
  101. thousandsSeparator: ',' // Thousands separator in resulting output
  102. }
  103. },
  104. onAfterSaveToFile: null, // function(data, fileName)
  105. onBeforeSaveToFile: null, // saveIt = function(data, fileName, type, charset, encoding): Return false to abort save process
  106. onCellData: null, // Text to export = function($cell, row, col, href, cellText, cellType)
  107. onCellHtmlData: null, // Text to export = function($cell, row, col, htmlContent)
  108. onCellHtmlHyperlink: null, // Text to export = function($cell, row, col, href, cellText)
  109. onIgnoreRow: null, // ignoreRow = function($tr, row): Return true to prevent export of the row
  110. onTableExportBegin: null, // function() - called when export starts
  111. onTableExportEnd: null, // function() - called when export ends
  112. outputMode: 'file', // 'file', 'string', 'base64' or 'window' (experimental)
  113. pdfmake: {
  114. enabled: false, // true: Use pdfmake as pdf producer instead of jspdf and jspdf-autotable
  115. docDefinition: {
  116. pageSize: 'A4', // 4A0,2A0,A{0-10},B{0-10},C{0-10},RA{0-4},SRA{0-4},EXECUTIVE,FOLIO,LEGAL,LETTER,TABLOID
  117. pageOrientation: 'portrait', // 'portrait' or 'landscape'
  118. styles: {
  119. header: {
  120. background: '#34495E',
  121. color: '#FFFFFF',
  122. bold: true,
  123. alignment: 'center',
  124. fillColor: '#34495E'
  125. },
  126. alternateRow: {
  127. fillColor: '#f5f5f5'
  128. }
  129. },
  130. defaultStyle: {
  131. color: '#000000',
  132. fontSize: 8,
  133. font: 'Roboto' // Default font is 'Roboto' which needs vfs_fonts.js to be included
  134. } // To export arabic characters include mirza_fonts.js _instead_ of vfs_fonts.js
  135. }, // For a chinese font include either gbsn00lp_fonts.js or ZCOOLXiaoWei_fonts.js _instead_ of vfs_fonts.js
  136. fonts: {}
  137. },
  138. preserve: {
  139. leadingWS: false, // preserve leading white spaces
  140. trailingWS: false // preserve trailing white spaces
  141. },
  142. preventInjection: true, // Prepend a single quote to cell strings that start with =,+,- or @ to prevent formula injection
  143. sql: {
  144. tableEnclosure: '`', // If table name or column names contain any characters except letters, numbers, and
  145. columnEnclosure: '`' // underscores, usually the name must be delimited by enclosing it in back quotes (`)
  146. },
  147. tbodySelector: 'tr',
  148. tfootSelector: 'tr', // Set empty ('') to prevent export of tfoot rows
  149. theadSelector: 'tr',
  150. tableName: 'Table',
  151. type: 'excel' // Export format: 'csv', 'tsv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf'
  152. };
  153. const pageFormats = { // Size in pt of various paper formats. Adopted from jsPDF.
  154. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94], 'a2': [1190.55, 1683.78],
  155. 'a3': [841.89, 1190.55], 'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
  156. 'a6': [297.64, 419.53], 'a7': [209.76, 297.64], 'a8': [147.40, 209.76],
  157. 'a9': [104.88, 147.40], 'a10': [73.70, 104.88],
  158. 'b0': [2834.65, 4008.19], 'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
  159. 'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63], 'b5': [498.90, 708.66],
  160. 'b6': [354.33, 498.90], 'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
  161. 'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
  162. 'c0': [2599.37, 3676.54],
  163. 'c1': [1836.85, 2599.37], 'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
  164. 'c4': [649.13, 918.43], 'c5': [459.21, 649.13], 'c6': [323.15, 459.21],
  165. 'c7': [229.61, 323.15], 'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
  166. 'c10': [79.37, 113.39],
  167. 'dl': [311.81, 623.62],
  168. 'letter': [612, 792], 'government-letter': [576, 756], 'legal': [612, 1008],
  169. 'junior-legal': [576, 360], 'ledger': [1224, 792], 'tabloid': [792, 1224],
  170. 'credit-card': [153, 243]
  171. };
  172. const jsPdfThemes = { // Styles for the themes
  173. 'striped': {
  174. table: {
  175. fillColor: 255,
  176. textColor: 80,
  177. fontStyle: 'normal',
  178. fillStyle: 'F'
  179. },
  180. header: {
  181. textColor: 255,
  182. fillColor: [41, 128, 185],
  183. rowHeight: 23,
  184. fontStyle: 'bold'
  185. },
  186. body: {},
  187. alternateRow: {fillColor: 245}
  188. },
  189. 'grid': {
  190. table: {
  191. fillColor: 255,
  192. textColor: 80,
  193. fontStyle: 'normal',
  194. lineWidth: 0.1,
  195. fillStyle: 'DF'
  196. },
  197. header: {
  198. textColor: 255,
  199. fillColor: [26, 188, 156],
  200. rowHeight: 23,
  201. fillStyle: 'F',
  202. fontStyle: 'bold'
  203. },
  204. body: {},
  205. alternateRow: {}
  206. },
  207. 'plain': {header: {fontStyle: 'bold'}}
  208. };
  209. let jsPdfDefaultStyles = { // Base style for all themes
  210. cellPadding: 5,
  211. fontSize: 10,
  212. fontName: "helvetica", // helvetica, times, courier, malgun
  213. lineColor: 200,
  214. lineWidth: 0.1,
  215. fontStyle: 'normal', // normal, bold, italic, bolditalic
  216. overflow: 'ellipsize', // visible, hidden, ellipsize or linebreak
  217. fillColor: 255,
  218. textColor: 20,
  219. halign: 'left', // left, center, right
  220. valign: 'top', // top, middle, bottom
  221. fillStyle: 'F', // 'S', 'F' or 'DF' (stroke, fill or fill then stroke)
  222. rowHeight: 20,
  223. columnWidth: 'auto'
  224. };
  225. const FONT_ROW_RATIO = 1.15;
  226. const el = this;
  227. let DownloadEvt = null;
  228. let $head_rows = [];
  229. let $rows = [];
  230. let rowIndex = 0;
  231. let trData = '';
  232. let colNames = [];
  233. let ranges = [];
  234. let blob;
  235. let $hiddenTableElements = [];
  236. let checkCellVisibility = false;
  237. $.extend(true, defaults, options);
  238. // Adopt deprecated options
  239. if (defaults.type === 'xlsx') {
  240. defaults.mso.fileFormat = defaults.type;
  241. defaults.type = 'excel';
  242. }
  243. if (typeof defaults.excelFileFormat !== 'undefined' && typeof defaults.mso.fileFormat === 'undefined')
  244. defaults.mso.fileFormat = defaults.excelFileFormat;
  245. if (typeof defaults.excelPageFormat !== 'undefined' && typeof defaults.mso.pageFormat === 'undefined')
  246. defaults.mso.pageFormat = defaults.excelPageFormat;
  247. if (typeof defaults.excelPageOrientation !== 'undefined' && typeof defaults.mso.pageOrientation === 'undefined')
  248. defaults.mso.pageOrientation = defaults.excelPageOrientation;
  249. if (typeof defaults.excelRTL !== 'undefined' && typeof defaults.mso.rtl === 'undefined')
  250. defaults.mso.rtl = defaults.excelRTL;
  251. if (typeof defaults.excelstyles !== 'undefined' && typeof defaults.mso.styles === 'undefined')
  252. defaults.mso.styles = defaults.excelstyles;
  253. if (typeof defaults.onMsoNumberFormat !== 'undefined' && typeof defaults.mso.onMsoNumberFormat === 'undefined')
  254. defaults.mso.onMsoNumberFormat = defaults.onMsoNumberFormat;
  255. if (typeof defaults.worksheetName !== 'undefined' && typeof defaults.mso.worksheetName === 'undefined')
  256. defaults.mso.worksheetName = defaults.worksheetName;
  257. if (typeof defaults.mso.xslx !== 'undefined' && typeof defaults.mso.xlsx === 'undefined')
  258. defaults.mso.xlsx = defaults.mso.xslx;
  259. // Check values of some options
  260. defaults.mso.pageOrientation = (defaults.mso.pageOrientation.substr(0, 1) === 'l') ? 'landscape' : 'portrait';
  261. defaults.date.html = defaults.date.html || '';
  262. if (defaults.date.html.length) {
  263. const patt = [];
  264. patt['dd'] = '(3[01]|[12][0-9]|0?[1-9])';
  265. patt['mm'] = '(1[012]|0?[1-9])';
  266. patt['yyyy'] = '((?:1[6-9]|2[0-2])\\d{2})';
  267. patt['yy'] = '(\\d{2})';
  268. const separator = defaults.date.html.match(/[^a-zA-Z0-9]/)[0];
  269. const formatItems = defaults.date.html.toLowerCase().split(separator);
  270. defaults.date.regex = '^\\s*';
  271. defaults.date.regex += patt[formatItems[0]];
  272. defaults.date.regex += '(.)'; // separator group
  273. defaults.date.regex += patt[formatItems[1]];
  274. defaults.date.regex += '\\2'; // identical separator group
  275. defaults.date.regex += patt[formatItems[2]];
  276. defaults.date.regex += '\\s*$';
  277. // 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*$'
  278. defaults.date.pattern = new RegExp(defaults.date.regex, 'g');
  279. let f = formatItems.indexOf('dd') + 1;
  280. defaults.date.match_d = f + (f > 1 ? 1 : 0);
  281. f = formatItems.indexOf('mm') + 1;
  282. defaults.date.match_m = f + (f > 1 ? 1 : 0);
  283. f = (formatItems.indexOf('yyyy') >= 0 ? formatItems.indexOf('yyyy') : formatItems.indexOf('yy')) + 1;
  284. defaults.date.match_y = f + (f > 1 ? 1 : 0);
  285. }
  286. colNames = GetColumnNames(el);
  287. if (typeof defaults.onTableExportBegin === 'function')
  288. defaults.onTableExportBegin();
  289. if (defaults.type === 'csv' || defaults.type === 'tsv' || defaults.type === 'txt') {
  290. let csvData = '';
  291. let rowLength = 0;
  292. ranges = [];
  293. rowIndex = 0;
  294. const csvString = function (cell, rowIndex, colIndex) {
  295. let result = '';
  296. if (cell !== null) {
  297. const dataString = parseString(cell, rowIndex, colIndex);
  298. const csvValue = (dataString === null || dataString === '') ? '' : dataString.toString();
  299. if (defaults.type === 'tsv') {
  300. if (dataString instanceof Date)
  301. dataString.toLocaleString();
  302. // According to http://www.iana.org/assignments/media-types/text/tab-separated-values
  303. // are fields that contain tabs not allowable in tsv encoding
  304. result = replaceAll(csvValue, '\t', ' ');
  305. } else {
  306. // Takes a string and encapsulates it (by default in double-quotes) if it
  307. // contains the csv field separator, spaces, or linebreaks.
  308. if (dataString instanceof Date)
  309. result = defaults.csvEnclosure + dataString.toLocaleString() + defaults.csvEnclosure;
  310. else {
  311. result = preventInjection(csvValue);
  312. result = replaceAll(result, defaults.csvEnclosure, defaults.csvEnclosure + defaults.csvEnclosure);
  313. if (result.indexOf(defaults.csvSeparator) >= 0 || /[\r\n ]/g.test(result))
  314. result = defaults.csvEnclosure + result + defaults.csvEnclosure;
  315. }
  316. }
  317. }
  318. return result;
  319. };
  320. const CollectCsvData = function ($rows, rowselector, length) {
  321. $rows.each(function () {
  322. trData = '';
  323. ForEachVisibleCell(this, rowselector, rowIndex, length + $rows.length,
  324. function (cell, row, col) {
  325. trData += csvString(cell, row, col) + (defaults.type === 'tsv' ? '\t' : defaults.csvSeparator);
  326. });
  327. trData = $.trim(trData).substring(0, trData.length - 1);
  328. if (trData.length > 0) {
  329. if (csvData.length > 0)
  330. csvData += '\n';
  331. csvData += trData;
  332. }
  333. rowIndex++;
  334. });
  335. return $rows.length;
  336. };
  337. rowLength += CollectCsvData($(el).find('thead').first().find(defaults.theadSelector), 'th,td', rowLength);
  338. findTableElements($(el), 'tbody').each(function () {
  339. rowLength += CollectCsvData(findTableElements($(this), defaults.tbodySelector), 'td,th', rowLength);
  340. });
  341. if (defaults.tfootSelector.length)
  342. CollectCsvData($(el).find('tfoot').first().find(defaults.tfootSelector), 'td,th', rowLength);
  343. csvData += '\n';
  344. //output
  345. if (defaults.outputMode === 'string')
  346. return csvData;
  347. if (defaults.outputMode === 'base64')
  348. return base64encode(csvData);
  349. if (defaults.outputMode === 'window') {
  350. downloadFile(false, 'data:text/' + (defaults.type === 'csv' ? 'csv' : 'plain') + ';charset=utf-8,', csvData);
  351. return;
  352. }
  353. saveToFile(csvData,
  354. defaults.fileName + '.' + defaults.type,
  355. 'text/' + (defaults.type === 'csv' ? 'csv' : 'plain'),
  356. 'utf-8',
  357. '',
  358. (defaults.type === 'csv' && defaults.csvUseBOM));
  359. } else if (defaults.type === 'sql') {
  360. // Header
  361. rowIndex = 0;
  362. ranges = [];
  363. let tdData = 'INSERT INTO ' + defaults.sql.tableEnclosure + defaults.tableName + defaults.sql.tableEnclosure + ' (';
  364. $head_rows = collectHeadRows($(el));
  365. $($head_rows).each(function () {
  366. ForEachVisibleCell(this, 'th,td', rowIndex, $head_rows.length,
  367. function (cell, row, col) {
  368. let colName = parseString(cell, row, col) || '';
  369. if (colName.indexOf(defaults.sql.columnEnclosure) > -1)
  370. colName = replaceAll(colName.toString(), defaults.sql.columnEnclosure, defaults.sql.columnEnclosure + defaults.sql.columnEnclosure);
  371. tdData += defaults.sql.columnEnclosure + colName + defaults.sql.columnEnclosure + ',';
  372. });
  373. rowIndex++;
  374. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  375. });
  376. tdData += ') VALUES ';
  377. // Data
  378. $rows = collectRows($(el));
  379. $($rows).each(function () {
  380. trData = '';
  381. ForEachVisibleCell(this, 'td,th', rowIndex, $head_rows.length + $rows.length,
  382. function (cell, row, col) {
  383. let dataString = parseString(cell, row, col) || '';
  384. if (dataString.indexOf('\'') > -1)
  385. dataString = replaceAll(dataString.toString(), '\'', '\'\'');
  386. trData += '\'' + dataString + '\',';
  387. });
  388. if (trData.length > 3) {
  389. tdData += '(' + trData;
  390. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  391. tdData += '),';
  392. }
  393. rowIndex++;
  394. });
  395. tdData = $.trim(tdData).substring(0, tdData.length - 1);
  396. tdData += ';';
  397. // Output
  398. if (defaults.outputMode === 'string')
  399. return tdData;
  400. if (defaults.outputMode === 'base64')
  401. return base64encode(tdData);
  402. saveToFile(tdData, defaults.fileName + '.sql', 'application/sql', 'utf-8', '', false);
  403. } else if (defaults.type === 'json') {
  404. const jsonHeaderArray = [];
  405. ranges = [];
  406. $head_rows = collectHeadRows($(el));
  407. $($head_rows).each(function () {
  408. const jsonArrayTd = [];
  409. ForEachVisibleCell(this, 'th,td', rowIndex, $head_rows.length,
  410. function (cell, row, col) {
  411. jsonArrayTd.push(parseString(cell, row, col));
  412. });
  413. jsonHeaderArray.push(jsonArrayTd);
  414. });
  415. // Data
  416. const jsonArray = [];
  417. $rows = collectRows($(el));
  418. $($rows).each(function () {
  419. const jsonObjectTd = {};
  420. let colIndex = 0;
  421. ForEachVisibleCell(this, 'td,th', rowIndex, $head_rows.length + $rows.length,
  422. function (cell, row, col) {
  423. if (jsonHeaderArray.length) {
  424. jsonObjectTd[jsonHeaderArray[jsonHeaderArray.length - 1][colIndex]] = parseString(cell, row, col);
  425. } else {
  426. jsonObjectTd[colIndex] = parseString(cell, row, col);
  427. }
  428. colIndex++;
  429. });
  430. if ($.isEmptyObject(jsonObjectTd) === false)
  431. jsonArray.push(jsonObjectTd);
  432. rowIndex++;
  433. });
  434. let save_data;
  435. if (defaults.jsonScope === 'head')
  436. save_data = JSON.stringify(jsonHeaderArray);
  437. else if (defaults.jsonScope === 'data')
  438. save_data = JSON.stringify(jsonArray);
  439. else // all
  440. save_data = JSON.stringify({header: jsonHeaderArray, data: jsonArray});
  441. if (defaults.outputMode === 'string')
  442. return save_data;
  443. if (defaults.outputMode === 'base64')
  444. return base64encode(save_data);
  445. saveToFile(save_data, defaults.fileName + '.json', 'application/json', 'utf-8', 'base64', false);
  446. } else if (defaults.type === 'xml') {
  447. rowIndex = 0;
  448. ranges = [];
  449. let xml = '<?xml version="1.0" encoding="utf-8"?>';
  450. xml += '<tabledata><fields>';
  451. // Header
  452. $head_rows = collectHeadRows($(el));
  453. $($head_rows).each(function () {
  454. ForEachVisibleCell(this, 'th,td', rowIndex, $head_rows.length,
  455. function (cell, row, col) {
  456. xml += '<field>' + parseString(cell, row, col) + '</field>';
  457. });
  458. rowIndex++;
  459. });
  460. xml += '</fields><data>';
  461. // Data
  462. let rowCount = 1;
  463. $rows = collectRows($(el));
  464. $($rows).each(function () {
  465. let colCount = 1;
  466. trData = '';
  467. ForEachVisibleCell(this, 'td,th', rowIndex, $head_rows.length + $rows.length,
  468. function (cell, row, col) {
  469. trData += '<column-' + colCount + '>' + parseString(cell, row, col) + '</column-' + colCount + '>';
  470. colCount++;
  471. });
  472. if (trData.length > 0 && trData !== '<column-1></column-1>') {
  473. xml += '<row id="' + rowCount + '">' + trData + '</row>';
  474. rowCount++;
  475. }
  476. rowIndex++;
  477. });
  478. xml += '</data></tabledata>';
  479. // Output
  480. if (defaults.outputMode === 'string')
  481. return xml;
  482. if (defaults.outputMode === 'base64')
  483. return base64encode(xml);
  484. saveToFile(xml, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false);
  485. } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xmlss') {
  486. const sheetData = [];
  487. const docNames = [];
  488. $(el).filter(function () {
  489. return isVisible($(this));
  490. }).each(function () {
  491. const $table = $(this);
  492. let ssName = '';
  493. if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length)
  494. ssName = defaults.mso.worksheetName + ' ' + (docNames.length + 1);
  495. else if (typeof defaults.mso.worksheetName[docNames.length] !== 'undefined')
  496. ssName = defaults.mso.worksheetName[docNames.length];
  497. if (!ssName.length)
  498. ssName = $table.find('caption').text() || '';
  499. if (!ssName.length)
  500. ssName = 'Table ' + (docNames.length + 1);
  501. ssName = $.trim(ssName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  502. docNames.push($('<div />').text(ssName).html());
  503. if (defaults.exportHiddenCells === false) {
  504. $hiddenTableElements = $table.find('tr, th, td').filter(':hidden');
  505. checkCellVisibility = $hiddenTableElements.length > 0;
  506. }
  507. rowIndex = 0;
  508. colNames = GetColumnNames(this);
  509. docData = '<Table>\r';
  510. function CollectXmlssData ($rows, rowselector, length) {
  511. const spans = [];
  512. $($rows).each(function () {
  513. let ssIndex = 0;
  514. let nCols = 0;
  515. trData = '';
  516. ForEachVisibleCell(this, 'td,th', rowIndex, length + $rows.length,
  517. function (cell, row, col) {
  518. if (cell !== null) {
  519. let style = '';
  520. let data = parseString(cell, row, col);
  521. let type = 'String';
  522. if (jQuery.isNumeric(data) !== false) {
  523. type = 'Number';
  524. } else {
  525. const number = parsePercent(data);
  526. if (number !== false) {
  527. data = number;
  528. type = 'Number';
  529. style += ' ss:StyleID="pct1"';
  530. }
  531. }
  532. if (type !== 'Number')
  533. data = data.replace(/\n/g, '<br>');
  534. let colspan = getColspan(cell);
  535. let rowspan = getRowspan(cell);
  536. // Skip spans
  537. $.each(spans, function () {
  538. const range = this;
  539. if (rowIndex >= range.s.r && rowIndex <= range.e.r && nCols >= range.s.c && nCols <= range.e.c) {
  540. for (let i = 0; i <= range.e.c - range.s.c; ++i) {
  541. nCols++;
  542. ssIndex++;
  543. }
  544. }
  545. });
  546. // Handle Row Span
  547. if (rowspan || colspan) {
  548. rowspan = rowspan || 1;
  549. colspan = colspan || 1;
  550. spans.push({
  551. s: {r: rowIndex, c: nCols},
  552. e: {r: rowIndex + rowspan - 1, c: nCols + colspan - 1}
  553. });
  554. }
  555. // Handle Colspan
  556. if (colspan > 1) {
  557. style += ' ss:MergeAcross="' + (colspan - 1) + '"';
  558. nCols += (colspan - 1);
  559. }
  560. if (rowspan > 1) {
  561. style += ' ss:MergeDown="' + (rowspan - 1) + '" ss:StyleID="rsp1"';
  562. }
  563. if (ssIndex > 0) {
  564. style += ' ss:Index="' + (nCols + 1) + '"';
  565. ssIndex = 0;
  566. }
  567. trData += '<Cell' + style + '><Data ss:Type="' + type + '">' +
  568. $('<div />').text(data).html() +
  569. '</Data></Cell>\r';
  570. nCols++;
  571. }
  572. });
  573. if (trData.length > 0)
  574. docData += '<Row ss:AutoFitHeight="0">\r' + trData + '</Row>\r';
  575. rowIndex++;
  576. });
  577. return $rows.length;
  578. }
  579. const rowLength = CollectXmlssData(collectHeadRows($table), 'th,td', 0);
  580. CollectXmlssData(collectRows($table), 'td,th', rowLength);
  581. docData += '</Table>\r';
  582. sheetData.push(docData);
  583. });
  584. const count = {};
  585. const firstOccurrences = {};
  586. let item, itemCount;
  587. for (let n = 0, c = docNames.length; n < c; n++) {
  588. item = docNames[n];
  589. itemCount = count[item];
  590. itemCount = count[item] = (itemCount == null ? 1 : itemCount + 1);
  591. if (itemCount === 2)
  592. docNames[firstOccurrences[item]] = docNames[firstOccurrences[item]].substring(0, 29) + '-1';
  593. if (count[item] > 1)
  594. docNames[n] = docNames[n].substring(0, 29) + '-' + count[item];
  595. else
  596. firstOccurrences[item] = n;
  597. }
  598. const CreationDate = new Date().toISOString();
  599. let xmlssDocFile = '<?xml version="1.0" encoding="UTF-8"?>\r' +
  600. '<?mso-application progid="Excel.Sheet"?>\r' +
  601. '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\r' +
  602. ' xmlns:o="urn:schemas-microsoft-com:office:office"\r' +
  603. ' xmlns:x="urn:schemas-microsoft-com:office:excel"\r' +
  604. ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"\r' +
  605. ' xmlns:html="http://www.w3.org/TR/REC-html40">\r' +
  606. '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">\r' +
  607. ' <Created>' + CreationDate + '</Created>\r' +
  608. '</DocumentProperties>\r' +
  609. '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">\r' +
  610. ' <AllowPNG/>\r' +
  611. '</OfficeDocumentSettings>\r' +
  612. '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">\r' +
  613. ' <WindowHeight>9000</WindowHeight>\r' +
  614. ' <WindowWidth>13860</WindowWidth>\r' +
  615. ' <WindowTopX>0</WindowTopX>\r' +
  616. ' <WindowTopY>0</WindowTopY>\r' +
  617. ' <ProtectStructure>False</ProtectStructure>\r' +
  618. ' <ProtectWindows>False</ProtectWindows>\r' +
  619. '</ExcelWorkbook>\r' +
  620. '<Styles>\r' +
  621. ' <Style ss:ID="Default" ss:Name="Normal">\r' +
  622. ' <Alignment ss:Vertical="Bottom"/>\r' +
  623. ' <Borders/>\r' +
  624. ' <Font/>\r' +
  625. ' <Interior/>\r' +
  626. ' <NumberFormat/>\r' +
  627. ' <Protection/>\r' +
  628. ' </Style>\r' +
  629. ' <Style ss:ID="rsp1">\r' +
  630. ' <Alignment ss:Vertical="Center"/>\r' +
  631. ' </Style>\r' +
  632. ' <Style ss:ID="pct1">\r' +
  633. ' <NumberFormat ss:Format="Percent"/>\r' +
  634. ' </Style>\r' +
  635. '</Styles>\r';
  636. for (let j = 0; j < sheetData.length; j++) {
  637. xmlssDocFile += '<Worksheet ss:Name="' + docNames[j] + '" ss:RightToLeft="' + (defaults.mso.rtl ? '1' : '0') + '">\r' +
  638. sheetData[j];
  639. if (defaults.mso.rtl) {
  640. xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">\r' +
  641. '<DisplayRightToLeft/>\r' +
  642. '</WorksheetOptions>\r';
  643. } else
  644. xmlssDocFile += '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"/>\r';
  645. xmlssDocFile += '</Worksheet>\r';
  646. }
  647. xmlssDocFile += '</Workbook>\r';
  648. if (defaults.outputMode === 'string')
  649. return xmlssDocFile;
  650. if (defaults.outputMode === 'base64')
  651. return base64encode(xmlssDocFile);
  652. saveToFile(xmlssDocFile, defaults.fileName + '.xml', 'application/xml', 'utf-8', 'base64', false);
  653. } else if (defaults.type === 'excel' && defaults.mso.fileFormat === 'xlsx') {
  654. const sheetNames = [];
  655. const workbook = XLSX.utils.book_new();
  656. // Multiple worksheets and .xlsx file extension #202
  657. $(el).filter(function () {
  658. return isVisible($(this));
  659. }).each(function () {
  660. const $table = $(this);
  661. const ws = xlsxTableToSheet(this);
  662. let sheetName = '';
  663. if (typeof defaults.mso.worksheetName === 'string' && defaults.mso.worksheetName.length)
  664. sheetName = defaults.mso.worksheetName + ' ' + (sheetNames.length + 1);
  665. else if (typeof defaults.mso.worksheetName[sheetNames.length] !== 'undefined')
  666. sheetName = defaults.mso.worksheetName[sheetNames.length];
  667. if (!sheetName.length)
  668. sheetName = $table.find('caption').text() || '';
  669. if (!sheetName.length)
  670. sheetName = 'Table ' + (sheetNames.length + 1);
  671. sheetName = $.trim(sheetName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  672. sheetNames.push(sheetName);
  673. XLSX.utils.book_append_sheet(workbook, ws, sheetName);
  674. });
  675. // add worksheet to workbook
  676. const wbData = XLSX.write(workbook, {type: 'binary', bookType: defaults.mso.fileFormat, bookSST: false});
  677. saveToFile(xlsxWorkbookToArrayBuffer(wbData),
  678. defaults.fileName + '.' + defaults.mso.fileFormat,
  679. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  680. 'UTF-8', '', false);
  681. } else if (defaults.type === 'excel' || defaults.type === 'xls' || defaults.type === 'word' || defaults.type === 'doc') {
  682. const MSDocType = (defaults.type === 'excel' || defaults.type === 'xls') ? 'excel' : 'word';
  683. const MSDocExt = (MSDocType === 'excel') ? 'xls' : 'doc';
  684. const MSDocSchema = 'xmlns:x="urn:schemas-microsoft-com:office:' + MSDocType + '"';
  685. docData = '';
  686. let docName = '';
  687. $(el).filter(function () {
  688. return isVisible($(this));
  689. }).each(function () {
  690. const $table = $(this);
  691. if (docName === '') {
  692. docName = defaults.mso.worksheetName || $table.find('caption').text() || 'Table';
  693. docName = $.trim(docName.replace(/[\\\/[\]*:?'"]/g, '').substring(0, 31));
  694. }
  695. if (defaults.exportHiddenCells === false) {
  696. $hiddenTableElements = $table.find('tr, th, td').filter(':hidden');
  697. checkCellVisibility = $hiddenTableElements.length > 0;
  698. }
  699. rowIndex = 0;
  700. ranges = [];
  701. colNames = GetColumnNames(this);
  702. // Header
  703. docData += '<table><thead>';
  704. $head_rows = collectHeadRows($table);
  705. $($head_rows).each(function () {
  706. const $row = $(this);
  707. const rowStyles = document.defaultView.getComputedStyle($row[0], null);
  708. trData = '';
  709. ForEachVisibleCell(this, 'th,td', rowIndex, $head_rows.length,
  710. function (cell, row, col) {
  711. if (cell !== null) {
  712. let thStyle = '';
  713. trData += '<th';
  714. if (defaults.mso.styles.length) {
  715. const cellStyles = document.defaultView.getComputedStyle(cell, null);
  716. for (let cssStyle in defaults.mso.styles) {
  717. const stylePropertyName = defaults.mso.styles[cssStyle];
  718. let thCss = getStyle(cellStyles, stylePropertyName);
  719. if (thCss === '')
  720. thCss = getStyle(rowStyles, stylePropertyName);
  721. if (thCss !== '' && thCss !== '0px none rgb(0, 0, 0)' && thCss !== 'rgba(0, 0, 0, 0)') {
  722. thStyle += (thStyle === '') ? 'style="' : ';';
  723. thStyle += stylePropertyName + ':' + thCss;
  724. }
  725. }
  726. }
  727. if (thStyle !== '')
  728. trData += ' ' + thStyle + '"';
  729. const tdColspan = getColspan(cell);
  730. if (tdColspan > 0)
  731. trData += ' colspan="' + tdColspan + '"';
  732. const tdRowspan = getRowspan(cell);
  733. if (tdRowspan > 0)
  734. trData += ' rowspan="' + tdRowspan + '"';
  735. trData += '>' + parseString(cell, row, col) + '</th>';
  736. }
  737. });
  738. if (trData.length > 0)
  739. docData += '<tr>' + trData + '</tr>';
  740. rowIndex++;
  741. });
  742. docData += '</thead><tbody>';
  743. // Data
  744. $rows = collectRows($table);
  745. $($rows).each(function () {
  746. const $row = $(this);
  747. let cellStyles = null;
  748. let rowStyles = null;
  749. trData = '';
  750. ForEachVisibleCell(this, 'td,th', rowIndex, $head_rows.length + $rows.length,
  751. function (cell, row, col) {
  752. if (cell !== null) {
  753. let tdValue = parseString(cell, row, col);
  754. let tdStyle = '';
  755. let tdCss = $(cell).attr('data-tableexport-msonumberformat');
  756. if (typeof tdCss === 'undefined' && typeof defaults.mso.onMsoNumberFormat === 'function')
  757. tdCss = defaults.mso.onMsoNumberFormat(cell, row, col);
  758. if (typeof tdCss !== 'undefined' && tdCss !== '')
  759. tdStyle = 'style="mso-number-format:\'' + tdCss + '\'';
  760. if (defaults.mso.styles.length) {
  761. cellStyles = document.defaultView.getComputedStyle(cell, null);
  762. rowStyles = null;
  763. for (let cssStyle in defaults.mso.styles) {
  764. const stylePropertyName = defaults.mso.styles[cssStyle];
  765. tdCss = getStyle(cellStyles, stylePropertyName);
  766. if (tdCss === '') {
  767. if (rowStyles === null)
  768. rowStyles = document.defaultView.getComputedStyle($row[0], null);
  769. tdCss = getStyle(rowStyles, stylePropertyName);
  770. }
  771. if (tdCss !== '' && tdCss !== '0px none rgb(0, 0, 0)' && tdCss !== 'rgba(0, 0, 0, 0)') {
  772. tdStyle += (tdStyle === '') ? 'style="' : ';';
  773. tdStyle += stylePropertyName + ':' + tdCss;
  774. }
  775. }
  776. }
  777. trData += '<td';
  778. if (tdStyle !== '')
  779. trData += ' ' + tdStyle + '"';
  780. const tdColspan = getColspan(cell);
  781. if (tdColspan > 0)
  782. trData += ' colspan="' + tdColspan + '"';
  783. const tdRowspan = getRowspan(cell);
  784. if (tdRowspan > 0)
  785. trData += ' rowspan="' + tdRowspan + '"';
  786. if (typeof tdValue === 'string' && tdValue !== '') {
  787. tdValue = preventInjection(tdValue);
  788. tdValue = tdValue.replace(/\n/g, '<br>');
  789. }
  790. trData += '>' + tdValue + '</td>';
  791. }
  792. });
  793. if (trData.length > 0)
  794. docData += '<tr>' + trData + '</tr>';
  795. rowIndex++;
  796. });
  797. if (defaults.displayTableName)
  798. docData += '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>' + defaults.tableName + '</p>')) + '</td></tr>';
  799. docData += '</tbody></table>';
  800. });
  801. //noinspection XmlUnusedNamespaceDeclaration
  802. let docFile = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' + MSDocSchema + ' xmlns="http://www.w3.org/TR/REC-html40">';
  803. docFile += '<head>';
  804. docFile += '<meta http-equiv="content-type" content="application/vnd.ms-' + MSDocType + '; charset=UTF-8">';
  805. if (MSDocType === 'excel') {
  806. docFile += '<!--[if gte mso 9]>';
  807. docFile += '<xml>';
  808. docFile += '<x:ExcelWorkbook>';
  809. docFile += '<x:ExcelWorksheets>';
  810. docFile += '<x:ExcelWorksheet>';
  811. docFile += '<x:Name>';
  812. docFile += docName;
  813. docFile += '</x:Name>';
  814. docFile += '<x:WorksheetOptions>';
  815. docFile += '<x:DisplayGridlines/>';
  816. if (defaults.mso.rtl)
  817. docFile += '<x:DisplayRightToLeft/>';
  818. docFile += '</x:WorksheetOptions>';
  819. docFile += '</x:ExcelWorksheet>';
  820. docFile += '</x:ExcelWorksheets>';
  821. docFile += '</x:ExcelWorkbook>';
  822. docFile += '</xml>';
  823. docFile += '<![endif]-->';
  824. }
  825. docFile += '<style>';
  826. docFile += '@page { size:' + defaults.mso.pageOrientation + '; mso-page-orientation:' + defaults.mso.pageOrientation + '; }';
  827. docFile += '@page Section1 {size:' + pageFormats[defaults.mso.pageFormat][0] + 'pt ' + pageFormats[defaults.mso.pageFormat][1] + 'pt';
  828. docFile += '; margin:1.0in 1.25in 1.0in 1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}';
  829. docFile += 'div.Section1 {page:Section1;}';
  830. docFile += '@page Section2 {size:' + pageFormats[defaults.mso.pageFormat][1] + 'pt ' + pageFormats[defaults.mso.pageFormat][0] + 'pt';
  831. 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;}';
  832. docFile += 'div.Section2 {page:Section2;}';
  833. docFile += 'br {mso-data-placement:same-cell;}';
  834. docFile += '</style>';
  835. docFile += '</head>';
  836. docFile += '<body>';
  837. docFile += '<div class="Section' + ((defaults.mso.pageOrientation === 'landscape') ? '2' : '1') + '">';
  838. docFile += docData;
  839. docFile += '</div>';
  840. docFile += '</body>';
  841. docFile += '</html>';
  842. if (defaults.outputMode === 'string')
  843. return docFile;
  844. if (defaults.outputMode === 'base64')
  845. return base64encode(docFile);
  846. saveToFile(docFile, defaults.fileName + '.' + MSDocExt, 'application/vnd.ms-' + MSDocType, '', 'base64', false);
  847. } else if (defaults.type === 'png') {
  848. html2canvas($(el)[0]).then(
  849. function (canvas) {
  850. const image = canvas.toDataURL();
  851. const byteString = atob(image.substring(22)); // remove data stuff
  852. const buffer = new ArrayBuffer(byteString.length);
  853. const intArray = new Uint8Array(buffer);
  854. for (let i = 0; i < byteString.length; i++)
  855. intArray[i] = byteString.charCodeAt(i);
  856. if (defaults.outputMode === 'string')
  857. return byteString;
  858. if (defaults.outputMode === 'base64')
  859. return base64encode(image);
  860. if (defaults.outputMode === 'window') {
  861. window.open(image);
  862. return;
  863. }
  864. saveToFile(buffer, defaults.fileName + '.png', 'image/png', '', '', false);
  865. });
  866. } else if (defaults.type === 'pdf') {
  867. if (defaults.pdfmake.enabled === true) {
  868. // pdf output using pdfmake
  869. // https://github.com/bpampuch/pdfmake
  870. const docDefinition = {
  871. content: []
  872. };
  873. $.extend(true, docDefinition, defaults.pdfmake.docDefinition);
  874. ranges = [];
  875. $(el).filter(function () {
  876. return isVisible($(this));
  877. }).each(function () {
  878. const $table = $(this);
  879. const widths = [];
  880. const body = [];
  881. rowIndex = 0;
  882. /**
  883. * @return {number}
  884. */
  885. const CollectPdfmakeData = function ($rows, colselector, length) {
  886. let rLength = 0;
  887. $($rows).each(function () {
  888. const r = [];
  889. ForEachVisibleCell(this, colselector, rowIndex, length,
  890. function (cell, row, col) {
  891. let cellContent;
  892. if (typeof cell !== 'undefined' && cell !== null) {
  893. const colspan = getColspan(cell);
  894. const rowspan = getRowspan(cell);
  895. cellContent = {text: parseString(cell, row, col) || ' '};
  896. if (colspan > 1 || rowspan > 1) {
  897. cellContent['colSpan'] = colspan || 1;
  898. cellContent['rowSpan'] = rowspan || 1;
  899. }
  900. } else
  901. cellContent = {text: ' '};
  902. if (colselector.indexOf('th') >= 0)
  903. cellContent['style'] = 'header';
  904. r.push(cellContent);
  905. });
  906. if (r.length)
  907. body.push(r);
  908. if (rLength < r.length)
  909. rLength = r.length;
  910. rowIndex++;
  911. });
  912. return rLength;
  913. };
  914. $head_rows = collectHeadRows($table);
  915. let colcount = CollectPdfmakeData($head_rows, 'th,td', $head_rows.length);
  916. for (let i = widths.length; i < colcount; i++)
  917. widths.push('*');
  918. // Data
  919. $rows = collectRows($table);
  920. colcount = CollectPdfmakeData($rows, 'td', $head_rows.length + $rows.length);
  921. for (let i = widths.length; i < colcount; i++)
  922. widths.push('*');
  923. docDefinition.content.push({ table: {
  924. headerRows: $head_rows.length ? $head_rows.length : null,
  925. widths: widths,
  926. body: body
  927. },
  928. layout: {
  929. layout: 'noBorders',
  930. hLineStyle: function (i, node) { return 0; },
  931. vLineWidth: function (i, node) { return 0; },
  932. hLineColor: function (i, node) { return i < node.table.headerRows ?
  933. defaults.pdfmake.docDefinition.styles.header.background :
  934. defaults.pdfmake.docDefinition.styles.alternateRow.fillColor; },
  935. vLineColor: function (i, node) { return i < node.table.headerRows ?
  936. defaults.pdfmake.docDefinition.styles.header.background :
  937. defaults.pdfmake.docDefinition.styles.alternateRow.fillColor; },
  938. fillColor: function (rowIndex, node, columnIndex) { return (rowIndex % 2 === 0) ?
  939. defaults.pdfmake.docDefinition.styles.alternateRow.fillColor :
  940. null; }
  941. },
  942. pageBreak: docDefinition.content.length ? "before" : undefined
  943. });
  944. }); // ...for each table
  945. if (typeof pdfMake !== 'undefined' && typeof pdfMake.createPdf !== 'undefined') {
  946. pdfMake.fonts = {
  947. Roboto: {
  948. normal: 'Roboto-Regular.ttf',
  949. bold: 'Roboto-Medium.ttf',
  950. italics: 'Roboto-Italic.ttf',
  951. bolditalics: 'Roboto-MediumItalic.ttf'
  952. }
  953. };
  954. // pdfmake >= 0.2.0 - replace pdfMake.vfs with pdfMake.virtualfs
  955. if (pdfMake.vfs.hasOwnProperty ('Mirza-Regular.ttf')) {
  956. docDefinition.defaultStyle.font = 'Mirza';
  957. $.extend(true, pdfMake.fonts, {Mirza: {normal: 'Mirza-Regular.ttf',
  958. bold: 'Mirza-Bold.ttf',
  959. italics: 'Mirza-Medium.ttf',
  960. bolditalics: 'Mirza-SemiBold.ttf'
  961. }});
  962. }
  963. else if (pdfMake.vfs.hasOwnProperty ('gbsn00lp.ttf')) {
  964. docDefinition.defaultStyle.font = 'gbsn00lp';
  965. $.extend(true, pdfMake.fonts, {gbsn00lp: {normal: 'gbsn00lp.ttf',
  966. bold: 'gbsn00lp.ttf',
  967. italics: 'gbsn00lp.ttf',
  968. bolditalics: 'gbsn00lp.ttf'
  969. }});
  970. }
  971. else if (pdfMake.vfs.hasOwnProperty ('ZCOOLXiaoWei-Regular.ttf')) {
  972. docDefinition.defaultStyle.font = 'ZCOOLXiaoWei';
  973. $.extend(true, pdfMake.fonts, {ZCOOLXiaoWei: {normal: 'ZCOOLXiaoWei-Regular.ttf',
  974. bold: 'ZCOOLXiaoWei-Regular.ttf',
  975. italics: 'ZCOOLXiaoWei-Regular.ttf',
  976. bolditalics: 'ZCOOLXiaoWei-Regular.ttf'
  977. }});
  978. }
  979. $.extend(true, pdfMake.fonts, defaults.pdfmake.fonts);
  980. // pdfmake <= 0.1.71
  981. pdfMake.createPdf(docDefinition).getBuffer(function (buffer) {
  982. saveToFile(buffer, defaults.fileName + '.pdf', 'application/pdf', '', '', false);
  983. });
  984. // pdfmake >= 0.2.0 - replace above code with:
  985. //pdfMake.createPdf(docDefinition).download(defaults.fileName);
  986. }
  987. } else if (defaults.jspdf.autotable === false) {
  988. // pdf output using jsPDF's core html support
  989. let doc = new jspdf.jsPDF({orientation: defaults.jspdf.orientation,
  990. unit: defaults.jspdf.unit,
  991. format: defaults.jspdf.format});
  992. doc.html(el[0], {
  993. callback: function () {
  994. jsPdfOutput(doc, false);
  995. },
  996. html2canvas: {scale: ((doc.internal.pageSize.width - defaults.jspdf.margins.left * 2) / el[0].scrollWidth)},
  997. x: defaults.jspdf.margins.left,
  998. y: defaults.jspdf.margins.top
  999. /*
  1000. margin: [
  1001. defaults.jspdf.margins.left,
  1002. defaults.jspdf.margins.top,
  1003. getPropertyUnitValue($(el).first().get(0), 'width', 'mm'),
  1004. getPropertyUnitValue($(el).first().get(0), 'height', 'mm')
  1005. ]
  1006. */
  1007. });
  1008. } else {
  1009. // pdf output using jsPDF AutoTable plugin
  1010. // https://github.com/simonbengtsson/jsPDF-AutoTable
  1011. let teOptions = defaults.jspdf.autotable.tableExport;
  1012. // When setting jspdf.format to 'bestfit' tableExport tries to choose
  1013. // the minimum required paper format and orientation in which the table
  1014. // (or tables in multitable mode) completely fits without column adjustment
  1015. if (typeof defaults.jspdf.format === 'string' && defaults.jspdf.format.toLowerCase() === 'bestfit') {
  1016. let rk = '', ro = '';
  1017. let mw = 0;
  1018. $(el).each(function () {
  1019. if (isVisible($(this))) {
  1020. const w = getPropertyUnitValue($(this).get(0), 'width', 'pt');
  1021. if (w > mw) {
  1022. if (w > pageFormats.a0[0]) {
  1023. rk = 'a0';
  1024. ro = 'l';
  1025. }
  1026. for (let key in pageFormats) {
  1027. if (pageFormats.hasOwnProperty(key)) {
  1028. if (pageFormats[key][1] > w) {
  1029. rk = key;
  1030. ro = 'l';
  1031. if (pageFormats[key][0] > w)
  1032. ro = 'p';
  1033. }
  1034. }
  1035. }
  1036. mw = w;
  1037. }
  1038. }
  1039. });
  1040. defaults.jspdf.format = (rk === '' ? 'a4' : rk);
  1041. defaults.jspdf.orientation = (ro === '' ? 'w' : ro);
  1042. }
  1043. // The jsPDF doc object is stored in defaults.jspdf.autotable.tableExport,
  1044. // thus it can be accessed from any callback function
  1045. if (teOptions.doc == null) {
  1046. teOptions.doc = new jspdf.jsPDF(defaults.jspdf.orientation,
  1047. defaults.jspdf.unit,
  1048. defaults.jspdf.format);
  1049. teOptions.wScaleFactor = 1;
  1050. teOptions.hScaleFactor = 1;
  1051. if (typeof defaults.jspdf.onDocCreated === 'function')
  1052. defaults.jspdf.onDocCreated(teOptions.doc);
  1053. }
  1054. jsPdfDefaultStyles.fontName = teOptions.doc.getFont().fontName;
  1055. if (teOptions.outputImages === true)
  1056. teOptions.images = {};
  1057. if (typeof teOptions.images !== 'undefined') {
  1058. $(el).filter(function () {
  1059. return isVisible($(this));
  1060. }).each(function () {
  1061. let rowCount = 0;
  1062. ranges = [];
  1063. if (defaults.exportHiddenCells === false) {
  1064. $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden');
  1065. checkCellVisibility = $hiddenTableElements.length > 0;
  1066. }
  1067. $head_rows = collectHeadRows($(this));
  1068. $rows = collectRows($(this));
  1069. $($rows).each(function () {
  1070. ForEachVisibleCell(this, 'td,th', $head_rows.length + rowCount, $head_rows.length + $rows.length,
  1071. function (cell) {
  1072. collectImages(cell, $(cell).children(), teOptions);
  1073. });
  1074. rowCount++;
  1075. });
  1076. });
  1077. $head_rows = [];
  1078. $rows = [];
  1079. }
  1080. loadImages(teOptions, function () {
  1081. $(el).filter(function () {
  1082. return isVisible($(this));
  1083. }).each(function () {
  1084. let colKey;
  1085. rowIndex = 0;
  1086. ranges = [];
  1087. if (defaults.exportHiddenCells === false) {
  1088. $hiddenTableElements = $(this).find('tr, th, td').filter(':hidden');
  1089. checkCellVisibility = $hiddenTableElements.length > 0;
  1090. }
  1091. colNames = GetColumnNames(this);
  1092. teOptions.columns = [];
  1093. teOptions.rows = [];
  1094. teOptions.teCells = {};
  1095. // onTable: optional callback function for every matching table that can be used
  1096. // to modify the tableExport options or to skip the output of a particular table
  1097. // if the table selector targets multiple tables
  1098. if (typeof teOptions.onTable === 'function')
  1099. if (teOptions.onTable($(this), defaults) === false)
  1100. return true; // continue to next iteration step (table)
  1101. // each table works with an own copy of AutoTable options
  1102. defaults.jspdf.autotable.tableExport = null; // avoid deep recursion error
  1103. const atOptions = $.extend(true, {}, defaults.jspdf.autotable);
  1104. defaults.jspdf.autotable.tableExport = teOptions;
  1105. atOptions.margin = {};
  1106. $.extend(true, atOptions.margin, defaults.jspdf.margins);
  1107. atOptions.tableExport = teOptions;
  1108. if (typeof atOptions.createdHeaderCell !== 'function') {
  1109. // apply some original css styles to pdf header cells
  1110. atOptions.createdHeaderCell = function (cell, data) {
  1111. if (typeof teOptions.columns [data.column.dataKey] !== 'undefined') {
  1112. const col = teOptions.columns [data.column.dataKey];
  1113. if (typeof col.rect !== 'undefined') {
  1114. let rh;
  1115. cell.contentWidth = col.rect.width;
  1116. if (typeof teOptions.heightRatio === 'undefined' || teOptions.heightRatio === 0) {
  1117. if (data.row.raw [data.column.dataKey].rowspan)
  1118. rh = data.row.raw [data.column.dataKey].rect.height / data.row.raw [data.column.dataKey].rowspan;
  1119. else
  1120. rh = data.row.raw [data.column.dataKey].rect.height;
  1121. teOptions.heightRatio = cell.styles.rowHeight / rh;
  1122. }
  1123. rh = data.row.raw [data.column.dataKey].rect.height * teOptions.heightRatio;
  1124. if (rh > cell.styles.rowHeight)
  1125. cell.styles.rowHeight = rh;
  1126. }
  1127. cell.styles.halign = (atOptions.headerStyles.halign === 'inherit') ? 'center' : atOptions.headerStyles.halign;
  1128. cell.styles.valign = atOptions.headerStyles.valign;
  1129. if (typeof col.style !== 'undefined' && col.style.hidden !== true) {
  1130. if (atOptions.headerStyles.halign === 'inherit')
  1131. cell.styles.halign = col.style.align;
  1132. if (atOptions.styles.fillColor === 'inherit')
  1133. cell.styles.fillColor = col.style.bcolor;
  1134. if (atOptions.styles.textColor === 'inherit')
  1135. cell.styles.textColor = col.style.color;
  1136. if (atOptions.styles.fontStyle === 'inherit')
  1137. cell.styles.fontStyle = col.style.fstyle;
  1138. }
  1139. }
  1140. };
  1141. }
  1142. if (typeof atOptions.createdCell !== 'function') {
  1143. // apply some original css styles to pdf table cells
  1144. atOptions.createdCell = function (cell, data) {
  1145. const tecell = teOptions.teCells [data.row.index + ':' + data.column.dataKey];
  1146. cell.styles.halign = (atOptions.styles.halign === 'inherit') ? 'center' : atOptions.styles.halign;
  1147. cell.styles.valign = atOptions.styles.valign;
  1148. if (typeof tecell !== 'undefined' && typeof tecell.style !== 'undefined' && tecell.style.hidden !== true) {
  1149. if (atOptions.styles.halign === 'inherit')
  1150. cell.styles.halign = tecell.style.align;
  1151. if (atOptions.styles.fillColor === 'inherit')
  1152. cell.styles.fillColor = tecell.style.bcolor;
  1153. if (atOptions.styles.textColor === 'inherit')
  1154. cell.styles.textColor = tecell.style.color;
  1155. if (atOptions.styles.fontStyle === 'inherit')
  1156. cell.styles.fontStyle = tecell.style.fstyle;
  1157. }
  1158. };
  1159. }
  1160. if (typeof atOptions.drawHeaderCell !== 'function') {
  1161. atOptions.drawHeaderCell = function (cell, data) {
  1162. const colopt = teOptions.columns [data.column.dataKey];
  1163. if ((colopt.style.hasOwnProperty('hidden') !== true || colopt.style.hidden !== true) &&
  1164. colopt.rowIndex >= 0)
  1165. return prepareAutoTableText(cell, data, colopt);
  1166. else
  1167. return false; // cell is hidden
  1168. };
  1169. }
  1170. if (typeof atOptions.drawCell !== 'function') {
  1171. atOptions.drawCell = function (cell, data) {
  1172. const teCell = teOptions.teCells [data.row.index + ':' + data.column.dataKey];
  1173. const draw2canvas = (typeof teCell !== 'undefined' && teCell.isCanvas);
  1174. if (draw2canvas !== true) {
  1175. if (prepareAutoTableText(cell, data, teCell)) {
  1176. teOptions.doc.rect(cell.x, cell.y, cell.width, cell.height, cell.styles.fillStyle);
  1177. if (typeof teCell !== 'undefined' &&
  1178. (typeof teCell.hasUserDefText === 'undefined' || teCell.hasUserDefText !== true) &&
  1179. typeof teCell.elements !== 'undefined' && teCell.elements.length) {
  1180. const hScale = cell.height / teCell.rect.height;
  1181. if (hScale > teOptions.hScaleFactor)
  1182. teOptions.hScaleFactor = hScale;
  1183. teOptions.wScaleFactor = cell.width / teCell.rect.width;
  1184. const ySave = cell.textPos.y;
  1185. drawAutotableElements(cell, teCell.elements, teOptions);
  1186. cell.textPos.y = ySave;
  1187. drawAutotableText(cell, teCell.elements, teOptions);
  1188. } else
  1189. drawAutotableText(cell, {}, teOptions);
  1190. }
  1191. } else {
  1192. const container = teCell.elements[0];
  1193. const imgId = $(container).attr('data-tableexport-canvas');
  1194. const r = container.getBoundingClientRect();
  1195. cell.width = r.width * teOptions.wScaleFactor;
  1196. cell.height = r.height * teOptions.hScaleFactor;
  1197. data.row.height = cell.height;
  1198. jsPdfDrawImage(cell, container, imgId, teOptions);
  1199. }
  1200. return false;
  1201. };
  1202. }
  1203. // collect header and data rows
  1204. teOptions.headerrows = [];
  1205. $head_rows = collectHeadRows($(this));
  1206. $($head_rows).each(function () {
  1207. colKey = 0;
  1208. teOptions.headerrows[rowIndex] = [];
  1209. ForEachVisibleCell(this, 'th,td', rowIndex, $head_rows.length,
  1210. function (cell, row, col) {
  1211. const obj = getCellStyles(cell);
  1212. obj.title = parseString(cell, row, col);
  1213. obj.key = colKey++;
  1214. obj.rowIndex = rowIndex;
  1215. teOptions.headerrows[rowIndex].push(obj);
  1216. });
  1217. rowIndex++;
  1218. });
  1219. if (rowIndex > 0) {
  1220. // iterate through last row
  1221. let lastrow = rowIndex - 1;
  1222. while (lastrow >= 0) {
  1223. $.each(teOptions.headerrows[lastrow], function () {
  1224. let obj = this;
  1225. if (lastrow > 0 && this.rect === null)
  1226. obj = teOptions.headerrows[lastrow - 1][this.key];
  1227. if (obj !== null && obj.rowIndex >= 0 &&
  1228. (obj.style.hasOwnProperty('hidden') !== true || obj.style.hidden !== true))
  1229. teOptions.columns.push(obj);
  1230. });
  1231. lastrow = (teOptions.columns.length > 0) ? -1 : lastrow - 1;
  1232. }
  1233. }
  1234. let rowCount = 0;
  1235. $rows = [];
  1236. $rows = collectRows($(this));
  1237. $($rows).each(function () {
  1238. const rowData = [];
  1239. colKey = 0;
  1240. ForEachVisibleCell(this, 'td,th', rowIndex, $head_rows.length + $rows.length,
  1241. function (cell, row, col) {
  1242. let obj;
  1243. if (typeof teOptions.columns[colKey] === 'undefined') {
  1244. // jsPDF-Autotable needs columns. Thus define hidden ones for tables without thead
  1245. obj = {
  1246. title: '',
  1247. key: colKey,
  1248. style: {
  1249. hidden: true
  1250. }
  1251. };
  1252. teOptions.columns.push(obj);
  1253. }
  1254. rowData.push(parseString(cell, row, col));
  1255. if (typeof cell !== 'undefined' && cell !== null) {
  1256. obj = getCellStyles(cell);
  1257. obj.isCanvas = cell.hasAttribute('data-tableexport-canvas');
  1258. obj.elements = obj.isCanvas ? $(cell) : $(cell).children();
  1259. if(typeof $(cell).data('teUserDefText') !== 'undefined')
  1260. obj.hasUserDefText = true;
  1261. teOptions.teCells [rowCount + ':' + colKey++] = obj;
  1262. } else {
  1263. obj = $.extend(true, {}, teOptions.teCells [rowCount + ':' + (colKey - 1)]);
  1264. obj.colspan = -1;
  1265. teOptions.teCells [rowCount + ':' + colKey++] = obj;
  1266. }
  1267. });
  1268. if (rowData.length) {
  1269. teOptions.rows.push(rowData);
  1270. rowCount++;
  1271. }
  1272. rowIndex++;
  1273. });
  1274. // onBeforeAutotable: optional callback function before calling
  1275. // jsPDF AutoTable that can be used to modify the AutoTable options
  1276. if (typeof teOptions.onBeforeAutotable === 'function')
  1277. teOptions.onBeforeAutotable($(this), teOptions.columns, teOptions.rows, atOptions);
  1278. jsPdfAutoTable(atOptions.tableExport.doc, teOptions.columns, teOptions.rows, atOptions);
  1279. // onAfterAutotable: optional callback function after returning
  1280. // from jsPDF AutoTable that can be used to modify the AutoTable options
  1281. if (typeof teOptions.onAfterAutotable === 'function')
  1282. teOptions.onAfterAutotable($(this), atOptions);
  1283. // set the start position for the next table (in case there is one)
  1284. defaults.jspdf.autotable.startY = jsPdfAutoTableEndPosY() + atOptions.margin.top;
  1285. });
  1286. jsPdfOutput(teOptions.doc, (typeof teOptions.images !== 'undefined' && jQuery.isEmptyObject(teOptions.images) === false));
  1287. if (typeof teOptions.headerrows !== 'undefined')
  1288. teOptions.headerrows.length = 0;
  1289. if (typeof teOptions.columns !== 'undefined')
  1290. teOptions.columns.length = 0;
  1291. if (typeof teOptions.rows !== 'undefined')
  1292. teOptions.rows.length = 0;
  1293. delete teOptions.doc;
  1294. teOptions.doc = null;
  1295. });
  1296. }
  1297. }
  1298. function collectHeadRows ($table) {
  1299. const result = [];
  1300. findTableElements($table, 'thead').each(function () {
  1301. result.push.apply(result, findTableElements($(this), defaults.theadSelector).toArray());
  1302. });
  1303. return result;
  1304. }
  1305. function collectRows ($table) {
  1306. const result = [];
  1307. findTableElements($table, 'tbody').each(function () {
  1308. result.push.apply(result, findTableElements($(this), defaults.tbodySelector).toArray());
  1309. });
  1310. if (defaults.tfootSelector.length) {
  1311. findTableElements($table, 'tfoot').each(function () {
  1312. result.push.apply(result, findTableElements($(this), defaults.tfootSelector).toArray());
  1313. });
  1314. }
  1315. return result;
  1316. }
  1317. function findTableElements ($parent, selector) {
  1318. const parentSelector = $parent[0].tagName;
  1319. const parentLevel = $parent.parents(parentSelector).length;
  1320. return $parent.find(selector).filter(function () {
  1321. return parentLevel === $(this).closest(parentSelector).parents(parentSelector).length;
  1322. });
  1323. }
  1324. function GetColumnNames (table) {
  1325. const result = [];
  1326. let maxCols = 0;
  1327. let row = 0;
  1328. let col = 0;
  1329. $(table).find('thead').first().find('th').each(function (index, el) {
  1330. const hasDataField = $(el).attr('data-field') !== undefined;
  1331. if (typeof el.parentNode.rowIndex !== 'undefined' && row !== el.parentNode.rowIndex) {
  1332. row = el.parentNode.rowIndex;
  1333. col = 0;
  1334. maxCols = 0;
  1335. }
  1336. const colSpan = getColspan(el);
  1337. maxCols += (colSpan ? colSpan : 1);
  1338. while (col < maxCols) {
  1339. result[col] = (hasDataField ? $(el).attr('data-field') : col.toString());
  1340. col++;
  1341. }
  1342. });
  1343. return result;
  1344. }
  1345. function isVisible ($element) {
  1346. let isRow = typeof $element[0].rowIndex !== 'undefined';
  1347. const isCell = isRow === false && typeof $element[0].cellIndex !== 'undefined';
  1348. const isElementVisible = (isCell || isRow) ? isTableElementVisible($element) : $element.is(':visible');
  1349. let tableexportDisplay = $element.attr('data-tableexport-display');
  1350. if (isCell && tableexportDisplay !== 'none' && tableexportDisplay !== 'always') {
  1351. $element = $($element[0].parentNode);
  1352. isRow = typeof $element[0].rowIndex !== 'undefined';
  1353. tableexportDisplay = $element.attr('data-tableexport-display');
  1354. }
  1355. if (isRow && tableexportDisplay !== 'none' && tableexportDisplay !== 'always') {
  1356. tableexportDisplay = $element.closest('table').attr('data-tableexport-display');
  1357. }
  1358. return tableexportDisplay !== 'none' && (isElementVisible === true || tableexportDisplay === 'always');
  1359. }
  1360. function isTableElementVisible ($element) {
  1361. let hiddenEls = [];
  1362. if (checkCellVisibility) {
  1363. hiddenEls = $hiddenTableElements.filter(function () {
  1364. let found = false;
  1365. if (this.nodeType === $element[0].nodeType) {
  1366. if (typeof this.rowIndex !== 'undefined' && this.rowIndex === $element[0].rowIndex)
  1367. found = true;
  1368. else if (typeof this.cellIndex !== 'undefined' && this.cellIndex === $element[0].cellIndex &&
  1369. typeof this.parentNode.rowIndex !== 'undefined' &&
  1370. typeof $element[0].parentNode.rowIndex !== 'undefined' &&
  1371. this.parentNode.rowIndex === $element[0].parentNode.rowIndex)
  1372. found = true;
  1373. }
  1374. return found;
  1375. });
  1376. }
  1377. return (checkCellVisibility === false || hiddenEls.length === 0);
  1378. }
  1379. function isColumnIgnored ($cell, rowLength, colIndex) {
  1380. let result = false;
  1381. if (isVisible($cell)) {
  1382. if (defaults.ignoreColumn.length > 0) {
  1383. if ($.inArray(colIndex, defaults.ignoreColumn) !== -1 ||
  1384. $.inArray(colIndex - rowLength, defaults.ignoreColumn) !== -1 ||
  1385. (colNames.length > colIndex && typeof colNames[colIndex] !== 'undefined' &&
  1386. $.inArray(colNames[colIndex], defaults.ignoreColumn) !== -1))
  1387. result = true;
  1388. }
  1389. } else
  1390. result = true;
  1391. return result;
  1392. }
  1393. function ForEachVisibleCell (tableRow, selector, rowIndex, rowCount, cellcallback) {
  1394. if (typeof (cellcallback) === 'function') {
  1395. let ignoreRow = false;
  1396. if (typeof defaults.onIgnoreRow === 'function')
  1397. ignoreRow = defaults.onIgnoreRow($(tableRow), rowIndex);
  1398. if (ignoreRow === false &&
  1399. (defaults.ignoreRow.length === 0 ||
  1400. ($.inArray(rowIndex, defaults.ignoreRow) === -1 &&
  1401. $.inArray(rowIndex - rowCount, defaults.ignoreRow) === -1)) &&
  1402. isVisible($(tableRow))) {
  1403. const $cells = findTableElements($(tableRow), selector);
  1404. let cellsCount = $cells.length;
  1405. let colCount = 0;
  1406. let colIndex = 0;
  1407. $cells.each(function () {
  1408. const $cell = $(this);
  1409. let colspan = getColspan(this);
  1410. let rowspan = getRowspan(this);
  1411. let c;
  1412. // Skip ranges
  1413. $.each(ranges, function () {
  1414. const range = this;
  1415. if (rowIndex > range.s.r && rowIndex <= range.e.r && colCount >= range.s.c && colCount <= range.e.c) {
  1416. for (c = 0; c <= range.e.c - range.s.c; ++c) {
  1417. cellsCount++;
  1418. colIndex++;
  1419. cellcallback(null, rowIndex, colCount++);
  1420. }
  1421. }
  1422. });
  1423. // Handle span's
  1424. if (rowspan || colspan) {
  1425. rowspan = rowspan || 1;
  1426. colspan = colspan || 1;
  1427. ranges.push({
  1428. s: {r: rowIndex, c: colCount},
  1429. e: {r: rowIndex + rowspan - 1, c: colCount + colspan - 1}
  1430. });
  1431. }
  1432. if (isColumnIgnored($cell, cellsCount, colIndex++) === false) {
  1433. // Handle value
  1434. cellcallback(this, rowIndex, colCount++);
  1435. }
  1436. // Handle colspan
  1437. if (colspan > 1) {
  1438. for (c = 0; c < colspan - 1; ++c) {
  1439. colIndex++;
  1440. cellcallback(null, rowIndex, colCount++);
  1441. }
  1442. }
  1443. });
  1444. // Skip ranges
  1445. $.each(ranges, function () {
  1446. const range = this;
  1447. if (rowIndex >= range.s.r && rowIndex <= range.e.r && colCount >= range.s.c && colCount <= range.e.c) {
  1448. for (let c = 0; c <= range.e.c - range.s.c; ++c) {
  1449. cellcallback(null, rowIndex, colCount++);
  1450. }
  1451. }
  1452. });
  1453. }
  1454. }
  1455. }
  1456. function jsPdfDrawImage (cell, container, imgId, teOptions) {
  1457. if (typeof teOptions.images !== 'undefined') {
  1458. const image = teOptions.images[imgId];
  1459. if (typeof image !== 'undefined') {
  1460. const r = container.getBoundingClientRect();
  1461. const arCell = cell.width / cell.height;
  1462. const arImg = r.width / r.height;
  1463. let imgWidth = cell.width;
  1464. let imgHeight = cell.height;
  1465. const px2pt = 0.264583 * 72 / 25.4;
  1466. let uy = 0;
  1467. if (arImg <= arCell) {
  1468. imgHeight = Math.min(cell.height, r.height);
  1469. imgWidth = r.width * imgHeight / r.height;
  1470. } else if (arImg > arCell) {
  1471. imgWidth = Math.min(cell.width, r.width);
  1472. imgHeight = r.height * imgWidth / r.width;
  1473. }
  1474. imgWidth *= px2pt;
  1475. imgHeight *= px2pt;
  1476. if (imgHeight < cell.height)
  1477. uy = (cell.height - imgHeight) / 2;
  1478. try {
  1479. teOptions.doc.addImage(image.src, cell.textPos.x, cell.y + uy, imgWidth, imgHeight);
  1480. } catch (e) {
  1481. // TODO: IE -> convert png to jpeg
  1482. }
  1483. cell.textPos.x += imgWidth;
  1484. }
  1485. }
  1486. }
  1487. function jsPdfOutput (doc, hasimages) {
  1488. if (defaults.outputMode === 'string')
  1489. return doc.output();
  1490. if (defaults.outputMode === 'base64')
  1491. return base64encode(doc.output());
  1492. if (defaults.outputMode === 'window') {
  1493. window.URL = window.URL || window.webkitURL;
  1494. window.open(window.URL.createObjectURL(doc.output('blob')));
  1495. return;
  1496. }
  1497. const fileName = defaults.fileName + '.pdf';
  1498. try {
  1499. const blob = doc.output('blob')
  1500. saveAs(blob, fileName);
  1501. if (typeof defaults.onAfterSaveToFile === 'function')
  1502. defaults.onAfterSaveToFile(blob, fileName);
  1503. } catch (e) {
  1504. downloadFile(fileName,
  1505. 'data:application/pdf' + (hasimages ? '' : ';base64') + ',',
  1506. hasimages ? doc.output('blob') : doc.output());
  1507. }
  1508. }
  1509. function prepareAutoTableText (cell, data, cellopt) {
  1510. let cs = 0
  1511. if (typeof cellopt !== 'undefined')
  1512. cs = cellopt.colspan;
  1513. if (cs >= 0) {
  1514. // colspan handling
  1515. let cellWidth = cell.width
  1516. let textPosX = cell.textPos.x
  1517. const i = data.table.columns.indexOf(data.column)
  1518. for (let c = 1; c < cs; c++) {
  1519. const column = data.table.columns[i + c]
  1520. cellWidth += column.width;
  1521. }
  1522. if (cs > 1) {
  1523. if (cell.styles.halign === 'right')
  1524. textPosX = cell.textPos.x + cellWidth - cell.width;
  1525. else if (cell.styles.halign === 'center')
  1526. textPosX = cell.textPos.x + (cellWidth - cell.width) / 2;
  1527. }
  1528. cell.width = cellWidth;
  1529. cell.textPos.x = textPosX;
  1530. if (typeof cellopt !== 'undefined' && cellopt.rowspan > 1)
  1531. cell.height = cell.height * cellopt.rowspan;
  1532. // fix jsPDF's calculation of text position
  1533. if (cell.styles.valign === 'middle' || cell.styles.valign === 'bottom') {
  1534. const splittedText = typeof cell.text === 'string' ? cell.text.split(/\r\n|\r|\n/g) : cell.text;
  1535. const lineCount = splittedText.length || 1;
  1536. if (lineCount > 2)
  1537. cell.textPos.y -= ((2 - FONT_ROW_RATIO) / 2 * data.row.styles.fontSize) * (lineCount - 2) / 3;
  1538. }
  1539. return true;
  1540. } else
  1541. return false; // cell is hidden (colspan = -1), don't draw it
  1542. }
  1543. function collectImages (cell, elements, teOptions) {
  1544. if (typeof cell !== 'undefined' && cell !== null) {
  1545. if (cell.hasAttribute('data-tableexport-canvas')) {
  1546. const imgId = new Date().getTime();
  1547. $(cell).attr('data-tableexport-canvas', imgId);
  1548. teOptions.images[imgId] = {
  1549. url: '[data-tableexport-canvas="' + imgId + '"]',
  1550. src: null
  1551. };
  1552. } else if (elements !== 'undefined' && elements != null) {
  1553. elements.each(function () {
  1554. if ($(this).is('img')) {
  1555. const imgId = strHashCode(this.src);
  1556. teOptions.images[imgId] = {
  1557. url: this.src,
  1558. src: this.src
  1559. };
  1560. }
  1561. collectImages(cell, $(this).children(), teOptions);
  1562. });
  1563. }
  1564. }
  1565. }
  1566. function loadImages (teOptions, callback) {
  1567. let imageCount = 0;
  1568. let pendingCount = 0;
  1569. function done () {
  1570. callback(imageCount);
  1571. }
  1572. function loadImage (image) {
  1573. if (image.url) {
  1574. if (!image.src) {
  1575. const $imgContainer = $(image.url);
  1576. if ($imgContainer.length) {
  1577. imageCount = ++pendingCount;
  1578. html2canvas($imgContainer[0]).then(function (canvas) {
  1579. image.src = canvas.toDataURL('image/png');
  1580. if (!--pendingCount)
  1581. done();
  1582. });
  1583. }
  1584. } else {
  1585. const img = new Image();
  1586. imageCount = ++pendingCount;
  1587. img.crossOrigin = 'Anonymous';
  1588. img.onerror = img.onload = function () {
  1589. if (img.complete) {
  1590. if (img.src.indexOf('data:image/') === 0) {
  1591. img.width = image.width || img.width || 0;
  1592. img.height = image.height || img.height || 0;
  1593. }
  1594. if (img.width + img.height) {
  1595. const canvas = document.createElement('canvas');
  1596. const ctx = canvas.getContext('2d');
  1597. canvas.width = img.width;
  1598. canvas.height = img.height;
  1599. ctx.drawImage(img, 0, 0);
  1600. image.src = canvas.toDataURL('image/png');
  1601. }
  1602. }
  1603. if (!--pendingCount)
  1604. done();
  1605. };
  1606. img.src = image.url;
  1607. }
  1608. }
  1609. }
  1610. if (typeof teOptions.images !== 'undefined') {
  1611. for (let i in teOptions.images)
  1612. if (teOptions.images.hasOwnProperty(i))
  1613. loadImage(teOptions.images[i]);
  1614. }
  1615. return pendingCount || done();
  1616. }
  1617. function drawAutotableElements (cell, elements, teOptions) {
  1618. elements.each(function () {
  1619. if ($(this).is('div')) {
  1620. const bColor = rgb2array(getStyle(this, 'background-color'), [255, 255, 255]);
  1621. const lColor = rgb2array(getStyle(this, 'border-top-color'), [0, 0, 0]);
  1622. const lWidth = getPropertyUnitValue(this, 'border-top-width', defaults.jspdf.unit);
  1623. const r = this.getBoundingClientRect();
  1624. const ux = this.offsetLeft * teOptions.wScaleFactor;
  1625. const uy = this.offsetTop * teOptions.hScaleFactor;
  1626. const uw = r.width * teOptions.wScaleFactor;
  1627. const uh = r.height * teOptions.hScaleFactor;
  1628. teOptions.doc.setDrawColor.apply(undefined, lColor);
  1629. teOptions.doc.setFillColor.apply(undefined, bColor);
  1630. teOptions.doc.setLineWidth(lWidth);
  1631. teOptions.doc.rect(cell.x + ux, cell.y + uy, uw, uh, lWidth ? 'FD' : 'F');
  1632. } else if ($(this).is('img')) {
  1633. const imgId = strHashCode(this.src);
  1634. jsPdfDrawImage(cell, this, imgId, teOptions);
  1635. }
  1636. drawAutotableElements(cell, $(this).children(), teOptions);
  1637. });
  1638. }
  1639. function drawAutotableText (cell, texttags, teOptions) {
  1640. if (typeof teOptions.onAutotableText === 'function') {
  1641. teOptions.onAutotableText(teOptions.doc, cell, texttags);
  1642. } else {
  1643. let x = cell.textPos.x;
  1644. let y = cell.textPos.y;
  1645. const style = {halign: cell.styles.halign, valign: cell.styles.valign};
  1646. if (texttags.length) {
  1647. let tag = texttags[0];
  1648. while (tag.previousSibling)
  1649. tag = tag.previousSibling;
  1650. let b = false, i = false;
  1651. while (tag) {
  1652. let txt = tag.innerText || tag.textContent || '';
  1653. const leadingSpace = (txt.length && txt[0] === ' ') ? ' ' : '';
  1654. const trailingSpace = (txt.length > 1 && txt[txt.length - 1] === ' ') ? ' ' : '';
  1655. if (defaults.preserve.leadingWS !== true)
  1656. txt = leadingSpace + trimLeft(txt);
  1657. if (defaults.preserve.trailingWS !== true)
  1658. txt = trimRight(txt) + trailingSpace;
  1659. if ($(tag).is('br')) {
  1660. x = cell.textPos.x;
  1661. y += teOptions.doc.internal.getFontSize();
  1662. }
  1663. if ($(tag).is('b'))
  1664. b = true;
  1665. else if ($(tag).is('i'))
  1666. i = true;
  1667. if (b || i)
  1668. teOptions.doc.setFont('undefined ', (b && i) ? 'bolditalic' : b ? 'bold' : 'italic');
  1669. let w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1670. if (w) {
  1671. if (cell.styles.overflow === 'linebreak' &&
  1672. x > cell.textPos.x && (x + w) > (cell.textPos.x + cell.width)) {
  1673. const chars = '.,!%*;:=-';
  1674. if (chars.indexOf(txt.charAt(0)) >= 0) {
  1675. const s = txt.charAt(0);
  1676. w = teOptions.doc.getStringUnitWidth(s) * teOptions.doc.internal.getFontSize();
  1677. if ((x + w) <= (cell.textPos.x + cell.width)) {
  1678. jsPdfAutoTableText(s, x, y, style);
  1679. txt = txt.substring(1, txt.length);
  1680. }
  1681. w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1682. }
  1683. x = cell.textPos.x;
  1684. y += teOptions.doc.internal.getFontSize();
  1685. }
  1686. if (cell.styles.overflow !== 'visible') {
  1687. while (txt.length && (x + w) > (cell.textPos.x + cell.width)) {
  1688. txt = txt.substring(0, txt.length - 1);
  1689. w = teOptions.doc.getStringUnitWidth(txt) * teOptions.doc.internal.getFontSize();
  1690. }
  1691. }
  1692. jsPdfAutoTableText(txt, x, y, style);
  1693. x += w;
  1694. }
  1695. if (b || i) {
  1696. if ($(tag).is('b'))
  1697. b = false;
  1698. else if ($(tag).is('i'))
  1699. i = false;
  1700. teOptions.doc.setFont('undefined ', (!b && !i) ? 'normal' : b ? 'bold' : 'italic');
  1701. }
  1702. tag = tag.nextSibling;
  1703. }
  1704. cell.textPos.x = x;
  1705. cell.textPos.y = y;
  1706. } else {
  1707. jsPdfAutoTableText(cell.text, cell.textPos.x, cell.textPos.y, style);
  1708. }
  1709. }
  1710. }
  1711. function escapeRegExp (string) {
  1712. return string == null ? '' : string.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
  1713. }
  1714. function replaceAll (string, find, replace) {
  1715. return string == null ? '' : string.toString().replace(new RegExp(escapeRegExp(find), 'g'), replace);
  1716. }
  1717. function trimLeft (string) {
  1718. return string == null ? '' : string.toString().replace(/^\s+/, '');
  1719. }
  1720. function trimRight (string) {
  1721. return string == null ? '' : string.toString().replace(/\s+$/, '');
  1722. }
  1723. function parseDateUTC (s) {
  1724. if (defaults.date.html.length === 0)
  1725. return false;
  1726. defaults.date.pattern.lastIndex = 0;
  1727. const match = defaults.date.pattern.exec(s);
  1728. if (match == null)
  1729. return false;
  1730. const y = +match[defaults.date.match_y];
  1731. if (y < 0 || y > 8099) return false;
  1732. const m = match[defaults.date.match_m] * 1;
  1733. const d = match[defaults.date.match_d] * 1;
  1734. if (!isFinite(d)) return false;
  1735. const o = new Date(y, m - 1, d, 0, 0, 0);
  1736. if (o.getFullYear() === y && o.getMonth() === (m - 1) && o.getDate() === d)
  1737. return new Date(Date.UTC(y, m - 1, d, 0, 0, 0));
  1738. else
  1739. return false;
  1740. }
  1741. function parseNumber (value) {
  1742. value = value || '0';
  1743. if ('' !== defaults.numbers.html.thousandsSeparator)
  1744. value = replaceAll(value, defaults.numbers.html.thousandsSeparator, '');
  1745. if ('.' !== defaults.numbers.html.decimalMark)
  1746. value = replaceAll(value, defaults.numbers.html.decimalMark, '.');
  1747. return typeof value === 'number' || jQuery.isNumeric(value) !== false ? value : false;
  1748. }
  1749. function parsePercent (value) {
  1750. if (value.indexOf('%') > -1) {
  1751. value = parseNumber(value.replace(/%/g, ''));
  1752. if (value !== false)
  1753. value = value / 100;
  1754. } else
  1755. value = false;
  1756. return value;
  1757. }
  1758. function parseString (cell, rowIndex, colIndex, cellInfo) {
  1759. let result = '';
  1760. let cellType = 'text';
  1761. if (cell !== null) {
  1762. const $cell = $(cell);
  1763. let htmlData;
  1764. $cell.removeData('teUserDefText');
  1765. if ($cell[0].hasAttribute('data-tableexport-canvas')) {
  1766. htmlData = '';
  1767. } else if ($cell[0].hasAttribute('data-tableexport-value')) {
  1768. htmlData = $cell.attr('data-tableexport-value');
  1769. htmlData = htmlData ? htmlData + '' : '';
  1770. $cell.data('teUserDefText', 1);
  1771. } else {
  1772. htmlData = $cell.html();
  1773. if (typeof defaults.onCellHtmlData === 'function') {
  1774. htmlData = defaults.onCellHtmlData($cell, rowIndex, colIndex, htmlData);
  1775. $cell.data('teUserDefText', 1);
  1776. }
  1777. else if (htmlData !== '') {
  1778. const html = $.parseHTML('<div>' + htmlData + '</div>', null, false);
  1779. let inputIndex = 0;
  1780. let selectIndex = 0;
  1781. htmlData = '';
  1782. $.each(html, function () {
  1783. if ($(this).is('input')) {
  1784. htmlData += $cell.find('input').eq(inputIndex++).val();
  1785. }
  1786. else if ($(this).is('select')) {
  1787. htmlData += $cell.find('select option:selected').eq(selectIndex++).text();
  1788. }
  1789. else if ($(this).is('br')) {
  1790. htmlData += '<br>';
  1791. }
  1792. else {
  1793. if (typeof $(this).html() === 'undefined')
  1794. htmlData += $(this).text();
  1795. else if (jQuery().bootstrapTable === undefined ||
  1796. ($(this).hasClass('fht-cell') === false && // BT 4
  1797. $(this).hasClass('filterControl') === false &&
  1798. $cell.parents('.detail-view').length === 0))
  1799. htmlData += $(this).html();
  1800. if ($(this).is('a')) {
  1801. const href = $cell.find('a').attr('href') || '';
  1802. if (typeof defaults.onCellHtmlHyperlink === 'function') {
  1803. result += defaults.onCellHtmlHyperlink($cell, rowIndex, colIndex, href, htmlData);
  1804. }
  1805. else if (defaults.htmlHyperlink === 'href') {
  1806. result += href;
  1807. }
  1808. else { // 'content'
  1809. result += htmlData;
  1810. }
  1811. htmlData = '';
  1812. }
  1813. }
  1814. });
  1815. }
  1816. }
  1817. if (htmlData && htmlData !== '' && defaults.htmlContent === true) {
  1818. result = $.trim(htmlData);
  1819. } else if (htmlData && htmlData !== '') {
  1820. const cellFormat = $cell.attr('data-tableexport-cellformat');
  1821. if (cellFormat !== '') {
  1822. let text = htmlData.replace(/\n/g, '\u2028').replace(/(<\s*br([^>]*)>)/gi, '\u2060');
  1823. const obj = $('<div/>').html(text).contents();
  1824. let number = false;
  1825. text = '';
  1826. $.each(obj.text().split('\u2028'), function (i, v) {
  1827. if (i > 0)
  1828. text += ' ';
  1829. if (defaults.preserve.leadingWS !== true)
  1830. v = trimLeft(v);
  1831. text += (defaults.preserve.trailingWS !== true) ? trimRight(v) : v;
  1832. });
  1833. $.each(text.split('\u2060'), function (i, v) {
  1834. if (i > 0)
  1835. result += '\n';
  1836. if (defaults.preserve.leadingWS !== true)
  1837. v = trimLeft(v);
  1838. if (defaults.preserve.trailingWS !== true)
  1839. v = trimRight(v);
  1840. result += v.replace(/\u00AD/g, ''); // remove soft hyphens
  1841. });
  1842. result = result.replace(/\u00A0/g, ' '); // replace nbsp's with spaces
  1843. if (defaults.type === 'json' ||
  1844. (defaults.type === 'excel' && defaults.mso.fileFormat === 'xmlss') ||
  1845. defaults.numbers.output === false) {
  1846. number = parseNumber(result);
  1847. if (number !== false) {
  1848. cellType = 'number';
  1849. result = Number(number);
  1850. }
  1851. } else if (defaults.numbers.html.decimalMark !== defaults.numbers.output.decimalMark ||
  1852. defaults.numbers.html.thousandsSeparator !== defaults.numbers.output.thousandsSeparator) {
  1853. number = parseNumber(result);
  1854. if (number !== false) {
  1855. const frac = ('' + number.substr(number < 0 ? 1 : 0)).split('.');
  1856. if (frac.length === 1)
  1857. frac[1] = '';
  1858. const mod = frac[0].length > 3 ? frac[0].length % 3 : 0;
  1859. cellType = 'number';
  1860. result = (number < 0 ? '-' : '') +
  1861. (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]) +
  1862. (frac[1].length ? defaults.numbers.output.decimalMark + frac[1] : '');
  1863. }
  1864. }
  1865. }
  1866. else
  1867. result = htmlData;
  1868. }
  1869. if (defaults.escape === true) {
  1870. //noinspection JSDeprecatedSymbols
  1871. result = escape(result);
  1872. }
  1873. if (typeof defaults.onCellData === 'function') {
  1874. result = defaults.onCellData($cell, rowIndex, colIndex, result, cellType);
  1875. $cell.data('teUserDefText', 1);
  1876. }
  1877. }
  1878. if (cellInfo !== undefined)
  1879. cellInfo.type = cellType;
  1880. return result;
  1881. }
  1882. function preventInjection (str) {
  1883. if (str.length > 0 && defaults.preventInjection === true) {
  1884. const chars = '=+-@';
  1885. if (chars.indexOf(str.charAt(0)) >= 0)
  1886. return ('\'' + str);
  1887. }
  1888. return str;
  1889. }
  1890. //noinspection JSUnusedLocalSymbols
  1891. function hyphenate (a, b, c) {
  1892. return b + '-' + c.toLowerCase();
  1893. }
  1894. function rgb2array (rgb_string, default_result) {
  1895. const re = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
  1896. const bits = re.exec(rgb_string);
  1897. let result = default_result;
  1898. if (bits)
  1899. result = [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])];
  1900. return result;
  1901. }
  1902. function getCellStyles (cell) {
  1903. let a = getStyle(cell, 'text-align');
  1904. const fw = getStyle(cell, 'font-weight');
  1905. const fs = getStyle(cell, 'font-style');
  1906. let f = '';
  1907. if (a === 'start')
  1908. a = getStyle(cell, 'direction') === 'rtl' ? 'right' : 'left';
  1909. if (fw >= 700)
  1910. f = 'bold';
  1911. if (fs === 'italic')
  1912. f += fs;
  1913. if (f === '')
  1914. f = 'normal';
  1915. const result = {
  1916. style: {
  1917. align: a,
  1918. bcolor: rgb2array(getStyle(cell, 'background-color'), [255, 255, 255]),
  1919. color: rgb2array(getStyle(cell, 'color'), [0, 0, 0]),
  1920. fstyle: f
  1921. },
  1922. colspan: getColspan(cell),
  1923. rowspan: getRowspan(cell)
  1924. };
  1925. if (cell !== null) {
  1926. const r = cell.getBoundingClientRect();
  1927. result.rect = {
  1928. width: r.width,
  1929. height: r.height
  1930. };
  1931. }
  1932. return result;
  1933. }
  1934. function getColspan (cell) {
  1935. let result = $(cell).attr('data-tableexport-colspan');
  1936. if (typeof result === 'undefined' && $(cell).is('[colspan]'))
  1937. result = $(cell).attr('colspan');
  1938. return (parseInt(result) || 0);
  1939. }
  1940. function getRowspan (cell) {
  1941. let result = $(cell).attr('data-tableexport-rowspan');
  1942. if (typeof result === 'undefined' && $(cell).is('[rowspan]'))
  1943. result = $(cell).attr('rowspan');
  1944. return (parseInt(result) || 0);
  1945. }
  1946. // get computed style property
  1947. function getStyle (target, prop) {
  1948. try {
  1949. if (window.getComputedStyle) { // gecko and webkit
  1950. prop = prop.replace(/([a-z])([A-Z])/, hyphenate); // requires hyphenated, not camel
  1951. if (typeof target === 'object' && target.nodeType !== undefined)
  1952. return window.getComputedStyle(target, null).getPropertyValue(prop);
  1953. if (typeof target === 'object' && target.length)
  1954. return target.getPropertyValue(prop);
  1955. return '';
  1956. }
  1957. if (target.currentStyle) { // ie
  1958. return target.currentStyle[prop];
  1959. }
  1960. return target.style[prop];
  1961. } catch (e) {
  1962. }
  1963. return '';
  1964. }
  1965. function getUnitValue (parent, value, unit) {
  1966. const baseline = 100; // any number serves
  1967. const temp = document.createElement('div'); // create temporary element
  1968. temp.style.overflow = 'hidden'; // in case baseline is set too low
  1969. temp.style.visibility = 'hidden'; // no need to show it
  1970. parent.appendChild(temp); // insert it into the parent for em, ex and %
  1971. temp.style.width = baseline + unit;
  1972. const factor = baseline / temp.offsetWidth;
  1973. parent.removeChild(temp); // clean up
  1974. return (value * factor);
  1975. }
  1976. function getPropertyUnitValue (target, prop, unit) {
  1977. const value = getStyle(target, prop); // get the computed style value
  1978. let numeric = value.match(/\d+/); // get the numeric component
  1979. if (numeric !== null) {
  1980. numeric = numeric[0]; // get the string
  1981. return getUnitValue(target.parentElement, numeric, unit);
  1982. }
  1983. return 0;
  1984. }
  1985. function xlsxWorkbookToArrayBuffer (s) {
  1986. const buf = new ArrayBuffer(s.length);
  1987. const view = new Uint8Array(buf);
  1988. for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  1989. return buf;
  1990. }
  1991. function xlsxTableToSheet (table) {
  1992. let ssfId;
  1993. const ws = ({});
  1994. const rows = table.getElementsByTagName('tr');
  1995. const sheetRows = Math.min(10000000, rows.length);
  1996. const range = {s: {r: 0, c: 0}, e: {r: 0, c: 0}};
  1997. let merges = [], midx = 0;
  1998. let _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  1999. let elt;
  2000. const ssfTable = XLSX.SSF.get_table();
  2001. for (; _R < rows.length && R < sheetRows; ++_R) {
  2002. const row = rows[_R];
  2003. let ignoreRow = false;
  2004. if (typeof defaults.onIgnoreRow === 'function')
  2005. ignoreRow = defaults.onIgnoreRow($(row), _R);
  2006. if (ignoreRow === true ||
  2007. (defaults.ignoreRow.length !== 0 &&
  2008. ($.inArray(_R, defaults.ignoreRow) !== -1 ||
  2009. $.inArray(_R - rows.length, defaults.ignoreRow) !== -1)) ||
  2010. isVisible($(row)) === false) {
  2011. continue;
  2012. }
  2013. const elts = (row.children);
  2014. let _CLength = 0;
  2015. for (_C = 0; _C < elts.length; ++_C) {
  2016. elt = elts[_C];
  2017. CS = +getColspan(elt) || 1;
  2018. _CLength += CS;
  2019. }
  2020. let CSOffset = 0;
  2021. for (_C = C = 0; _C < elts.length; ++_C) {
  2022. elt = elts[_C];
  2023. CS = +getColspan(elt) || 1;
  2024. const col = _C + CSOffset;
  2025. if (isColumnIgnored($(elt), _CLength, col + (col < C ? C - col : 0)))
  2026. continue;
  2027. CSOffset += CS - 1;
  2028. for (midx = 0; midx < merges.length; ++midx) {
  2029. const m = merges[midx];
  2030. if (m.s.c == C && m.s.r <= R && R <= m.e.r) {
  2031. C = m.e.c + 1;
  2032. midx = -1;
  2033. }
  2034. }
  2035. if ((RS = +getRowspan(elt)) > 0 || CS > 1)
  2036. merges.push({s: {r: R, c: C}, e: {r: R + (RS || 1) - 1, c: C + CS - 1}});
  2037. const cellInfo = {type: ''};
  2038. let v = parseString(elt, _R, _C + CSOffset, cellInfo);
  2039. let o = {t: 's', v: v};
  2040. let _t = '';
  2041. const cellFormat = $(elt).attr('data-tableexport-cellformat') || undefined;
  2042. if (cellFormat !== '') {
  2043. ssfId = parseInt($(elt).attr('data-tableexport-xlsxformatid') || 0);
  2044. if (ssfId === 0 &&
  2045. typeof defaults.mso.xlsx.formatId.numbers === 'function')
  2046. ssfId = defaults.mso.xlsx.formatId.numbers($(elt), _R, _C + CSOffset);
  2047. if (ssfId === 0 &&
  2048. typeof defaults.mso.xlsx.formatId.date === 'function')
  2049. ssfId = defaults.mso.xlsx.formatId.date($(elt), _R, _C + CSOffset);
  2050. if (ssfId === 49 || ssfId === '@')
  2051. _t = 's';
  2052. else if (cellInfo.type === 'number' ||
  2053. (ssfId > 0 && ssfId < 14) || (ssfId > 36 && ssfId < 41) || ssfId === 48)
  2054. _t = 'n';
  2055. else if (cellInfo.type === 'date' ||
  2056. (ssfId > 13 && ssfId < 37) || (ssfId > 44 && ssfId < 48) || ssfId === 56)
  2057. _t = 'd';
  2058. } else
  2059. _t = 's';
  2060. if (v != null) {
  2061. let vd;
  2062. if (v.length === 0) {
  2063. o.t = 'z';
  2064. }
  2065. else if (v.trim().length === 0) {
  2066. }
  2067. else if (_t === 's') {
  2068. }
  2069. else if (cellInfo.type === 'function') {
  2070. o = {f: v};
  2071. }
  2072. else if (v === 'TRUE') {
  2073. o = {t: 'b', v: true};
  2074. }
  2075. else if (v === 'FALSE') {
  2076. o = {t: 'b', v: false};
  2077. }
  2078. else if (_t === 'n' || isFinite(xlsxToNumber(v, defaults.numbers.output))) { // yes, defaults.numbers.output is right
  2079. const vn = xlsxToNumber(v, defaults.numbers.output);
  2080. if (ssfId === 0 && typeof defaults.mso.xlsx.formatId.numbers !== 'function') {
  2081. ssfId = defaults.mso.xlsx.formatId.numbers;
  2082. }
  2083. if (isFinite(vn) || isFinite(v))
  2084. o = {
  2085. t: 'n',
  2086. v: (isFinite(vn) ? vn : v),
  2087. z: (typeof ssfId === 'string') ? ssfId :
  2088. (ssfId in ssfTable ? ssfTable[ssfId] :
  2089. ssfId === defaults.mso.xlsx.formatId.currency ? defaults.mso.xlsx.format.currency :
  2090. '0.00')
  2091. };
  2092. }
  2093. else if ((vd = parseDateUTC(v)) !== false || _t === 'd') {
  2094. if (ssfId === 0 && typeof defaults.mso.xlsx.formatId.date !== 'function') {
  2095. ssfId = defaults.mso.xlsx.formatId.date;
  2096. }
  2097. o = {
  2098. t: 'd',
  2099. v: (vd !== false ? vd : v),
  2100. z: (typeof ssfId === 'string') ? ssfId : (ssfId in ssfTable ? ssfTable[ssfId] : 'm/d/yy')
  2101. };
  2102. }
  2103. const $aTag = $(elt).find('a');
  2104. if ($aTag && $aTag.length) {
  2105. const href = $aTag[0].hasAttribute("href") ? $aTag.attr('href') : '';
  2106. const content = (defaults.htmlHyperlink !== 'href' || href === '') ? v : '';
  2107. const hyperlink = (href !== '') ? '=HYPERLINK("' + href + (content.length ? '","' + content : '') + '")' : '';
  2108. if (hyperlink !== '') {
  2109. if (typeof defaults.mso.xlsx.onHyperlink === 'function') {
  2110. v = defaults.mso.xlsx.onHyperlink($(elt), _R, _C, href, content, hyperlink);
  2111. if (v.indexOf('=HYPERLINK') !== 0) {
  2112. o = {t: 's', v: v};
  2113. } else {
  2114. o = {f: v};
  2115. }
  2116. } else {
  2117. o = {f: hyperlink};
  2118. }
  2119. }
  2120. }
  2121. }
  2122. ws[xlsxEncodeCell({c: C, r: R})] = o;
  2123. if (range.e.c < C) {
  2124. range.e.c = C;
  2125. }
  2126. C += CS;
  2127. }
  2128. ++R;
  2129. }
  2130. if (merges.length) {
  2131. ws['!merges'] = (ws["!merges"] || []).concat(merges);
  2132. }
  2133. range.e.r = Math.max(range.e.r, R - 1);
  2134. ws['!ref'] = xlsxEncodeRange(range);
  2135. if (R >= sheetRows) {
  2136. ws['!fullref'] = xlsxEncodeRange((range.e.r = rows.length - _R + R - 1, range));
  2137. }
  2138. return ws;
  2139. }
  2140. function xlsxEncodeRow (row) {
  2141. return '' + (row + 1);
  2142. }
  2143. function xlsxEncodeCol (col) {
  2144. let s = '';
  2145. for (++col; col; col = Math.floor((col - 1) / 26)) {
  2146. s = String.fromCharCode(((col - 1) % 26) + 65) + s;
  2147. }
  2148. return s;
  2149. }
  2150. function xlsxEncodeCell (cell) {
  2151. return xlsxEncodeCol(cell.c) + xlsxEncodeRow(cell.r);
  2152. }
  2153. function xlsxEncodeRange (cs, ce) {
  2154. if (typeof ce === 'undefined' || typeof ce === 'number') {
  2155. return xlsxEncodeRange(cs.s, cs.e);
  2156. }
  2157. if (typeof cs !== 'string') {
  2158. cs = xlsxEncodeCell((cs));
  2159. }
  2160. if (typeof ce !== 'string') {
  2161. ce = xlsxEncodeCell((ce));
  2162. }
  2163. return cs === ce ? cs : cs + ':' + ce;
  2164. }
  2165. function xlsxToNumber (s, numbersFormat) {
  2166. let v = Number(s);
  2167. if (isFinite(v)) return v;
  2168. let wt = 1;
  2169. let ss = s;
  2170. if ('' !== numbersFormat.thousandsSeparator)
  2171. ss = ss.replace(new RegExp('([\\d])' + numbersFormat.thousandsSeparator + '([\\d])', 'g'), '$1$2');
  2172. if ('.' !== numbersFormat.decimalMark)
  2173. ss = ss.replace(new RegExp('([\\d])' + numbersFormat.decimalMark + '([\\d])', 'g'), '$1.$2');
  2174. ss = ss.replace(/[$]/g, '').replace(/[%]/g, function () {
  2175. wt *= 100;
  2176. return '';
  2177. });
  2178. if (isFinite(v = Number(ss))) return v / wt;
  2179. ss = ss.replace(/[(](.*)[)]/, function ($$, $1) {
  2180. wt = -wt;
  2181. return $1;
  2182. });
  2183. if (isFinite(v = Number(ss))) return v / wt;
  2184. return v;
  2185. }
  2186. function strHashCode (str) {
  2187. let hash = 0, i, chr, len;
  2188. if (str.length === 0) return hash;
  2189. for (i = 0, len = str.length; i < len; i++) {
  2190. chr = str.charCodeAt(i);
  2191. hash = ((hash << 5) - hash) + chr;
  2192. hash |= 0; // Convert to 32bit integer
  2193. }
  2194. return hash;
  2195. }
  2196. function saveToFile (data, fileName, type, charset, encoding, bom) {
  2197. let saveIt = true;
  2198. if (typeof defaults.onBeforeSaveToFile === 'function') {
  2199. saveIt = defaults.onBeforeSaveToFile(data, fileName, type, charset, encoding);
  2200. if (typeof saveIt !== 'boolean')
  2201. saveIt = true;
  2202. }
  2203. if (saveIt) {
  2204. try {
  2205. if (bom)
  2206. blob = new Blob([String.fromCharCode(0xFEFF), [data]], { type: type + ';charset=' + charset});
  2207. else
  2208. blob = new Blob([data], {type: type + ';charset=' + charset});
  2209. saveAs(blob, fileName, {autoBom: false});
  2210. if (typeof defaults.onAfterSaveToFile === 'function')
  2211. defaults.onAfterSaveToFile(data, fileName);
  2212. } catch (e) {
  2213. downloadFile(fileName,
  2214. 'data:' + type +
  2215. (charset.length ? ';charset=' + charset : '') +
  2216. (encoding.length ? ';' + encoding : '') + ',',
  2217. (bom ? ('\ufeff' + data) : data));
  2218. }
  2219. }
  2220. }
  2221. function downloadFile (filename, header, data) {
  2222. const ua = window.navigator.userAgent;
  2223. if (filename !== false && window.navigator.msSaveOrOpenBlob) {
  2224. //noinspection JSUnresolvedFunction
  2225. window.navigator.msSaveOrOpenBlob(new Blob([data]), filename);
  2226. } else if (filename !== false && (ua.indexOf('MSIE ') > 0 || !!ua.match(/Trident.*rv\:11\./))) {
  2227. // Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin)
  2228. // based on sampopes answer on http://stackoverflow.com/questions/22317951
  2229. // ! Not working for json and pdf format !
  2230. const frame = document.createElement('iframe');
  2231. if (frame) {
  2232. document.body.appendChild(frame);
  2233. frame.setAttribute('style', 'display:none');
  2234. frame.contentDocument.open('txt/plain', 'replace');
  2235. frame.contentDocument.write(data);
  2236. frame.contentDocument.close();
  2237. frame.contentWindow.focus();
  2238. const extension = filename.substr((filename.lastIndexOf('.') + 1));
  2239. switch (extension) {
  2240. case 'doc':
  2241. case 'json':
  2242. case 'png':
  2243. case 'pdf':
  2244. case 'xls':
  2245. case 'xlsx':
  2246. filename += '.txt';
  2247. break;
  2248. }
  2249. frame.contentDocument.execCommand('SaveAs', true, filename);
  2250. document.body.removeChild(frame);
  2251. }
  2252. } else {
  2253. const DownloadLink = document.createElement('a');
  2254. if (DownloadLink) {
  2255. let blobUrl = null;
  2256. DownloadLink.style.display = 'none';
  2257. if (filename !== false)
  2258. DownloadLink.download = filename;
  2259. else
  2260. DownloadLink.target = '_blank';
  2261. if (typeof data === 'object') {
  2262. window.URL = window.URL || window.webkitURL;
  2263. const binaryData = [];
  2264. binaryData.push(data);
  2265. blobUrl = window.URL.createObjectURL(new Blob(binaryData, {type: header}));
  2266. DownloadLink.href = blobUrl;
  2267. }
  2268. else if (header.toLowerCase().indexOf('base64,') >= 0) {
  2269. DownloadLink.href = header + base64encode(data);
  2270. }
  2271. else {
  2272. DownloadLink.href = header + encodeURIComponent(data);
  2273. }
  2274. document.body.appendChild(DownloadLink);
  2275. if (document.createEvent) {
  2276. if (DownloadEvt === null)
  2277. DownloadEvt = document.createEvent('MouseEvents');
  2278. DownloadEvt.initEvent('click', true, false);
  2279. DownloadLink.dispatchEvent(DownloadEvt);
  2280. }
  2281. else if (document.createEventObject)
  2282. DownloadLink.fireEvent('onclick');
  2283. else if (typeof DownloadLink.onclick === 'function')
  2284. DownloadLink.onclick();
  2285. setTimeout(function () {
  2286. if (blobUrl)
  2287. window.URL.revokeObjectURL(blobUrl);
  2288. document.body.removeChild(DownloadLink);
  2289. if (typeof defaults.onAfterSaveToFile === 'function')
  2290. defaults.onAfterSaveToFile(data, filename);
  2291. }, 100);
  2292. }
  2293. }
  2294. }
  2295. function utf8Encode (text) {
  2296. if (typeof text === 'string') {
  2297. text = text.replace(/\x0d\x0a/g, '\x0a');
  2298. let utfText = '';
  2299. for (let n = 0; n < text.length; n++) {
  2300. const c = text.charCodeAt(n);
  2301. if (c < 128) {
  2302. utfText += String.fromCharCode(c);
  2303. } else if ((c > 127) && (c < 2048)) {
  2304. utfText += String.fromCharCode((c >> 6) | 192);
  2305. utfText += String.fromCharCode((c & 63) | 128);
  2306. } else {
  2307. utfText += String.fromCharCode((c >> 12) | 224);
  2308. utfText += String.fromCharCode(((c >> 6) & 63) | 128);
  2309. utfText += String.fromCharCode((c & 63) | 128);
  2310. }
  2311. }
  2312. return utfText;
  2313. }
  2314. return text;
  2315. }
  2316. function base64encode (input) {
  2317. let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  2318. const keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  2319. let output = '';
  2320. let i = 0;
  2321. input = utf8Encode(input);
  2322. while (i < input.length) {
  2323. chr1 = input.charCodeAt(i++);
  2324. chr2 = input.charCodeAt(i++);
  2325. chr3 = input.charCodeAt(i++);
  2326. enc1 = chr1 >> 2;
  2327. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2328. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  2329. enc4 = chr3 & 63;
  2330. if (isNaN(chr2)) {
  2331. enc3 = enc4 = 64;
  2332. } else if (isNaN(chr3)) {
  2333. enc4 = 64;
  2334. }
  2335. output = output +
  2336. keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  2337. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  2338. }
  2339. return output;
  2340. }
  2341. // ----------------------------------------------------------------------------------------------------
  2342. // jsPDF-AutoTable 2.0.17 - BEGIN
  2343. // Adopted and adapted source code from https://github.com/simonbengtsson/jsPDF-AutoTable
  2344. // ----------------------------------------------------------------------------------------------------
  2345. var jsPdfDoc, // The current jspdf instance
  2346. jsPdfCursor, // An object keeping track of the x and y position of the next table cell to draw
  2347. jsPdfSettings, // Default options merged with user options
  2348. jsPdfPageCount, // The page count the current table spans
  2349. jsPdfTable; // The current Table instance
  2350. function jsPdfAutoTable (doc, headers, data, options) {
  2351. jsPdfValidateInput(headers, data, options);
  2352. jsPdfDoc = doc;
  2353. jsPdfSettings = jsPdfInitOptions(options || {});
  2354. jsPdfPageCount = 1;
  2355. // Need a cursor y as it needs to be reset after each page (row.y can't do that)
  2356. jsPdfCursor = { y: jsPdfSettings.startY === false ? jsPdfSettings.margin.top : jsPdfSettings.startY };
  2357. const userStyles = {
  2358. textColor: 30, // Setting text color to dark gray as it can't be obtained from jsPDF
  2359. fontSize: jsPdfDoc.internal.getFontSize(),
  2360. fontStyle: jsPdfDoc.internal.getFont().fontStyle,
  2361. fontName: jsPdfDoc.internal.getFont().fontName
  2362. };
  2363. // Create the table model with its columns, rows and cells
  2364. jsPdfCreateModels(headers, data);
  2365. jsPdfCalculateWidths();
  2366. // Page break if there is room for only the first data row
  2367. const firstRowHeight = jsPdfTable.rows[0] && jsPdfSettings.pageBreak === 'auto' ? jsPdfTable.rows[0].height : 0;
  2368. let minTableBottomPos = jsPdfSettings.startY + jsPdfSettings.margin.bottom + jsPdfTable.headerRow.height + firstRowHeight;
  2369. if (jsPdfSettings.pageBreak === 'avoid') {
  2370. minTableBottomPos += jsPdfTable.height;
  2371. }
  2372. if ((jsPdfSettings.pageBreak === 'always' && jsPdfSettings.startY !== false) ||
  2373. (jsPdfSettings.startY !== false && minTableBottomPos > jsPdfDoc.internal.pageSize.height)) {
  2374. jsPdfDoc.addPage();
  2375. jsPdfCursor.y = jsPdfSettings.margin.top;
  2376. }
  2377. jsPdfApplyStyles(userStyles);
  2378. jsPdfSettings.beforePageContent(jsPdfHooksData());
  2379. if (jsPdfSettings.drawHeaderRow(jsPdfTable.headerRow, jsPdfHooksData({row: jsPdfTable.headerRow})) !== false) {
  2380. jsPdfPrintRow(jsPdfTable.headerRow, jsPdfSettings.drawHeaderCell);
  2381. }
  2382. jsPdfApplyStyles(userStyles);
  2383. jsPdfPrintRows();
  2384. jsPdfSettings.afterPageContent(jsPdfHooksData());
  2385. jsPdfApplyStyles(userStyles);
  2386. return jsPdfDoc;
  2387. }
  2388. /**
  2389. * Returns the Y position of the last drawn cell
  2390. * @returns int
  2391. */
  2392. function jsPdfAutoTableEndPosY () {
  2393. if (typeof jsPdfCursor === 'undefined' || typeof jsPdfCursor.y === 'undefined') {
  2394. return 0;
  2395. }
  2396. return jsPdfCursor.y;
  2397. }
  2398. /**
  2399. * Improved text function with halign and valign support
  2400. * Inspiration from:
  2401. * http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113
  2402. */
  2403. function jsPdfAutoTableText (text, x, y, styles) {
  2404. if (typeof x !== 'number' || typeof y !== 'number') {
  2405. console.error('The x and y parameters are required. Missing for the text: ', text);
  2406. }
  2407. const fontSize = jsPdfDoc.internal.getFontSize() / jsPdfDoc.internal.scaleFactor;
  2408. // As defined in jsPDF source code
  2409. const lineHeightProportion = FONT_ROW_RATIO;
  2410. const splitRegex = /\r\n|\r|\n/g;
  2411. let splittedText = null;
  2412. let lineCount = 1;
  2413. if (styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right') {
  2414. splittedText = typeof text === 'string' ? text.split(splitRegex) : text;
  2415. lineCount = splittedText.length || 1;
  2416. }
  2417. // Align the top
  2418. y += fontSize * (2 - lineHeightProportion);
  2419. if (styles.valign === 'middle')
  2420. y -= (lineCount / 2) * fontSize;
  2421. else if (styles.valign === 'bottom')
  2422. y -= lineCount * fontSize;
  2423. if (styles.halign === 'center' || styles.halign === 'right') {
  2424. let alignSize = fontSize;
  2425. if (styles.halign === 'center')
  2426. alignSize *= 0.5;
  2427. if (splittedText && lineCount >= 1) {
  2428. for (let iLine = 0; iLine < splittedText.length; iLine++) {
  2429. jsPdfDoc.text(splittedText[iLine], x - jsPdfDoc.getStringUnitWidth(splittedText[iLine]) * alignSize, y);
  2430. y += fontSize;
  2431. }
  2432. return jsPdfDoc;
  2433. }
  2434. x -= jsPdfDoc.getStringUnitWidth(text) * alignSize;
  2435. }
  2436. jsPdfDoc.text(text, x, y);
  2437. return jsPdfDoc;
  2438. }
  2439. function jsPdfValidateInput(headers, data, options) {
  2440. if (!headers || typeof headers !== 'object') {
  2441. console.error("The headers should be an object or array, is: " + typeof headers);
  2442. }
  2443. if (!data || typeof data !== 'object') {
  2444. console.error("The data should be an object or array, is: " + typeof data);
  2445. }
  2446. if (!!options && typeof options !== 'object') {
  2447. console.error("The data should be an object or array, is: " + typeof data);
  2448. }
  2449. if (!Array.prototype.forEach) {
  2450. console.error("The current browser does not support Array.prototype.forEach which is required for jsPDF-AutoTable");
  2451. }
  2452. }
  2453. function jsPdfInitOptions(userOptions) {
  2454. const settings = jsPdfExtend(jsPdfDefaultOptions(), userOptions);
  2455. // Options
  2456. if (typeof settings.extendWidth !== 'undefined') {
  2457. settings.tableWidth = settings.extendWidth ? 'auto' : 'wrap';
  2458. console.error("Use of deprecated option: extendWidth, use tableWidth instead.");
  2459. }
  2460. if (typeof settings.margins !== 'undefined') {
  2461. if (typeof settings.margin === 'undefined') settings.margin = settings.margins;
  2462. console.error("Use of deprecated option: margins, use margin instead.");
  2463. }
  2464. [['padding', 'cellPadding'], ['lineHeight', 'rowHeight'], 'fontSize', 'overflow'].forEach(function (o) {
  2465. const deprecatedOption = typeof o === 'string' ? o : o[0];
  2466. const style = typeof o === 'string' ? o : o[1];
  2467. if (typeof settings[deprecatedOption] !== 'undefined') {
  2468. if (typeof settings.styles[style] === 'undefined') {
  2469. settings.styles[style] = settings[deprecatedOption];
  2470. }
  2471. console.error("Use of deprecated option: " + deprecatedOption + ", use the style " + style + " instead.");
  2472. }
  2473. });
  2474. // Unifying
  2475. const marginSetting = settings.margin;
  2476. settings.margin = {};
  2477. if (typeof marginSetting.horizontal === 'number') {
  2478. marginSetting.right = marginSetting.horizontal;
  2479. marginSetting.left = marginSetting.horizontal;
  2480. }
  2481. if (typeof marginSetting.vertical === 'number') {
  2482. marginSetting.top = marginSetting.vertical;
  2483. marginSetting.bottom = marginSetting.vertical;
  2484. }
  2485. ['top', 'right', 'bottom', 'left'].forEach(function (side, i) {
  2486. if (typeof marginSetting === 'number') {
  2487. settings.margin[side] = marginSetting;
  2488. } else {
  2489. const key = Array.isArray(marginSetting) ? i : side;
  2490. settings.margin[side] = typeof marginSetting[key] === 'number' ? marginSetting[key] : 40;
  2491. }
  2492. });
  2493. return settings;
  2494. }
  2495. /**
  2496. * Create models from the user input
  2497. *
  2498. * @param inputHeaders
  2499. * @param inputData
  2500. */
  2501. function jsPdfCreateModels(inputHeaders, inputData) {
  2502. jsPdfTable = new jsPdfTableClass();
  2503. jsPdfTable.x = jsPdfSettings.margin.left;
  2504. const splitRegex = /\r\n|\r|\n/g;
  2505. // Header row and columns
  2506. const headerRow = new jsPdfRowClass(inputHeaders);
  2507. headerRow.index = -1;
  2508. const themeStyles = jsPdfExtend(jsPdfDefaultStyles, jsPdfThemes[jsPdfSettings.theme].table, jsPdfThemes[jsPdfSettings.theme].header);
  2509. headerRow.styles = jsPdfExtend(themeStyles, jsPdfSettings.styles, jsPdfSettings.headerStyles);
  2510. // Columns and header row
  2511. inputHeaders.forEach(function (rawColumn, dataKey) {
  2512. if (typeof rawColumn === 'object') {
  2513. dataKey = typeof rawColumn.dataKey !== 'undefined' ? rawColumn.dataKey : rawColumn.key;
  2514. }
  2515. if (typeof rawColumn.width !== 'undefined') {
  2516. console.error("Use of deprecated option: column.width, use column.styles.columnWidth instead.");
  2517. }
  2518. const col = new jsPdfColumnClass(dataKey);
  2519. col.styles = jsPdfSettings.columnStyles[col.dataKey] || {};
  2520. jsPdfTable.columns.push(col);
  2521. const cell = new jsPdfCellClass();
  2522. cell.raw = typeof rawColumn === 'object' ? rawColumn.title : rawColumn;
  2523. // jsPDF AutoTable plugin v2.0.14 fix: each cell needs its own styles object
  2524. //cell.styles = jsPdfExtend(headerRow.styles);
  2525. cell.styles = $.extend({}, headerRow.styles);
  2526. cell.text = '' + cell.raw;
  2527. cell.contentWidth = cell.styles.cellPadding * 2 + jsPdfGetStringWidth(cell.text, cell.styles);
  2528. cell.text = cell.text.split(splitRegex);
  2529. headerRow.cells[dataKey] = cell;
  2530. jsPdfSettings.createdHeaderCell(cell, {column: col, row: headerRow, settings: jsPdfSettings});
  2531. });
  2532. jsPdfTable.headerRow = headerRow;
  2533. // Rows och cells
  2534. inputData.forEach(function (rawRow, i) {
  2535. const row = new jsPdfRowClass(rawRow);
  2536. const isAlternate = i % 2 === 0;
  2537. const themeStyles = jsPdfExtend(jsPdfDefaultStyles, jsPdfThemes[jsPdfSettings.theme].table, isAlternate ? jsPdfThemes[jsPdfSettings.theme].alternateRow : {});
  2538. const userStyles = jsPdfExtend(jsPdfSettings.styles, jsPdfSettings.bodyStyles, isAlternate ? jsPdfSettings.alternateRowStyles : {});
  2539. row.styles = jsPdfExtend(themeStyles, userStyles);
  2540. row.index = i;
  2541. jsPdfTable.columns.forEach(function (column) {
  2542. const cell = new jsPdfCellClass();
  2543. cell.raw = rawRow[column.dataKey];
  2544. cell.styles = jsPdfExtend(row.styles, column.styles);
  2545. cell.text = typeof cell.raw !== 'undefined' ? '' + cell.raw : ''; // Stringify 0 and false, but not undefined
  2546. row.cells[column.dataKey] = cell;
  2547. jsPdfSettings.createdCell(cell, jsPdfHooksData({column: column, row: row}));
  2548. cell.contentWidth = cell.styles.cellPadding * 2 + jsPdfGetStringWidth(cell.text, cell.styles);
  2549. cell.text = cell.text.split(splitRegex);
  2550. });
  2551. jsPdfTable.rows.push(row);
  2552. });
  2553. }
  2554. /**
  2555. * Calculate the column widths
  2556. */
  2557. function jsPdfCalculateWidths() {
  2558. // Column and table content width
  2559. let tableContentWidth = 0;
  2560. jsPdfTable.columns.forEach(function (column) {
  2561. column.contentWidth = jsPdfTable.headerRow.cells[column.dataKey].contentWidth;
  2562. jsPdfTable.rows.forEach(function (row) {
  2563. const cellWidth = row.cells[column.dataKey].contentWidth;
  2564. if (cellWidth > column.contentWidth) {
  2565. column.contentWidth = cellWidth;
  2566. }
  2567. });
  2568. column.width = column.contentWidth;
  2569. tableContentWidth += column.contentWidth;
  2570. });
  2571. jsPdfTable.contentWidth = tableContentWidth;
  2572. const maxTableWidth = jsPdfDoc.internal.pageSize.width - jsPdfSettings.margin.left - jsPdfSettings.margin.right;
  2573. let preferredTableWidth = maxTableWidth; // settings.tableWidth === 'auto'
  2574. if (typeof jsPdfSettings.tableWidth === 'number') {
  2575. preferredTableWidth = jsPdfSettings.tableWidth;
  2576. } else if (jsPdfSettings.tableWidth === 'wrap') {
  2577. preferredTableWidth = jsPdfTable.contentWidth;
  2578. }
  2579. jsPdfTable.width = preferredTableWidth < maxTableWidth ? preferredTableWidth : maxTableWidth;
  2580. // To avoid subjecting columns with little content with the chosen overflow method,
  2581. // never shrink a column more than the table divided by column count (its "fair part")
  2582. const dynamicColumns = [];
  2583. let dynamicColumnsContentWidth = 0;
  2584. const fairWidth = jsPdfTable.width / jsPdfTable.columns.length;
  2585. let staticWidth = 0;
  2586. jsPdfTable.columns.forEach(function (column) {
  2587. const colStyles = jsPdfExtend(jsPdfDefaultStyles, jsPdfThemes[jsPdfSettings.theme].table, jsPdfSettings.styles, column.styles);
  2588. if (colStyles.columnWidth === 'wrap') {
  2589. column.width = column.contentWidth;
  2590. } else if (typeof colStyles.columnWidth === 'number') {
  2591. column.width = colStyles.columnWidth;
  2592. } else if (colStyles.columnWidth === 'auto' || true) {
  2593. if (column.contentWidth <= fairWidth && jsPdfTable.contentWidth > jsPdfTable.width) {
  2594. column.width = column.contentWidth;
  2595. } else {
  2596. dynamicColumns.push(column);
  2597. dynamicColumnsContentWidth += column.contentWidth;
  2598. column.width = 0;
  2599. }
  2600. }
  2601. staticWidth += column.width;
  2602. });
  2603. // Distributes extra width or trims columns down to fit
  2604. jsPdfDistributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth);
  2605. // Row height, table height and text overflow
  2606. jsPdfTable.height = 0;
  2607. const all = jsPdfTable.rows.concat(jsPdfTable.headerRow);
  2608. all.forEach(function (row, i) {
  2609. let lineBreakCount = 0;
  2610. let cursorX = jsPdfTable.x;
  2611. jsPdfTable.columns.forEach(function (col) {
  2612. const cell = row.cells[col.dataKey];
  2613. col.x = cursorX;
  2614. jsPdfApplyStyles(cell.styles);
  2615. const textSpace = col.width - cell.styles.cellPadding * 2;
  2616. if (cell.styles.overflow === 'linebreak') {
  2617. // Add one pt to textSpace to fix rounding error
  2618. cell.text = jsPdfDoc.splitTextToSize(cell.text, textSpace + 1, {fontSize: cell.styles.fontSize});
  2619. } else if (cell.styles.overflow === 'ellipsize') {
  2620. cell.text = jsPdfEllipsize(cell.text, textSpace, cell.styles);
  2621. } else if (cell.styles.overflow === 'visible') {
  2622. // Do nothing
  2623. } else if (cell.styles.overflow === 'hidden') {
  2624. cell.text = jsPdfEllipsize(cell.text, textSpace, cell.styles, '');
  2625. } else if (typeof cell.styles.overflow === 'function') {
  2626. cell.text = cell.styles.overflow(cell.text, textSpace);
  2627. } else {
  2628. console.error("Unrecognized overflow type: " + cell.styles.overflow);
  2629. }
  2630. const count = Array.isArray(cell.text) ? cell.text.length - 1 : 0;
  2631. if (count > lineBreakCount) {
  2632. lineBreakCount = count;
  2633. }
  2634. cursorX += col.width;
  2635. });
  2636. row.heightStyle = row.styles.rowHeight;
  2637. // TODO Pick the highest row based on font size as well
  2638. row.height = (row.heightStyle + lineBreakCount * row.styles.fontSize * FONT_ROW_RATIO) +
  2639. ((2 - FONT_ROW_RATIO) / 2 * row.styles.fontSize); // Fix jsPDF Autotable's row height calculation
  2640. jsPdfTable.height += row.height;
  2641. });
  2642. }
  2643. function jsPdfDistributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth) {
  2644. const extraWidth = jsPdfTable.width - staticWidth - dynamicColumnsContentWidth;
  2645. for (let i = 0; i < dynamicColumns.length; i++) {
  2646. const col = dynamicColumns[i];
  2647. const ratio = col.contentWidth / dynamicColumnsContentWidth;
  2648. // A column turned out to be none dynamic, start over recursively
  2649. const isNoneDynamic = col.contentWidth + extraWidth * ratio < fairWidth;
  2650. if (extraWidth < 0 && isNoneDynamic) {
  2651. dynamicColumns.splice(i, 1);
  2652. dynamicColumnsContentWidth -= col.contentWidth;
  2653. col.width = fairWidth;
  2654. staticWidth += col.width;
  2655. jsPdfDistributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth);
  2656. break;
  2657. } else {
  2658. col.width = col.contentWidth + extraWidth * ratio;
  2659. }
  2660. }
  2661. }
  2662. function jsPdfPrintRows() {
  2663. jsPdfTable.rows.forEach(function (row, i) {
  2664. if (jsPdfIsNewPage(row.height)) {
  2665. jsPdfAddPage();
  2666. }
  2667. row.y = jsPdfCursor.y;
  2668. if (jsPdfSettings.drawRow(row, jsPdfHooksData({row: row})) !== false) {
  2669. jsPdfPrintRow(row, jsPdfSettings.drawCell);
  2670. }
  2671. });
  2672. }
  2673. function jsPdfAddPage() {
  2674. jsPdfSettings.afterPageContent(jsPdfHooksData());
  2675. jsPdfDoc.addPage();
  2676. jsPdfPageCount++;
  2677. jsPdfCursor = {x: jsPdfSettings.margin.left, y: jsPdfSettings.margin.top};
  2678. jsPdfSettings.beforePageContent(jsPdfHooksData());
  2679. if (jsPdfSettings.drawHeaderRow(jsPdfTable.headerRow, jsPdfHooksData({row: jsPdfTable.headerRow})) !== false) {
  2680. jsPdfPrintRow(jsPdfTable.headerRow, jsPdfSettings.drawHeaderCell);
  2681. }
  2682. }
  2683. /**
  2684. * Add a new page if cursor is at the end of page
  2685. * @param rowHeight
  2686. * @returns {boolean}
  2687. */
  2688. function jsPdfIsNewPage(rowHeight) {
  2689. const afterRowPos = jsPdfCursor.y + rowHeight + jsPdfSettings.margin.bottom;
  2690. return afterRowPos >= jsPdfDoc.internal.pageSize.height;
  2691. }
  2692. function jsPdfPrintRow(row, hookHandler) {
  2693. for (let i = 0; i < jsPdfTable.columns.length; i++) {
  2694. const column = jsPdfTable.columns[i];
  2695. const cell = row.cells[column.dataKey];
  2696. if(!cell) {
  2697. continue;
  2698. }
  2699. jsPdfApplyStyles(cell.styles);
  2700. cell.x = column.x;
  2701. cell.y = jsPdfCursor.y;
  2702. cell.height = row.height;
  2703. cell.width = column.width;
  2704. if (cell.styles.valign === 'top') {
  2705. cell.textPos.y = jsPdfCursor.y + cell.styles.cellPadding;
  2706. } else if (cell.styles.valign === 'bottom') {
  2707. cell.textPos.y = jsPdfCursor.y + row.height - cell.styles.cellPadding;
  2708. } else {
  2709. cell.textPos.y = jsPdfCursor.y + row.height / 2;
  2710. }
  2711. if (cell.styles.halign === 'right') {
  2712. cell.textPos.x = cell.x + cell.width - cell.styles.cellPadding;
  2713. } else if (cell.styles.halign === 'center') {
  2714. cell.textPos.x = cell.x + cell.width / 2;
  2715. } else {
  2716. cell.textPos.x = cell.x + cell.styles.cellPadding;
  2717. }
  2718. const data = jsPdfHooksData({column: column, row: row});
  2719. if (hookHandler(cell, data) !== false) {
  2720. jsPdfDoc.rect(cell.x, cell.y, cell.width, cell.height, cell.styles.fillStyle);
  2721. jsPdfAutoTableText(cell.text, cell.textPos.x, cell.textPos.y, {
  2722. halign: cell.styles.halign,
  2723. valign: cell.styles.valign
  2724. });
  2725. }
  2726. }
  2727. jsPdfCursor.y += row.height;
  2728. }
  2729. function jsPdfApplyStyles(styles) {
  2730. const arr = [
  2731. {func: jsPdfDoc.setFillColor, value: styles.fillColor},
  2732. {func: jsPdfDoc.setTextColor, value: styles.textColor},
  2733. {func: jsPdfDoc.setFont, value: styles.font, style: styles.fontStyle},
  2734. {func: jsPdfDoc.setDrawColor, value: styles.lineColor},
  2735. {func: jsPdfDoc.setLineWidth, value: styles.lineWidth},
  2736. {func: jsPdfDoc.setFont, value: styles.font},
  2737. {func: jsPdfDoc.setFontSize, value: styles.fontSize}
  2738. ];
  2739. arr.forEach(function (obj) {
  2740. if (typeof obj.value !== 'undefined') {
  2741. if (obj.value.constructor === Array) {
  2742. obj.func.apply(jsPdfDoc, obj.value);
  2743. } else if (typeof obj.style !== 'undefined') {
  2744. obj.func(obj.value, obj.style);
  2745. } else {
  2746. obj.func(obj.value);
  2747. }
  2748. }
  2749. });
  2750. }
  2751. function jsPdfHooksData(additionalData) {
  2752. additionalData = additionalData || {};
  2753. const data = {
  2754. pageCount: jsPdfPageCount,
  2755. settings: jsPdfSettings,
  2756. table: jsPdfTable,
  2757. cursor: jsPdfCursor
  2758. };
  2759. for (let prop in additionalData) {
  2760. if (additionalData.hasOwnProperty(prop)) {
  2761. data[prop] = additionalData[prop];
  2762. }
  2763. }
  2764. return data;
  2765. }
  2766. /**
  2767. * Ellipsize the text to fit in the width
  2768. */
  2769. function jsPdfEllipsize(text, width, styles, ellipsizeStr) {
  2770. ellipsizeStr = typeof ellipsizeStr !== 'undefined' ? ellipsizeStr : '...';
  2771. if (Array.isArray(text)) {
  2772. text.forEach(function (str, i) {
  2773. text[i] = jsPdfEllipsize(str, width, styles, ellipsizeStr);
  2774. });
  2775. return text;
  2776. }
  2777. if (width >= jsPdfGetStringWidth(text, styles)) {
  2778. return text;
  2779. }
  2780. while (width < jsPdfGetStringWidth(text + ellipsizeStr, styles)) {
  2781. if (text.length < 2) {
  2782. break;
  2783. }
  2784. text = text.substring(0, text.length - 1);
  2785. }
  2786. return text.trim() + ellipsizeStr;
  2787. }
  2788. function jsPdfGetStringWidth(text, styles) {
  2789. jsPdfApplyStyles(styles);
  2790. const w = jsPdfDoc.getStringUnitWidth(text);
  2791. return w * styles.fontSize;
  2792. }
  2793. function jsPdfExtend(defaults) {
  2794. const extended = {};
  2795. let prop;
  2796. for (prop in defaults) {
  2797. if (defaults.hasOwnProperty(prop)) {
  2798. extended[prop] = defaults[prop];
  2799. }
  2800. }
  2801. for (let i = 1; i < arguments.length; i++) {
  2802. const options = arguments[i]
  2803. for (prop in options) {
  2804. if (options.hasOwnProperty(prop)) {
  2805. extended[prop] = options[prop];
  2806. }
  2807. }
  2808. }
  2809. return extended;
  2810. }
  2811. // ----------------------------------------------------------------------------------------------------
  2812. // jsPDF-AutoTable 2.0.17 - END
  2813. // ----------------------------------------------------------------------------------------------------
  2814. if (typeof defaults.onTableExportEnd === 'function')
  2815. defaults.onTableExportEnd();
  2816. return this;
  2817. };
  2818. // See README.md for documentation of the options
  2819. // See examples.js for usage examples
  2820. function jsPdfDefaultOptions () {
  2821. return {
  2822. // Styling
  2823. theme: 'striped', // 'striped', 'grid' or 'plain'
  2824. styles: {},
  2825. headerStyles: {},
  2826. bodyStyles: {},
  2827. alternateRowStyles: {},
  2828. columnStyles: {},
  2829. // Properties
  2830. startY: false, // false indicates the margin.top value
  2831. margin: 40,
  2832. pageBreak: 'auto', // 'auto', 'avoid', 'always'
  2833. tableWidth: 'auto', // number, 'auto', 'wrap'
  2834. // Hooks
  2835. createdHeaderCell: function (cell, data) {},
  2836. createdCell: function (cell, data) {},
  2837. drawHeaderRow: function (row, data) {},
  2838. drawRow: function (row, data) {},
  2839. drawHeaderCell: function (cell, data) {},
  2840. drawCell: function (cell, data) {},
  2841. beforePageContent: function (data) {},
  2842. afterPageContent: function (data) {}
  2843. }
  2844. }
  2845. var jsPdfTableClass = /** class */ (function () {
  2846. function jsPdfTableClass() { /** constructor */
  2847. this.height = 0;
  2848. this.width = 0;
  2849. this.x = 0;
  2850. this.y = 0;
  2851. this.contentWidth = 0;
  2852. this.rows = [];
  2853. this.columns = [];
  2854. this.headerRow = null;
  2855. this.settings = {};
  2856. }
  2857. return jsPdfTableClass;
  2858. }());
  2859. var jsPdfRowClass = /** class */ (function () {
  2860. function jsPdfRowClass(raw) { /** constructor */
  2861. this.raw = raw || {};
  2862. this.index = 0;
  2863. this.styles = {};
  2864. this.cells = {};
  2865. this.height = 0;
  2866. this.y = 0;
  2867. }
  2868. return jsPdfRowClass;
  2869. }());
  2870. var jsPdfCellClass = /** class */ (function () {
  2871. function jsPdfCellClass(raw) { /** constructor */
  2872. this.raw = raw;
  2873. this.styles = {};
  2874. this.text = '';
  2875. this.contentWidth = 0;
  2876. this.textPos = {};
  2877. this.height = 0;
  2878. this.width = 0;
  2879. this.x = 0;
  2880. this.y = 0;
  2881. }
  2882. return jsPdfCellClass;
  2883. }());
  2884. var jsPdfColumnClass = /** class */ (function () {
  2885. function jsPdfColumnClass(dataKey) { /** constructor */
  2886. this.dataKey = dataKey;
  2887. this.options = {};
  2888. this.styles = {};
  2889. this.contentWidth = 0;
  2890. this.width = 0;
  2891. this.x = 0;
  2892. }
  2893. return jsPdfColumnClass;
  2894. }());
  2895. })(jQuery);