jspdf.js 588 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.jspdf = factory());
  5. }(this, (function () { 'use strict';
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  7. return typeof obj;
  8. } : function (obj) {
  9. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  10. };
  11. var asyncGenerator = function () {
  12. function AwaitValue(value) {
  13. this.value = value;
  14. }
  15. function AsyncGenerator(gen) {
  16. var front, back;
  17. function send(key, arg) {
  18. return new Promise(function (resolve, reject) {
  19. var request = {
  20. key: key,
  21. arg: arg,
  22. resolve: resolve,
  23. reject: reject,
  24. next: null
  25. };
  26. if (back) {
  27. back = back.next = request;
  28. } else {
  29. front = back = request;
  30. resume(key, arg);
  31. }
  32. });
  33. }
  34. function resume(key, arg) {
  35. try {
  36. var result = gen[key](arg);
  37. var value = result.value;
  38. if (value instanceof AwaitValue) {
  39. Promise.resolve(value.value).then(function (arg) {
  40. resume("next", arg);
  41. }, function (arg) {
  42. resume("throw", arg);
  43. });
  44. } else {
  45. settle(result.done ? "return" : "normal", result.value);
  46. }
  47. } catch (err) {
  48. settle("throw", err);
  49. }
  50. }
  51. function settle(type, value) {
  52. switch (type) {
  53. case "return":
  54. front.resolve({
  55. value: value,
  56. done: true
  57. });
  58. break;
  59. case "throw":
  60. front.reject(value);
  61. break;
  62. default:
  63. front.resolve({
  64. value: value,
  65. done: false
  66. });
  67. break;
  68. }
  69. front = front.next;
  70. if (front) {
  71. resume(front.key, front.arg);
  72. } else {
  73. back = null;
  74. }
  75. }
  76. this._invoke = send;
  77. if (typeof gen.return !== "function") {
  78. this.return = undefined;
  79. }
  80. }
  81. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  82. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  83. return this;
  84. };
  85. }
  86. AsyncGenerator.prototype.next = function (arg) {
  87. return this._invoke("next", arg);
  88. };
  89. AsyncGenerator.prototype.throw = function (arg) {
  90. return this._invoke("throw", arg);
  91. };
  92. AsyncGenerator.prototype.return = function (arg) {
  93. return this._invoke("return", arg);
  94. };
  95. return {
  96. wrap: function (fn) {
  97. return function () {
  98. return new AsyncGenerator(fn.apply(this, arguments));
  99. };
  100. },
  101. await: function (value) {
  102. return new AwaitValue(value);
  103. }
  104. };
  105. }();
  106. var get$1 = function get$1(object, property, receiver) {
  107. if (object === null) object = Function.prototype;
  108. var desc = Object.getOwnPropertyDescriptor(object, property);
  109. if (desc === undefined) {
  110. var parent = Object.getPrototypeOf(object);
  111. if (parent === null) {
  112. return undefined;
  113. } else {
  114. return get$1(parent, property, receiver);
  115. }
  116. } else if ("value" in desc) {
  117. return desc.value;
  118. } else {
  119. var getter = desc.get;
  120. if (getter === undefined) {
  121. return undefined;
  122. }
  123. return getter.call(receiver);
  124. }
  125. };
  126. var set$1 = function set$1(object, property, value, receiver) {
  127. var desc = Object.getOwnPropertyDescriptor(object, property);
  128. if (desc === undefined) {
  129. var parent = Object.getPrototypeOf(object);
  130. if (parent !== null) {
  131. set$1(parent, property, value, receiver);
  132. }
  133. } else if ("value" in desc && desc.writable) {
  134. desc.value = value;
  135. } else {
  136. var setter = desc.set;
  137. if (setter !== undefined) {
  138. setter.call(receiver, value);
  139. }
  140. }
  141. return value;
  142. };
  143. /** @preserve
  144. * jsPDF - PDF Document creation from JavaScript
  145. * Version 1.3.4 Built on 2017-04-10T14:14:44.483Z
  146. * CommitID cf4827d221
  147. *
  148. * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  149. * 2010 Aaron Spike, https://github.com/acspike
  150. * 2012 Willow Systems Corporation, willow-systems.com
  151. * 2012 Pablo Hess, https://github.com/pablohess
  152. * 2012 Florian Jenett, https://github.com/fjenett
  153. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  154. * 2013 Youssef Beddad, https://github.com/lifof
  155. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  156. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  157. * 2013 Jeremy Morel, https://github.com/jmorel
  158. * 2013 Christoph Hartmann, https://github.com/chris-rock
  159. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  160. * 2014 James Makes, https://github.com/dollaruw
  161. * 2014 Diego Casorran, https://github.com/diegocr
  162. * 2014 Steven Spungin, https://github.com/Flamenco
  163. * 2014 Kenneth Glassey, https://github.com/Gavvers
  164. *
  165. * Licensed under the MIT License
  166. *
  167. * Contributor(s):
  168. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  169. * kim3er, mfo, alnorth, Flamenco
  170. */
  171. /**
  172. * Creates new jsPDF document object instance.
  173. *
  174. * @class
  175. * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
  176. * @param unit Measurement unit to be used when coordinates are specified.
  177. * One of "pt" (points), "mm" (Default), "cm", "in"
  178. * @param format One of 'pageFormats' as shown below, default: a4
  179. * @returns {jsPDF}
  180. * @name jsPDF
  181. */
  182. var jsPDF = function (global) {
  183. 'use strict';
  184. var pdfVersion = '1.3',
  185. pageFormats = { // Size in pt of various paper formats
  186. 'a0': [2383.94, 3370.39],
  187. 'a1': [1683.78, 2383.94],
  188. 'a2': [1190.55, 1683.78],
  189. 'a3': [841.89, 1190.55],
  190. 'a4': [595.28, 841.89],
  191. 'a5': [419.53, 595.28],
  192. 'a6': [297.64, 419.53],
  193. 'a7': [209.76, 297.64],
  194. 'a8': [147.40, 209.76],
  195. 'a9': [104.88, 147.40],
  196. 'a10': [73.70, 104.88],
  197. 'b0': [2834.65, 4008.19],
  198. 'b1': [2004.09, 2834.65],
  199. 'b2': [1417.32, 2004.09],
  200. 'b3': [1000.63, 1417.32],
  201. 'b4': [708.66, 1000.63],
  202. 'b5': [498.90, 708.66],
  203. 'b6': [354.33, 498.90],
  204. 'b7': [249.45, 354.33],
  205. 'b8': [175.75, 249.45],
  206. 'b9': [124.72, 175.75],
  207. 'b10': [87.87, 124.72],
  208. 'c0': [2599.37, 3676.54],
  209. 'c1': [1836.85, 2599.37],
  210. 'c2': [1298.27, 1836.85],
  211. 'c3': [918.43, 1298.27],
  212. 'c4': [649.13, 918.43],
  213. 'c5': [459.21, 649.13],
  214. 'c6': [323.15, 459.21],
  215. 'c7': [229.61, 323.15],
  216. 'c8': [161.57, 229.61],
  217. 'c9': [113.39, 161.57],
  218. 'c10': [79.37, 113.39],
  219. 'dl': [311.81, 623.62],
  220. 'letter': [612, 792],
  221. 'government-letter': [576, 756],
  222. 'legal': [612, 1008],
  223. 'junior-legal': [576, 360],
  224. 'ledger': [1224, 792],
  225. 'tabloid': [792, 1224],
  226. 'credit-card': [153, 243]
  227. };
  228. /**
  229. * jsPDF's Internal PubSub Implementation.
  230. * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
  231. * Backward compatible rewritten on 2014 by
  232. * Diego Casorran, https://github.com/diegocr
  233. *
  234. * @class
  235. * @name PubSub
  236. * @ignore This should not be in the public docs.
  237. */
  238. function PubSub(context) {
  239. var topics = {};
  240. this.subscribe = function (topic, callback, once) {
  241. if (typeof callback !== 'function') {
  242. return false;
  243. }
  244. if (!topics.hasOwnProperty(topic)) {
  245. topics[topic] = {};
  246. }
  247. var id = Math.random().toString(35);
  248. topics[topic][id] = [callback, !!once];
  249. return id;
  250. };
  251. this.unsubscribe = function (token) {
  252. for (var topic in topics) {
  253. if (topics[topic][token]) {
  254. delete topics[topic][token];
  255. return true;
  256. }
  257. }
  258. return false;
  259. };
  260. this.publish = function (topic) {
  261. if (topics.hasOwnProperty(topic)) {
  262. var args = Array.prototype.slice.call(arguments, 1),
  263. idr = [];
  264. for (var id in topics[topic]) {
  265. var sub = topics[topic][id];
  266. try {
  267. sub[0].apply(context, args);
  268. } catch (ex) {
  269. if (global.console) {
  270. console.error('jsPDF PubSub Error', ex.message, ex);
  271. }
  272. }
  273. if (sub[1]) idr.push(id);
  274. }
  275. if (idr.length) idr.forEach(this.unsubscribe);
  276. }
  277. };
  278. }
  279. /**
  280. * @constructor
  281. * @private
  282. */
  283. function jsPDF(orientation, unit, format, compressPdf) {
  284. var options = {};
  285. if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
  286. options = orientation;
  287. orientation = options.orientation;
  288. unit = options.unit || unit;
  289. format = options.format || format;
  290. compressPdf = options.compress || options.compressPdf || compressPdf;
  291. }
  292. // Default options
  293. unit = unit || 'mm';
  294. format = format || 'a4';
  295. orientation = ('' + (orientation || 'P')).toLowerCase();
  296. var format_as_string = ('' + format).toLowerCase(),
  297. compress = !!compressPdf && typeof Uint8Array === 'function',
  298. textColor = options.textColor || '0 g',
  299. drawColor = options.drawColor || '0 G',
  300. activeFontSize = options.fontSize || 16,
  301. lineHeightProportion = options.lineHeight || 1.15,
  302. lineWidth = options.lineWidth || 0.200025,
  303. // 2mm
  304. objectNumber = 2,
  305. // 'n' Current object number
  306. outToPages = !1,
  307. // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  308. offsets = [],
  309. // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  310. fonts = {},
  311. // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  312. fontmap = {},
  313. // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  314. activeFontKey,
  315. // will be string representing the KEY of the font as combination of fontName + fontStyle
  316. k,
  317. // Scale factor
  318. tmp,
  319. page = 0,
  320. currentPage,
  321. pages = [],
  322. pagesContext = [],
  323. // same index as pages and pagedim
  324. pagedim = [],
  325. content = [],
  326. additionalObjects = [],
  327. lineCapID = 0,
  328. lineJoinID = 0,
  329. content_length = 0,
  330. pageWidth,
  331. pageHeight,
  332. pageMode,
  333. zoomMode,
  334. layoutMode,
  335. documentProperties = {
  336. 'title': '',
  337. 'subject': '',
  338. 'author': '',
  339. 'keywords': '',
  340. 'creator': ''
  341. },
  342. API = {},
  343. events = new PubSub(API),
  344. /////////////////////
  345. // Private functions
  346. /////////////////////
  347. f2 = function f2(number) {
  348. return number.toFixed(2); // Ie, %.2f
  349. },
  350. f3 = function f3(number) {
  351. return number.toFixed(3); // Ie, %.3f
  352. },
  353. padd2 = function padd2(number) {
  354. return ('0' + parseInt(number)).slice(-2);
  355. },
  356. out = function out(string) {
  357. if (outToPages) {
  358. /* set by beginPage */
  359. pages[currentPage].push(string);
  360. } else {
  361. // +1 for '\n' that will be used to join 'content'
  362. content_length += string.length + 1;
  363. content.push(string);
  364. }
  365. },
  366. newObject = function newObject() {
  367. // Begin a new object
  368. objectNumber++;
  369. offsets[objectNumber] = content_length;
  370. out(objectNumber + ' 0 obj');
  371. return objectNumber;
  372. },
  373. // Does not output the object until after the pages have been output.
  374. // Returns an object containing the objectId and content.
  375. // All pages have been added so the object ID can be estimated to start right after.
  376. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  377. newAdditionalObject = function newAdditionalObject() {
  378. var objId = pages.length * 2 + 1;
  379. objId += additionalObjects.length;
  380. var obj = {
  381. objId: objId,
  382. content: ''
  383. };
  384. additionalObjects.push(obj);
  385. return obj;
  386. },
  387. // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  388. newObjectDeferred = function newObjectDeferred() {
  389. objectNumber++;
  390. offsets[objectNumber] = function () {
  391. return content_length;
  392. };
  393. return objectNumber;
  394. },
  395. newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
  396. offsets[oid] = content_length;
  397. },
  398. putStream = function putStream(str) {
  399. out('stream');
  400. out(str);
  401. out('endstream');
  402. },
  403. putPages = function putPages() {
  404. var n,
  405. p,
  406. arr,
  407. i,
  408. deflater,
  409. adler32,
  410. adler32cs,
  411. wPt,
  412. hPt,
  413. pageObjectNumbers = [];
  414. adler32cs = global.adler32cs || jsPDF.adler32cs;
  415. if (compress && typeof adler32cs === 'undefined') {
  416. compress = false;
  417. }
  418. // outToPages = false as set in endDocument(). out() writes to content.
  419. for (n = 1; n <= page; n++) {
  420. pageObjectNumbers.push(newObject());
  421. wPt = (pageWidth = pagedim[n].width) * k;
  422. hPt = (pageHeight = pagedim[n].height) * k;
  423. out('<</Type /Page');
  424. out('/Parent 1 0 R');
  425. out('/Resources 2 0 R');
  426. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  427. // Added for annotation plugin
  428. events.publish('putPage', {
  429. pageNumber: n,
  430. page: pages[n]
  431. });
  432. out('/Contents ' + (objectNumber + 1) + ' 0 R');
  433. out('>>');
  434. out('endobj');
  435. // Page content
  436. p = pages[n].join('\n');
  437. newObject();
  438. if (compress) {
  439. arr = [];
  440. i = p.length;
  441. while (i--) {
  442. arr[i] = p.charCodeAt(i);
  443. }
  444. adler32 = adler32cs.from(p);
  445. deflater = new Deflater(6);
  446. deflater.append(new Uint8Array(arr));
  447. p = deflater.flush();
  448. arr = new Uint8Array(p.length + 6);
  449. arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
  450. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
  451. p = String.fromCharCode.apply(null, arr);
  452. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  453. } else {
  454. out('<</Length ' + p.length + '>>');
  455. }
  456. putStream(p);
  457. out('endobj');
  458. }
  459. offsets[1] = content_length;
  460. out('1 0 obj');
  461. out('<</Type /Pages');
  462. var kids = '/Kids [';
  463. for (i = 0; i < page; i++) {
  464. kids += pageObjectNumbers[i] + ' 0 R ';
  465. }
  466. out(kids + ']');
  467. out('/Count ' + page);
  468. out('>>');
  469. out('endobj');
  470. events.publish('postPutPages');
  471. },
  472. putFont = function putFont(font) {
  473. font.objectNumber = newObject();
  474. out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
  475. if (typeof font.encoding === 'string') {
  476. out('/Encoding/' + font.encoding);
  477. }
  478. out('/Subtype/Type1>>');
  479. out('endobj');
  480. },
  481. putFonts = function putFonts() {
  482. for (var fontKey in fonts) {
  483. if (fonts.hasOwnProperty(fontKey)) {
  484. putFont(fonts[fontKey]);
  485. }
  486. }
  487. },
  488. putXobjectDict = function putXobjectDict() {
  489. // Loop through images, or other data objects
  490. events.publish('putXobjectDict');
  491. },
  492. putResourceDictionary = function putResourceDictionary() {
  493. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  494. out('/Font <<');
  495. // Do this for each font, the '1' bit is the index of the font
  496. for (var fontKey in fonts) {
  497. if (fonts.hasOwnProperty(fontKey)) {
  498. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  499. }
  500. }
  501. out('>>');
  502. out('/XObject <<');
  503. putXobjectDict();
  504. out('>>');
  505. },
  506. putResources = function putResources() {
  507. putFonts();
  508. events.publish('putResources');
  509. // Resource dictionary
  510. offsets[2] = content_length;
  511. out('2 0 obj');
  512. out('<<');
  513. putResourceDictionary();
  514. out('>>');
  515. out('endobj');
  516. events.publish('postPutResources');
  517. },
  518. putAdditionalObjects = function putAdditionalObjects() {
  519. events.publish('putAdditionalObjects');
  520. for (var i = 0; i < additionalObjects.length; i++) {
  521. var obj = additionalObjects[i];
  522. offsets[obj.objId] = content_length;
  523. out(obj.objId + ' 0 obj');
  524. out(obj.content);
  525. out('endobj');
  526. }
  527. objectNumber += additionalObjects.length;
  528. events.publish('postPutAdditionalObjects');
  529. },
  530. addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  531. // this is mapping structure for quick font key lookup.
  532. // returns the KEY of the font (ex: "F1") for a given
  533. // pair of font name and type (ex: "Arial". "Italic")
  534. if (!fontmap.hasOwnProperty(fontName)) {
  535. fontmap[fontName] = {};
  536. }
  537. fontmap[fontName][fontStyle] = fontKey;
  538. },
  539. /**
  540. * FontObject describes a particular font as member of an instnace of jsPDF
  541. *
  542. * It's a collection of properties like 'id' (to be used in PDF stream),
  543. * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  544. *
  545. * @class
  546. * @public
  547. * @property id {String} PDF-document-instance-specific label assinged to the font.
  548. * @property PostScriptName {String} PDF specification full name for the font
  549. * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  550. * @name FontObject
  551. * @ignore This should not be in the public docs.
  552. */
  553. addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
  554. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  555. // This is FontObject
  556. font = fonts[fontKey] = {
  557. 'id': fontKey,
  558. 'PostScriptName': PostScriptName,
  559. 'fontName': fontName,
  560. 'fontStyle': fontStyle,
  561. 'encoding': encoding,
  562. 'metadata': {}
  563. };
  564. addToFontDictionary(fontKey, fontName, fontStyle);
  565. events.publish('addFont', font);
  566. return fontKey;
  567. },
  568. addFonts = function addFonts() {
  569. var HELVETICA = "helvetica",
  570. TIMES = "times",
  571. COURIER = "courier",
  572. NORMAL = "normal",
  573. BOLD = "bold",
  574. ITALIC = "italic",
  575. BOLD_ITALIC = "bolditalic",
  576. encoding = 'StandardEncoding',
  577. ZAPF = "zapfdingbats",
  578. standardFonts = [['Helvetica', HELVETICA, NORMAL], ['Helvetica-Bold', HELVETICA, BOLD], ['Helvetica-Oblique', HELVETICA, ITALIC], ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC], ['Courier', COURIER, NORMAL], ['Courier-Bold', COURIER, BOLD], ['Courier-Oblique', COURIER, ITALIC], ['Courier-BoldOblique', COURIER, BOLD_ITALIC], ['Times-Roman', TIMES, NORMAL], ['Times-Bold', TIMES, BOLD], ['Times-Italic', TIMES, ITALIC], ['Times-BoldItalic', TIMES, BOLD_ITALIC], ['ZapfDingbats', ZAPF]];
  579. for (var i = 0, l = standardFonts.length; i < l; i++) {
  580. var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
  581. // adding aliases for standard fonts, this time matching the capitalization
  582. var parts = standardFonts[i][0].split('-');
  583. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  584. }
  585. events.publish('addFonts', {
  586. fonts: fonts,
  587. dictionary: fontmap
  588. });
  589. },
  590. SAFE = function __safeCall(fn) {
  591. fn.foo = function __safeCallWrapper() {
  592. try {
  593. return fn.apply(this, arguments);
  594. } catch (e) {
  595. var stack = e.stack || '';
  596. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  597. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  598. if (global.console) {
  599. global.console.error(m, e);
  600. if (global.alert) alert(m);
  601. } else {
  602. throw new Error(m);
  603. }
  604. }
  605. };
  606. fn.foo.bar = fn;
  607. return fn.foo;
  608. },
  609. to8bitStream = function to8bitStream(text, flags) {
  610. /**
  611. * PDF 1.3 spec:
  612. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  613. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  614. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  615. * to be a meaningful beginning of a word or phrase.) The remainder of the
  616. * string consists of Unicode character codes, according to the UTF-16 encoding
  617. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  618. * are represented as 2 bytes per character, with the high-order byte appearing first
  619. * in the string."
  620. *
  621. * In other words, if there are chars in a string with char code above 255, we
  622. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  623. *
  624. * HOWEVER!
  625. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  626. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  627. *
  628. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  629. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  630. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  631. * code page. There, however, all characters in the stream are treated as GIDs,
  632. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  633. * that is tied to a font).
  634. *
  635. * To signal this "special" PDFEscape / to8bitStream handling mode,
  636. * API.text() function sets (unless you overwrite it with manual values
  637. * given to API.text(.., flags) )
  638. * flags.autoencode = true
  639. * flags.noBOM = true
  640. *
  641. * ===================================================================================
  642. * `flags` properties relied upon:
  643. * .sourceEncoding = string with encoding label.
  644. * "Unicode" by default. = encoding of the incoming text.
  645. * pass some non-existing encoding name
  646. * (ex: 'Do not touch my strings! I know what I am doing.')
  647. * to make encoding code skip the encoding step.
  648. * .outputEncoding = Either valid PDF encoding name
  649. * (must be supported by jsPDF font metrics, otherwise no encoding)
  650. * or a JS object, where key = sourceCharCode, value = outputCharCode
  651. * missing keys will be treated as: sourceCharCode === outputCharCode
  652. * .noBOM
  653. * See comment higher above for explanation for why this is important
  654. * .autoencode
  655. * See comment higher above for explanation for why this is important
  656. */
  657. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  658. flags = flags || {};
  659. sourceEncoding = flags.sourceEncoding || 'Unicode';
  660. outputEncoding = flags.outputEncoding;
  661. // This 'encoding' section relies on font metrics format
  662. // attached to font objects by, among others,
  663. // "Willow Systems' standard_font_metrics plugin"
  664. // see jspdf.plugin.standard_font_metrics.js for format
  665. // of the font.metadata.encoding Object.
  666. // It should be something like
  667. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  668. // .widths = {0:width, code:width, ..., 'fof':divisor}
  669. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  670. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  671. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  672. // each font has default encoding. Some have it clearly defined.
  673. if (!outputEncoding && fonts[activeFontKey].encoding) {
  674. outputEncoding = fonts[activeFontKey].encoding;
  675. }
  676. // Hmmm, the above did not work? Let's try again, in different place.
  677. if (!outputEncoding && encodingBlock.codePages) {
  678. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  679. }
  680. if (typeof outputEncoding === 'string') {
  681. outputEncoding = encodingBlock[outputEncoding];
  682. }
  683. // we want output encoding to be a JS Object, where
  684. // key = sourceEncoding's character code and
  685. // value = outputEncoding's character code.
  686. if (outputEncoding) {
  687. isUnicode = false;
  688. newtext = [];
  689. for (i = 0, l = text.length; i < l; i++) {
  690. ch = outputEncoding[text.charCodeAt(i)];
  691. if (ch) {
  692. newtext.push(String.fromCharCode(ch));
  693. } else {
  694. newtext.push(text[i]);
  695. }
  696. // since we are looping over chars anyway, might as well
  697. // check for residual unicodeness
  698. if (newtext[i].charCodeAt(0) >> 8) {
  699. /* more than 255 */
  700. isUnicode = true;
  701. }
  702. }
  703. text = newtext.join('');
  704. }
  705. }
  706. i = text.length;
  707. // isUnicode may be set to false above. Hence the triple-equal to undefined
  708. while (isUnicode === undefined && i !== 0) {
  709. if (text.charCodeAt(i - 1) >> 8) {
  710. /* more than 255 */
  711. isUnicode = true;
  712. }
  713. i--;
  714. }
  715. if (!isUnicode) {
  716. return text;
  717. }
  718. newtext = flags.noBOM ? [] : [254, 255];
  719. for (i = 0, l = text.length; i < l; i++) {
  720. ch = text.charCodeAt(i);
  721. bch = ch >> 8; // divide by 256
  722. if (bch >> 8) {
  723. /* something left after dividing by 256 second time */
  724. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  725. }
  726. newtext.push(bch);
  727. newtext.push(ch - (bch << 8));
  728. }
  729. return String.fromCharCode.apply(undefined, newtext);
  730. },
  731. pdfEscape = function pdfEscape(text, flags) {
  732. /**
  733. * Replace '/', '(', and ')' with pdf-safe versions
  734. *
  735. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  736. * we also need to reference a unicode font and embed it - royal pain in the rear.
  737. *
  738. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  739. * which JavaScript Strings are happy to provide. So, while we still cannot display
  740. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  741. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  742. * is still parseable.
  743. * This will allow immediate support for unicode in document properties strings.
  744. */
  745. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  746. },
  747. putInfo = function putInfo() {
  748. out('/Producer (jsPDF ' + jsPDF.version + ')');
  749. for (var key in documentProperties) {
  750. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  751. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  752. }
  753. }
  754. var created = new Date(),
  755. tzoffset = created.getTimezoneOffset(),
  756. tzsign = tzoffset < 0 ? '+' : '-',
  757. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  758. tzmin = Math.abs(tzoffset % 60),
  759. tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  760. out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
  761. },
  762. putCatalog = function putCatalog() {
  763. out('/Type /Catalog');
  764. out('/Pages 1 0 R');
  765. // PDF13ref Section 7.2.1
  766. if (!zoomMode) zoomMode = 'fullwidth';
  767. switch (zoomMode) {
  768. case 'fullwidth':
  769. out('/OpenAction [3 0 R /FitH null]');
  770. break;
  771. case 'fullheight':
  772. out('/OpenAction [3 0 R /FitV null]');
  773. break;
  774. case 'fullpage':
  775. out('/OpenAction [3 0 R /Fit]');
  776. break;
  777. case 'original':
  778. out('/OpenAction [3 0 R /XYZ null null 1]');
  779. break;
  780. default:
  781. var pcn = '' + zoomMode;
  782. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  783. if (typeof zoomMode === 'number') {
  784. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  785. }
  786. }
  787. if (!layoutMode) layoutMode = 'continuous';
  788. switch (layoutMode) {
  789. case 'continuous':
  790. out('/PageLayout /OneColumn');
  791. break;
  792. case 'single':
  793. out('/PageLayout /SinglePage');
  794. break;
  795. case 'two':
  796. case 'twoleft':
  797. out('/PageLayout /TwoColumnLeft');
  798. break;
  799. case 'tworight':
  800. out('/PageLayout /TwoColumnRight');
  801. break;
  802. }
  803. if (pageMode) {
  804. /**
  805. * A name object specifying how the document should be displayed when opened:
  806. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  807. * UseOutlines : Document outline visible
  808. * UseThumbs : Thumbnail images visible
  809. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  810. */
  811. out('/PageMode /' + pageMode);
  812. }
  813. events.publish('putCatalog');
  814. },
  815. putTrailer = function putTrailer() {
  816. out('/Size ' + (objectNumber + 1));
  817. out('/Root ' + objectNumber + ' 0 R');
  818. out('/Info ' + (objectNumber - 1) + ' 0 R');
  819. },
  820. beginPage = function beginPage(width, height) {
  821. // Dimensions are stored as user units and converted to points on output
  822. var orientation = typeof height === 'string' && height.toLowerCase();
  823. if (typeof width === 'string') {
  824. var format = width.toLowerCase();
  825. if (pageFormats.hasOwnProperty(format)) {
  826. width = pageFormats[format][0] / k;
  827. height = pageFormats[format][1] / k;
  828. }
  829. }
  830. if (Array.isArray(width)) {
  831. height = width[1];
  832. width = width[0];
  833. }
  834. if (orientation) {
  835. switch (orientation.substr(0, 1)) {
  836. case 'l':
  837. if (height > width) orientation = 's';
  838. break;
  839. case 'p':
  840. if (width > height) orientation = 's';
  841. break;
  842. }
  843. if (orientation === 's') {
  844. tmp = width;
  845. width = height;
  846. height = tmp;
  847. }
  848. }
  849. outToPages = true;
  850. pages[++page] = [];
  851. pagedim[page] = {
  852. width: Number(width) || pageWidth,
  853. height: Number(height) || pageHeight
  854. };
  855. pagesContext[page] = {};
  856. _setPage(page);
  857. },
  858. _addPage = function _addPage() {
  859. beginPage.apply(this, arguments);
  860. // Set line width
  861. out(f2(lineWidth * k) + ' w');
  862. // Set draw color
  863. out(drawColor);
  864. // resurrecting non-default line caps, joins
  865. if (lineCapID !== 0) {
  866. out(lineCapID + ' J');
  867. }
  868. if (lineJoinID !== 0) {
  869. out(lineJoinID + ' j');
  870. }
  871. events.publish('addPage', {
  872. pageNumber: page
  873. });
  874. },
  875. _deletePage = function _deletePage(n) {
  876. if (n > 0 && n <= page) {
  877. pages.splice(n, 1);
  878. pagedim.splice(n, 1);
  879. page--;
  880. if (currentPage > page) {
  881. currentPage = page;
  882. }
  883. this.setPage(currentPage);
  884. }
  885. },
  886. _setPage = function _setPage(n) {
  887. if (n > 0 && n <= page) {
  888. currentPage = n;
  889. pageWidth = pagedim[n].width;
  890. pageHeight = pagedim[n].height;
  891. }
  892. },
  893. /**
  894. * Returns a document-specific font key - a label assigned to a
  895. * font name + font type combination at the time the font was added
  896. * to the font inventory.
  897. *
  898. * Font key is used as label for the desired font for a block of text
  899. * to be added to the PDF document stream.
  900. * @private
  901. * @function
  902. * @param fontName {String} can be undefined on "falthy" to indicate "use current"
  903. * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  904. * @returns {String} Font key.
  905. */
  906. _getFont = function _getFont(fontName, fontStyle) {
  907. var key;
  908. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  909. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  910. if (fontName !== undefined) {
  911. fontName = fontName.toLowerCase();
  912. }
  913. switch (fontName) {
  914. case 'sans-serif':
  915. case 'verdana':
  916. case 'arial':
  917. case 'helvetica':
  918. fontName = 'helvetica';
  919. break;
  920. case 'fixed':
  921. case 'monospace':
  922. case 'terminal':
  923. case 'courier':
  924. fontName = 'courier';
  925. break;
  926. case 'serif':
  927. case 'cursive':
  928. case 'fantasy':
  929. default:
  930. fontName = 'times';
  931. break;
  932. }
  933. try {
  934. // get a string like 'F3' - the KEY corresponding tot he font + type combination.
  935. key = fontmap[fontName][fontStyle];
  936. } catch (e) {}
  937. if (!key) {
  938. //throw new Error("Unable to look up font label for font '" + fontName + "', '"
  939. //+ fontStyle + "'. Refer to getFontList() for available fonts.");
  940. key = fontmap['times'][fontStyle];
  941. if (key == null) {
  942. key = fontmap['times']['normal'];
  943. }
  944. }
  945. return key;
  946. },
  947. buildDocument = function buildDocument() {
  948. outToPages = false; // switches out() to content
  949. objectNumber = 2;
  950. content_length = 0;
  951. content = [];
  952. offsets = [];
  953. additionalObjects = [];
  954. // Added for AcroForm
  955. events.publish('buildDocument');
  956. // putHeader()
  957. out('%PDF-' + pdfVersion);
  958. putPages();
  959. // Must happen after putPages
  960. // Modifies current object Id
  961. putAdditionalObjects();
  962. putResources();
  963. // Info
  964. newObject();
  965. out('<<');
  966. putInfo();
  967. out('>>');
  968. out('endobj');
  969. // Catalog
  970. newObject();
  971. out('<<');
  972. putCatalog();
  973. out('>>');
  974. out('endobj');
  975. // Cross-ref
  976. var o = content_length,
  977. i,
  978. p = "0000000000";
  979. out('xref');
  980. out('0 ' + (objectNumber + 1));
  981. out(p + ' 65535 f ');
  982. for (i = 1; i <= objectNumber; i++) {
  983. var offset = offsets[i];
  984. if (typeof offset === 'function') {
  985. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  986. } else {
  987. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  988. }
  989. }
  990. // Trailer
  991. out('trailer');
  992. out('<<');
  993. putTrailer();
  994. out('>>');
  995. out('startxref');
  996. out('' + o);
  997. out('%%EOF');
  998. outToPages = true;
  999. return content.join('\n');
  1000. },
  1001. getStyle = function getStyle(style) {
  1002. // see path-painting operators in PDF spec
  1003. var op = 'S'; // stroke
  1004. if (style === 'F') {
  1005. op = 'f'; // fill
  1006. } else if (style === 'FD' || style === 'DF') {
  1007. op = 'B'; // both
  1008. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  1009. /*
  1010. Allow direct use of these PDF path-painting operators:
  1011. - f fill using nonzero winding number rule
  1012. - f* fill using even-odd rule
  1013. - B fill then stroke with fill using non-zero winding number rule
  1014. - B* fill then stroke with fill using even-odd rule
  1015. */
  1016. op = style;
  1017. }
  1018. return op;
  1019. },
  1020. getArrayBuffer = function getArrayBuffer() {
  1021. var data = buildDocument(),
  1022. len = data.length,
  1023. ab = new ArrayBuffer(len),
  1024. u8 = new Uint8Array(ab);
  1025. while (len--) {
  1026. u8[len] = data.charCodeAt(len);
  1027. }return ab;
  1028. },
  1029. getBlob = function getBlob() {
  1030. return new Blob([getArrayBuffer()], {
  1031. type: "application/pdf"
  1032. });
  1033. },
  1034. /**
  1035. * Generates the PDF document.
  1036. *
  1037. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1038. *
  1039. * @param {String} type A string identifying one of the possible output types.
  1040. * @param {Object} options An object providing some additional signalling to PDF generator.
  1041. * @function
  1042. * @returns {jsPDF}
  1043. * @methodOf jsPDF#
  1044. * @name output
  1045. */
  1046. _output = SAFE(function (type, options) {
  1047. var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
  1048. switch (type) {
  1049. case undefined:
  1050. return buildDocument();
  1051. case 'save':
  1052. if (navigator.getUserMedia) {
  1053. if (global.URL === undefined || global.URL.createObjectURL === undefined) {
  1054. return API.output('dataurlnewwindow');
  1055. }
  1056. }
  1057. saveAs(getBlob(), options);
  1058. if (typeof saveAs.unload === 'function') {
  1059. if (global.setTimeout) {
  1060. setTimeout(saveAs.unload, 911);
  1061. }
  1062. }
  1063. break;
  1064. case 'arraybuffer':
  1065. return getArrayBuffer();
  1066. case 'blob':
  1067. return getBlob();
  1068. case 'bloburi':
  1069. case 'bloburl':
  1070. // User is responsible of calling revokeObjectURL
  1071. return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
  1072. case 'datauristring':
  1073. case 'dataurlstring':
  1074. return datauri;
  1075. case 'dataurlnewwindow':
  1076. var nW = global.open(datauri);
  1077. if (nW || typeof safari === "undefined") return nW;
  1078. /* pass through */
  1079. case 'datauri':
  1080. case 'dataurl':
  1081. return global.document.location.href = datauri;
  1082. default:
  1083. throw new Error('Output type "' + type + '" is not supported.');
  1084. }
  1085. // @TODO: Add different output options
  1086. });
  1087. switch (unit) {
  1088. case 'pt':
  1089. k = 1;
  1090. break;
  1091. case 'mm':
  1092. k = 72 / 25.4000508;
  1093. break;
  1094. case 'cm':
  1095. k = 72 / 2.54000508;
  1096. break;
  1097. case 'in':
  1098. k = 72;
  1099. break;
  1100. case 'px':
  1101. k = 96 / 72;
  1102. break;
  1103. case 'pc':
  1104. k = 12;
  1105. break;
  1106. case 'em':
  1107. k = 12;
  1108. break;
  1109. case 'ex':
  1110. k = 6;
  1111. break;
  1112. default:
  1113. throw 'Invalid unit: ' + unit;
  1114. }
  1115. //---------------------------------------
  1116. // Public API
  1117. /**
  1118. * Object exposing internal API to plugins
  1119. * @public
  1120. */
  1121. API.internal = {
  1122. 'pdfEscape': pdfEscape,
  1123. 'getStyle': getStyle,
  1124. /**
  1125. * Returns {FontObject} describing a particular font.
  1126. * @public
  1127. * @function
  1128. * @param fontName {String} (Optional) Font's family name
  1129. * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  1130. * @returns {FontObject}
  1131. */
  1132. 'getFont': function getFont() {
  1133. return fonts[_getFont.apply(API, arguments)];
  1134. },
  1135. 'getFontSize': function getFontSize() {
  1136. return activeFontSize;
  1137. },
  1138. 'getLineHeight': function getLineHeight() {
  1139. return activeFontSize * lineHeightProportion;
  1140. },
  1141. 'write': function write(string1 /*, string2, string3, etc */) {
  1142. out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
  1143. },
  1144. 'getCoordinateString': function getCoordinateString(value) {
  1145. return f2(value * k);
  1146. },
  1147. 'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
  1148. return f2((pageHeight - value) * k);
  1149. },
  1150. 'collections': {},
  1151. 'newObject': newObject,
  1152. 'newAdditionalObject': newAdditionalObject,
  1153. 'newObjectDeferred': newObjectDeferred,
  1154. 'newObjectDeferredBegin': newObjectDeferredBegin,
  1155. 'putStream': putStream,
  1156. 'events': events,
  1157. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  1158. // units of measurement.
  1159. // scaleFactor is set at initialization of the document and calculated against the stated
  1160. // default measurement units for the document.
  1161. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  1162. // through multiplication.
  1163. 'scaleFactor': k,
  1164. 'pageSize': {
  1165. get width() {
  1166. return pageWidth;
  1167. },
  1168. get height() {
  1169. return pageHeight;
  1170. }
  1171. },
  1172. 'output': function output(type, options) {
  1173. return _output(type, options);
  1174. },
  1175. 'getNumberOfPages': function getNumberOfPages() {
  1176. return pages.length - 1;
  1177. },
  1178. 'pages': pages,
  1179. 'out': out,
  1180. 'f2': f2,
  1181. 'getPageInfo': function getPageInfo(pageNumberOneBased) {
  1182. var objId = (pageNumberOneBased - 1) * 2 + 3;
  1183. return {
  1184. objId: objId,
  1185. pageNumber: pageNumberOneBased,
  1186. pageContext: pagesContext[pageNumberOneBased]
  1187. };
  1188. },
  1189. 'getCurrentPageInfo': function getCurrentPageInfo() {
  1190. var objId = (currentPage - 1) * 2 + 3;
  1191. return {
  1192. objId: objId,
  1193. pageNumber: currentPage,
  1194. pageContext: pagesContext[currentPage]
  1195. };
  1196. },
  1197. 'getPDFVersion': function getPDFVersion() {
  1198. return pdfVersion;
  1199. }
  1200. };
  1201. /**
  1202. * Adds (and transfers the focus to) new page to the PDF document.
  1203. * @function
  1204. * @returns {jsPDF}
  1205. *
  1206. * @methodOf jsPDF#
  1207. * @name addPage
  1208. */
  1209. API.addPage = function () {
  1210. _addPage.apply(this, arguments);
  1211. return this;
  1212. };
  1213. /**
  1214. * Adds (and transfers the focus to) new page to the PDF document.
  1215. * @function
  1216. * @returns {jsPDF}
  1217. *
  1218. * @methodOf jsPDF#
  1219. * @name setPage
  1220. * @param {Number} page Switch the active page to the page number specified
  1221. * @example
  1222. * doc = jsPDF()
  1223. * doc.addPage()
  1224. * doc.addPage()
  1225. * doc.text('I am on page 3', 10, 10)
  1226. * doc.setPage(1)
  1227. * doc.text('I am on page 1', 10, 10)
  1228. */
  1229. API.setPage = function () {
  1230. _setPage.apply(this, arguments);
  1231. return this;
  1232. };
  1233. API.insertPage = function (beforePage) {
  1234. this.addPage();
  1235. this.movePage(currentPage, beforePage);
  1236. return this;
  1237. };
  1238. API.movePage = function (targetPage, beforePage) {
  1239. if (targetPage > beforePage) {
  1240. var tmpPages = pages[targetPage];
  1241. var tmpPagedim = pagedim[targetPage];
  1242. var tmpPagesContext = pagesContext[targetPage];
  1243. for (var i = targetPage; i > beforePage; i--) {
  1244. pages[i] = pages[i - 1];
  1245. pagedim[i] = pagedim[i - 1];
  1246. pagesContext[i] = pagesContext[i - 1];
  1247. }
  1248. pages[beforePage] = tmpPages;
  1249. pagedim[beforePage] = tmpPagedim;
  1250. pagesContext[beforePage] = tmpPagesContext;
  1251. this.setPage(beforePage);
  1252. } else if (targetPage < beforePage) {
  1253. var tmpPages = pages[targetPage];
  1254. var tmpPagedim = pagedim[targetPage];
  1255. var tmpPagesContext = pagesContext[targetPage];
  1256. for (var i = targetPage; i < beforePage; i++) {
  1257. pages[i] = pages[i + 1];
  1258. pagedim[i] = pagedim[i + 1];
  1259. pagesContext[i] = pagesContext[i + 1];
  1260. }
  1261. pages[beforePage] = tmpPages;
  1262. pagedim[beforePage] = tmpPagedim;
  1263. pagesContext[beforePage] = tmpPagesContext;
  1264. this.setPage(beforePage);
  1265. }
  1266. return this;
  1267. };
  1268. API.deletePage = function () {
  1269. _deletePage.apply(this, arguments);
  1270. return this;
  1271. };
  1272. /**
  1273. * Set the display mode options of the page like zoom and layout.
  1274. *
  1275. * @param {integer|String} zoom You can pass an integer or percentage as
  1276. * a string. 2 will scale the document up 2x, '200%' will scale up by the
  1277. * same amount. You can also set it to 'fullwidth', 'fullheight',
  1278. * 'fullpage', or 'original'.
  1279. *
  1280. * Only certain PDF readers support this, such as Adobe Acrobat
  1281. *
  1282. * @param {String} layout Layout mode can be: 'continuous' - this is the
  1283. * default continuous scroll. 'single' - the single page mode only shows one
  1284. * page at a time. 'twoleft' - two column left mode, first page starts on
  1285. * the left, and 'tworight' - pages are laid out in two columns, with the
  1286. * first page on the right. This would be used for books.
  1287. * @param {String} pmode 'UseOutlines' - it shows the
  1288. * outline of the document on the left. 'UseThumbs' - shows thumbnails along
  1289. * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
  1290. *
  1291. * @function
  1292. * @returns {jsPDF}
  1293. * @name setDisplayMode
  1294. */
  1295. API.setDisplayMode = function (zoom, layout, pmode) {
  1296. zoomMode = zoom;
  1297. layoutMode = layout;
  1298. pageMode = pmode;
  1299. var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
  1300. if (validPageModes.indexOf(pmode) == -1) {
  1301. throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
  1302. }
  1303. return this;
  1304. },
  1305. /**
  1306. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1307. *
  1308. * @function
  1309. * @param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
  1310. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1311. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1312. * @param {Object} flags Collection of settings signalling how the text must be encoded. Defaults are sane. If you think you want to pass some flags, you likely can read the source.
  1313. * @returns {jsPDF}
  1314. * @methodOf jsPDF#
  1315. * @name text
  1316. */
  1317. API.text = function (text, x, y, flags, angle, align) {
  1318. /**
  1319. * Inserts something like this into PDF
  1320. * BT
  1321. * /F1 16 Tf % Font name + size
  1322. * 16 TL % How many units down for next line in multiline text
  1323. * 0 g % color
  1324. * 28.35 813.54 Td % position
  1325. * (line one) Tj
  1326. * T* (line two) Tj
  1327. * T* (line three) Tj
  1328. * ET
  1329. */
  1330. function ESC(s) {
  1331. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1332. return pdfEscape(s, flags);
  1333. }
  1334. // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1335. // in effort to make all calls have similar signature like
  1336. // function(data, coordinates... , miscellaneous)
  1337. // this method had its args flipped.
  1338. // code below allows backward compatibility with old arg order.
  1339. if (typeof text === 'number') {
  1340. tmp = y;
  1341. y = x;
  1342. x = text;
  1343. text = tmp;
  1344. }
  1345. // If there are any newlines in text, we assume
  1346. // the user wanted to print multiple lines, so break the
  1347. // text up into an array. If the text is already an array,
  1348. // we assume the user knows what they are doing.
  1349. // Convert text into an array anyway to simplify
  1350. // later code.
  1351. if (typeof text === 'string') {
  1352. if (text.match(/[\n\r]/)) {
  1353. text = text.split(/\r\n|\r|\n/g);
  1354. } else {
  1355. text = [text];
  1356. }
  1357. }
  1358. if (typeof angle === 'string') {
  1359. align = angle;
  1360. angle = null;
  1361. }
  1362. if (typeof flags === 'string') {
  1363. align = flags;
  1364. flags = null;
  1365. }
  1366. if (typeof flags === 'number') {
  1367. angle = flags;
  1368. flags = null;
  1369. }
  1370. var xtra = '',
  1371. mode = 'Td',
  1372. todo;
  1373. if (angle) {
  1374. angle *= Math.PI / 180;
  1375. var c = Math.cos(angle),
  1376. s = Math.sin(angle);
  1377. xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ");
  1378. mode = 'Tm';
  1379. }
  1380. flags = flags || {};
  1381. if (!('noBOM' in flags)) flags.noBOM = true;
  1382. if (!('autoencode' in flags)) flags.autoencode = true;
  1383. var strokeOption = '';
  1384. var pageContext = this.internal.getCurrentPageInfo().pageContext;
  1385. if (true === flags.stroke) {
  1386. if (pageContext.lastTextWasStroke !== true) {
  1387. strokeOption = '1 Tr\n';
  1388. pageContext.lastTextWasStroke = true;
  1389. }
  1390. } else {
  1391. if (pageContext.lastTextWasStroke) {
  1392. strokeOption = '0 Tr\n';
  1393. }
  1394. pageContext.lastTextWasStroke = false;
  1395. }
  1396. if (typeof this._runningPageHeight === 'undefined') {
  1397. this._runningPageHeight = 0;
  1398. }
  1399. if (typeof text === 'string') {
  1400. text = ESC(text);
  1401. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1402. // we don't want to destroy original text array, so cloning it
  1403. var sa = text.concat(),
  1404. da = [],
  1405. len = sa.length;
  1406. // we do array.join('text that must not be PDFescaped")
  1407. // thus, pdfEscape each component separately
  1408. while (len--) {
  1409. da.push(ESC(sa.shift()));
  1410. }
  1411. var linesLeft = Math.ceil((pageHeight - y - this._runningPageHeight) * k / (activeFontSize * lineHeightProportion));
  1412. if (0 <= linesLeft && linesLeft < da.length + 1) {
  1413. //todo = da.splice(linesLeft-1);
  1414. }
  1415. if (align) {
  1416. var left,
  1417. prevX,
  1418. maxLineLength,
  1419. leading = activeFontSize * lineHeightProportion,
  1420. lineWidths = text.map(function (v) {
  1421. return this.getStringUnitWidth(v) * activeFontSize / k;
  1422. }, this);
  1423. maxLineLength = Math.max.apply(Math, lineWidths);
  1424. // The first line uses the "main" Td setting,
  1425. // and the subsequent lines are offset by the
  1426. // previous line's x coordinate.
  1427. if (align === "center") {
  1428. // The passed in x coordinate defines
  1429. // the center point.
  1430. left = x - maxLineLength / 2;
  1431. x -= lineWidths[0] / 2;
  1432. } else if (align === "right") {
  1433. // The passed in x coordinate defines the
  1434. // rightmost point of the text.
  1435. left = x - maxLineLength;
  1436. x -= lineWidths[0];
  1437. } else {
  1438. throw new Error('Unrecognized alignment option, use "center" or "right".');
  1439. }
  1440. prevX = x;
  1441. text = da[0];
  1442. for (var i = 1, len = da.length; i < len; i++) {
  1443. var delta = maxLineLength - lineWidths[i];
  1444. if (align === "center") delta /= 2;
  1445. // T* = x-offset leading Td ( text )
  1446. text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
  1447. prevX = left + delta;
  1448. }
  1449. } else {
  1450. text = da.join(") Tj\nT* (");
  1451. }
  1452. } else {
  1453. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1454. }
  1455. // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
  1456. // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
  1457. // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
  1458. // Thus, there is NO useful, *reliable* concept of "default" font for a page.
  1459. // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
  1460. // - readers dealing smartly with brokenness of jsPDF's markup.
  1461. var curY;
  1462. if (todo) {
  1463. //this.addPage();
  1464. //this._runningPageHeight += y - (activeFontSize * 1.7 / k);
  1465. //curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1466. } else {
  1467. curY = f2((pageHeight - y) * k);
  1468. }
  1469. //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
  1470. // if (curY < 0){
  1471. // console.log('auto page break');
  1472. // this.addPage();
  1473. // this._runningPageHeight = y - (activeFontSize * 1.7 / k);
  1474. // curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1475. // }
  1476. out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1477. activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
  1478. strokeOption + // stroke option
  1479. textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
  1480. if (todo) {
  1481. //this.text( todo, x, activeFontSize * 1.7 / k);
  1482. //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
  1483. this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
  1484. }
  1485. return this;
  1486. };
  1487. /**
  1488. * Letter spacing method to print text with gaps
  1489. *
  1490. * @function
  1491. * @param {String|Array} text String to be added to the page.
  1492. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1493. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1494. * @param {Number} spacing Spacing (in units declared at inception)
  1495. * @returns {jsPDF}
  1496. * @methodOf jsPDF#
  1497. * @name lstext
  1498. * @deprecated We'll be removing this function. It doesn't take character width into account.
  1499. */
  1500. API.lstext = function (text, x, y, spacing) {
  1501. console.warn('jsPDF.lstext is deprecated');
  1502. for (var i = 0, len = text.length; i < len; i++, x += spacing) {
  1503. this.text(text[i], x, y);
  1504. }return this;
  1505. };
  1506. API.line = function (x1, y1, x2, y2) {
  1507. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  1508. };
  1509. API.clip = function () {
  1510. // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
  1511. // Call .clip() after calling .rect() with a style argument of null
  1512. out('W'); // clip
  1513. out('S'); // stroke path; necessary for clip to work
  1514. };
  1515. /**
  1516. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  1517. * We introduce the fixed version so as to not break API.
  1518. * @param fillRule
  1519. */
  1520. API.clip_fixed = function (fillRule) {
  1521. // Call .clip() after calling drawing ops with a style argument of null
  1522. // W is the PDF clipping op
  1523. if ('evenodd' === fillRule) {
  1524. out('W*');
  1525. } else {
  1526. out('W');
  1527. }
  1528. // End the path object without filling or stroking it.
  1529. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  1530. // (see Section 4.4.3, “Clipping Path Operators”)
  1531. out('n');
  1532. };
  1533. /**
  1534. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1535. * All data points in `lines` are relative to last line origin.
  1536. * `x`, `y` become x1,y1 for first line / curve in the set.
  1537. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1538. * For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
  1539. *
  1540. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1541. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1542. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1543. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1544. * @param {Number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
  1545. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1546. * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1547. * @function
  1548. * @returns {jsPDF}
  1549. * @methodOf jsPDF#
  1550. * @name lines
  1551. */
  1552. API.lines = function (lines, x, y, scale, style, closed) {
  1553. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1554. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1555. // in effort to make all calls have similar signature like
  1556. // function(content, coordinateX, coordinateY , miscellaneous)
  1557. // this method had its args flipped.
  1558. // code below allows backward compatibility with old arg order.
  1559. if (typeof lines === 'number') {
  1560. tmp = y;
  1561. y = x;
  1562. x = lines;
  1563. lines = tmp;
  1564. }
  1565. scale = scale || [1, 1];
  1566. // starting point
  1567. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1568. scalex = scale[0];
  1569. scaley = scale[1];
  1570. l = lines.length;
  1571. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1572. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1573. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1574. x4 = x; // last / ending point = starting point for first item.
  1575. y4 = y; // last / ending point = starting point for first item.
  1576. for (i = 0; i < l; i++) {
  1577. leg = lines[i];
  1578. if (leg.length === 2) {
  1579. // simple line
  1580. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1581. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1582. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1583. } else {
  1584. // bezier curve
  1585. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1586. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1587. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1588. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1589. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1590. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1591. out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
  1592. }
  1593. }
  1594. if (closed) {
  1595. out(' h');
  1596. }
  1597. // stroking / filling / both the path
  1598. if (style !== null) {
  1599. out(getStyle(style));
  1600. }
  1601. return this;
  1602. };
  1603. /**
  1604. * Adds a rectangle to PDF
  1605. *
  1606. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1607. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1608. * @param {Number} w Width (in units declared at inception of PDF document)
  1609. * @param {Number} h Height (in units declared at inception of PDF document)
  1610. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1611. * @function
  1612. * @returns {jsPDF}
  1613. * @methodOf jsPDF#
  1614. * @name rect
  1615. */
  1616. API.rect = function (x, y, w, h, style) {
  1617. var op = getStyle(style);
  1618. out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
  1619. if (style !== null) {
  1620. out(getStyle(style));
  1621. }
  1622. return this;
  1623. };
  1624. /**
  1625. * Adds a triangle to PDF
  1626. *
  1627. * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1628. * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1629. * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1630. * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1631. * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1632. * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1633. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1634. * @function
  1635. * @returns {jsPDF}
  1636. * @methodOf jsPDF#
  1637. * @name triangle
  1638. */
  1639. API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  1640. this.lines([[x2 - x1, y2 - y1], // vector to point 2
  1641. [x3 - x2, y3 - y2], // vector to point 3
  1642. [x1 - x3, y1 - y3] // closing vector back to point 1
  1643. ], x1, y1, // start of path
  1644. [1, 1], style, true);
  1645. return this;
  1646. };
  1647. /**
  1648. * Adds a rectangle with rounded corners to PDF
  1649. *
  1650. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1651. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1652. * @param {Number} w Width (in units declared at inception of PDF document)
  1653. * @param {Number} h Height (in units declared at inception of PDF document)
  1654. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1655. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1656. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1657. * @function
  1658. * @returns {jsPDF}
  1659. * @methodOf jsPDF#
  1660. * @name roundedRect
  1661. */
  1662. API.roundedRect = function (x, y, w, h, rx, ry, style) {
  1663. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  1664. this.lines([[w - 2 * rx, 0], [rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry], [0, h - 2 * ry], [0, ry * MyArc, -(rx * MyArc), ry, -rx, ry], [-w + 2 * rx, 0], [-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry], [0, -h + 2 * ry], [0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]], x + rx, y, // start of path
  1665. [1, 1], style);
  1666. return this;
  1667. };
  1668. /**
  1669. * Adds an ellipse to PDF
  1670. *
  1671. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1672. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1673. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1674. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1675. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1676. * @function
  1677. * @returns {jsPDF}
  1678. * @methodOf jsPDF#
  1679. * @name ellipse
  1680. */
  1681. API.ellipse = function (x, y, rx, ry, style) {
  1682. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1683. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1684. out([f2((x + rx) * k), f2((pageHeight - y) * k), 'm', f2((x + rx) * k), f2((pageHeight - (y - ly)) * k), f2((x + lx) * k), f2((pageHeight - (y - ry)) * k), f2(x * k), f2((pageHeight - (y - ry)) * k), 'c'].join(' '));
  1685. out([f2((x - lx) * k), f2((pageHeight - (y - ry)) * k), f2((x - rx) * k), f2((pageHeight - (y - ly)) * k), f2((x - rx) * k), f2((pageHeight - y) * k), 'c'].join(' '));
  1686. out([f2((x - rx) * k), f2((pageHeight - (y + ly)) * k), f2((x - lx) * k), f2((pageHeight - (y + ry)) * k), f2(x * k), f2((pageHeight - (y + ry)) * k), 'c'].join(' '));
  1687. out([f2((x + lx) * k), f2((pageHeight - (y + ry)) * k), f2((x + rx) * k), f2((pageHeight - (y + ly)) * k), f2((x + rx) * k), f2((pageHeight - y) * k), 'c'].join(' '));
  1688. if (style !== null) {
  1689. out(getStyle(style));
  1690. }
  1691. return this;
  1692. };
  1693. /**
  1694. * Adds an circle to PDF
  1695. *
  1696. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1697. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1698. * @param {Number} r Radius (in units declared at inception of PDF document)
  1699. * @param {String} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  1700. * @function
  1701. * @returns {jsPDF}
  1702. * @methodOf jsPDF#
  1703. * @name circle
  1704. */
  1705. API.circle = function (x, y, r, style) {
  1706. return this.ellipse(x, y, r, r, style);
  1707. };
  1708. /**
  1709. * Adds a properties to the PDF document
  1710. *
  1711. * @param {Object} A property_name-to-property_value object structure.
  1712. * @function
  1713. * @returns {jsPDF}
  1714. * @methodOf jsPDF#
  1715. * @name setProperties
  1716. */
  1717. API.setProperties = function (properties) {
  1718. // copying only those properties we can render.
  1719. for (var property in documentProperties) {
  1720. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1721. documentProperties[property] = properties[property];
  1722. }
  1723. }
  1724. return this;
  1725. };
  1726. /**
  1727. * Sets font size for upcoming text elements.
  1728. *
  1729. * @param {Number} size Font size in points.
  1730. * @function
  1731. * @returns {jsPDF}
  1732. * @methodOf jsPDF#
  1733. * @name setFontSize
  1734. */
  1735. API.setFontSize = function (size) {
  1736. activeFontSize = size;
  1737. return this;
  1738. };
  1739. /**
  1740. * Sets text font face, variant for upcoming text elements.
  1741. * See output of jsPDF.getFontList() for possible font names, styles.
  1742. *
  1743. * @param {String} fontName Font name or family. Example: "times"
  1744. * @param {String} fontStyle Font style or variant. Example: "italic"
  1745. * @function
  1746. * @returns {jsPDF}
  1747. * @methodOf jsPDF#
  1748. * @name setFont
  1749. */
  1750. API.setFont = function (fontName, fontStyle) {
  1751. activeFontKey = _getFont(fontName, fontStyle);
  1752. // if font is not found, the above line blows up and we never go further
  1753. return this;
  1754. };
  1755. /**
  1756. * Switches font style or variant for upcoming text elements,
  1757. * while keeping the font face or family same.
  1758. * See output of jsPDF.getFontList() for possible font names, styles.
  1759. *
  1760. * @param {String} style Font style or variant. Example: "italic"
  1761. * @function
  1762. * @returns {jsPDF}
  1763. * @methodOf jsPDF#
  1764. * @name setFontStyle
  1765. */
  1766. API.setFontStyle = API.setFontType = function (style) {
  1767. activeFontKey = _getFont(undefined, style);
  1768. // if font is not found, the above line blows up and we never go further
  1769. return this;
  1770. };
  1771. /**
  1772. * Returns an object - a tree of fontName to fontStyle relationships available to
  1773. * active PDF document.
  1774. *
  1775. * @public
  1776. * @function
  1777. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  1778. * @methodOf jsPDF#
  1779. * @name getFontList
  1780. */
  1781. API.getFontList = function () {
  1782. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  1783. var list = {},
  1784. fontName,
  1785. fontStyle,
  1786. tmp;
  1787. for (fontName in fontmap) {
  1788. if (fontmap.hasOwnProperty(fontName)) {
  1789. list[fontName] = tmp = [];
  1790. for (fontStyle in fontmap[fontName]) {
  1791. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  1792. tmp.push(fontStyle);
  1793. }
  1794. }
  1795. }
  1796. }
  1797. return list;
  1798. };
  1799. /**
  1800. * Add a custom font.
  1801. *
  1802. * @param {String} Postscript name of the Font. Example: "Menlo-Regular"
  1803. * @param {String} Name of font-family from @font-face definition. Example: "Menlo Regular"
  1804. * @param {String} Font style. Example: "normal"
  1805. * @function
  1806. * @returns the {fontKey} (same as the internal method)
  1807. * @methodOf jsPDF#
  1808. * @name addFont
  1809. */
  1810. API.addFont = function (postScriptName, fontName, fontStyle) {
  1811. addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
  1812. };
  1813. /**
  1814. * Sets line width for upcoming lines.
  1815. *
  1816. * @param {Number} width Line width (in units declared at inception of PDF document)
  1817. * @function
  1818. * @returns {jsPDF}
  1819. * @methodOf jsPDF#
  1820. * @name setLineWidth
  1821. */
  1822. API.setLineWidth = function (width) {
  1823. out((width * k).toFixed(2) + ' w');
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the stroke color for upcoming elements.
  1828. *
  1829. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1830. * color space is implied.
  1831. *
  1832. * When only ch1 is given, "Gray" color space is implied and it
  1833. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1834. * if values are communicated as String types, or in range from 0 (black)
  1835. * to 255 (white) if communicated as Number type.
  1836. * The RGB-like 0-255 range is provided for backward compatibility.
  1837. *
  1838. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1839. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1840. * (max intensity) if values are communicated as String types, or
  1841. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1842. * as Number types.
  1843. * The RGB-like 0-255 range is provided for backward compatibility.
  1844. *
  1845. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1846. * value must be a in the range from 0.00 (0% concentration) to to
  1847. * 1.00 (100% concentration)
  1848. *
  1849. * Because JavaScript treats fixed point numbers badly (rounds to
  1850. * floating point nearest to binary representation) it is highly advised to
  1851. * communicate the fractional numbers as String types, not JavaScript Number type.
  1852. *
  1853. * @param {Number|String} ch1 Color channel value
  1854. * @param {Number|String} ch2 Color channel value
  1855. * @param {Number|String} ch3 Color channel value
  1856. * @param {Number|String} ch4 Color channel value
  1857. *
  1858. * @function
  1859. * @returns {jsPDF}
  1860. * @methodOf jsPDF#
  1861. * @name setDrawColor
  1862. */
  1863. API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  1864. var color;
  1865. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1866. // Gray color space.
  1867. if (typeof ch1 === 'string') {
  1868. color = ch1 + ' G';
  1869. } else {
  1870. color = f2(ch1 / 255) + ' G';
  1871. }
  1872. } else if (ch4 === undefined) {
  1873. // RGB
  1874. if (typeof ch1 === 'string') {
  1875. color = [ch1, ch2, ch3, 'RG'].join(' ');
  1876. } else {
  1877. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
  1878. }
  1879. } else {
  1880. // CMYK
  1881. if (typeof ch1 === 'string') {
  1882. color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
  1883. } else {
  1884. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
  1885. }
  1886. }
  1887. out(color);
  1888. return this;
  1889. };
  1890. /**
  1891. * Sets the fill color for upcoming elements.
  1892. *
  1893. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1894. * color space is implied.
  1895. *
  1896. * When only ch1 is given, "Gray" color space is implied and it
  1897. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1898. * if values are communicated as String types, or in range from 0 (black)
  1899. * to 255 (white) if communicated as Number type.
  1900. * The RGB-like 0-255 range is provided for backward compatibility.
  1901. *
  1902. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1903. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1904. * (max intensity) if values are communicated as String types, or
  1905. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1906. * as Number types.
  1907. * The RGB-like 0-255 range is provided for backward compatibility.
  1908. *
  1909. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1910. * value must be a in the range from 0.00 (0% concentration) to to
  1911. * 1.00 (100% concentration)
  1912. *
  1913. * Because JavaScript treats fixed point numbers badly (rounds to
  1914. * floating point nearest to binary representation) it is highly advised to
  1915. * communicate the fractional numbers as String types, not JavaScript Number type.
  1916. *
  1917. * @param {Number|String} ch1 Color channel value
  1918. * @param {Number|String} ch2 Color channel value
  1919. * @param {Number|String} ch3 Color channel value
  1920. * @param {Number|String} ch4 Color channel value
  1921. *
  1922. * @function
  1923. * @returns {jsPDF}
  1924. * @methodOf jsPDF#
  1925. * @name setFillColor
  1926. */
  1927. API.setFillColor = function (ch1, ch2, ch3, ch4) {
  1928. var color;
  1929. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1930. // Gray color space.
  1931. if (typeof ch1 === 'string') {
  1932. color = ch1 + ' g';
  1933. } else {
  1934. color = f2(ch1 / 255) + ' g';
  1935. }
  1936. } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
  1937. // RGB
  1938. if (typeof ch1 === 'string') {
  1939. color = [ch1, ch2, ch3, 'rg'].join(' ');
  1940. } else {
  1941. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
  1942. }
  1943. if (ch4 && ch4.a === 0) {
  1944. //TODO Implement transparency.
  1945. //WORKAROUND use white for now
  1946. color = ['255', '255', '255', 'rg'].join(' ');
  1947. }
  1948. } else {
  1949. // CMYK
  1950. if (typeof ch1 === 'string') {
  1951. color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
  1952. } else {
  1953. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
  1954. }
  1955. }
  1956. out(color);
  1957. return this;
  1958. };
  1959. /**
  1960. * Sets the text color for upcoming elements.
  1961. * If only one, first argument is given,
  1962. * treats the value as gray-scale color value.
  1963. *
  1964. * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
  1965. * @param {Number} g Green channel color value in range 0-255
  1966. * @param {Number} b Blue channel color value in range 0-255
  1967. * @function
  1968. * @returns {jsPDF}
  1969. * @methodOf jsPDF#
  1970. * @name setTextColor
  1971. */
  1972. API.setTextColor = function (r, g, b) {
  1973. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  1974. var hex = parseInt(r.substr(1), 16);
  1975. r = hex >> 16 & 255;
  1976. g = hex >> 8 & 255;
  1977. b = hex & 255;
  1978. }
  1979. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  1980. textColor = f3(r / 255) + ' g';
  1981. } else {
  1982. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  1983. }
  1984. return this;
  1985. };
  1986. /**
  1987. * Is an Object providing a mapping from human-readable to
  1988. * integer flag values designating the varieties of line cap
  1989. * and join styles.
  1990. *
  1991. * @returns {Object}
  1992. * @fieldOf jsPDF#
  1993. * @name CapJoinStyles
  1994. */
  1995. API.CapJoinStyles = {
  1996. 0: 0,
  1997. 'butt': 0,
  1998. 'but': 0,
  1999. 'miter': 0,
  2000. 1: 1,
  2001. 'round': 1,
  2002. 'rounded': 1,
  2003. 'circle': 1,
  2004. 2: 2,
  2005. 'projecting': 2,
  2006. 'project': 2,
  2007. 'square': 2,
  2008. 'bevel': 2
  2009. };
  2010. /**
  2011. * Sets the line cap styles
  2012. * See {jsPDF.CapJoinStyles} for variants
  2013. *
  2014. * @param {String|Number} style A string or number identifying the type of line cap
  2015. * @function
  2016. * @returns {jsPDF}
  2017. * @methodOf jsPDF#
  2018. * @name setLineCap
  2019. */
  2020. API.setLineCap = function (style) {
  2021. var id = this.CapJoinStyles[style];
  2022. if (id === undefined) {
  2023. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2024. }
  2025. lineCapID = id;
  2026. out(id + ' J');
  2027. return this;
  2028. };
  2029. /**
  2030. * Sets the line join styles
  2031. * See {jsPDF.CapJoinStyles} for variants
  2032. *
  2033. * @param {String|Number} style A string or number identifying the type of line join
  2034. * @function
  2035. * @returns {jsPDF}
  2036. * @methodOf jsPDF#
  2037. * @name setLineJoin
  2038. */
  2039. API.setLineJoin = function (style) {
  2040. var id = this.CapJoinStyles[style];
  2041. if (id === undefined) {
  2042. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2043. }
  2044. lineJoinID = id;
  2045. out(id + ' j');
  2046. return this;
  2047. };
  2048. // Output is both an internal (for plugins) and external function
  2049. API.output = _output;
  2050. /**
  2051. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  2052. * @param {String} filename The filename including extension.
  2053. *
  2054. * @function
  2055. * @returns {jsPDF}
  2056. * @methodOf jsPDF#
  2057. * @name save
  2058. */
  2059. API.save = function (filename) {
  2060. API.output('save', filename);
  2061. };
  2062. // applying plugins (more methods) ON TOP of built-in API.
  2063. // this is intentional as we allow plugins to override
  2064. // built-ins
  2065. for (var plugin in jsPDF.API) {
  2066. if (jsPDF.API.hasOwnProperty(plugin)) {
  2067. if (plugin === 'events' && jsPDF.API.events.length) {
  2068. (function (events, newEvents) {
  2069. // jsPDF.API.events is a JS Array of Arrays
  2070. // where each Array is a pair of event name, handler
  2071. // Events were added by plugins to the jsPDF instantiator.
  2072. // These are always added to the new instance and some ran
  2073. // during instantiation.
  2074. var eventname, handler_and_args, i;
  2075. for (i = newEvents.length - 1; i !== -1; i--) {
  2076. // subscribe takes 3 args: 'topic', function, runonce_flag
  2077. // if undefined, runonce is false.
  2078. // users can attach callback directly,
  2079. // or they can attach an array with [callback, runonce_flag]
  2080. // that's what the "apply" magic is for below.
  2081. eventname = newEvents[i][0];
  2082. handler_and_args = newEvents[i][1];
  2083. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  2084. }
  2085. })(events, jsPDF.API.events);
  2086. } else {
  2087. API[plugin] = jsPDF.API[plugin];
  2088. }
  2089. }
  2090. }
  2091. //////////////////////////////////////////////////////
  2092. // continuing initialization of jsPDF Document object
  2093. //////////////////////////////////////////////////////
  2094. // Add the first page automatically
  2095. addFonts();
  2096. activeFontKey = 'F1';
  2097. _addPage(format, orientation);
  2098. events.publish('initialized');
  2099. return API;
  2100. }
  2101. /**
  2102. * jsPDF.API is a STATIC property of jsPDF class.
  2103. * jsPDF.API is an object you can add methods and properties to.
  2104. * The methods / properties you add will show up in new jsPDF objects.
  2105. *
  2106. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  2107. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  2108. * Examples:
  2109. * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  2110. * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  2111. *
  2112. * @static
  2113. * @public
  2114. * @memberOf jsPDF
  2115. * @name API
  2116. *
  2117. * @example
  2118. * jsPDF.API.mymethod = function(){
  2119. * // 'this' will be ref to internal API object. see jsPDF source
  2120. * // , so you can refer to built-in methods like so:
  2121. * // this.line(....)
  2122. * // this.text(....)
  2123. * }
  2124. * var pdfdoc = new jsPDF()
  2125. * pdfdoc.mymethod() // <- !!!!!!
  2126. */
  2127. jsPDF.API = {
  2128. events: []
  2129. };
  2130. jsPDF.version = "1.x-master";
  2131. if (typeof define === 'function' && define.amd) {
  2132. define('jsPDF', function () {
  2133. return jsPDF;
  2134. });
  2135. } else if (typeof module !== 'undefined' && module.exports) {
  2136. module.exports = jsPDF;
  2137. } else {
  2138. global.jsPDF = jsPDF;
  2139. }
  2140. return jsPDF;
  2141. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  2142. /**
  2143. * jsPDF AcroForm Plugin
  2144. * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
  2145. *
  2146. * Licensed under the MIT License.
  2147. * http://opensource.org/licenses/mit-license
  2148. */
  2149. (window.AcroForm = function (jsPDFAPI) {
  2150. 'use strict';
  2151. var AcroForm = window.AcroForm;
  2152. AcroForm.scale = function (x) {
  2153. return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
  2154. };
  2155. AcroForm.antiScale = function (x) {
  2156. return 1 / acroformPlugin.internal.scaleFactor * x;
  2157. };
  2158. var acroformPlugin = {
  2159. fields: [],
  2160. xForms: [],
  2161. /**
  2162. * acroFormDictionaryRoot contains information about the AcroForm Dictionary
  2163. * 0: The Event-Token, the AcroFormDictionaryCallback has
  2164. * 1: The Object ID of the Root
  2165. */
  2166. acroFormDictionaryRoot: null,
  2167. /**
  2168. * After the PDF gets evaluated, the reference to the root has to be reset,
  2169. * this indicates, whether the root has already been printed out
  2170. */
  2171. printedOut: false,
  2172. internal: null
  2173. };
  2174. jsPDF.API.acroformPlugin = acroformPlugin;
  2175. var annotReferenceCallback = function annotReferenceCallback() {
  2176. for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
  2177. var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
  2178. // add Annot Reference!
  2179. if (formObject.hasAnnotation) {
  2180. // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
  2181. createAnnotationReference.call(this, formObject);
  2182. }
  2183. }
  2184. };
  2185. var createAcroForm = function createAcroForm() {
  2186. if (this.acroformPlugin.acroFormDictionaryRoot) {
  2187. //return;
  2188. throw new Error("Exception while creating AcroformDictionary");
  2189. }
  2190. // The Object Number of the AcroForm Dictionary
  2191. this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
  2192. this.acroformPlugin.internal = this.internal;
  2193. // add Callback for creating the AcroForm Dictionary
  2194. this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  2195. this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
  2196. // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
  2197. this.internal.events.subscribe('putCatalog', putCatalogCallback);
  2198. // Register event, that creates all Fields
  2199. this.internal.events.subscribe('postPutPages', createFieldCallback);
  2200. };
  2201. /**
  2202. * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
  2203. * (Requires the Annotation Plugin)
  2204. */
  2205. var createAnnotationReference = function createAnnotationReference(object) {
  2206. var options = {
  2207. type: 'reference',
  2208. object: object
  2209. };
  2210. jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
  2211. };
  2212. var putForm = function putForm(formObject) {
  2213. if (this.acroformPlugin.printedOut) {
  2214. this.acroformPlugin.printedOut = false;
  2215. this.acroformPlugin.acroFormDictionaryRoot = null;
  2216. }
  2217. if (!this.acroformPlugin.acroFormDictionaryRoot) {
  2218. createAcroForm.call(this);
  2219. }
  2220. this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  2221. };
  2222. // Callbacks
  2223. var putCatalogCallback = function putCatalogCallback() {
  2224. //Put reference to AcroForm to DocumentCatalog
  2225. if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  2226. // for safety, shouldn't normally be the case
  2227. this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  2228. } else {
  2229. console.log('Root missing...');
  2230. }
  2231. };
  2232. /**
  2233. * Adds /Acroform X 0 R to Document Catalog,
  2234. * and creates the AcroForm Dictionary
  2235. */
  2236. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  2237. // Remove event
  2238. this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
  2239. delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
  2240. this.acroformPlugin.printedOut = true;
  2241. };
  2242. /**
  2243. * Creates the single Fields and writes them into the Document
  2244. *
  2245. * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
  2246. * (for the FormXObjects...)
  2247. */
  2248. var createFieldCallback = function createFieldCallback(fieldArray) {
  2249. var standardFields = !fieldArray;
  2250. if (!fieldArray) {
  2251. // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
  2252. // Print out Root
  2253. this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
  2254. this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
  2255. }
  2256. var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
  2257. for (var i in fieldArray) {
  2258. var key = i;
  2259. var form = fieldArray[i];
  2260. var oldRect = form.Rect;
  2261. if (form.Rect) {
  2262. form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
  2263. }
  2264. // Start Writing the Object
  2265. this.internal.newObjectDeferredBegin(form.objId);
  2266. var content = "";
  2267. content += form.objId + " 0 obj\n";
  2268. content += "<<\n" + form.getContent();
  2269. form.Rect = oldRect;
  2270. if (form.hasAppearanceStream && !form.appearanceStreamContent) {
  2271. // Calculate Appearance
  2272. var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
  2273. content += "/AP << /N " + appearance + " >>\n";
  2274. this.acroformPlugin.xForms.push(appearance);
  2275. }
  2276. // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
  2277. if (form.appearanceStreamContent) {
  2278. content += "/AP << ";
  2279. // Iterate over N,R and D
  2280. for (var k in form.appearanceStreamContent) {
  2281. var value = form.appearanceStreamContent[k];
  2282. content += "/" + k + " ";
  2283. content += "<< ";
  2284. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  2285. // appearanceStream is an Array or Object!
  2286. for (var i in value) {
  2287. var obj = value[i];
  2288. if (typeof obj === 'function') {
  2289. // if Function is referenced, call it in order to get the FormXObject
  2290. obj = obj.call(this, form);
  2291. }
  2292. content += "/" + i + " " + obj + " ";
  2293. // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
  2294. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2295. }
  2296. } else {
  2297. var obj = value;
  2298. if (typeof obj === 'function') {
  2299. // if Function is referenced, call it in order to get the FormXObject
  2300. obj = obj.call(this, form);
  2301. }
  2302. content += "/" + i + " " + obj + " \n";
  2303. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2304. }
  2305. content += " >>\n";
  2306. }
  2307. // appearance stream is a normal Object..
  2308. content += ">>\n";
  2309. }
  2310. content += ">>\nendobj\n";
  2311. this.internal.out(content);
  2312. }
  2313. if (standardFields) {
  2314. createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
  2315. }
  2316. };
  2317. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  2318. for (var i in fieldArray) {
  2319. var key = i;
  2320. var form = fieldArray[i];
  2321. // Start Writing the Object
  2322. this.internal.newObjectDeferredBegin(form && form.objId);
  2323. var content = "";
  2324. content += form ? form.getString() : '';
  2325. this.internal.out(content);
  2326. delete fieldArray[key];
  2327. }
  2328. };
  2329. // Public:
  2330. jsPDFAPI.addField = function (fieldObject) {
  2331. //var opt = parseOptions(fieldObject);
  2332. if (fieldObject instanceof AcroForm.TextField) {
  2333. addTextField.call(this, fieldObject);
  2334. } else if (fieldObject instanceof AcroForm.ChoiceField) {
  2335. addChoiceField.call(this, fieldObject);
  2336. } else if (fieldObject instanceof AcroForm.Button) {
  2337. addButton.call(this, fieldObject);
  2338. } else if (fieldObject instanceof AcroForm.ChildClass) {
  2339. putForm.call(this, fieldObject);
  2340. } else if (fieldObject) {
  2341. // try to put..
  2342. putForm.call(this, fieldObject);
  2343. }
  2344. fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
  2345. return this;
  2346. };
  2347. // ############### sort in:
  2348. /**
  2349. * Button
  2350. * FT = Btn
  2351. */
  2352. var addButton = function addButton(options) {
  2353. var options = options || new AcroForm.Field();
  2354. options.FT = '/Btn';
  2355. /**
  2356. * Calculating the Ff entry:
  2357. *
  2358. * The Ff entry contains flags, that have to be set bitwise
  2359. * In the Following the number in the Comment is the BitPosition
  2360. */
  2361. var flags = options.Ff || 0;
  2362. // 17, Pushbutton
  2363. if (options.pushbutton) {
  2364. // Options.pushbutton should be 1 or 0
  2365. flags = AcroForm.internal.setBitPosition(flags, 17);
  2366. delete options.pushbutton;
  2367. }
  2368. //16, Radio
  2369. if (options.radio) {
  2370. //flags = options.Ff | options.radio << 15;
  2371. flags = AcroForm.internal.setBitPosition(flags, 16);
  2372. delete options.radio;
  2373. }
  2374. // 15, NoToggleToOff (Radio buttons only
  2375. if (options.noToggleToOff) {
  2376. //flags = options.Ff | options.noToggleToOff << 14;
  2377. flags = AcroForm.internal.setBitPosition(flags, 15);
  2378. //delete options.noToggleToOff;
  2379. }
  2380. // In case, there is no Flag set, it is a check-box
  2381. options.Ff = flags;
  2382. putForm.call(this, options);
  2383. };
  2384. var addTextField = function addTextField(options) {
  2385. var options = options || new AcroForm.Field();
  2386. options.FT = '/Tx';
  2387. /**
  2388. * Calculating the Ff entry:
  2389. *
  2390. * The Ff entry contains flags, that have to be set bitwise
  2391. * In the Following the number in the Comment is the BitPosition
  2392. */
  2393. var flags = options.Ff || 0;
  2394. // 13, multiline
  2395. if (options.multiline) {
  2396. // Set Flag
  2397. flags = flags | 1 << 12;
  2398. // Remove multiline from FieldObject
  2399. //delete options.multiline;
  2400. }
  2401. // 14, Password
  2402. if (options.password) {
  2403. flags = flags | 1 << 13;
  2404. //delete options.password;
  2405. }
  2406. // 21, FileSelect, PDF 1.4...
  2407. if (options.fileSelect) {
  2408. flags = flags | 1 << 20;
  2409. //delete options.fileSelect;
  2410. }
  2411. // 23, DoNotSpellCheck, PDF 1.4...
  2412. if (options.doNotSpellCheck) {
  2413. flags = flags | 1 << 22;
  2414. //delete options.doNotSpellCheck;
  2415. }
  2416. // 24, DoNotScroll, PDF 1.4...
  2417. if (options.doNotScroll) {
  2418. flags = flags | 1 << 23;
  2419. //delete options.doNotScroll;
  2420. }
  2421. options.Ff = options.Ff || flags;
  2422. // Add field
  2423. putForm.call(this, options);
  2424. };
  2425. var addChoiceField = function addChoiceField(opt) {
  2426. var options = opt || new AcroForm.Field();
  2427. options.FT = '/Ch';
  2428. /**
  2429. * Calculating the Ff entry:
  2430. *
  2431. * The Ff entry contains flags, that have to be set bitwise
  2432. * In the Following the number in the Comment is the BitPosition
  2433. */
  2434. var flags = options.Ff || 0;
  2435. // 18, Combo (If not set, the choiceField is a listBox!!)
  2436. if (options.combo) {
  2437. // Set Flag
  2438. flags = AcroForm.internal.setBitPosition(flags, 18);
  2439. // Remove combo from FieldObject
  2440. delete options.combo;
  2441. }
  2442. // 19, Edit
  2443. if (options.edit) {
  2444. flags = AcroForm.internal.setBitPosition(flags, 19);
  2445. delete options.edit;
  2446. }
  2447. // 20, Sort
  2448. if (options.sort) {
  2449. flags = AcroForm.internal.setBitPosition(flags, 20);
  2450. delete options.sort;
  2451. }
  2452. // 22, MultiSelect (PDF 1.4)
  2453. if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
  2454. flags = AcroForm.internal.setBitPosition(flags, 22);
  2455. delete options.multiSelect;
  2456. }
  2457. // 23, DoNotSpellCheck (PDF 1.4)
  2458. if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
  2459. flags = AcroForm.internal.setBitPosition(flags, 23);
  2460. delete options.doNotSpellCheck;
  2461. }
  2462. options.Ff = flags;
  2463. //options.hasAnnotation = true;
  2464. // Add field
  2465. putForm.call(this, options);
  2466. };
  2467. })(jsPDF.API);
  2468. var AcroForm = window.AcroForm;
  2469. AcroForm.internal = {};
  2470. AcroForm.createFormXObject = function (formObject) {
  2471. var xobj = new AcroForm.FormXObject();
  2472. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  2473. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  2474. xobj.BBox = [0, 0, width, height];
  2475. return xobj;
  2476. };
  2477. // Contains Methods for creating standard appearances
  2478. AcroForm.Appearance = {
  2479. CheckBox: {
  2480. createAppearanceStream: function createAppearanceStream() {
  2481. var appearance = {
  2482. N: {
  2483. On: AcroForm.Appearance.CheckBox.YesNormal
  2484. },
  2485. D: {
  2486. On: AcroForm.Appearance.CheckBox.YesPushDown,
  2487. Off: AcroForm.Appearance.CheckBox.OffPushDown
  2488. }
  2489. };
  2490. return appearance;
  2491. },
  2492. /**
  2493. * If any other icons are needed, the number between the brackets can be changed
  2494. * @returns {string}
  2495. */
  2496. createMK: function createMK() {
  2497. // 3-> Hook
  2498. return "<< /CA (3)>>";
  2499. },
  2500. /**
  2501. * Returns the standard On Appearance for a CheckBox
  2502. * @returns {AcroForm.FormXObject}
  2503. */
  2504. YesPushDown: function YesPushDown(formObject) {
  2505. var xobj = AcroForm.createFormXObject(formObject);
  2506. var stream = "";
  2507. // F13 is ZapfDingbats (Symbolic)
  2508. formObject.Q = 1; // set text-alignment as centered
  2509. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
  2510. stream += "0.749023 g\n\
  2511. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2512. f\n\
  2513. BMC\n\
  2514. q\n\
  2515. 0 0 1 rg\n\
  2516. /F13 " + calcRes.fontSize + " Tf 0 g\n\
  2517. BT\n";
  2518. stream += calcRes.text;
  2519. stream += "ET\n\
  2520. Q\n\
  2521. EMC\n";
  2522. xobj.stream = stream;
  2523. return xobj;
  2524. },
  2525. YesNormal: function YesNormal(formObject) {
  2526. var xobj = AcroForm.createFormXObject(formObject);
  2527. var stream = "";
  2528. formObject.Q = 1; // set text-alignment as centered
  2529. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formObject) * 0.9);
  2530. stream += "1 g\n\
  2531. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2532. f\n\
  2533. q\n\
  2534. 0 0 1 rg\n\
  2535. 0 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
  2536. W\n\
  2537. n\n\
  2538. 0 g\n\
  2539. BT\n\
  2540. /F13 " + calcRes.fontSize + " Tf 0 g\n";
  2541. stream += calcRes.text;
  2542. stream += "ET\n\
  2543. Q\n";
  2544. xobj.stream = stream;
  2545. return xobj;
  2546. },
  2547. /**
  2548. * Returns the standard Off Appearance for a CheckBox
  2549. * @returns {AcroForm.FormXObject}
  2550. */
  2551. OffPushDown: function OffPushDown(formObject) {
  2552. var xobj = AcroForm.createFormXObject(formObject);
  2553. var stream = "";
  2554. stream += "0.749023 g\n\
  2555. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2556. f\n";
  2557. xobj.stream = stream;
  2558. return xobj;
  2559. }
  2560. },
  2561. RadioButton: {
  2562. Circle: {
  2563. createAppearanceStream: function createAppearanceStream(name) {
  2564. var appearanceStreamContent = {
  2565. D: {
  2566. 'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
  2567. },
  2568. N: {}
  2569. };
  2570. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
  2571. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
  2572. return appearanceStreamContent;
  2573. },
  2574. createMK: function createMK() {
  2575. return "<< /CA (l)>>";
  2576. },
  2577. YesNormal: function YesNormal(formObject) {
  2578. var xobj = AcroForm.createFormXObject(formObject);
  2579. var stream = "";
  2580. // Make the Radius of the Circle relative to min(height, width) of formObject
  2581. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2582. // The Borderpadding...
  2583. DotRadius *= 0.9;
  2584. var c = AcroForm.Appearance.internal.Bezier_C;
  2585. /*
  2586. The Following is a Circle created with Bezier-Curves.
  2587. */
  2588. stream += "q\n\
  2589. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2590. " + DotRadius + " 0 m\n\
  2591. " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2592. -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2593. -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2594. " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2595. f\n\
  2596. Q\n";
  2597. xobj.stream = stream;
  2598. return xobj;
  2599. },
  2600. YesPushDown: function YesPushDown(formObject) {
  2601. var xobj = AcroForm.createFormXObject(formObject);
  2602. var stream = "";
  2603. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2604. // The Borderpadding...
  2605. DotRadius *= 0.9;
  2606. // Save results for later use; no need to waste processor ticks on doing math
  2607. var k = DotRadius * 2;
  2608. // var c = AcroForm.Appearance.internal.Bezier_C;
  2609. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2610. var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
  2611. // stream += "0.749023 g\n\
  2612. // q\n\
  2613. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2614. // " + DotRadius * 2 + " 0 m\n\
  2615. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2616. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2617. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2618. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2619. // f\n\
  2620. // Q\n\
  2621. // 0 g\n\
  2622. // q\n\
  2623. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2624. // " + DotRadius + " 0 m\n\
  2625. // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2626. // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2627. // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2628. // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2629. // f\n\
  2630. // Q\n";
  2631. // FASTER VERSION with less processor ticks spent on math operations
  2632. stream += "0.749023 g\n\
  2633. q\n\
  2634. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2635. " + k + " 0 m\n\
  2636. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2637. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2638. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2639. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2640. f\n\
  2641. Q\n\
  2642. 0 g\n\
  2643. q\n\
  2644. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2645. " + DotRadius + " 0 m\n\
  2646. " + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2647. -" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
  2648. -" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2649. " + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
  2650. f\n\
  2651. Q\n";
  2652. xobj.stream = stream;
  2653. return xobj;
  2654. },
  2655. OffPushDown: function OffPushDown(formObject) {
  2656. var xobj = AcroForm.createFormXObject(formObject);
  2657. var stream = "";
  2658. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2659. // The Borderpadding...
  2660. DotRadius *= 0.9;
  2661. // Save results for later use; no need to waste processor ticks on doing math
  2662. var k = DotRadius * 2;
  2663. // var c = AcroForm.Appearance.internal.Bezier_C;
  2664. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2665. // stream += "0.749023 g\n\
  2666. // q\n\
  2667. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2668. // " + DotRadius * 2 + " 0 m\n\
  2669. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2670. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2671. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2672. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2673. // f\n\
  2674. // Q\n";
  2675. // FASTER VERSION with less processor ticks spent on math operations
  2676. stream += "0.749023 g\n\
  2677. q\n\
  2678. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2679. " + k + " 0 m\n\
  2680. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2681. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2682. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2683. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2684. f\n\
  2685. Q\n";
  2686. xobj.stream = stream;
  2687. return xobj;
  2688. }
  2689. },
  2690. Cross: {
  2691. /**
  2692. * Creates the Actual AppearanceDictionary-References
  2693. * @param name
  2694. * @returns
  2695. */
  2696. createAppearanceStream: function createAppearanceStream(name) {
  2697. var appearanceStreamContent = {
  2698. D: {
  2699. 'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
  2700. },
  2701. N: {}
  2702. };
  2703. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
  2704. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
  2705. return appearanceStreamContent;
  2706. },
  2707. createMK: function createMK() {
  2708. return "<< /CA (8)>>";
  2709. },
  2710. YesNormal: function YesNormal(formObject) {
  2711. var xobj = AcroForm.createFormXObject(formObject);
  2712. var stream = "";
  2713. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2714. stream += "q\n\
  2715. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2716. W\n\
  2717. n\n\
  2718. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2719. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2720. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2721. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2722. s\n\
  2723. Q\n";
  2724. xobj.stream = stream;
  2725. return xobj;
  2726. },
  2727. YesPushDown: function YesPushDown(formObject) {
  2728. var xobj = AcroForm.createFormXObject(formObject);
  2729. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2730. var stream = "";
  2731. stream += "0.749023 g\n\
  2732. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2733. f\n\
  2734. q\n\
  2735. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2736. W\n\
  2737. n\n\
  2738. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2739. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2740. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2741. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2742. s\n\
  2743. Q\n";
  2744. xobj.stream = stream;
  2745. return xobj;
  2746. },
  2747. OffPushDown: function OffPushDown(formObject) {
  2748. var xobj = AcroForm.createFormXObject(formObject);
  2749. var stream = "";
  2750. stream += "0.749023 g\n\
  2751. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2752. f\n";
  2753. xobj.stream = stream;
  2754. return xobj;
  2755. }
  2756. }
  2757. },
  2758. /**
  2759. * Returns the standard Appearance
  2760. * @returns {AcroForm.FormXObject}
  2761. */
  2762. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  2763. var stream = "";
  2764. // Set Helvetica to Standard Font (size: auto)
  2765. // Color: Black
  2766. stream += "/Helv 0 Tf 0 g";
  2767. return stream;
  2768. }
  2769. };
  2770. AcroForm.Appearance.internal = {
  2771. Bezier_C: 0.551915024494,
  2772. calculateCross: function calculateCross(formObject) {
  2773. var min = function min(x, y) {
  2774. return x > y ? y : x;
  2775. };
  2776. var width = AcroForm.Appearance.internal.getWidth(formObject);
  2777. var height = AcroForm.Appearance.internal.getHeight(formObject);
  2778. var a = min(width, height);
  2779. var crossSize = a;
  2780. var borderPadding = 2; // The Padding in px
  2781. var cross = {
  2782. x1: { // upperLeft
  2783. x: (width - a) / 2,
  2784. y: (height - a) / 2 + a },
  2785. x2: { // lowerRight
  2786. x: (width - a) / 2 + a,
  2787. y: (height - a) / 2 //borderPadding
  2788. },
  2789. x3: { // lowerLeft
  2790. x: (width - a) / 2,
  2791. y: (height - a) / 2 //borderPadding
  2792. },
  2793. x4: { // upperRight
  2794. x: (width - a) / 2 + a,
  2795. y: (height - a) / 2 + a }
  2796. };
  2797. return cross;
  2798. }
  2799. };
  2800. AcroForm.Appearance.internal.getWidth = function (formObject) {
  2801. return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
  2802. };
  2803. AcroForm.Appearance.internal.getHeight = function (formObject) {
  2804. return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
  2805. };
  2806. // ##########################
  2807. //### For inheritance:
  2808. AcroForm.internal.inherit = function (child, parent) {
  2809. var ObjectCreate = Object.create || function (o) {
  2810. var F = function F() {};
  2811. F.prototype = o;
  2812. return new F();
  2813. };
  2814. child.prototype = Object.create(parent.prototype);
  2815. child.prototype.constructor = child;
  2816. };
  2817. // ### Handy Functions:
  2818. AcroForm.internal.arrayToPdfArray = function (array) {
  2819. if (Array.isArray(array)) {
  2820. var content = ' [';
  2821. for (var i in array) {
  2822. var element = array[i].toString();
  2823. content += element;
  2824. content += i < array.length - 1 ? ' ' : '';
  2825. }
  2826. content += ']';
  2827. return content;
  2828. }
  2829. };
  2830. AcroForm.internal.toPdfString = function (string) {
  2831. string = string || "";
  2832. // put Bracket at the Beginning of the String
  2833. if (string.indexOf('(') !== 0) {
  2834. string = '(' + string;
  2835. }
  2836. if (string.substring(string.length - 1) != ')') {
  2837. string += '(';
  2838. }
  2839. return string;
  2840. };
  2841. // ##########################
  2842. // Classes
  2843. // ##########################
  2844. AcroForm.PDFObject = function () {
  2845. // The Object ID in the PDF Object Model
  2846. // todo
  2847. var _objId;
  2848. Object.defineProperty(this, 'objId', {
  2849. get: function get() {
  2850. if (!_objId) {
  2851. if (this.internal) {
  2852. _objId = this.internal.newObjectDeferred();
  2853. } else if (jsPDF.API.acroformPlugin.internal) {
  2854. // todo - find better option, that doesn't rely on a Global Static var
  2855. _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
  2856. }
  2857. }
  2858. if (!_objId) {
  2859. console.log("Couldn't create Object ID");
  2860. }
  2861. return _objId;
  2862. },
  2863. configurable: false
  2864. });
  2865. };
  2866. AcroForm.PDFObject.prototype.toString = function () {
  2867. return this.objId + " 0 R";
  2868. };
  2869. AcroForm.PDFObject.prototype.getString = function () {
  2870. var res = this.objId + " 0 obj\n<<";
  2871. var content = this.getContent();
  2872. res += content + ">>\n";
  2873. if (this.stream) {
  2874. res += "stream\n";
  2875. res += this.stream;
  2876. res += "endstream\n";
  2877. }
  2878. res += "endobj\n";
  2879. return res;
  2880. };
  2881. AcroForm.PDFObject.prototype.getContent = function () {
  2882. /**
  2883. * Prints out all enumerable Variables from the Object
  2884. * @param fieldObject
  2885. * @returns {string}
  2886. */
  2887. var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
  2888. var content = '';
  2889. var keys = Object.keys(fieldObject).filter(function (key) {
  2890. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  2891. });
  2892. for (var i in keys) {
  2893. var key = keys[i];
  2894. var value = fieldObject[key];
  2895. /*if (key == 'Rect' && value) {
  2896. value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
  2897. }*/
  2898. if (value) {
  2899. if (Array.isArray(value)) {
  2900. content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
  2901. } else if (value instanceof AcroForm.PDFObject) {
  2902. // In case it is a reference to another PDFObject, take the referennce number
  2903. content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
  2904. } else {
  2905. content += '/' + key + ' ' + value + '\n';
  2906. }
  2907. }
  2908. }
  2909. return content;
  2910. };
  2911. var object = "";
  2912. object += createContentFromFieldObject(this);
  2913. return object;
  2914. };
  2915. AcroForm.FormXObject = function () {
  2916. AcroForm.PDFObject.call(this);
  2917. this.Type = "/XObject";
  2918. this.Subtype = "/Form";
  2919. this.FormType = 1;
  2920. this.BBox;
  2921. this.Matrix;
  2922. this.Resources = "2 0 R";
  2923. this.PieceInfo;
  2924. var _stream;
  2925. Object.defineProperty(this, 'Length', {
  2926. enumerable: true,
  2927. get: function get() {
  2928. return _stream !== undefined ? _stream.length : 0;
  2929. }
  2930. });
  2931. Object.defineProperty(this, 'stream', {
  2932. enumerable: false,
  2933. set: function set(val) {
  2934. _stream = val;
  2935. },
  2936. get: function get() {
  2937. if (_stream) {
  2938. return _stream;
  2939. } else {
  2940. return null;
  2941. }
  2942. }
  2943. });
  2944. };
  2945. AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
  2946. AcroForm.AcroFormDictionary = function () {
  2947. AcroForm.PDFObject.call(this);
  2948. var _Kids = [];
  2949. Object.defineProperty(this, 'Kids', {
  2950. enumerable: false,
  2951. configurable: true,
  2952. get: function get() {
  2953. if (_Kids.length > 0) {
  2954. return _Kids;
  2955. } else {
  2956. return;
  2957. }
  2958. }
  2959. });
  2960. Object.defineProperty(this, 'Fields', {
  2961. enumerable: true,
  2962. configurable: true,
  2963. get: function get() {
  2964. return _Kids;
  2965. }
  2966. });
  2967. // Default Appearance
  2968. this.DA;
  2969. };
  2970. AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
  2971. // ##### The Objects, the User can Create:
  2972. // The Field Object contains the Variables, that every Field needs
  2973. // Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
  2974. AcroForm.Field = function () {
  2975. 'use strict';
  2976. AcroForm.PDFObject.call(this);
  2977. var _Rect;
  2978. Object.defineProperty(this, 'Rect', {
  2979. enumerable: true,
  2980. configurable: false,
  2981. get: function get() {
  2982. if (!_Rect) {
  2983. return;
  2984. }
  2985. var tmp = _Rect;
  2986. //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
  2987. return tmp;
  2988. },
  2989. set: function set(val) {
  2990. _Rect = val;
  2991. }
  2992. });
  2993. var _FT = "";
  2994. Object.defineProperty(this, 'FT', {
  2995. enumerable: true,
  2996. set: function set(val) {
  2997. _FT = val;
  2998. },
  2999. get: function get() {
  3000. return _FT;
  3001. }
  3002. });
  3003. /**
  3004. * The Partial name of the Field Object.
  3005. * It has to be unique.
  3006. */
  3007. var _T;
  3008. Object.defineProperty(this, 'T', {
  3009. enumerable: true,
  3010. configurable: false,
  3011. set: function set(val) {
  3012. _T = val;
  3013. },
  3014. get: function get() {
  3015. if (!_T || _T.length < 1) {
  3016. if (this instanceof AcroForm.ChildClass) {
  3017. // In case of a Child from a Radio´Group, you don't need a FieldName!!!
  3018. return;
  3019. }
  3020. return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
  3021. }
  3022. if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
  3023. return _T;
  3024. }
  3025. return "(" + _T + ")";
  3026. }
  3027. });
  3028. var _DA;
  3029. // Defines the default appearance (Needed for variable Text)
  3030. Object.defineProperty(this, 'DA', {
  3031. enumerable: true,
  3032. get: function get() {
  3033. if (!_DA) {
  3034. return;
  3035. }
  3036. return '(' + _DA + ')';
  3037. },
  3038. set: function set(val) {
  3039. _DA = val;
  3040. }
  3041. });
  3042. var _DV;
  3043. // Defines the default value
  3044. Object.defineProperty(this, 'DV', {
  3045. enumerable: true,
  3046. configurable: true,
  3047. get: function get() {
  3048. if (!_DV) {
  3049. return;
  3050. }
  3051. return _DV;
  3052. },
  3053. set: function set(val) {
  3054. _DV = val;
  3055. }
  3056. });
  3057. //this.Type = "/Annot";
  3058. //this.Subtype = "/Widget";
  3059. Object.defineProperty(this, 'Type', {
  3060. enumerable: true,
  3061. get: function get() {
  3062. return this.hasAnnotation ? "/Annot" : null;
  3063. }
  3064. });
  3065. Object.defineProperty(this, 'Subtype', {
  3066. enumerable: true,
  3067. get: function get() {
  3068. return this.hasAnnotation ? "/Widget" : null;
  3069. }
  3070. });
  3071. /**
  3072. *
  3073. * @type {Array}
  3074. */
  3075. this.BG;
  3076. Object.defineProperty(this, 'hasAnnotation', {
  3077. enumerable: false,
  3078. get: function get() {
  3079. if (this.Rect || this.BC || this.BG) {
  3080. return true;
  3081. }
  3082. return false;
  3083. }
  3084. });
  3085. Object.defineProperty(this, 'hasAppearanceStream', {
  3086. enumerable: false,
  3087. configurable: true,
  3088. writable: true
  3089. });
  3090. Object.defineProperty(this, 'page', {
  3091. enumerable: false,
  3092. configurable: true,
  3093. writable: true
  3094. });
  3095. };
  3096. AcroForm.Field.FieldNum = 0;
  3097. AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
  3098. AcroForm.ChoiceField = function () {
  3099. AcroForm.Field.call(this);
  3100. // Field Type = Choice Field
  3101. this.FT = "/Ch";
  3102. // options
  3103. this.Opt = [];
  3104. this.V = '()';
  3105. // Top Index
  3106. this.TI = 0;
  3107. /**
  3108. * Defines, whether the
  3109. * @type {boolean}
  3110. */
  3111. this.combo = false;
  3112. /**
  3113. * Defines, whether the Choice Field is an Edit Field.
  3114. * An Edit Field is automatically an Combo Field.
  3115. */
  3116. Object.defineProperty(this, 'edit', {
  3117. enumerable: true,
  3118. set: function set(val) {
  3119. if (val == true) {
  3120. this._edit = true;
  3121. // ComboBox has to be true
  3122. this.combo = true;
  3123. } else {
  3124. this._edit = false;
  3125. }
  3126. },
  3127. get: function get() {
  3128. if (!this._edit) {
  3129. return false;
  3130. }
  3131. return this._edit;
  3132. },
  3133. configurable: false
  3134. });
  3135. this.hasAppearanceStream = true;
  3136. Object.defineProperty(this, 'V', {
  3137. get: function get() {
  3138. AcroForm.internal.toPdfString();
  3139. }
  3140. });
  3141. };
  3142. AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
  3143. window["ChoiceField"] = AcroForm.ChoiceField;
  3144. AcroForm.ListBox = function () {
  3145. AcroForm.ChoiceField.call(this);
  3146. //var combo = true;
  3147. };
  3148. AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
  3149. window["ListBox"] = AcroForm.ListBox;
  3150. AcroForm.ComboBox = function () {
  3151. AcroForm.ListBox.call(this);
  3152. this.combo = true;
  3153. };
  3154. AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
  3155. window["ComboBox"] = AcroForm.ComboBox;
  3156. AcroForm.EditBox = function () {
  3157. AcroForm.ComboBox.call(this);
  3158. this.edit = true;
  3159. };
  3160. AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
  3161. window["EditBox"] = AcroForm.EditBox;
  3162. AcroForm.Button = function () {
  3163. AcroForm.Field.call(this);
  3164. this.FT = "/Btn";
  3165. //this.hasAnnotation = true;
  3166. };
  3167. AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
  3168. window["Button"] = AcroForm.Button;
  3169. AcroForm.PushButton = function () {
  3170. AcroForm.Button.call(this);
  3171. this.pushbutton = true;
  3172. };
  3173. AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
  3174. window["PushButton"] = AcroForm.PushButton;
  3175. AcroForm.RadioButton = function () {
  3176. AcroForm.Button.call(this);
  3177. this.radio = true;
  3178. var _Kids = [];
  3179. Object.defineProperty(this, 'Kids', {
  3180. enumerable: true,
  3181. get: function get() {
  3182. if (_Kids.length > 0) {
  3183. return _Kids;
  3184. }
  3185. }
  3186. });
  3187. Object.defineProperty(this, '__Kids', {
  3188. get: function get() {
  3189. return _Kids;
  3190. }
  3191. });
  3192. var _noToggleToOff;
  3193. Object.defineProperty(this, 'noToggleToOff', {
  3194. enumerable: false,
  3195. get: function get() {
  3196. return _noToggleToOff;
  3197. },
  3198. set: function set(val) {
  3199. _noToggleToOff = val;
  3200. }
  3201. });
  3202. //this.hasAnnotation = false;
  3203. };
  3204. AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
  3205. window["RadioButton"] = AcroForm.RadioButton;
  3206. /*
  3207. * The Child classs of a RadioButton (the radioGroup)
  3208. * -> The single Buttons
  3209. */
  3210. AcroForm.ChildClass = function (parent, name) {
  3211. AcroForm.Field.call(this);
  3212. this.Parent = parent;
  3213. // todo: set AppearanceType as variable that can be set from the outside...
  3214. this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
  3215. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  3216. // Set Print in the Annot Flag
  3217. this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
  3218. // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
  3219. this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
  3220. // Default Appearance is Off
  3221. this.AS = "/Off"; // + name;
  3222. this._Name = name;
  3223. };
  3224. AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
  3225. AcroForm.RadioButton.prototype.setAppearance = function (appearance) {
  3226. if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
  3227. console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  3228. return;
  3229. }
  3230. for (var i in this.__Kids) {
  3231. var child = this.__Kids[i];
  3232. child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
  3233. child.MK = appearance.createMK();
  3234. }
  3235. };
  3236. AcroForm.RadioButton.prototype.createOption = function (name) {
  3237. var parent = this;
  3238. var kidCount = this.__Kids.length;
  3239. // Create new Child for RadioGroup
  3240. var child = new AcroForm.ChildClass(parent, name);
  3241. // Add to Parent
  3242. this.__Kids.push(child);
  3243. jsPDF.API.addField(child);
  3244. return child;
  3245. };
  3246. AcroForm.CheckBox = function () {
  3247. Button.call(this);
  3248. this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
  3249. this.MK = AcroForm.Appearance.CheckBox.createMK();
  3250. this.AS = "/On";
  3251. this.V = "/On";
  3252. };
  3253. AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
  3254. window["CheckBox"] = AcroForm.CheckBox;
  3255. AcroForm.TextField = function () {
  3256. AcroForm.Field.call(this);
  3257. this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
  3258. this.F = 4;
  3259. var _V;
  3260. Object.defineProperty(this, 'V', {
  3261. get: function get() {
  3262. if (_V) {
  3263. return "(" + _V + ")";
  3264. } else {
  3265. return _V;
  3266. }
  3267. },
  3268. enumerable: true,
  3269. set: function set(val) {
  3270. _V = val;
  3271. }
  3272. });
  3273. var _DV;
  3274. Object.defineProperty(this, 'DV', {
  3275. get: function get() {
  3276. if (_DV) {
  3277. return "(" + _DV + ")";
  3278. } else {
  3279. return _DV;
  3280. }
  3281. },
  3282. enumerable: true,
  3283. set: function set(val) {
  3284. _DV = val;
  3285. }
  3286. });
  3287. var _multiline = false;
  3288. Object.defineProperty(this, 'multiline', {
  3289. enumerable: false,
  3290. get: function get() {
  3291. return _multiline;
  3292. },
  3293. set: function set(val) {
  3294. _multiline = val;
  3295. }
  3296. });
  3297. //this.multiline = false;
  3298. //this.password = false;
  3299. /**
  3300. * For PDF 1.4
  3301. * @type {boolean}
  3302. */
  3303. //this.fileSelect = false;
  3304. /**
  3305. * For PDF 1.4
  3306. * @type {boolean}
  3307. */
  3308. //this.doNotSpellCheck = false;
  3309. /**
  3310. * For PDF 1.4
  3311. * @type {boolean}
  3312. */
  3313. //this.doNotScroll = false;
  3314. var _MaxLen = false;
  3315. Object.defineProperty(this, 'MaxLen', {
  3316. enumerable: true,
  3317. get: function get() {
  3318. return _MaxLen;
  3319. },
  3320. set: function set(val) {
  3321. _MaxLen = val;
  3322. }
  3323. });
  3324. Object.defineProperty(this, 'hasAppearanceStream', {
  3325. enumerable: false,
  3326. get: function get() {
  3327. return this.V || this.DV;
  3328. }
  3329. });
  3330. };
  3331. AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
  3332. window["TextField"] = AcroForm.TextField;
  3333. AcroForm.PasswordField = function () {
  3334. TextField.call(this);
  3335. Object.defineProperty(this, 'password', {
  3336. value: true,
  3337. enumerable: false,
  3338. configurable: false,
  3339. writable: false
  3340. });
  3341. };
  3342. AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
  3343. window["PasswordField"] = AcroForm.PasswordField;
  3344. // ############ internal functions
  3345. /*
  3346. * small workaround for calculating the TextMetric approximately
  3347. * @param text
  3348. * @param fontsize
  3349. * @returns {TextMetrics} (Has Height and Width)
  3350. */
  3351. AcroForm.internal.calculateFontSpace = function (text, fontsize, fonttype) {
  3352. var fonttype = fonttype || "helvetica";
  3353. //re-use canvas object for speed improvements
  3354. var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
  3355. var context = canvas.getContext('2d');
  3356. context.save();
  3357. var newFont = fontsize + " " + fonttype;
  3358. context.font = newFont;
  3359. var res = context.measureText(text);
  3360. context.fontcolor = 'black';
  3361. // Calculate height:
  3362. var context = canvas.getContext('2d');
  3363. res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
  3364. context.restore();
  3365. var width = res.width;
  3366. return res;
  3367. };
  3368. AcroForm.internal.calculateX = function (formObject, text, font, maxFontSize) {
  3369. var maxFontSize = maxFontSize || 12;
  3370. var font = font || "helvetica";
  3371. var returnValue = {
  3372. text: "",
  3373. fontSize: ""
  3374. };
  3375. // Remove Brackets
  3376. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  3377. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
  3378. // split into array of words
  3379. var textSplit = text.split(' ');
  3380. /**
  3381. * the color could be ((alpha)||(r,g,b)||(c,m,y,k))
  3382. * @type {string}
  3383. */
  3384. var color = "0 g\n";
  3385. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3386. var lineSpacing = 2;
  3387. var borderPadding = 2;
  3388. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  3389. height = height < 0 ? -height : height;
  3390. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  3391. width = width < 0 ? -width : width;
  3392. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3393. if (i + 1 < textSplit.length) {
  3394. var tmp = lastLine + " " + textSplit[i + 1];
  3395. var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
  3396. var FieldWidth = width - 2 * borderPadding;
  3397. return TextWidth <= FieldWidth;
  3398. } else {
  3399. return false;
  3400. }
  3401. };
  3402. fontSize++;
  3403. FontSize: while (true) {
  3404. var text = "";
  3405. fontSize--;
  3406. var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
  3407. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3408. startY += lineSpacing;
  3409. var startX = -borderPadding;
  3410. var lastX = startX,
  3411. lastY = startY;
  3412. var firstWordInLine = 0,
  3413. lastWordInLine = 0;
  3414. var lastLength = 0;
  3415. var y = 0;
  3416. if (fontSize == 0) {
  3417. // In case, the Text doesn't fit at all
  3418. fontSize = 12;
  3419. text = "(...) Tj\n";
  3420. text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
  3421. break;
  3422. }
  3423. lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
  3424. var lastLine = "";
  3425. var lineCount = 0;
  3426. Line: for (var i in textSplit) {
  3427. lastLine += textSplit[i] + " ";
  3428. // Remove last blank
  3429. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3430. var key = parseInt(i);
  3431. lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
  3432. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3433. var isLastWord = i >= textSplit.length - 1;
  3434. if (nextLineIsSmaller && !isLastWord) {
  3435. lastLine += " ";
  3436. continue; // Line
  3437. } else if (!nextLineIsSmaller && !isLastWord) {
  3438. if (!formObject.multiline) {
  3439. continue FontSize;
  3440. } else {
  3441. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3442. // If the Text is higher than the FieldObject
  3443. continue FontSize;
  3444. }
  3445. lastWordInLine = key;
  3446. // go on
  3447. }
  3448. } else if (isLastWord) {
  3449. lastWordInLine = key;
  3450. } else {
  3451. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3452. // If the Text is higher than the FieldObject
  3453. continue FontSize;
  3454. }
  3455. }
  3456. var line = '';
  3457. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3458. line += textSplit[x] + ' ';
  3459. }
  3460. // Remove last blank
  3461. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
  3462. //lastLength -= blankSpace.width;
  3463. lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
  3464. // Calculate startX
  3465. switch (formObject.Q) {
  3466. case 2:
  3467. // Right justified
  3468. startX = width - lastLength - borderPadding;
  3469. break;
  3470. case 1:
  3471. // Q = 1 := Text-Alignment: Center
  3472. startX = (width - lastLength) / 2;
  3473. break;
  3474. case 0:
  3475. default:
  3476. startX = borderPadding;
  3477. break;
  3478. }
  3479. text += startX + ' ' + lastY + ' Td\n';
  3480. text += '(' + line + ') Tj\n';
  3481. // reset X in PDF
  3482. text += -startX + ' 0 Td\n';
  3483. // After a Line, adjust y position
  3484. lastY = -(fontSize + lineSpacing);
  3485. lastX = startX;
  3486. // Reset for next iteration step
  3487. lastLength = 0;
  3488. firstWordInLine = lastWordInLine + 1;
  3489. lineCount++;
  3490. lastLine = "";
  3491. continue Line;
  3492. }
  3493. break;
  3494. }
  3495. returnValue.text = text;
  3496. returnValue.fontSize = fontSize;
  3497. return returnValue;
  3498. };
  3499. AcroForm.internal.calculateAppearanceStream = function (formObject) {
  3500. if (formObject.appearanceStreamContent) {
  3501. // If appearanceStream is already set, use it
  3502. return formObject.appearanceStreamContent;
  3503. }
  3504. if (!formObject.V && !formObject.DV) {
  3505. return;
  3506. }
  3507. // else calculate it
  3508. var stream = '';
  3509. var text = formObject.V || formObject.DV;
  3510. var calcRes = AcroForm.internal.calculateX(formObject, text);
  3511. stream += '/Tx BMC\n' + 'q\n' +
  3512. //color + '\n' +
  3513. '/F1 ' + calcRes.fontSize + ' Tf\n' +
  3514. // Text Matrix
  3515. '1 0 0 1 0 0 Tm\n';
  3516. // Begin Text
  3517. stream += 'BT\n';
  3518. stream += calcRes.text;
  3519. // End Text
  3520. stream += 'ET\n';
  3521. stream += 'Q\n' + 'EMC\n';
  3522. var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
  3523. appearanceStreamContent.stream = stream;
  3524. var appearance = {
  3525. N: {
  3526. 'Normal': appearanceStreamContent
  3527. }
  3528. };
  3529. return appearanceStreamContent;
  3530. };
  3531. /*
  3532. * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
  3533. * @param x
  3534. * @param y
  3535. * @param w
  3536. * @param h
  3537. * @returns {*[]}
  3538. */
  3539. AcroForm.internal.calculateCoordinates = function (x, y, w, h) {
  3540. var coordinates = {};
  3541. if (this.internal) {
  3542. var mmtopx = function mmtopx(x) {
  3543. return x * this.internal.scaleFactor;
  3544. };
  3545. if (Array.isArray(x)) {
  3546. x[0] = AcroForm.scale(x[0]);
  3547. x[1] = AcroForm.scale(x[1]);
  3548. x[2] = AcroForm.scale(x[2]);
  3549. x[3] = AcroForm.scale(x[3]);
  3550. coordinates.lowerLeft_X = x[0] || 0;
  3551. coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
  3552. coordinates.upperRight_X = x[0] + x[2] || 0;
  3553. coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
  3554. } else {
  3555. x = AcroForm.scale(x);
  3556. y = AcroForm.scale(y);
  3557. w = AcroForm.scale(w);
  3558. h = AcroForm.scale(h);
  3559. coordinates.lowerLeft_X = x || 0;
  3560. coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
  3561. coordinates.upperRight_X = x + w || 0;
  3562. coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
  3563. }
  3564. } else {
  3565. // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
  3566. if (Array.isArray(x)) {
  3567. coordinates.lowerLeft_X = x[0] || 0;
  3568. coordinates.lowerLeft_Y = x[1] || 0;
  3569. coordinates.upperRight_X = x[0] + x[2] || 0;
  3570. coordinates.upperRight_Y = x[1] + x[3] || 0;
  3571. } else {
  3572. coordinates.lowerLeft_X = x || 0;
  3573. coordinates.lowerLeft_Y = y || 0;
  3574. coordinates.upperRight_X = x + w || 0;
  3575. coordinates.upperRight_Y = y + h || 0;
  3576. }
  3577. }
  3578. return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
  3579. };
  3580. AcroForm.internal.calculateColor = function (r, g, b) {
  3581. var color = new Array(3);
  3582. color.r = r | 0;
  3583. color.g = g | 0;
  3584. color.b = b | 0;
  3585. return color;
  3586. };
  3587. AcroForm.internal.getBitPosition = function (variable, position) {
  3588. variable = variable || 0;
  3589. var bitMask = 1;
  3590. bitMask = bitMask << position - 1;
  3591. return variable | bitMask;
  3592. };
  3593. AcroForm.internal.setBitPosition = function (variable, position, value) {
  3594. variable = variable || 0;
  3595. value = value || 1;
  3596. var bitMask = 1;
  3597. bitMask = bitMask << position - 1;
  3598. if (value == 1) {
  3599. // Set the Bit to 1
  3600. var variable = variable | bitMask;
  3601. } else {
  3602. // Set the Bit to 0
  3603. var variable = variable & ~bitMask;
  3604. }
  3605. return variable;
  3606. };
  3607. /**
  3608. * jsPDF addHTML PlugIn
  3609. * Copyright (c) 2014 Diego Casorran
  3610. *
  3611. * Licensed under the MIT License.
  3612. * http://opensource.org/licenses/mit-license
  3613. */
  3614. (function (jsPDFAPI) {
  3615. 'use strict';
  3616. /**
  3617. * Renders an HTML element to canvas object which added to the PDF
  3618. *
  3619. * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
  3620. * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
  3621. *
  3622. * @returns {jsPDF}
  3623. * @name addHTML
  3624. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  3625. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  3626. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  3627. * @param options {Object} Additional options, check the code below.
  3628. * @param callback {Function} to call when the rendering has finished.
  3629. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  3630. * case the image is positioned at 0x0 covering the whole PDF document
  3631. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  3632. * @deprecated This is being replace with a vector-supporting API. See
  3633. * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
  3634. */
  3635. jsPDFAPI.addHTML = function (element, x, y, options, callback) {
  3636. 'use strict';
  3637. if (typeof html2canvas === 'undefined' && typeof rasterizeHTML === 'undefined') throw new Error('You need either ' + 'https://github.com/niklasvh/html2canvas' + ' or https://github.com/cburgmer/rasterizeHTML.js');
  3638. if (typeof x !== 'number') {
  3639. options = x;
  3640. callback = y;
  3641. }
  3642. if (typeof options === 'function') {
  3643. callback = options;
  3644. options = null;
  3645. }
  3646. var I = this.internal,
  3647. K = I.scaleFactor,
  3648. W = I.pageSize.width,
  3649. H = I.pageSize.height;
  3650. options = options || {};
  3651. options.onrendered = function (obj) {
  3652. x = parseInt(x) || 0;
  3653. y = parseInt(y) || 0;
  3654. var dim = options.dim || {};
  3655. var h = dim.h || 0;
  3656. var w = dim.w || Math.min(W, obj.width / K) - x;
  3657. var format = 'JPEG';
  3658. if (options.format) format = options.format;
  3659. if (obj.height > H && options.pagesplit) {
  3660. var crop = function () {
  3661. var cy = 0;
  3662. while (1) {
  3663. var canvas = document.createElement('canvas');
  3664. canvas.width = Math.min(W * K, obj.width);
  3665. canvas.height = Math.min(H * K, obj.height - cy);
  3666. var ctx = canvas.getContext('2d');
  3667. ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
  3668. var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
  3669. this.addImage.apply(this, args);
  3670. cy += canvas.height;
  3671. if (cy >= obj.height) break;
  3672. this.addPage();
  3673. }
  3674. callback(w, cy, null, args);
  3675. }.bind(this);
  3676. if (obj.nodeName === 'CANVAS') {
  3677. var img = new Image();
  3678. img.onload = crop;
  3679. img.src = obj.toDataURL("image/png");
  3680. obj = img;
  3681. } else {
  3682. crop();
  3683. }
  3684. } else {
  3685. var alias = Math.random().toString(35);
  3686. var args = [obj, x, y, w, h, format, alias, 'SLOW'];
  3687. this.addImage.apply(this, args);
  3688. callback(w, h, alias, args);
  3689. }
  3690. }.bind(this);
  3691. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  3692. return html2canvas(element, options);
  3693. }
  3694. if (typeof rasterizeHTML !== 'undefined') {
  3695. var meth = 'drawDocument';
  3696. if (typeof element === 'string') {
  3697. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  3698. }
  3699. options.width = options.width || W * K;
  3700. return rasterizeHTML[meth](element, void 0, options).then(function (r) {
  3701. options.onrendered(r.image);
  3702. }, function (e) {
  3703. callback(null, e);
  3704. });
  3705. }
  3706. return null;
  3707. };
  3708. })(jsPDF.API);
  3709. /** @preserve
  3710. * jsPDF addImage plugin
  3711. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  3712. * 2013 Chris Dowling, https://github.com/gingerchris
  3713. * 2013 Trinh Ho, https://github.com/ineedfat
  3714. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  3715. * 2013 Norah Smith, https://github.com/burnburnrocket
  3716. * 2014 Diego Casorran, https://github.com/diegocr
  3717. * 2014 James Robb, https://github.com/jamesbrobb
  3718. *
  3719. *
  3720. */
  3721. (function (jsPDFAPI) {
  3722. 'use strict';
  3723. var namespace = 'addImage_',
  3724. supported_image_types = ['jpeg', 'jpg', 'png'];
  3725. // Image functionality ported from pdf.js
  3726. var putImage = function putImage(img) {
  3727. var objectNumber = this.internal.newObject(),
  3728. out = this.internal.write,
  3729. putStream = this.internal.putStream;
  3730. img['n'] = objectNumber;
  3731. out('<</Type /XObject');
  3732. out('/Subtype /Image');
  3733. out('/Width ' + img['w']);
  3734. out('/Height ' + img['h']);
  3735. if (img['cs'] === this.color_spaces.INDEXED) {
  3736. out('/ColorSpace [/Indexed /DeviceRGB '
  3737. // if an indexed png defines more than one colour with transparency, we've created a smask
  3738. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
  3739. } else {
  3740. out('/ColorSpace /' + img['cs']);
  3741. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  3742. out('/Decode [1 0 1 0 1 0 1 0]');
  3743. }
  3744. }
  3745. out('/BitsPerComponent ' + img['bpc']);
  3746. if ('f' in img) {
  3747. out('/Filter /' + img['f']);
  3748. }
  3749. if ('dp' in img) {
  3750. out('/DecodeParms <<' + img['dp'] + '>>');
  3751. }
  3752. if ('trns' in img && img['trns'].constructor == Array) {
  3753. var trns = '',
  3754. i = 0,
  3755. len = img['trns'].length;
  3756. for (; i < len; i++) {
  3757. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  3758. }out('/Mask [' + trns + ']');
  3759. }
  3760. if ('smask' in img) {
  3761. out('/SMask ' + (objectNumber + 1) + ' 0 R');
  3762. }
  3763. out('/Length ' + img['data'].length + '>>');
  3764. putStream(img['data']);
  3765. out('endobj');
  3766. // Soft mask
  3767. if ('smask' in img) {
  3768. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  3769. var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
  3770. if ('f' in img) smask.f = img['f'];
  3771. putImage.call(this, smask);
  3772. }
  3773. //Palette
  3774. if (img['cs'] === this.color_spaces.INDEXED) {
  3775. this.internal.newObject();
  3776. //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  3777. //putStream(zlib.compress(img['pal']));
  3778. out('<< /Length ' + img['pal'].length + '>>');
  3779. putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
  3780. out('endobj');
  3781. }
  3782. },
  3783. putResourcesCallback = function putResourcesCallback() {
  3784. var images = this.internal.collections[namespace + 'images'];
  3785. for (var i in images) {
  3786. putImage.call(this, images[i]);
  3787. }
  3788. },
  3789. putXObjectsDictCallback = function putXObjectsDictCallback() {
  3790. var images = this.internal.collections[namespace + 'images'],
  3791. out = this.internal.write,
  3792. image;
  3793. for (var i in images) {
  3794. image = images[i];
  3795. out('/I' + image['i'], image['n'], '0', 'R');
  3796. }
  3797. },
  3798. checkCompressValue = function checkCompressValue(value) {
  3799. if (value && typeof value === 'string') value = value.toUpperCase();
  3800. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  3801. },
  3802. getImages = function getImages() {
  3803. var images = this.internal.collections[namespace + 'images'];
  3804. //first run, so initialise stuff
  3805. if (!images) {
  3806. this.internal.collections[namespace + 'images'] = images = {};
  3807. this.internal.events.subscribe('putResources', putResourcesCallback);
  3808. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  3809. }
  3810. return images;
  3811. },
  3812. getImageIndex = function getImageIndex(images) {
  3813. var imageIndex = 0;
  3814. if (images) {
  3815. // this is NOT the first time this method is ran on this instance of jsPDF object.
  3816. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  3817. var i = 0;
  3818. for (var e in o) {
  3819. if (o.hasOwnProperty(e)) {
  3820. i++;
  3821. }
  3822. }
  3823. return i;
  3824. }(images);
  3825. }
  3826. return imageIndex;
  3827. },
  3828. notDefined = function notDefined(value) {
  3829. return typeof value === 'undefined' || value === null;
  3830. },
  3831. generateAliasFromData = function generateAliasFromData(data) {
  3832. return typeof data === 'string' && jsPDFAPI.sHashCode(data);
  3833. },
  3834. doesNotSupportImageType = function doesNotSupportImageType(type) {
  3835. return supported_image_types.indexOf(type) === -1;
  3836. },
  3837. processMethodNotEnabled = function processMethodNotEnabled(type) {
  3838. return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
  3839. },
  3840. isDOMElement = function isDOMElement(object) {
  3841. return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
  3842. },
  3843. createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
  3844. //if element is an image which uses data url definition, just return the dataurl
  3845. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  3846. var src = '' + element.getAttribute('src');
  3847. if (!angle && src.indexOf('data:image/') === 0) return src;
  3848. // only if the user doesn't care about a format
  3849. if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
  3850. }
  3851. if (element.nodeName === 'CANVAS') {
  3852. var canvas = element;
  3853. } else {
  3854. var canvas = document.createElement('canvas');
  3855. canvas.width = element.clientWidth || element.width;
  3856. canvas.height = element.clientHeight || element.height;
  3857. var ctx = canvas.getContext('2d');
  3858. if (!ctx) {
  3859. throw 'addImage requires canvas to be supported by browser.';
  3860. }
  3861. if (angle) {
  3862. var x,
  3863. y,
  3864. b,
  3865. c,
  3866. s,
  3867. w,
  3868. h,
  3869. to_radians = Math.PI / 180,
  3870. angleInRadians;
  3871. if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
  3872. x = angle.x;
  3873. y = angle.y;
  3874. b = angle.bg;
  3875. angle = angle.angle;
  3876. }
  3877. angleInRadians = angle * to_radians;
  3878. c = Math.abs(Math.cos(angleInRadians));
  3879. s = Math.abs(Math.sin(angleInRadians));
  3880. w = canvas.width;
  3881. h = canvas.height;
  3882. canvas.width = h * s + w * c;
  3883. canvas.height = h * c + w * s;
  3884. if (isNaN(x)) x = canvas.width / 2;
  3885. if (isNaN(y)) y = canvas.height / 2;
  3886. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3887. ctx.fillStyle = b || 'white';
  3888. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3889. ctx.save();
  3890. ctx.translate(x, y);
  3891. ctx.rotate(angleInRadians);
  3892. ctx.drawImage(element, -(w / 2), -(h / 2));
  3893. ctx.rotate(-angleInRadians);
  3894. ctx.translate(-x, -y);
  3895. ctx.restore();
  3896. } else {
  3897. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  3898. }
  3899. }
  3900. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  3901. },
  3902. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  3903. var cached_info;
  3904. if (images) {
  3905. for (var e in images) {
  3906. if (alias === images[e].alias) {
  3907. cached_info = images[e];
  3908. break;
  3909. }
  3910. }
  3911. }
  3912. return cached_info;
  3913. },
  3914. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  3915. if (!w && !h) {
  3916. w = -96;
  3917. h = -96;
  3918. }
  3919. if (w < 0) {
  3920. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  3921. }
  3922. if (h < 0) {
  3923. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  3924. }
  3925. if (w === 0) {
  3926. w = h * info['w'] / info['h'];
  3927. }
  3928. if (h === 0) {
  3929. h = w * info['h'] / info['w'];
  3930. }
  3931. return [w, h];
  3932. },
  3933. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
  3934. var dims = determineWidthAndHeight.call(this, w, h, info),
  3935. coord = this.internal.getCoordinateString,
  3936. vcoord = this.internal.getVerticalCoordinateString;
  3937. w = dims[0];
  3938. h = dims[1];
  3939. images[index] = info;
  3940. this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
  3941. , coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
  3942. };
  3943. /**
  3944. * COLOR SPACES
  3945. */
  3946. jsPDFAPI.color_spaces = {
  3947. DEVICE_RGB: 'DeviceRGB',
  3948. DEVICE_GRAY: 'DeviceGray',
  3949. DEVICE_CMYK: 'DeviceCMYK',
  3950. CAL_GREY: 'CalGray',
  3951. CAL_RGB: 'CalRGB',
  3952. LAB: 'Lab',
  3953. ICC_BASED: 'ICCBased',
  3954. INDEXED: 'Indexed',
  3955. PATTERN: 'Pattern',
  3956. SEPARATION: 'Separation',
  3957. DEVICE_N: 'DeviceN'
  3958. };
  3959. /**
  3960. * DECODE METHODS
  3961. */
  3962. jsPDFAPI.decode = {
  3963. DCT_DECODE: 'DCTDecode',
  3964. FLATE_DECODE: 'FlateDecode',
  3965. LZW_DECODE: 'LZWDecode',
  3966. JPX_DECODE: 'JPXDecode',
  3967. JBIG2_DECODE: 'JBIG2Decode',
  3968. ASCII85_DECODE: 'ASCII85Decode',
  3969. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  3970. RUN_LENGTH_DECODE: 'RunLengthDecode',
  3971. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  3972. };
  3973. /**
  3974. * IMAGE COMPRESSION TYPES
  3975. */
  3976. jsPDFAPI.image_compression = {
  3977. NONE: 'NONE',
  3978. FAST: 'FAST',
  3979. MEDIUM: 'MEDIUM',
  3980. SLOW: 'SLOW'
  3981. };
  3982. jsPDFAPI.sHashCode = function (str) {
  3983. return Array.prototype.reduce && str.split("").reduce(function (a, b) {
  3984. a = (a << 5) - a + b.charCodeAt(0);return a & a;
  3985. }, 0);
  3986. };
  3987. jsPDFAPI.isString = function (object) {
  3988. return typeof object === 'string';
  3989. };
  3990. /**
  3991. * Strips out and returns info from a valid base64 data URI
  3992. * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  3993. * @returns an Array containing the following
  3994. * [0] the complete data URI
  3995. * [1] <MIME-type>
  3996. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  3997. * [4] <data>
  3998. */
  3999. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  4000. return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI)
  4001. );
  4002. };
  4003. /**
  4004. * Check to see if ArrayBuffer is supported
  4005. */
  4006. jsPDFAPI.supportsArrayBuffer = function () {
  4007. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  4008. };
  4009. /**
  4010. * Tests supplied object to determine if ArrayBuffer
  4011. * @param {Object[object]}
  4012. */
  4013. jsPDFAPI.isArrayBuffer = function (object) {
  4014. if (!this.supportsArrayBuffer()) return false;
  4015. return object instanceof ArrayBuffer;
  4016. };
  4017. /**
  4018. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  4019. * @param {Object[object]}
  4020. */
  4021. jsPDFAPI.isArrayBufferView = function (object) {
  4022. if (!this.supportsArrayBuffer()) return false;
  4023. if (typeof Uint32Array === 'undefined') return false;
  4024. return object instanceof Int8Array || object instanceof Uint8Array || typeof Uint8ClampedArray !== 'undefined' && object instanceof Uint8ClampedArray || object instanceof Int16Array || object instanceof Uint16Array || object instanceof Int32Array || object instanceof Uint32Array || object instanceof Float32Array || object instanceof Float64Array;
  4025. };
  4026. /**
  4027. * Exactly what it says on the tin
  4028. */
  4029. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  4030. /*
  4031. * not sure how efficient this will be will bigger files. Is there a native method?
  4032. */
  4033. var len = binary_string.length;
  4034. var bytes = new Uint8Array(len);
  4035. for (var i = 0; i < len; i++) {
  4036. bytes[i] = binary_string.charCodeAt(i);
  4037. }
  4038. return bytes;
  4039. };
  4040. /**
  4041. * @see this discussion
  4042. * http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers
  4043. *
  4044. * As stated, i imagine the method below is highly inefficent for large files.
  4045. *
  4046. * Also of note from Mozilla,
  4047. *
  4048. * "However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats)."
  4049. *
  4050. * https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView
  4051. *
  4052. * Although i'm strugglig to see how StringView solves this issue? Doesn't appear to be a direct method for conversion?
  4053. *
  4054. * Async method using Blob and FileReader could be best, but i'm not sure how to fit it into the flow?
  4055. */
  4056. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  4057. /*if('TextDecoder' in window){
  4058. var decoder = new TextDecoder('ascii');
  4059. return decoder.decode(buffer);
  4060. }*/
  4061. if (this.isArrayBuffer(buffer)) buffer = new Uint8Array(buffer);
  4062. var binary_string = '';
  4063. var len = buffer.byteLength;
  4064. for (var i = 0; i < len; i++) {
  4065. binary_string += String.fromCharCode(buffer[i]);
  4066. }
  4067. return binary_string;
  4068. /*
  4069. * Another solution is the method below - convert array buffer straight to base64 and then use atob
  4070. */
  4071. //return atob(this.arrayBufferToBase64(buffer));
  4072. };
  4073. /**
  4074. * Converts an ArrayBuffer directly to base64
  4075. *
  4076. * Taken from here
  4077. *
  4078. * http://jsperf.com/encoding-xhr-image-data/31
  4079. *
  4080. * Need to test if this is a better solution for larger files
  4081. *
  4082. */
  4083. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  4084. var base64 = '';
  4085. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  4086. var bytes = new Uint8Array(arrayBuffer);
  4087. var byteLength = bytes.byteLength;
  4088. var byteRemainder = byteLength % 3;
  4089. var mainLength = byteLength - byteRemainder;
  4090. var a, b, c, d;
  4091. var chunk;
  4092. // Main loop deals with bytes in chunks of 3
  4093. for (var i = 0; i < mainLength; i = i + 3) {
  4094. // Combine the three bytes into a single integer
  4095. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
  4096. // Use bitmasks to extract 6-bit segments from the triplet
  4097. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  4098. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  4099. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  4100. d = chunk & 63; // 63 = 2^6 - 1
  4101. // Convert the raw binary segments to the appropriate ASCII encoding
  4102. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  4103. }
  4104. // Deal with the remaining bytes and padding
  4105. if (byteRemainder == 1) {
  4106. chunk = bytes[mainLength];
  4107. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  4108. // Set the 4 least significant bits to zero
  4109. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  4110. base64 += encodings[a] + encodings[b] + '==';
  4111. } else if (byteRemainder == 2) {
  4112. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  4113. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  4114. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  4115. // Set the 2 least significant bits to zero
  4116. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  4117. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  4118. }
  4119. return base64;
  4120. };
  4121. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  4122. var info = {
  4123. alias: alias,
  4124. w: wd,
  4125. h: ht,
  4126. cs: cs,
  4127. bpc: bpc,
  4128. i: imageIndex,
  4129. data: data
  4130. // n: objectNumber will be added by putImage code
  4131. };
  4132. if (f) info.f = f;
  4133. if (dp) info.dp = dp;
  4134. if (trns) info.trns = trns;
  4135. if (pal) info.pal = pal;
  4136. if (smask) info.smask = smask;
  4137. if (p) info.p = p; // predictor parameter for PNG compression
  4138. return info;
  4139. };
  4140. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  4141. 'use strict';
  4142. if (typeof format !== 'string') {
  4143. var tmp = h;
  4144. h = w;
  4145. w = y;
  4146. y = x;
  4147. x = format;
  4148. format = tmp;
  4149. }
  4150. if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  4151. var options = imageData;
  4152. imageData = options.imageData;
  4153. format = options.format || format;
  4154. x = options.x || x || 0;
  4155. y = options.y || y || 0;
  4156. w = options.w || w;
  4157. h = options.h || h;
  4158. alias = options.alias || alias;
  4159. compression = options.compression || compression;
  4160. rotation = options.rotation || options.angle || rotation;
  4161. }
  4162. if (isNaN(x) || isNaN(y)) {
  4163. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  4164. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  4165. }
  4166. var images = getImages.call(this),
  4167. info;
  4168. if (!(info = checkImagesForAlias(imageData, images))) {
  4169. var dataAsBinaryString;
  4170. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
  4171. if (notDefined(alias)) alias = generateAliasFromData(imageData);
  4172. if (!(info = checkImagesForAlias(alias, images))) {
  4173. if (this.isString(imageData)) {
  4174. var base64Info = this.extractInfoFromBase64DataURI(imageData);
  4175. if (base64Info) {
  4176. format = base64Info[2];
  4177. imageData = atob(base64Info[3]); //convert to binary string
  4178. } else {
  4179. if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
  4180. }
  4181. }
  4182. format = (format || 'JPEG').toLowerCase();
  4183. if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
  4184. if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
  4185. /**
  4186. * need to test if it's more efficient to convert all binary strings
  4187. * to TypedArray - or should we just leave and process as string?
  4188. */
  4189. if (this.supportsArrayBuffer()) {
  4190. // no need to convert if imageData is already uint8array
  4191. if (!(imageData instanceof Uint8Array)) {
  4192. dataAsBinaryString = imageData;
  4193. imageData = this.binaryStringToUint8Array(imageData);
  4194. }
  4195. }
  4196. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  4197. if (!info) throw new Error('An unkwown error occurred whilst processing the image');
  4198. }
  4199. }
  4200. writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
  4201. return this;
  4202. };
  4203. /**
  4204. * JPEG SUPPORT
  4205. **/
  4206. //takes a string imgData containing the raw bytes of
  4207. //a jpeg image and returns [width, height]
  4208. //Algorithm from: http://www.64lines.com/jpeg-width-height
  4209. var getJpegSize = function getJpegSize(imgData) {
  4210. 'use strict';
  4211. var width, height, numcomponents;
  4212. // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  4213. if (!imgData.charCodeAt(0) === 0xff || !imgData.charCodeAt(1) === 0xd8 || !imgData.charCodeAt(2) === 0xff || !imgData.charCodeAt(3) === 0xe0 || !imgData.charCodeAt(6) === 'J'.charCodeAt(0) || !imgData.charCodeAt(7) === 'F'.charCodeAt(0) || !imgData.charCodeAt(8) === 'I'.charCodeAt(0) || !imgData.charCodeAt(9) === 'F'.charCodeAt(0) || !imgData.charCodeAt(10) === 0x00) {
  4214. throw new Error('getJpegSize requires a binary string jpeg file');
  4215. }
  4216. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  4217. var i = 4,
  4218. len = imgData.length;
  4219. while (i < len) {
  4220. i += blockLength;
  4221. if (imgData.charCodeAt(i) !== 0xff) {
  4222. throw new Error('getJpegSize could not find the size of the image');
  4223. }
  4224. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  4225. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  4226. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  4227. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  4228. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  4229. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  4230. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  4231. imgData.charCodeAt(i + 1) === 0xc7) {
  4232. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  4233. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  4234. numcomponents = imgData.charCodeAt(i + 9);
  4235. return [width, height, numcomponents];
  4236. } else {
  4237. i += 2;
  4238. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  4239. }
  4240. }
  4241. },
  4242. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  4243. var hdr = data[0] << 8 | data[1];
  4244. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  4245. var len = data.length,
  4246. block = (data[4] << 8) + data[5],
  4247. pos = 4,
  4248. bytes,
  4249. width,
  4250. height,
  4251. numcomponents;
  4252. while (pos < len) {
  4253. pos += block;
  4254. bytes = readBytes(data, pos);
  4255. block = (bytes[2] << 8) + bytes[3];
  4256. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  4257. bytes = readBytes(data, pos + 5);
  4258. width = (bytes[2] << 8) + bytes[3];
  4259. height = (bytes[0] << 8) + bytes[1];
  4260. numcomponents = bytes[4];
  4261. return { width: width, height: height, numcomponents: numcomponents };
  4262. }
  4263. pos += 2;
  4264. }
  4265. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  4266. },
  4267. readBytes = function readBytes(data, offset) {
  4268. return data.subarray(offset, offset + 5);
  4269. };
  4270. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString) {
  4271. 'use strict';
  4272. var colorSpace = this.color_spaces.DEVICE_RGB,
  4273. filter = this.decode.DCT_DECODE,
  4274. bpc = 8,
  4275. dims;
  4276. if (this.isString(data)) {
  4277. dims = getJpegSize(data);
  4278. return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4279. }
  4280. if (this.isArrayBuffer(data)) data = new Uint8Array(data);
  4281. if (this.isArrayBufferView(data)) {
  4282. dims = getJpegSizeFromBytes(data);
  4283. // if we already have a stored binary string rep use that
  4284. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  4285. return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4286. }
  4287. return null;
  4288. };
  4289. jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
  4290. return this.processJPEG.apply(this, arguments);
  4291. };
  4292. })(jsPDF.API);
  4293. /**
  4294. * jsPDF Annotations PlugIn
  4295. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4296. *
  4297. * Licensed under the MIT License.
  4298. * http://opensource.org/licenses/mit-license
  4299. */
  4300. /**
  4301. * There are many types of annotations in a PDF document. Annotations are placed
  4302. * on a page at a particular location. They are not 'attached' to an object.
  4303. * <br />
  4304. * This plugin current supports <br />
  4305. * <li> Goto Page (set pageNumber and top in options)
  4306. * <li> Goto Name (set name and top in options)
  4307. * <li> Goto URL (set url in options)
  4308. * <p>
  4309. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  4310. * (set magFactor in options). XYZ is the default.
  4311. * </p>
  4312. * <p>
  4313. * Links, Text, Popup, and FreeText are supported.
  4314. * </p>
  4315. * <p>
  4316. * Options In PDF spec Not Implemented Yet
  4317. * <li> link border
  4318. * <li> named target
  4319. * <li> page coordinates
  4320. * <li> destination page scaling and layout
  4321. * <li> actions other than URL and GotoPage
  4322. * <li> background / hover actions
  4323. * </p>
  4324. */
  4325. /*
  4326. Destination Magnification Factors
  4327. See PDF 1.3 Page 386 for meanings and options
  4328. [supported]
  4329. XYZ (options; left top zoom)
  4330. Fit (no options)
  4331. FitH (options: top)
  4332. FitV (options: left)
  4333. [not supported]
  4334. FitR
  4335. FitB
  4336. FitBH
  4337. FitBV
  4338. */
  4339. (function (jsPDFAPI) {
  4340. 'use strict';
  4341. var annotationPlugin = {
  4342. /**
  4343. * An array of arrays, indexed by <em>pageNumber</em>.
  4344. */
  4345. annotations: [],
  4346. f2: function f2(number) {
  4347. return number.toFixed(2);
  4348. },
  4349. notEmpty: function notEmpty(obj) {
  4350. if (typeof obj != 'undefined') {
  4351. if (obj != '') {
  4352. return true;
  4353. }
  4354. }
  4355. }
  4356. };
  4357. jsPDF.API.annotationPlugin = annotationPlugin;
  4358. jsPDF.API.events.push(['addPage', function (info) {
  4359. this.annotationPlugin.annotations[info.pageNumber] = [];
  4360. }]);
  4361. jsPDFAPI.events.push(['putPage', function (info) {
  4362. //TODO store annotations in pageContext so reorder/remove will not affect them.
  4363. var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
  4364. var found = false;
  4365. for (var a = 0; a < pageAnnos.length && !found; a++) {
  4366. var anno = pageAnnos[a];
  4367. switch (anno.type) {
  4368. case 'link':
  4369. if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
  4370. found = true;
  4371. break;
  4372. }
  4373. case 'reference':
  4374. case 'text':
  4375. case 'freetext':
  4376. found = true;
  4377. break;
  4378. }
  4379. }
  4380. if (found == false) {
  4381. return;
  4382. }
  4383. this.internal.write("/Annots [");
  4384. var f2 = this.annotationPlugin.f2;
  4385. var k = this.internal.scaleFactor;
  4386. var pageHeight = this.internal.pageSize.height;
  4387. var pageInfo = this.internal.getPageInfo(info.pageNumber);
  4388. for (var a = 0; a < pageAnnos.length; a++) {
  4389. var anno = pageAnnos[a];
  4390. switch (anno.type) {
  4391. case 'reference':
  4392. // References to Widget Anotations (for AcroForm Fields)
  4393. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  4394. break;
  4395. case 'text':
  4396. // Create a an object for both the text and the popup
  4397. var objText = this.internal.newAdditionalObject();
  4398. var objPopup = this.internal.newAdditionalObject();
  4399. var title = anno.title || 'Note';
  4400. var rect = "/Rect [" + f2(anno.bounds.x * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + " " + f2((anno.bounds.x + anno.bounds.w) * k) + " " + f2((pageHeight - anno.bounds.y) * k) + "] ";
  4401. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4402. line += ' /Popup ' + objPopup.objId + " 0 R";
  4403. line += ' /P ' + pageInfo.objId + " 0 R";
  4404. line += ' /T (' + title + ') >>';
  4405. objText.content = line;
  4406. var parent = objText.objId + ' 0 R';
  4407. var popoff = 30;
  4408. var rect = "/Rect [" + f2((anno.bounds.x + popoff) * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + " " + f2((anno.bounds.x + anno.bounds.w + popoff) * k) + " " + f2((pageHeight - anno.bounds.y) * k) + "] ";
  4409. //var rect2 = "/Rect [" + f2(anno.bounds.x * k) + " " + f2((pageHeight - anno.bounds.y) * k) + " " + f2(anno.bounds.x + anno.bounds.w * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + "] ";
  4410. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  4411. if (anno.open) {
  4412. line += ' /Open true';
  4413. }
  4414. line += ' >>';
  4415. objPopup.content = line;
  4416. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  4417. break;
  4418. case 'freetext':
  4419. var rect = "/Rect [" + f2(anno.bounds.x * k) + " " + f2((pageHeight - anno.bounds.y) * k) + " " + f2(anno.bounds.x + anno.bounds.w * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + "] ";
  4420. var color = anno.color || '#000000';
  4421. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4422. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  4423. line += ' /Border [0 0 0]';
  4424. line += ' >>';
  4425. this.internal.write(line);
  4426. break;
  4427. case 'link':
  4428. if (anno.options.name) {
  4429. var loc = this.annotations._nameMap[anno.options.name];
  4430. anno.options.pageNumber = loc.page;
  4431. anno.options.top = loc.y;
  4432. } else {
  4433. if (!anno.options.top) {
  4434. anno.options.top = 0;
  4435. }
  4436. }
  4437. //var pageHeight = this.internal.pageSize.height * this.internal.scaleFactor;
  4438. var rect = "/Rect [" + f2(anno.x * k) + " " + f2((pageHeight - anno.y) * k) + " " + f2(anno.x + anno.w * k) + " " + f2(pageHeight - (anno.y + anno.h) * k) + "] ";
  4439. var line = '';
  4440. if (anno.options.url) {
  4441. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  4442. } else if (anno.options.pageNumber) {
  4443. // first page is 0
  4444. var info = this.internal.getPageInfo(anno.options.pageNumber);
  4445. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  4446. anno.options.magFactor = anno.options.magFactor || "XYZ";
  4447. switch (anno.options.magFactor) {
  4448. case 'Fit':
  4449. line += ' /Fit]';
  4450. break;
  4451. case 'FitH':
  4452. //anno.options.top = anno.options.top || f2(pageHeight * k);
  4453. line += ' /FitH ' + anno.options.top + ']';
  4454. break;
  4455. case 'FitV':
  4456. anno.options.left = anno.options.left || 0;
  4457. line += ' /FitV ' + anno.options.left + ']';
  4458. break;
  4459. case 'XYZ':
  4460. default:
  4461. var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
  4462. anno.options.left = anno.options.left || 0;
  4463. // 0 or null zoom will not change zoom factor
  4464. if (typeof anno.options.zoom === 'undefined') {
  4465. anno.options.zoom = 0;
  4466. }
  4467. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  4468. break;
  4469. }
  4470. } else {
  4471. // TODO error - should not be here
  4472. }
  4473. if (line != '') {
  4474. line += " >>";
  4475. this.internal.write(line);
  4476. }
  4477. break;
  4478. }
  4479. }
  4480. this.internal.write("]");
  4481. }]);
  4482. jsPDFAPI.createAnnotation = function (options) {
  4483. switch (options.type) {
  4484. case 'link':
  4485. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  4486. break;
  4487. case 'text':
  4488. case 'freetext':
  4489. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
  4490. break;
  4491. }
  4492. };
  4493. /**
  4494. * valid options
  4495. * <li> pageNumber or url [required]
  4496. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4497. */
  4498. jsPDFAPI.link = function (x, y, w, h, options) {
  4499. 'use strict';
  4500. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4501. x: x,
  4502. y: y,
  4503. w: w,
  4504. h: h,
  4505. options: options,
  4506. type: 'link'
  4507. });
  4508. };
  4509. /**
  4510. * valid options
  4511. * <li> pageNumber or url [required]
  4512. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4513. */
  4514. jsPDFAPI.link = function (x, y, w, h, options) {
  4515. 'use strict';
  4516. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4517. x: x,
  4518. y: y,
  4519. w: w,
  4520. h: h,
  4521. options: options,
  4522. type: 'link'
  4523. });
  4524. };
  4525. /**
  4526. * Currently only supports single line text.
  4527. * Returns the width of the text/link
  4528. */
  4529. jsPDFAPI.textWithLink = function (text, x, y, options) {
  4530. 'use strict';
  4531. var width = this.getTextWidth(text);
  4532. var height = this.internal.getLineHeight();
  4533. this.text(text, x, y);
  4534. //TODO We really need the text baseline height to do this correctly.
  4535. // Or ability to draw text on top, bottom, center, or baseline.
  4536. y += height * .2;
  4537. this.link(x, y - height, width, height, options);
  4538. return width;
  4539. };
  4540. //TODO move into external library
  4541. jsPDFAPI.getTextWidth = function (text) {
  4542. 'use strict';
  4543. var fontSize = this.internal.getFontSize();
  4544. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  4545. return txtWidth;
  4546. };
  4547. //TODO move into external library
  4548. jsPDFAPI.getLineHeight = function () {
  4549. return this.internal.getLineHeight();
  4550. };
  4551. return this;
  4552. })(jsPDF.API);
  4553. /**
  4554. * jsPDF Autoprint Plugin
  4555. *
  4556. * Licensed under the MIT License.
  4557. * http://opensource.org/licenses/mit-license
  4558. */
  4559. /**
  4560. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  4561. * Reader.
  4562. *
  4563. * @returns {jsPDF}
  4564. * @name autoPrint
  4565. * @example
  4566. * var doc = new jsPDF()
  4567. * doc.text(10, 10, 'This is a test')
  4568. * doc.autoPrint()
  4569. * doc.save('autoprint.pdf')
  4570. */
  4571. (function (jsPDFAPI) {
  4572. 'use strict';
  4573. jsPDFAPI.autoPrint = function () {
  4574. 'use strict';
  4575. var refAutoPrintTag;
  4576. this.internal.events.subscribe('postPutResources', function () {
  4577. refAutoPrintTag = this.internal.newObject();
  4578. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  4579. });
  4580. this.internal.events.subscribe("putCatalog", function () {
  4581. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  4582. });
  4583. return this;
  4584. };
  4585. })(jsPDF.API);
  4586. /**
  4587. * jsPDF Canvas PlugIn
  4588. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4589. *
  4590. * Licensed under the MIT License.
  4591. * http://opensource.org/licenses/mit-license
  4592. */
  4593. /**
  4594. * This plugin mimics the HTML5 Canvas
  4595. *
  4596. * The goal is to provide a way for current canvas users to print directly to a PDF.
  4597. */
  4598. (function (jsPDFAPI) {
  4599. 'use strict';
  4600. jsPDFAPI.events.push(['initialized', function () {
  4601. this.canvas.pdf = this;
  4602. }]);
  4603. jsPDFAPI.canvas = {
  4604. getContext: function getContext(name) {
  4605. this.pdf.context2d._canvas = this;
  4606. return this.pdf.context2d;
  4607. },
  4608. style: {}
  4609. };
  4610. Object.defineProperty(jsPDFAPI.canvas, 'width', {
  4611. get: function get() {
  4612. return this._width;
  4613. },
  4614. set: function set(value) {
  4615. this._width = value;
  4616. this.getContext('2d').pageWrapX = value + 1;
  4617. }
  4618. });
  4619. Object.defineProperty(jsPDFAPI.canvas, 'height', {
  4620. get: function get() {
  4621. return this._height;
  4622. },
  4623. set: function set(value) {
  4624. this._height = value;
  4625. this.getContext('2d').pageWrapY = value + 1;
  4626. }
  4627. });
  4628. return this;
  4629. })(jsPDF.API);
  4630. /** ====================================================================
  4631. * jsPDF Cell plugin
  4632. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  4633. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  4634. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  4635. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  4636. * 2014 James Hall, james@parall.ax
  4637. * 2014 Diego Casorran, https://github.com/diegocr
  4638. *
  4639. *
  4640. * ====================================================================
  4641. */
  4642. (function (jsPDFAPI) {
  4643. 'use strict';
  4644. /*jslint browser:true */
  4645. /*global document: false, jsPDF */
  4646. var fontName,
  4647. fontSize,
  4648. fontStyle,
  4649. padding = 3,
  4650. margin = 13,
  4651. headerFunction,
  4652. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
  4653. pages = 1,
  4654. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  4655. lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
  4656. },
  4657. getLastCellPosition = function getLastCellPosition() {
  4658. return lastCellPos;
  4659. },
  4660. NO_MARGINS = { left: 0, top: 0, bottom: 0 };
  4661. jsPDFAPI.setHeaderFunction = function (func) {
  4662. headerFunction = func;
  4663. };
  4664. jsPDFAPI.getTextDimensions = function (txt) {
  4665. fontName = this.internal.getFont().fontName;
  4666. fontSize = this.table_font_size || this.internal.getFontSize();
  4667. fontStyle = this.internal.getFont().fontStyle;
  4668. // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
  4669. var px2pt = 0.264583 * 72 / 25.4,
  4670. dimensions,
  4671. text;
  4672. text = document.createElement('font');
  4673. text.id = "jsPDFCell";
  4674. try {
  4675. text.style.fontStyle = fontStyle;
  4676. } catch (e) {
  4677. text.style.fontWeight = fontStyle;
  4678. }
  4679. text.style.fontName = fontName;
  4680. text.style.fontSize = fontSize + 'pt';
  4681. try {
  4682. text.textContent = txt;
  4683. } catch (e) {
  4684. text.innerText = txt;
  4685. }
  4686. document.body.appendChild(text);
  4687. dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
  4688. document.body.removeChild(text);
  4689. return dimensions;
  4690. };
  4691. jsPDFAPI.cellAddPage = function () {
  4692. var margins = this.margins || NO_MARGINS;
  4693. this.addPage();
  4694. setLastCellPosition(margins.left, margins.top, undefined, undefined);
  4695. //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  4696. pages += 1;
  4697. };
  4698. jsPDFAPI.cellInitialize = function () {
  4699. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
  4700. pages = 1;
  4701. };
  4702. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  4703. var curCell = getLastCellPosition();
  4704. var pgAdded = false;
  4705. // If this is not the first cell, we must change its position
  4706. if (curCell.ln !== undefined) {
  4707. if (curCell.ln === ln) {
  4708. //Same line
  4709. x = curCell.x + curCell.w;
  4710. y = curCell.y;
  4711. } else {
  4712. //New line
  4713. var margins = this.margins || NO_MARGINS;
  4714. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
  4715. this.cellAddPage();
  4716. pgAdded = true;
  4717. if (this.printHeaders && this.tableHeaderRow) {
  4718. this.printHeaderRow(ln, true);
  4719. }
  4720. }
  4721. //We ignore the passed y: the lines may have different heights
  4722. y = getLastCellPosition().y + getLastCellPosition().h;
  4723. if (pgAdded) y = margin + 10;
  4724. }
  4725. }
  4726. if (txt[0] !== undefined) {
  4727. if (this.printingHeaderRow) {
  4728. this.rect(x, y, w, h, 'FD');
  4729. } else {
  4730. this.rect(x, y, w, h);
  4731. }
  4732. if (align === 'right') {
  4733. if (!(txt instanceof Array)) {
  4734. txt = [txt];
  4735. }
  4736. for (var i = 0; i < txt.length; i++) {
  4737. var currentLine = txt[i];
  4738. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
  4739. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  4740. }
  4741. } else {
  4742. this.text(txt, x + padding, y + this.internal.getLineHeight());
  4743. }
  4744. }
  4745. setLastCellPosition(x, y, w, h, ln);
  4746. return this;
  4747. };
  4748. /**
  4749. * Return the maximum value from an array
  4750. * @param array
  4751. * @param comparisonFn
  4752. * @returns {*}
  4753. */
  4754. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  4755. var max = array[0],
  4756. i,
  4757. ln,
  4758. item;
  4759. for (i = 0, ln = array.length; i < ln; i += 1) {
  4760. item = array[i];
  4761. if (comparisonFn) {
  4762. if (comparisonFn(max, item) === -1) {
  4763. max = item;
  4764. }
  4765. } else {
  4766. if (item > max) {
  4767. max = item;
  4768. }
  4769. }
  4770. }
  4771. return max;
  4772. };
  4773. /**
  4774. * Create a table from a set of data.
  4775. * @param {Integer} [x] : left-position for top-left corner of table
  4776. * @param {Integer} [y] top-position for top-left corner of table
  4777. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  4778. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  4779. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  4780. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  4781. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  4782. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  4783. */
  4784. jsPDFAPI.table = function (x, y, data, headers, config) {
  4785. if (!data) {
  4786. throw 'No data for PDF table';
  4787. }
  4788. var headerNames = [],
  4789. headerPrompts = [],
  4790. header,
  4791. i,
  4792. ln,
  4793. cln,
  4794. columnMatrix = {},
  4795. columnWidths = {},
  4796. columnData,
  4797. column,
  4798. columnMinWidths = [],
  4799. j,
  4800. tableHeaderConfigs = [],
  4801. model,
  4802. jln,
  4803. func,
  4804. //set up defaults. If a value is provided in config, defaults will be overwritten:
  4805. autoSize = false,
  4806. printHeaders = true,
  4807. fontSize = 12,
  4808. margins = NO_MARGINS;
  4809. margins.width = this.internal.pageSize.width;
  4810. if (config) {
  4811. //override config defaults if the user has specified non-default behavior:
  4812. if (config.autoSize === true) {
  4813. autoSize = true;
  4814. }
  4815. if (config.printHeaders === false) {
  4816. printHeaders = false;
  4817. }
  4818. if (config.fontSize) {
  4819. fontSize = config.fontSize;
  4820. }
  4821. if (config.css && typeof config.css['font-size'] !== "undefined") {
  4822. fontSize = config.css['font-size'] * 16;
  4823. }
  4824. if (config.margins) {
  4825. margins = config.margins;
  4826. }
  4827. }
  4828. /**
  4829. * @property {Number} lnMod
  4830. * Keep track of the current line number modifier used when creating cells
  4831. */
  4832. this.lnMod = 0;
  4833. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
  4834. this.printHeaders = printHeaders;
  4835. this.margins = margins;
  4836. this.setFontSize(fontSize);
  4837. this.table_font_size = fontSize;
  4838. // Set header values
  4839. if (headers === undefined || headers === null) {
  4840. // No headers defined so we derive from data
  4841. headerNames = Object.keys(data[0]);
  4842. } else if (headers[0] && typeof headers[0] !== 'string') {
  4843. var px2pt = 0.264583 * 72 / 25.4;
  4844. // Split header configs into names and prompts
  4845. for (i = 0, ln = headers.length; i < ln; i += 1) {
  4846. header = headers[i];
  4847. headerNames.push(header.name);
  4848. headerPrompts.push(header.prompt);
  4849. columnWidths[header.name] = header.width * px2pt;
  4850. }
  4851. } else {
  4852. headerNames = headers;
  4853. }
  4854. if (autoSize) {
  4855. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  4856. func = function func(rec) {
  4857. return rec[header];
  4858. };
  4859. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4860. header = headerNames[i];
  4861. columnMatrix[header] = data.map(func);
  4862. // get header width
  4863. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
  4864. column = columnMatrix[header];
  4865. // get cell widths
  4866. for (j = 0, cln = column.length; j < cln; j += 1) {
  4867. columnData = column[j];
  4868. columnMinWidths.push(this.getTextDimensions(columnData).w);
  4869. }
  4870. // get final column width
  4871. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
  4872. //have to reset
  4873. columnMinWidths = [];
  4874. }
  4875. }
  4876. // -- Construct the table
  4877. if (printHeaders) {
  4878. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
  4879. // Construct the header row
  4880. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4881. header = headerNames[i];
  4882. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  4883. }
  4884. // Store the table header config
  4885. this.setTableHeaderRow(tableHeaderConfigs);
  4886. // Print the header for the start of the table
  4887. this.printHeaderRow(1, false);
  4888. }
  4889. // Construct the data rows
  4890. for (i = 0, ln = data.length; i < ln; i += 1) {
  4891. var lineHeight;
  4892. model = data[i];
  4893. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  4894. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  4895. header = headerNames[j];
  4896. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  4897. }
  4898. }
  4899. this.lastCellPos = lastCellPos;
  4900. this.table_x = x;
  4901. this.table_y = y;
  4902. return this;
  4903. };
  4904. /**
  4905. * Calculate the height for containing the highest column
  4906. * @param {String[]} headerNames is the header, used as keys to the data
  4907. * @param {Integer[]} columnWidths is size of each column
  4908. * @param {Object[]} model is the line of data we want to calculate the height of
  4909. */
  4910. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  4911. var header,
  4912. lineHeight = 0;
  4913. for (var j = 0; j < headerNames.length; j++) {
  4914. header = headerNames[j];
  4915. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  4916. var h = this.internal.getLineHeight() * model[header].length + padding;
  4917. if (h > lineHeight) lineHeight = h;
  4918. }
  4919. return lineHeight;
  4920. };
  4921. /**
  4922. * Store the config for outputting a table header
  4923. * @param {Object[]} config
  4924. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  4925. * except the ln parameter is excluded
  4926. */
  4927. jsPDFAPI.setTableHeaderRow = function (config) {
  4928. this.tableHeaderRow = config;
  4929. };
  4930. /**
  4931. * Output the store header row
  4932. * @param lineNumber The line number to output the header at
  4933. */
  4934. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  4935. if (!this.tableHeaderRow) {
  4936. throw 'Property tableHeaderRow does not exist.';
  4937. }
  4938. var tableHeaderCell, tmpArray, i, ln;
  4939. this.printingHeaderRow = true;
  4940. if (headerFunction !== undefined) {
  4941. var position = headerFunction(this, pages);
  4942. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  4943. }
  4944. this.setFontStyle('bold');
  4945. var tempHeaderConf = [];
  4946. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  4947. this.setFillColor(200, 200, 200);
  4948. tableHeaderCell = this.tableHeaderRow[i];
  4949. if (new_page) {
  4950. this.margins.top = margin;
  4951. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  4952. tempHeaderConf.push(tableHeaderCell);
  4953. }
  4954. tmpArray = [].concat(tableHeaderCell);
  4955. this.cell.apply(this, tmpArray.concat(lineNumber));
  4956. }
  4957. if (tempHeaderConf.length > 0) {
  4958. this.setTableHeaderRow(tempHeaderConf);
  4959. }
  4960. this.setFontStyle('normal');
  4961. this.printingHeaderRow = false;
  4962. };
  4963. })(jsPDF.API);
  4964. /**
  4965. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4966. *
  4967. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  4968. */
  4969. /**
  4970. * This plugin mimics the HTML5 Canvas's context2d.
  4971. *
  4972. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  4973. */
  4974. /**
  4975. * TODO implement stroke opacity (refactor from fill() method )
  4976. * TODO transform angle and radii parameters
  4977. */
  4978. /**
  4979. * require('jspdf.js'); require('lib/css_colors.js');
  4980. */
  4981. (function (jsPDFAPI) {
  4982. 'use strict';
  4983. jsPDFAPI.events.push(['initialized', function () {
  4984. this.context2d.pdf = this;
  4985. this.context2d.internal.pdf = this;
  4986. this.context2d.ctx = new context();
  4987. this.context2d.ctxStack = [];
  4988. this.context2d.path = [];
  4989. }]);
  4990. jsPDFAPI.context2d = {
  4991. pageWrapXEnabled: false,
  4992. pageWrapYEnabled: false,
  4993. pageWrapX: 9999999,
  4994. pageWrapY: 9999999,
  4995. ctx: new context(),
  4996. f2: function f2(number) {
  4997. return number.toFixed(2);
  4998. },
  4999. fillRect: function fillRect(x, y, w, h) {
  5000. if (this._isFillTransparent()) {
  5001. return;
  5002. }
  5003. x = this._wrapX(x);
  5004. y = this._wrapY(y);
  5005. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5006. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5007. },
  5008. strokeRect: function strokeRect(x, y, w, h) {
  5009. if (this._isStrokeTransparent()) {
  5010. return;
  5011. }
  5012. x = this._wrapX(x);
  5013. y = this._wrapY(y);
  5014. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5015. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
  5016. },
  5017. /**
  5018. * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  5019. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  5020. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  5021. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  5022. * @param x
  5023. * @param y
  5024. * @param w
  5025. * @param h
  5026. */
  5027. clearRect: function clearRect(x, y, w, h) {
  5028. if (this.ctx.ignoreClearRect) {
  5029. return;
  5030. }
  5031. x = this._wrapX(x);
  5032. y = this._wrapY(y);
  5033. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5034. this.save();
  5035. this.setFillStyle('#ffffff');
  5036. //TODO This is hack to fill with white.
  5037. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5038. this.restore();
  5039. },
  5040. save: function save() {
  5041. this.ctx._fontSize = this.pdf.internal.getFontSize();
  5042. var ctx = new context();
  5043. ctx.copy(this.ctx);
  5044. this.ctxStack.push(this.ctx);
  5045. this.ctx = ctx;
  5046. },
  5047. restore: function restore() {
  5048. this.ctx = this.ctxStack.pop();
  5049. this.setFillStyle(this.ctx.fillStyle);
  5050. this.setStrokeStyle(this.ctx.strokeStyle);
  5051. this.setFont(this.ctx.font);
  5052. this.pdf.setFontSize(this.ctx._fontSize);
  5053. this.setLineCap(this.ctx.lineCap);
  5054. this.setLineWidth(this.ctx.lineWidth);
  5055. this.setLineJoin(this.ctx.lineJoin);
  5056. },
  5057. rect: function rect(x, y, w, h) {
  5058. this.moveTo(x, y);
  5059. this.lineTo(x + w, y);
  5060. this.lineTo(x + w, y + h);
  5061. this.lineTo(x, y + h);
  5062. this.lineTo(x, y); //TODO not needed
  5063. this.closePath();
  5064. },
  5065. beginPath: function beginPath() {
  5066. this.path = [];
  5067. },
  5068. closePath: function closePath() {
  5069. this.path.push({
  5070. type: 'close'
  5071. });
  5072. },
  5073. _getRgba: function _getRgba(style) {
  5074. // get the decimal values of r, g, and b;
  5075. var rgba = {};
  5076. if (this.internal.rxTransparent.test(style)) {
  5077. rgba.r = 0;
  5078. rgba.g = 0;
  5079. rgba.b = 0;
  5080. rgba.a = 0;
  5081. } else {
  5082. var m = this.internal.rxRgb.exec(style);
  5083. if (m != null) {
  5084. rgba.r = parseInt(m[1]);
  5085. rgba.g = parseInt(m[2]);
  5086. rgba.b = parseInt(m[3]);
  5087. rgba.a = 1;
  5088. } else {
  5089. m = this.internal.rxRgba.exec(style);
  5090. if (m != null) {
  5091. rgba.r = parseInt(m[1]);
  5092. rgba.g = parseInt(m[2]);
  5093. rgba.b = parseInt(m[3]);
  5094. rgba.a = parseFloat(m[4]);
  5095. } else {
  5096. rgba.a = 1;
  5097. if (style.charAt(0) != '#') {
  5098. style = CssColors.colorNameToHex(style);
  5099. if (!style) {
  5100. style = '#000000';
  5101. }
  5102. } else {}
  5103. if (style.length === 4) {
  5104. rgba.r = style.substring(1, 2);
  5105. rgba.r += r;
  5106. rgba.g = style.substring(2, 3);
  5107. rgba.g += g;
  5108. rgba.b = style.substring(3, 4);
  5109. rgba.b += b;
  5110. } else {
  5111. rgba.r = style.substring(1, 3);
  5112. rgba.g = style.substring(3, 5);
  5113. rgba.b = style.substring(5, 7);
  5114. }
  5115. rgba.r = parseInt(rgba.r, 16);
  5116. rgba.g = parseInt(rgba.g, 16);
  5117. rgba.b = parseInt(rgba.b, 16);
  5118. }
  5119. }
  5120. }
  5121. rgba.style = style;
  5122. return rgba;
  5123. },
  5124. setFillStyle: function setFillStyle(style) {
  5125. // get the decimal values of r, g, and b;
  5126. var r, g, b, a;
  5127. if (this.internal.rxTransparent.test(style)) {
  5128. r = 0;
  5129. g = 0;
  5130. b = 0;
  5131. a = 0;
  5132. } else {
  5133. var m = this.internal.rxRgb.exec(style);
  5134. if (m != null) {
  5135. r = parseInt(m[1]);
  5136. g = parseInt(m[2]);
  5137. b = parseInt(m[3]);
  5138. a = 1;
  5139. } else {
  5140. m = this.internal.rxRgba.exec(style);
  5141. if (m != null) {
  5142. r = parseInt(m[1]);
  5143. g = parseInt(m[2]);
  5144. b = parseInt(m[3]);
  5145. a = parseFloat(m[4]);
  5146. } else {
  5147. a = 1;
  5148. if (style.charAt(0) != '#') {
  5149. style = CssColors.colorNameToHex(style);
  5150. if (!style) {
  5151. style = '#000000';
  5152. }
  5153. } else {}
  5154. if (style.length === 4) {
  5155. r = style.substring(1, 2);
  5156. r += r;
  5157. g = style.substring(2, 3);
  5158. g += g;
  5159. b = style.substring(3, 4);
  5160. b += b;
  5161. } else {
  5162. r = style.substring(1, 3);
  5163. g = style.substring(3, 5);
  5164. b = style.substring(5, 7);
  5165. }
  5166. r = parseInt(r, 16);
  5167. g = parseInt(g, 16);
  5168. b = parseInt(b, 16);
  5169. }
  5170. }
  5171. }
  5172. this.ctx.fillStyle = style;
  5173. this.ctx._isFillTransparent = a == 0;
  5174. this.ctx._fillOpacity = a;
  5175. this.pdf.setFillColor(r, g, b, {
  5176. a: a
  5177. });
  5178. this.pdf.setTextColor(r, g, b, {
  5179. a: a
  5180. });
  5181. },
  5182. setStrokeStyle: function setStrokeStyle(style) {
  5183. var rgba = this._getRgba(style);
  5184. this.ctx.strokeStyle = rgba.style;
  5185. this.ctx._isStrokeTransparent = rgba.a == 0;
  5186. this.ctx._strokeOpacity = rgba.a;
  5187. //TODO jsPDF to handle rgba
  5188. if (rgba.a === 0) {
  5189. this.pdf.setDrawColor(255, 255, 255);
  5190. } else if (rgba.a === 1) {
  5191. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5192. } else {
  5193. //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
  5194. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5195. }
  5196. },
  5197. fillText: function fillText(text, x, y, maxWidth) {
  5198. if (this._isFillTransparent()) {
  5199. return;
  5200. }
  5201. x = this._wrapX(x);
  5202. y = this._wrapY(y);
  5203. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5204. x = xpt[0];
  5205. y = xpt[1];
  5206. var rads = this._matrix_rotation(this.ctx._transform);
  5207. var degs = rads * 57.2958;
  5208. //TODO only push the clip if it has not been applied to the current PDF context
  5209. if (this.ctx._clip_path.length > 0) {
  5210. var lines;
  5211. if (window.outIntercept) {
  5212. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5213. } else {
  5214. lines = this.internal.getCurrentPage();
  5215. }
  5216. lines.push("q");
  5217. var origPath = this.path;
  5218. this.path = this.ctx._clip_path;
  5219. this.ctx._clip_path = [];
  5220. this._fill(null, true);
  5221. this.ctx._clip_path = this.path;
  5222. this.path = origPath;
  5223. }
  5224. // We only use X axis as scale hint
  5225. var scale = 1;
  5226. try {
  5227. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5228. } catch (e) {
  5229. console.warn(e);
  5230. }
  5231. // In some cases the transform was very small (5.715760606202283e-17). Most likely a canvg rounding error.
  5232. if (scale < .01) {
  5233. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5234. } else {
  5235. var oldSize = this.pdf.internal.getFontSize();
  5236. this.pdf.setFontSize(oldSize * scale);
  5237. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5238. this.pdf.setFontSize(oldSize);
  5239. }
  5240. if (this.ctx._clip_path.length > 0) {
  5241. lines.push('Q');
  5242. }
  5243. },
  5244. strokeText: function strokeText(text, x, y, maxWidth) {
  5245. if (this._isStrokeTransparent()) {
  5246. return;
  5247. }
  5248. x = this._wrapX(x);
  5249. y = this._wrapY(y);
  5250. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5251. x = xpt[0];
  5252. y = xpt[1];
  5253. var rads = this._matrix_rotation(this.ctx._transform);
  5254. var degs = rads * 57.2958;
  5255. //TODO only push the clip if it has not been applied to the current PDF context
  5256. if (this.ctx._clip_path.length > 0) {
  5257. var lines;
  5258. if (window.outIntercept) {
  5259. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5260. } else {
  5261. lines = this.internal.getCurrentPage();
  5262. }
  5263. lines.push("q");
  5264. var origPath = this.path;
  5265. this.path = this.ctx._clip_path;
  5266. this.ctx._clip_path = [];
  5267. this._fill(null, true);
  5268. this.ctx._clip_path = this.path;
  5269. this.path = origPath;
  5270. }
  5271. var scale = 1;
  5272. // We only use the X axis as scale hint
  5273. try {
  5274. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5275. } catch (e) {
  5276. console.warn(e);
  5277. }
  5278. if (scale === 1) {
  5279. this.pdf.text(text, x, this._getBaseline(y), {
  5280. stroke: true
  5281. }, degs);
  5282. } else {
  5283. var oldSize = this.pdf.internal.getFontSize();
  5284. this.pdf.setFontSize(oldSize * scale);
  5285. this.pdf.text(text, x, this._getBaseline(y), {
  5286. stroke: true
  5287. }, degs);
  5288. this.pdf.setFontSize(oldSize);
  5289. }
  5290. if (this.ctx._clip_path.length > 0) {
  5291. lines.push('Q');
  5292. }
  5293. },
  5294. setFont: function setFont(font) {
  5295. this.ctx.font = font;
  5296. //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
  5297. var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
  5298. m = rx.exec(font);
  5299. if (m != null) {
  5300. var fontStyle = m[1];
  5301. var fontVariant = m[2];
  5302. var fontWeight = m[3];
  5303. var fontSize = m[4];
  5304. var fontSizeUnit = m[5];
  5305. var fontFamily = m[6];
  5306. if ('px' === fontSizeUnit) {
  5307. fontSize = Math.floor(parseFloat(fontSize));
  5308. // fontSize = fontSize * 1.25;
  5309. } else if ('em' === fontSizeUnit) {
  5310. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5311. } else {
  5312. fontSize = Math.floor(parseFloat(fontSize));
  5313. }
  5314. this.pdf.setFontSize(fontSize);
  5315. if (fontWeight === 'bold' || fontWeight === '700') {
  5316. this.pdf.setFontStyle('bold');
  5317. } else {
  5318. if (fontStyle === 'italic') {
  5319. this.pdf.setFontStyle('italic');
  5320. } else {
  5321. this.pdf.setFontStyle('normal');
  5322. }
  5323. }
  5324. var name = fontFamily;
  5325. var parts = name.toLowerCase().split(/\s*,\s*/);
  5326. var jsPdfFontName;
  5327. if (parts.indexOf('arial') != -1) {
  5328. jsPdfFontName = 'Arial';
  5329. } else if (parts.indexOf('verdana') != -1) {
  5330. jsPdfFontName = 'Verdana';
  5331. } else if (parts.indexOf('helvetica') != -1) {
  5332. jsPdfFontName = 'Helvetica';
  5333. } else if (parts.indexOf('sans-serif') != -1) {
  5334. jsPdfFontName = 'sans-serif';
  5335. } else if (parts.indexOf('fixed') != -1) {
  5336. jsPdfFontName = 'Fixed';
  5337. } else if (parts.indexOf('monospace') != -1) {
  5338. jsPdfFontName = 'Monospace';
  5339. } else if (parts.indexOf('terminal') != -1) {
  5340. jsPdfFontName = 'Terminal';
  5341. } else if (parts.indexOf('courier') != -1) {
  5342. jsPdfFontName = 'Courier';
  5343. } else if (parts.indexOf('times') != -1) {
  5344. jsPdfFontName = 'Times';
  5345. } else if (parts.indexOf('cursive') != -1) {
  5346. jsPdfFontName = 'Cursive';
  5347. } else if (parts.indexOf('fantasy') != -1) {
  5348. jsPdfFontName = 'Fantasy';
  5349. } else if (parts.indexOf('serif') != -1) {
  5350. jsPdfFontName = 'Serif';
  5351. } else {
  5352. jsPdfFontName = 'Serif';
  5353. }
  5354. //TODO check more cases
  5355. var style;
  5356. if ('bold' === fontWeight) {
  5357. style = 'bold';
  5358. } else {
  5359. style = 'normal';
  5360. }
  5361. this.pdf.setFont(jsPdfFontName, style);
  5362. } else {
  5363. var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
  5364. var m = rx.exec(font);
  5365. if (m != null) {
  5366. var size = m[1];
  5367. var unit = m[2];
  5368. var name = m[3];
  5369. var style = m[4];
  5370. if (!style) {
  5371. style = 'normal';
  5372. }
  5373. if ('em' === fontSizeUnit) {
  5374. size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5375. } else {
  5376. size = Math.floor(parseFloat(size));
  5377. }
  5378. this.pdf.setFontSize(size);
  5379. this.pdf.setFont(name, style);
  5380. }
  5381. }
  5382. },
  5383. setTextBaseline: function setTextBaseline(baseline) {
  5384. this.ctx.textBaseline = baseline;
  5385. },
  5386. getTextBaseline: function getTextBaseline() {
  5387. return this.ctx.textBaseline;
  5388. },
  5389. //TODO implement textAlign
  5390. setTextAlign: function setTextAlign(align) {
  5391. this.ctx.textAlign = align;
  5392. },
  5393. getTextAlign: function getTextAlign() {
  5394. return this.ctx.textAlign;
  5395. },
  5396. setLineWidth: function setLineWidth(width) {
  5397. this.ctx.lineWidth = width;
  5398. this.pdf.setLineWidth(width);
  5399. },
  5400. setLineCap: function setLineCap(style) {
  5401. this.ctx.lineCap = style;
  5402. this.pdf.setLineCap(style);
  5403. },
  5404. setLineJoin: function setLineJoin(style) {
  5405. this.ctx.lineJoin = style;
  5406. this.pdf.setLineJoin(style);
  5407. },
  5408. moveTo: function moveTo(x, y) {
  5409. x = this._wrapX(x);
  5410. y = this._wrapY(y);
  5411. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5412. x = xpt[0];
  5413. y = xpt[1];
  5414. var obj = {
  5415. type: 'mt',
  5416. x: x,
  5417. y: y
  5418. };
  5419. this.path.push(obj);
  5420. },
  5421. _wrapX: function _wrapX(x) {
  5422. if (this.pageWrapXEnabled) {
  5423. return x % this.pageWrapX;
  5424. } else {
  5425. return x;
  5426. }
  5427. },
  5428. _wrapY: function _wrapY(y) {
  5429. if (this.pageWrapYEnabled) {
  5430. this._gotoPage(this._page(y));
  5431. return (y - this.lastBreak) % this.pageWrapY;
  5432. } else {
  5433. return y;
  5434. }
  5435. },
  5436. transform: function transform(a, b, c, d, e, f) {
  5437. //TODO apply to current transformation instead of replacing
  5438. this.ctx._transform = [a, b, c, d, e, f];
  5439. },
  5440. setTransform: function setTransform(a, b, c, d, e, f) {
  5441. this.ctx._transform = [a, b, c, d, e, f];
  5442. },
  5443. _getTransform: function _getTransform() {
  5444. return this.ctx._transform;
  5445. },
  5446. lastBreak: 0,
  5447. // Y Position of page breaks.
  5448. pageBreaks: [],
  5449. // returns: One-based Page Number
  5450. // Should only be used if pageWrapYEnabled is true
  5451. _page: function _page(y) {
  5452. if (this.pageWrapYEnabled) {
  5453. this.lastBreak = 0;
  5454. var manualBreaks = 0;
  5455. var autoBreaks = 0;
  5456. for (var i = 0; i < this.pageBreaks.length; i++) {
  5457. if (y >= this.pageBreaks[i]) {
  5458. manualBreaks++;
  5459. if (this.lastBreak === 0) {
  5460. autoBreaks++;
  5461. }
  5462. var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
  5463. this.lastBreak = this.pageBreaks[i];
  5464. var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
  5465. autoBreaks += pagesSinceLastBreak;
  5466. }
  5467. }
  5468. if (this.lastBreak === 0) {
  5469. var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
  5470. autoBreaks += pagesSinceLastBreak;
  5471. }
  5472. return autoBreaks + manualBreaks;
  5473. } else {
  5474. return this.pdf.internal.getCurrentPageInfo().pageNumber;
  5475. }
  5476. },
  5477. _gotoPage: function _gotoPage(pageOneBased) {
  5478. // This is a stub to be overriden if needed
  5479. },
  5480. lineTo: function lineTo(x, y) {
  5481. x = this._wrapX(x);
  5482. y = this._wrapY(y);
  5483. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5484. x = xpt[0];
  5485. y = xpt[1];
  5486. var obj = {
  5487. type: 'lt',
  5488. x: x,
  5489. y: y
  5490. };
  5491. this.path.push(obj);
  5492. },
  5493. bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
  5494. x1 = this._wrapX(x1);
  5495. y1 = this._wrapY(y1);
  5496. x2 = this._wrapX(x2);
  5497. y2 = this._wrapY(y2);
  5498. x = this._wrapX(x);
  5499. y = this._wrapY(y);
  5500. var xpt;
  5501. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5502. x = xpt[0];
  5503. y = xpt[1];
  5504. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5505. x1 = xpt[0];
  5506. y1 = xpt[1];
  5507. xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
  5508. x2 = xpt[0];
  5509. y2 = xpt[1];
  5510. var obj = {
  5511. type: 'bct',
  5512. x1: x1,
  5513. y1: y1,
  5514. x2: x2,
  5515. y2: y2,
  5516. x: x,
  5517. y: y
  5518. };
  5519. this.path.push(obj);
  5520. },
  5521. quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
  5522. x1 = this._wrapX(x1);
  5523. y1 = this._wrapY(y1);
  5524. x = this._wrapX(x);
  5525. y = this._wrapY(y);
  5526. var xpt;
  5527. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5528. x = xpt[0];
  5529. y = xpt[1];
  5530. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5531. x1 = xpt[0];
  5532. y1 = xpt[1];
  5533. var obj = {
  5534. type: 'qct',
  5535. x1: x1,
  5536. y1: y1,
  5537. x: x,
  5538. y: y
  5539. };
  5540. this.path.push(obj);
  5541. },
  5542. arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
  5543. x = this._wrapX(x);
  5544. y = this._wrapY(y);
  5545. if (!this._matrix_is_identity(this.ctx._transform)) {
  5546. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5547. x = xpt[0];
  5548. y = xpt[1];
  5549. var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
  5550. var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
  5551. radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
  5552. //TODO angles need to be transformed
  5553. }
  5554. var obj = {
  5555. type: 'arc',
  5556. x: x,
  5557. y: y,
  5558. radius: radius,
  5559. startAngle: startAngle,
  5560. endAngle: endAngle,
  5561. anticlockwise: anticlockwise
  5562. };
  5563. this.path.push(obj);
  5564. },
  5565. drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
  5566. if (x2 !== undefined) {
  5567. x = x2;
  5568. y = y2;
  5569. w = w2;
  5570. h = h2;
  5571. }
  5572. x = this._wrapX(x);
  5573. y = this._wrapY(y);
  5574. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5575. var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
  5576. // TODO implement source clipping and image scaling
  5577. var format;
  5578. var rx = /data:image\/(\w+).*/i;
  5579. var m = rx.exec(img);
  5580. if (m != null) {
  5581. format = m[1];
  5582. } else {
  5583. // format = "jpeg";
  5584. format = "png";
  5585. }
  5586. this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
  5587. },
  5588. /**
  5589. * Multiply the first matrix by the second
  5590. * @param m1
  5591. * @param m2
  5592. * @returns {*[]}
  5593. * @private
  5594. */
  5595. _matrix_multiply: function _matrix_multiply(m2, m1) {
  5596. var sx = m1[0];
  5597. var shy = m1[1];
  5598. var shx = m1[2];
  5599. var sy = m1[3];
  5600. var tx = m1[4];
  5601. var ty = m1[5];
  5602. var t0 = sx * m2[0] + shy * m2[2];
  5603. var t2 = shx * m2[0] + sy * m2[2];
  5604. var t4 = tx * m2[0] + ty * m2[2] + m2[4];
  5605. shy = sx * m2[1] + shy * m2[3];
  5606. sy = shx * m2[1] + sy * m2[3];
  5607. ty = tx * m2[1] + ty * m2[3] + m2[5];
  5608. sx = t0;
  5609. shx = t2;
  5610. tx = t4;
  5611. return [sx, shy, shx, sy, tx, ty];
  5612. },
  5613. _matrix_rotation: function _matrix_rotation(m) {
  5614. return Math.atan2(m[2], m[0]);
  5615. },
  5616. _matrix_decompose: function _matrix_decompose(matrix) {
  5617. var a = matrix[0];
  5618. var b = matrix[1];
  5619. var c = matrix[2];
  5620. var d = matrix[3];
  5621. var scaleX = Math.sqrt(a * a + b * b);
  5622. a /= scaleX;
  5623. b /= scaleX;
  5624. var shear = a * c + b * d;
  5625. c -= a * shear;
  5626. d -= b * shear;
  5627. var scaleY = Math.sqrt(c * c + d * d);
  5628. c /= scaleY;
  5629. d /= scaleY;
  5630. shear /= scaleY;
  5631. if (a * d < b * c) {
  5632. a = -a;
  5633. b = -b;
  5634. shear = -shear;
  5635. scaleX = -scaleX;
  5636. }
  5637. return {
  5638. scale: [scaleX, 0, 0, scaleY, 0, 0],
  5639. translate: [1, 0, 0, 1, matrix[4], matrix[5]],
  5640. rotate: [a, b, -b, a, 0, 0],
  5641. skew: [1, 0, shear, 1, 0, 0]
  5642. };
  5643. },
  5644. _matrix_map_point: function _matrix_map_point(m1, pt) {
  5645. var sx = m1[0];
  5646. var shy = m1[1];
  5647. var shx = m1[2];
  5648. var sy = m1[3];
  5649. var tx = m1[4];
  5650. var ty = m1[5];
  5651. var px = pt[0];
  5652. var py = pt[1];
  5653. var x = px * sx + py * shx + tx;
  5654. var y = px * shy + py * sy + ty;
  5655. return [x, y];
  5656. },
  5657. _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
  5658. var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
  5659. return { x: xpt[0], y: xpt[1] };
  5660. },
  5661. _matrix_map_rect: function _matrix_map_rect(m1, rect) {
  5662. var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
  5663. var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
  5664. return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
  5665. },
  5666. _matrix_is_identity: function _matrix_is_identity(m1) {
  5667. if (m1[0] != 1) {
  5668. return false;
  5669. }
  5670. if (m1[1] != 0) {
  5671. return false;
  5672. }
  5673. if (m1[2] != 0) {
  5674. return false;
  5675. }
  5676. if (m1[3] != 1) {
  5677. return false;
  5678. }
  5679. if (m1[4] != 0) {
  5680. return false;
  5681. }
  5682. if (m1[5] != 0) {
  5683. return false;
  5684. }
  5685. return true;
  5686. },
  5687. rotate: function rotate(angle) {
  5688. var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
  5689. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5690. },
  5691. scale: function scale(sx, sy) {
  5692. var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
  5693. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5694. },
  5695. translate: function translate(x, y) {
  5696. var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
  5697. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5698. },
  5699. stroke: function stroke() {
  5700. if (this.ctx._clip_path.length > 0) {
  5701. var lines;
  5702. if (window.outIntercept) {
  5703. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5704. } else {
  5705. lines = this.internal.getCurrentPage();
  5706. }
  5707. lines.push("q");
  5708. var origPath = this.path;
  5709. this.path = this.ctx._clip_path;
  5710. this.ctx._clip_path = [];
  5711. this._stroke(true);
  5712. this.ctx._clip_path = this.path;
  5713. this.path = origPath;
  5714. this._stroke(false);
  5715. lines.push("Q");
  5716. } else {
  5717. this._stroke(false);
  5718. }
  5719. },
  5720. _stroke: function _stroke(isClip) {
  5721. if (!isClip && this._isStrokeTransparent()) {
  5722. return;
  5723. }
  5724. //TODO opacity
  5725. var moves = [];
  5726. var closed = false;
  5727. var xPath = this.path;
  5728. for (var i = 0; i < xPath.length; i++) {
  5729. var pt = xPath[i];
  5730. switch (pt.type) {
  5731. case 'mt':
  5732. moves.push({ start: pt, deltas: [], abs: [] });
  5733. break;
  5734. case 'lt':
  5735. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5736. moves[moves.length - 1].deltas.push(delta);
  5737. moves[moves.length - 1].abs.push(pt);
  5738. break;
  5739. case 'bct':
  5740. var delta = [pt.x1 - xPath[i - 1].x, pt.y1 - xPath[i - 1].y, pt.x2 - xPath[i - 1].x, pt.y2 - xPath[i - 1].y, pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5741. moves[moves.length - 1].deltas.push(delta);
  5742. break;
  5743. case 'qct':
  5744. // convert to bezier
  5745. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5746. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5747. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5748. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5749. var x3 = pt.x;
  5750. var y3 = pt.y;
  5751. var delta = [x1 - xPath[i - 1].x, y1 - xPath[i - 1].y, x2 - xPath[i - 1].x, y2 - xPath[i - 1].y, x3 - xPath[i - 1].x, y3 - xPath[i - 1].y];
  5752. moves[moves.length - 1].deltas.push(delta);
  5753. break;
  5754. case 'arc':
  5755. //TODO this was hack to avoid out-of-bounds issue
  5756. // No move-to before drawing the arc
  5757. if (moves.length == 0) {
  5758. moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
  5759. }
  5760. moves[moves.length - 1].arc = true;
  5761. moves[moves.length - 1].abs.push(pt);
  5762. break;
  5763. case 'close':
  5764. closed = true;
  5765. break;
  5766. }
  5767. }
  5768. for (var i = 0; i < moves.length; i++) {
  5769. var style;
  5770. if (i == moves.length - 1) {
  5771. style = 's';
  5772. } else {
  5773. style = null;
  5774. }
  5775. if (moves[i].arc) {
  5776. var arcs = moves[i].abs;
  5777. for (var ii = 0; ii < arcs.length; ii++) {
  5778. var arc = arcs[ii];
  5779. var start = arc.startAngle * 360 / (2 * Math.PI);
  5780. var end = arc.endAngle * 360 / (2 * Math.PI);
  5781. var x = arc.x;
  5782. var y = arc.y;
  5783. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
  5784. }
  5785. } else {
  5786. var x = moves[i].start.x;
  5787. var y = moves[i].start.y;
  5788. if (!isClip) {
  5789. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5790. } else {
  5791. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5792. this.pdf.clip_fixed();
  5793. }
  5794. }
  5795. }
  5796. },
  5797. _isFillTransparent: function _isFillTransparent() {
  5798. return this.ctx._isFillTransparent || this.globalAlpha == 0;
  5799. },
  5800. _isStrokeTransparent: function _isStrokeTransparent() {
  5801. return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
  5802. },
  5803. fill: function fill(fillRule) {
  5804. //evenodd or nonzero (default)
  5805. if (this.ctx._clip_path.length > 0) {
  5806. var lines;
  5807. if (window.outIntercept) {
  5808. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5809. } else {
  5810. lines = this.internal.getCurrentPage();
  5811. }
  5812. lines.push("q");
  5813. var origPath = this.path;
  5814. this.path = this.ctx._clip_path;
  5815. this.ctx._clip_path = [];
  5816. this._fill(fillRule, true);
  5817. this.ctx._clip_path = this.path;
  5818. this.path = origPath;
  5819. this._fill(fillRule, false);
  5820. lines.push('Q');
  5821. } else {
  5822. this._fill(fillRule, false);
  5823. }
  5824. },
  5825. _fill: function _fill(fillRule, isClip) {
  5826. if (this._isFillTransparent()) {
  5827. return;
  5828. }
  5829. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5830. var lines;
  5831. if (window.outIntercept) {
  5832. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5833. } else {
  5834. lines = this.internal.getCurrentPage();
  5835. }
  5836. // if (this.ctx._clip_path.length > 0) {
  5837. // lines.push('q');
  5838. // var oldPath = this.path;
  5839. // this.path = this.ctx._clip_path;
  5840. // this.ctx._clip_path = [];
  5841. // this._fill(fillRule, true);
  5842. // this.ctx._clip_path = this.path;
  5843. // this.path = oldPath;
  5844. // }
  5845. var moves = [];
  5846. var outInterceptOld = window.outIntercept;
  5847. if (v2Support) {
  5848. // Blend and Mask
  5849. switch (this.ctx.globalCompositeOperation) {
  5850. case 'normal':
  5851. case 'source-over':
  5852. break;
  5853. case 'destination-in':
  5854. case 'destination-out':
  5855. //TODO this need to be added to the current group or page
  5856. // define a mask stream
  5857. var obj = this.pdf.internal.newStreamObject();
  5858. // define a mask state
  5859. var obj2 = this.pdf.internal.newObject2();
  5860. obj2.push('<</Type /ExtGState');
  5861. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5862. obj2.push('>>');
  5863. // add mask to page resources
  5864. var gsName = 'MASK' + obj2.objId;
  5865. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5866. var instruction = '/' + gsName + ' gs';
  5867. // add mask to page, group, or stream
  5868. lines.splice(0, 0, 'q');
  5869. lines.splice(1, 0, instruction);
  5870. lines.push('Q');
  5871. window.outIntercept = obj;
  5872. break;
  5873. default:
  5874. var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
  5875. if (dictionaryEntry) {
  5876. this.pdf.internal.out(dictionaryEntry + ' gs');
  5877. }
  5878. break;
  5879. }
  5880. }
  5881. var alpha = this.ctx.globalAlpha;
  5882. if (this.ctx._fillOpacity < 1) {
  5883. // TODO combine this with global opacity
  5884. alpha = this.ctx._fillOpacity;
  5885. }
  5886. //TODO check for an opacity graphics state that was already created
  5887. //TODO do not set opacity if current value is already active
  5888. if (v2Support) {
  5889. var objOpac = this.pdf.internal.newObject2();
  5890. objOpac.push('<</Type /ExtGState');
  5891. //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
  5892. //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
  5893. objOpac.push('/CA ' + alpha); // Stroke
  5894. objOpac.push('/ca ' + alpha); // Not Stroke
  5895. objOpac.push('>>');
  5896. var gsName = 'GS_O_' + objOpac.objId;
  5897. this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
  5898. this.pdf.internal.out('/' + gsName + ' gs');
  5899. }
  5900. var xPath = this.path;
  5901. for (var i = 0; i < xPath.length; i++) {
  5902. var pt = xPath[i];
  5903. switch (pt.type) {
  5904. case 'mt':
  5905. moves.push({ start: pt, deltas: [], abs: [] });
  5906. break;
  5907. case 'lt':
  5908. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5909. moves[moves.length - 1].deltas.push(delta);
  5910. moves[moves.length - 1].abs.push(pt);
  5911. break;
  5912. case 'bct':
  5913. var delta = [pt.x1 - xPath[i - 1].x, pt.y1 - xPath[i - 1].y, pt.x2 - xPath[i - 1].x, pt.y2 - xPath[i - 1].y, pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5914. moves[moves.length - 1].deltas.push(delta);
  5915. break;
  5916. case 'qct':
  5917. // convert to bezier
  5918. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5919. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5920. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5921. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5922. var x3 = pt.x;
  5923. var y3 = pt.y;
  5924. var delta = [x1 - xPath[i - 1].x, y1 - xPath[i - 1].y, x2 - xPath[i - 1].x, y2 - xPath[i - 1].y, x3 - xPath[i - 1].x, y3 - xPath[i - 1].y];
  5925. moves[moves.length - 1].deltas.push(delta);
  5926. break;
  5927. case 'arc':
  5928. //TODO this was hack to avoid out-of-bounds issue when drawing circle
  5929. // No move-to before drawing the arc
  5930. if (moves.length === 0) {
  5931. moves.push({ deltas: [], abs: [] });
  5932. }
  5933. moves[moves.length - 1].arc = true;
  5934. moves[moves.length - 1].abs.push(pt);
  5935. break;
  5936. case 'close':
  5937. moves.push({ close: true });
  5938. break;
  5939. }
  5940. }
  5941. for (var i = 0; i < moves.length; i++) {
  5942. var style;
  5943. if (i == moves.length - 1) {
  5944. style = 'f';
  5945. if (fillRule === 'evenodd') {
  5946. style += '*';
  5947. }
  5948. } else {
  5949. style = null;
  5950. }
  5951. if (moves[i].close) {
  5952. this.pdf.internal.out('h');
  5953. this.pdf.internal.out('f');
  5954. } else if (moves[i].arc) {
  5955. if (moves[i].start) {
  5956. this.internal.move2(this, moves[i].start.x, moves[i].start.y);
  5957. }
  5958. var arcs = moves[i].abs;
  5959. for (var ii = 0; ii < arcs.length; ii++) {
  5960. var arc = arcs[ii];
  5961. //TODO lines deltas were getting in here
  5962. if (typeof arc.startAngle !== 'undefined') {
  5963. var start = arc.startAngle * 360 / (2 * Math.PI);
  5964. var end = arc.endAngle * 360 / (2 * Math.PI);
  5965. var x = arc.x;
  5966. var y = arc.y;
  5967. if (ii === 0) {
  5968. this.internal.move2(this, x, y);
  5969. }
  5970. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
  5971. if (ii === arcs.length - 1) {
  5972. // The original arc move did not occur because of the algorithm
  5973. if (moves[i].start) {
  5974. var x = moves[i].start.x;
  5975. var y = moves[i].start.y;
  5976. this.internal.line2(c2d, x, y);
  5977. }
  5978. }
  5979. } else {
  5980. this.internal.line2(c2d, arc.x, arc.y);
  5981. }
  5982. }
  5983. } else {
  5984. var x = moves[i].start.x;
  5985. var y = moves[i].start.y;
  5986. if (!isClip) {
  5987. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5988. } else {
  5989. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5990. this.pdf.clip_fixed();
  5991. }
  5992. }
  5993. }
  5994. window.outIntercept = outInterceptOld;
  5995. // if (this.ctx._clip_path.length > 0) {
  5996. // lines.push('Q');
  5997. // }
  5998. },
  5999. pushMask: function pushMask() {
  6000. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  6001. if (!v2Support) {
  6002. console.log('jsPDF v2 not enabled');
  6003. return;
  6004. }
  6005. // define a mask stream
  6006. var obj = this.pdf.internal.newStreamObject();
  6007. // define a mask state
  6008. var obj2 = this.pdf.internal.newObject2();
  6009. obj2.push('<</Type /ExtGState');
  6010. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  6011. obj2.push('>>');
  6012. // add mask to page resources
  6013. var gsName = 'MASK' + obj2.objId;
  6014. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  6015. var instruction = '/' + gsName + ' gs';
  6016. this.pdf.internal.out(instruction);
  6017. },
  6018. clip: function clip() {
  6019. //TODO do we reset the path, or just copy it?
  6020. if (this.ctx._clip_path.length > 0) {
  6021. for (var i = 0; i < this.path.length; i++) {
  6022. this.ctx._clip_path.push(this.path[i]);
  6023. }
  6024. } else {
  6025. this.ctx._clip_path = this.path;
  6026. }
  6027. this.path = [];
  6028. },
  6029. measureText: function measureText(text) {
  6030. var pdf = this.pdf;
  6031. return {
  6032. getWidth: function getWidth() {
  6033. var fontSize = pdf.internal.getFontSize();
  6034. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  6035. // Convert points to pixels
  6036. txtWidth *= 1.3333;
  6037. return txtWidth;
  6038. },
  6039. get width() {
  6040. return this.getWidth(text);
  6041. }
  6042. };
  6043. },
  6044. _getBaseline: function _getBaseline(y) {
  6045. var height = parseInt(this.pdf.internal.getFontSize());
  6046. // TODO Get descent from font descriptor
  6047. var descent = height * .25;
  6048. switch (this.ctx.textBaseline) {
  6049. case 'bottom':
  6050. return y - descent;
  6051. case 'top':
  6052. return y + height;
  6053. case 'hanging':
  6054. return y + height - descent;
  6055. case 'middle':
  6056. return y + height / 2 - descent;
  6057. case 'ideographic':
  6058. // TODO not implemented
  6059. return y;
  6060. case 'alphabetic':
  6061. default:
  6062. return y;
  6063. }
  6064. }
  6065. };
  6066. var c2d = jsPDFAPI.context2d;
  6067. // accessor methods
  6068. Object.defineProperty(c2d, 'fillStyle', {
  6069. set: function set(value) {
  6070. this.setFillStyle(value);
  6071. },
  6072. get: function get() {
  6073. return this.ctx.fillStyle;
  6074. }
  6075. });
  6076. Object.defineProperty(c2d, 'strokeStyle', {
  6077. set: function set(value) {
  6078. this.setStrokeStyle(value);
  6079. },
  6080. get: function get() {
  6081. return this.ctx.strokeStyle;
  6082. }
  6083. });
  6084. Object.defineProperty(c2d, 'lineWidth', {
  6085. set: function set(value) {
  6086. this.setLineWidth(value);
  6087. },
  6088. get: function get() {
  6089. return this.ctx.lineWidth;
  6090. }
  6091. });
  6092. Object.defineProperty(c2d, 'lineCap', {
  6093. set: function set(val) {
  6094. this.setLineCap(val);
  6095. },
  6096. get: function get() {
  6097. return this.ctx.lineCap;
  6098. }
  6099. });
  6100. Object.defineProperty(c2d, 'lineJoin', {
  6101. set: function set(val) {
  6102. this.setLineJoin(val);
  6103. },
  6104. get: function get() {
  6105. return this.ctx.lineJoin;
  6106. }
  6107. });
  6108. Object.defineProperty(c2d, 'miterLimit', {
  6109. set: function set(val) {
  6110. this.ctx.miterLimit = val;
  6111. },
  6112. get: function get() {
  6113. return this.ctx.miterLimit;
  6114. }
  6115. });
  6116. Object.defineProperty(c2d, 'textBaseline', {
  6117. set: function set(value) {
  6118. this.setTextBaseline(value);
  6119. },
  6120. get: function get() {
  6121. return this.getTextBaseline();
  6122. }
  6123. });
  6124. Object.defineProperty(c2d, 'textAlign', {
  6125. set: function set(value) {
  6126. this.setTextAlign(value);
  6127. },
  6128. get: function get() {
  6129. return this.getTextAlign();
  6130. }
  6131. });
  6132. Object.defineProperty(c2d, 'font', {
  6133. set: function set(value) {
  6134. this.setFont(value);
  6135. },
  6136. get: function get() {
  6137. return this.ctx.font;
  6138. }
  6139. });
  6140. Object.defineProperty(c2d, 'globalCompositeOperation', {
  6141. set: function set(value) {
  6142. this.ctx.globalCompositeOperation = value;
  6143. },
  6144. get: function get() {
  6145. return this.ctx.globalCompositeOperation;
  6146. }
  6147. });
  6148. Object.defineProperty(c2d, 'globalAlpha', {
  6149. set: function set(value) {
  6150. this.ctx.globalAlpha = value;
  6151. },
  6152. get: function get() {
  6153. return this.ctx.globalAlpha;
  6154. }
  6155. });
  6156. // Not HTML API
  6157. Object.defineProperty(c2d, 'ignoreClearRect', {
  6158. set: function set(value) {
  6159. this.ctx.ignoreClearRect = value;
  6160. },
  6161. get: function get() {
  6162. return this.ctx.ignoreClearRect;
  6163. }
  6164. });
  6165. // End Not HTML API
  6166. c2d.internal = {};
  6167. c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  6168. c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  6169. c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  6170. // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
  6171. c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
  6172. var includeMove = true;
  6173. var k = this.pdf.internal.scaleFactor;
  6174. var pageHeight = this.pdf.internal.pageSize.height;
  6175. var f2 = this.pdf.internal.f2;
  6176. var a1r = a1 * (Math.PI / 180);
  6177. var a2r = a2 * (Math.PI / 180);
  6178. var curves = this.createArc(r, a1r, a2r, anticlockwise);
  6179. var pathData = null;
  6180. for (var i = 0; i < curves.length; i++) {
  6181. var curve = curves[i];
  6182. if (includeMove && i === 0) {
  6183. this.pdf.internal.out([f2((curve.x1 + xc) * k), f2((pageHeight - (curve.y1 + yc)) * k), 'm', f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'].join(' '));
  6184. } else {
  6185. this.pdf.internal.out([f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'].join(' '));
  6186. }
  6187. //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
  6188. c2d._lastPoint = { x: xc, y: yc };
  6189. // f2((curve.x1 + xc) * k), f2((pageHeight - (curve.y1 + yc)) * k), 'm', f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'
  6190. }
  6191. if (style !== null) {
  6192. this.pdf.internal.out(this.pdf.internal.getStyle(style));
  6193. }
  6194. };
  6195. /**
  6196. *
  6197. * @param x Edge point X
  6198. * @param y Edge point Y
  6199. * @param r Radius
  6200. * @param a1 start angle
  6201. * @param a2 end angle
  6202. * @param anticlockwise
  6203. * @param style
  6204. * @param isClip
  6205. */
  6206. c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
  6207. // we need to convert from cartesian to polar here methinks.
  6208. var centerX = x; // + r;
  6209. var centerY = y;
  6210. if (!isClip) {
  6211. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
  6212. } else {
  6213. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
  6214. this.pdf.clip_fixed();
  6215. }
  6216. };
  6217. c2d.internal.move2 = function (c2d, x, y) {
  6218. var k = this.pdf.internal.scaleFactor;
  6219. var pageHeight = this.pdf.internal.pageSize.height;
  6220. var f2 = this.pdf.internal.f2;
  6221. this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
  6222. c2d._lastPoint = { x: x, y: y };
  6223. };
  6224. c2d.internal.line2 = function (c2d, dx, dy) {
  6225. var k = this.pdf.internal.scaleFactor;
  6226. var pageHeight = this.pdf.internal.pageSize.height;
  6227. var f2 = this.pdf.internal.f2;
  6228. //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
  6229. var pt = { x: dx, y: dy };
  6230. this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
  6231. //this.pdf.internal.out('f');
  6232. c2d._lastPoint = pt;
  6233. };
  6234. /**
  6235. * Return a array of objects that represent bezier curves which approximate the circular arc centered at the origin, from startAngle to endAngle (radians) with the specified radius.
  6236. *
  6237. * Each bezier curve is an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
  6238. */
  6239. c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
  6240. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
  6241. var twoPI = Math.PI * 2;
  6242. var piOverTwo = Math.PI / 2.0;
  6243. // normalize startAngle, endAngle to [0, 2PI]
  6244. var startAngleN = startAngle;
  6245. if (startAngleN < twoPI || startAngleN > twoPI) {
  6246. startAngleN = startAngleN % twoPI;
  6247. }
  6248. if (startAngleN < 0) {
  6249. startAngleN = twoPI + startAngleN;
  6250. }
  6251. while (startAngle > endAngle) {
  6252. startAngle = startAngle - twoPI;
  6253. }
  6254. var totalAngle = Math.abs(endAngle - startAngle);
  6255. if (totalAngle < twoPI) {
  6256. if (anticlockwise) {
  6257. totalAngle = twoPI - totalAngle;
  6258. }
  6259. }
  6260. // Compute the sequence of arc curves, up to PI/2 at a time.
  6261. var curves = [];
  6262. var sgn = anticlockwise ? -1 : +1;
  6263. var a1 = startAngleN;
  6264. for (; totalAngle > EPSILON;) {
  6265. var remain = sgn * Math.min(totalAngle, piOverTwo);
  6266. var a2 = a1 + remain;
  6267. curves.push(this.createSmallArc(radius, a1, a2));
  6268. totalAngle -= Math.abs(a2 - a1);
  6269. a1 = a2;
  6270. }
  6271. return curves;
  6272. };
  6273. c2d.internal.getCurrentPage = function () {
  6274. return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
  6275. };
  6276. /**
  6277. * Cubic bezier approximation of a circular arc centered at the origin, from (radians) a1 to a2, where a2-a1 < pi/2. The arc's radius is r.
  6278. *
  6279. * Returns an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
  6280. *
  6281. * This algorithm is based on the approach described in: A. Riškus, "Approximation of a Cubic Bezier Curve by Circular Arcs and Vice Versa," Information Technology and Control, 35(4), 2006 pp. 371-378.
  6282. */
  6283. c2d.internal.createSmallArc = function (r, a1, a2) {
  6284. // Compute all four points for an arc that subtends the same total angle
  6285. // but is centered on the X-axis
  6286. var a = (a2 - a1) / 2.0;
  6287. var x4 = r * Math.cos(a);
  6288. var y4 = r * Math.sin(a);
  6289. var x1 = x4;
  6290. var y1 = -y4;
  6291. var q1 = x1 * x1 + y1 * y1;
  6292. var q2 = q1 + x1 * x4 + y1 * y4;
  6293. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  6294. var x2 = x1 - k2 * y1;
  6295. var y2 = y1 + k2 * x1;
  6296. var x3 = x2;
  6297. var y3 = -y2;
  6298. // Find the arc points' actual locations by computing x1,y1 and x4,y4
  6299. // and rotating the control points by a + a1
  6300. var ar = a + a1;
  6301. var cos_ar = Math.cos(ar);
  6302. var sin_ar = Math.sin(ar);
  6303. return {
  6304. x1: r * Math.cos(a1),
  6305. y1: r * Math.sin(a1),
  6306. x2: x2 * cos_ar - y2 * sin_ar,
  6307. y2: x2 * sin_ar + y2 * cos_ar,
  6308. x3: x3 * cos_ar - y3 * sin_ar,
  6309. y3: x3 * sin_ar + y3 * cos_ar,
  6310. x4: r * Math.cos(a2),
  6311. y4: r * Math.sin(a2)
  6312. };
  6313. };
  6314. function context() {
  6315. this._isStrokeTransparent = false;
  6316. this._strokeOpacity = 1;
  6317. this.strokeStyle = '#000000';
  6318. this.fillStyle = '#000000';
  6319. this._isFillTransparent = false;
  6320. this._fillOpacity = 1;
  6321. this.font = "12pt times";
  6322. this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
  6323. this.textAlign = 'start';
  6324. this.lineWidth = 1;
  6325. this.lineJoin = 'miter'; // round, bevel, miter
  6326. this.lineCap = 'butt'; // butt, round, square
  6327. this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
  6328. this.globalCompositeOperation = 'normal';
  6329. this.globalAlpha = 1.0;
  6330. this._clip_path = [];
  6331. // TODO miter limit //default 10
  6332. // Not HTML API
  6333. this.ignoreClearRect = false;
  6334. this.copy = function (ctx) {
  6335. this._isStrokeTransparent = ctx._isStrokeTransparent;
  6336. this._strokeOpacity = ctx._strokeOpacity;
  6337. this.strokeStyle = ctx.strokeStyle;
  6338. this._isFillTransparent = ctx._isFillTransparent;
  6339. this._fillOpacity = ctx._fillOpacity;
  6340. this.fillStyle = ctx.fillStyle;
  6341. this.font = ctx.font;
  6342. this.lineWidth = ctx.lineWidth;
  6343. this.lineJoin = ctx.lineJoin;
  6344. this.lineCap = ctx.lineCap;
  6345. this.textBaseline = ctx.textBaseline;
  6346. this.textAlign = ctx.textAlign;
  6347. this._fontSize = ctx._fontSize;
  6348. this._transform = ctx._transform.slice(0);
  6349. this.globalCompositeOperation = ctx.globalCompositeOperation;
  6350. this.globalAlpha = ctx.globalAlpha;
  6351. this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
  6352. // Not HTML API
  6353. this.ignoreClearRect = ctx.ignoreClearRect;
  6354. };
  6355. }
  6356. return this;
  6357. })(jsPDF.API);
  6358. /** @preserve
  6359. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  6360. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  6361. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  6362. * 2014 Diego Casorran, https://github.com/diegocr
  6363. * 2014 Daniel Husar, https://github.com/danielhusar
  6364. * 2014 Wolfgang Gassler, https://github.com/woolfg
  6365. * 2014 Steven Spungin, https://github.com/flamenco
  6366. *
  6367. *
  6368. * ====================================================================
  6369. */
  6370. (function (jsPDFAPI) {
  6371. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  6372. clone = function () {
  6373. return function (obj) {
  6374. Clone.prototype = obj;
  6375. return new Clone();
  6376. };
  6377. function Clone() {}
  6378. }();
  6379. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  6380. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  6381. i = 0;
  6382. l = array.length;
  6383. fragment = void 0;
  6384. lTrimmed = false;
  6385. rTrimmed = false;
  6386. while (!lTrimmed && i !== l) {
  6387. fragment = array[i] = array[i].trimLeft();
  6388. if (fragment) {
  6389. lTrimmed = true;
  6390. }
  6391. i++;
  6392. }
  6393. i = l - 1;
  6394. while (l && !rTrimmed && i !== -1) {
  6395. fragment = array[i] = array[i].trimRight();
  6396. if (fragment) {
  6397. rTrimmed = true;
  6398. }
  6399. i--;
  6400. }
  6401. r = /\s+$/g;
  6402. trailingSpace = true;
  6403. i = 0;
  6404. while (i !== l) {
  6405. // Leave the line breaks intact
  6406. if (array[i] != "\u2028") {
  6407. fragment = array[i].replace(/\s+/g, " ");
  6408. if (trailingSpace) {
  6409. fragment = fragment.trimLeft();
  6410. }
  6411. if (fragment) {
  6412. trailingSpace = r.test(fragment);
  6413. }
  6414. array[i] = fragment;
  6415. }
  6416. i++;
  6417. }
  6418. return array;
  6419. };
  6420. Renderer = function Renderer(pdf, x, y, settings) {
  6421. this.pdf = pdf;
  6422. this.x = x;
  6423. this.y = y;
  6424. this.settings = settings;
  6425. //list of functions which are called after each element-rendering process
  6426. this.watchFunctions = [];
  6427. this.init();
  6428. return this;
  6429. };
  6430. ResolveFont = function ResolveFont(css_font_family_string) {
  6431. var name, part, parts;
  6432. name = void 0;
  6433. parts = css_font_family_string.split(",");
  6434. part = parts.shift();
  6435. while (!name && part) {
  6436. name = FontNameDB[part.trim().toLowerCase()];
  6437. part = parts.shift();
  6438. }
  6439. return name;
  6440. };
  6441. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  6442. //IE8 issues
  6443. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  6444. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  6445. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  6446. }
  6447. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  6448. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  6449. }
  6450. var normal, undef, value;
  6451. undef = void 0;
  6452. normal = 16.00;
  6453. value = UnitedNumberMap[css_line_height_string];
  6454. if (value) {
  6455. return value;
  6456. }
  6457. value = {
  6458. "xx-small": 9,
  6459. "x-small": 11,
  6460. small: 13,
  6461. medium: 16,
  6462. large: 19,
  6463. "x-large": 23,
  6464. "xx-large": 28,
  6465. auto: 0
  6466. }[{ css_line_height_string: css_line_height_string }];
  6467. if (value !== undef) {
  6468. return UnitedNumberMap[css_line_height_string] = value / normal;
  6469. }
  6470. if (value = parseFloat(css_line_height_string)) {
  6471. return UnitedNumberMap[css_line_height_string] = value / normal;
  6472. }
  6473. value = css_line_height_string.match(/([\d\.]+)(px)/);
  6474. if (value.length === 3) {
  6475. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  6476. }
  6477. return UnitedNumberMap[css_line_height_string] = 1;
  6478. };
  6479. GetCSS = function GetCSS(element) {
  6480. var css, tmp, computedCSSElement;
  6481. computedCSSElement = function (el) {
  6482. var compCSS;
  6483. compCSS = function (el) {
  6484. if (document.defaultView && document.defaultView.getComputedStyle) {
  6485. return document.defaultView.getComputedStyle(el, null);
  6486. } else if (el.currentStyle) {
  6487. return el.currentStyle;
  6488. } else {
  6489. return el.style;
  6490. }
  6491. }(el);
  6492. return function (prop) {
  6493. prop = prop.replace(/-\D/g, function (match) {
  6494. return match.charAt(1).toUpperCase();
  6495. });
  6496. return compCSS[prop];
  6497. };
  6498. }(element);
  6499. css = {};
  6500. tmp = void 0;
  6501. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  6502. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  6503. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  6504. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  6505. if (tmp === "bold") {
  6506. if (css["font-style"] === "normal") {
  6507. css["font-style"] = tmp;
  6508. } else {
  6509. css["font-style"] = tmp + css["font-style"];
  6510. }
  6511. }
  6512. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  6513. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  6514. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  6515. tmp = css["display"] === "block";
  6516. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  6517. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  6518. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  6519. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  6520. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  6521. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  6522. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  6523. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  6524. css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
  6525. //float and clearing of floats
  6526. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  6527. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  6528. css["color"] = computedCSSElement("color");
  6529. return css;
  6530. };
  6531. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  6532. var handlers, i, isHandledElsewhere, l, t;
  6533. isHandledElsewhere = false;
  6534. i = void 0;
  6535. l = void 0;
  6536. t = void 0;
  6537. handlers = elementHandlers["#" + element.id];
  6538. if (handlers) {
  6539. if (typeof handlers === "function") {
  6540. isHandledElsewhere = handlers(element, renderer);
  6541. } else {
  6542. i = 0;
  6543. l = handlers.length;
  6544. while (!isHandledElsewhere && i !== l) {
  6545. isHandledElsewhere = handlers[i](element, renderer);
  6546. i++;
  6547. }
  6548. }
  6549. }
  6550. handlers = elementHandlers[element.nodeName];
  6551. if (!isHandledElsewhere && handlers) {
  6552. if (typeof handlers === "function") {
  6553. isHandledElsewhere = handlers(element, renderer);
  6554. } else {
  6555. i = 0;
  6556. l = handlers.length;
  6557. while (!isHandledElsewhere && i !== l) {
  6558. isHandledElsewhere = handlers[i](element, renderer);
  6559. i++;
  6560. }
  6561. }
  6562. }
  6563. return isHandledElsewhere;
  6564. };
  6565. tableToJson = function tableToJson(table, renderer) {
  6566. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  6567. data = [];
  6568. headers = [];
  6569. i = 0;
  6570. l = table.rows[0].cells.length;
  6571. table_with = table.clientWidth;
  6572. while (i < l) {
  6573. cell = table.rows[0].cells[i];
  6574. headers[i] = {
  6575. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  6576. prompt: cell.textContent.replace(/\r?\n/g, ''),
  6577. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
  6578. };
  6579. i++;
  6580. }
  6581. i = 1;
  6582. while (i < table.rows.length) {
  6583. tableRow = table.rows[i];
  6584. rowData = {};
  6585. j = 0;
  6586. while (j < tableRow.cells.length) {
  6587. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  6588. j++;
  6589. }
  6590. data.push(rowData);
  6591. i++;
  6592. }
  6593. return table_obj = {
  6594. rows: data,
  6595. headers: headers
  6596. };
  6597. };
  6598. var SkipNode = {
  6599. SCRIPT: 1,
  6600. STYLE: 1,
  6601. NOSCRIPT: 1,
  6602. OBJECT: 1,
  6603. EMBED: 1,
  6604. SELECT: 1
  6605. };
  6606. var listCount = 1;
  6607. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  6608. var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
  6609. cns = element.childNodes;
  6610. cn = void 0;
  6611. fragmentCSS = GetCSS(element);
  6612. isBlock = fragmentCSS.display === "block";
  6613. if (isBlock) {
  6614. renderer.setBlockBoundary();
  6615. renderer.setBlockStyle(fragmentCSS);
  6616. }
  6617. px2pt = 0.264583 * 72 / 25.4;
  6618. i = 0;
  6619. l = cns.length;
  6620. while (i < l) {
  6621. cn = cns[i];
  6622. if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
  6623. //execute all watcher functions to e.g. reset floating
  6624. renderer.executeWatchFunctions(cn);
  6625. /*** HEADER rendering **/
  6626. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  6627. var header = cn;
  6628. //store old top margin
  6629. var oldMarginTop = renderer.pdf.margins_doc.top;
  6630. //subscribe for new page event and render header first on every page
  6631. renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
  6632. //set current y position to old margin
  6633. renderer.y = oldMarginTop;
  6634. //render all child nodes of the header element
  6635. _DrillForContent(header, renderer, elementHandlers);
  6636. //set margin to old margin + rendered header + 10 space to prevent overlapping
  6637. //important for other plugins (e.g. table) to start rendering at correct position after header
  6638. renderer.pdf.margins_doc.top = renderer.y + 10;
  6639. renderer.y += 10;
  6640. }, false);
  6641. }
  6642. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  6643. if (~cn.textContent.indexOf("ADD_PAGE")) {
  6644. renderer.pdf.addPage();
  6645. renderer.y = renderer.pdf.margins_doc.top;
  6646. }
  6647. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  6648. /*** IMAGE RENDERING ***/
  6649. var cached_image;
  6650. if (cn.nodeName === "IMG") {
  6651. var url = cn.getAttribute("src");
  6652. cached_image = images[renderer.pdf.sHashCode(url) || url];
  6653. }
  6654. if (cached_image) {
  6655. if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  6656. renderer.pdf.addPage();
  6657. renderer.y = renderer.pdf.margins_doc.top;
  6658. //check if we have to set back some values due to e.g. header rendering for new page
  6659. renderer.executeWatchFunctions(cn);
  6660. }
  6661. var imagesCSS = GetCSS(cn);
  6662. var imageX = renderer.x;
  6663. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
  6664. //define additional paddings, margins which have to be taken into account for margin calculations
  6665. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  6666. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  6667. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  6668. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
  6669. //if float is set to right, move the image to the right border
  6670. //add space if margin is set
  6671. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  6672. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  6673. } else {
  6674. imageX += additionalSpaceLeft;
  6675. }
  6676. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  6677. cached_image = undefined;
  6678. //if the float prop is specified we have to float the text around the image
  6679. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  6680. //add functiont to set back coordinates after image rendering
  6681. renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
  6682. //undo drawing box adaptions which were set by floating
  6683. if (renderer.y >= thresholdY) {
  6684. renderer.x += diffX;
  6685. renderer.settings.width += diffWidth;
  6686. return true;
  6687. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  6688. renderer.x += diffX;
  6689. renderer.y = thresholdY;
  6690. renderer.settings.width += diffWidth;
  6691. return true;
  6692. } else {
  6693. return false;
  6694. }
  6695. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
  6696. //reset floating by clear:both divs
  6697. //just set cursorY after the floating element
  6698. renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
  6699. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  6700. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  6701. renderer.y = yPositionAfterFloating;
  6702. return true;
  6703. } else {
  6704. return false;
  6705. }
  6706. } else {
  6707. return true;
  6708. }
  6709. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
  6710. //if floating is set we decrease the available width by the image width
  6711. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
  6712. //if left just add the image width to the X coordinate
  6713. if (imagesCSS['float'] === 'left') {
  6714. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  6715. }
  6716. } else {
  6717. //if no floating is set, move the rendering cursor after the image height
  6718. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  6719. }
  6720. /*** TABLE RENDERING ***/
  6721. } else if (cn.nodeName === "TABLE") {
  6722. table2json = tableToJson(cn, renderer);
  6723. renderer.y += 10;
  6724. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  6725. autoSize: false,
  6726. printHeaders: elementHandlers.printHeaders,
  6727. margins: renderer.pdf.margins_doc,
  6728. css: GetCSS(cn)
  6729. });
  6730. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  6731. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  6732. listCount = 1;
  6733. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6734. _DrillForContent(cn, renderer, elementHandlers);
  6735. }
  6736. renderer.y += 10;
  6737. } else if (cn.nodeName === "LI") {
  6738. var temp = renderer.x;
  6739. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  6740. renderer.y += 3;
  6741. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6742. _DrillForContent(cn, renderer, elementHandlers);
  6743. }
  6744. renderer.x = temp;
  6745. } else if (cn.nodeName === "BR") {
  6746. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  6747. renderer.addText("\u2028", clone(fragmentCSS));
  6748. } else {
  6749. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6750. _DrillForContent(cn, renderer, elementHandlers);
  6751. }
  6752. }
  6753. } else if (cn.nodeType === 3) {
  6754. var value = cn.nodeValue;
  6755. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  6756. if (cn.parentNode.parentNode.nodeName === "OL") {
  6757. value = listCount++ + '. ' + value;
  6758. } else {
  6759. var fontSize = fragmentCSS["font-size"];
  6760. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  6761. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  6762. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  6763. cb = function cb(x, y) {
  6764. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  6765. };
  6766. }
  6767. }
  6768. // Only add the text if the text node is in the body element
  6769. // Add compatibility with IE11
  6770. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  6771. renderer.addText(value, fragmentCSS);
  6772. }
  6773. } else if (typeof cn === "string") {
  6774. renderer.addText(cn, fragmentCSS);
  6775. }
  6776. }
  6777. i++;
  6778. }
  6779. elementHandlers.outY = renderer.y;
  6780. if (isBlock) {
  6781. return renderer.setBlockBoundary(cb);
  6782. }
  6783. };
  6784. images = {};
  6785. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  6786. var imgs = element.getElementsByTagName('img'),
  6787. l = imgs.length,
  6788. found_images,
  6789. x = 0;
  6790. function done() {
  6791. renderer.pdf.internal.events.publish('imagesLoaded');
  6792. cb(found_images);
  6793. }
  6794. function loadImage(url, width, height) {
  6795. if (!url) return;
  6796. var img = new Image();
  6797. found_images = ++x;
  6798. img.crossOrigin = '';
  6799. img.onerror = img.onload = function () {
  6800. if (img.complete) {
  6801. //to support data urls in images, set width and height
  6802. //as those values are not recognized automatically
  6803. if (img.src.indexOf('data:image/') === 0) {
  6804. img.width = width || img.width || 0;
  6805. img.height = height || img.height || 0;
  6806. }
  6807. //if valid image add to known images array
  6808. if (img.width + img.height) {
  6809. var hash = renderer.pdf.sHashCode(url) || url;
  6810. images[hash] = images[hash] || img;
  6811. }
  6812. }
  6813. if (! --x) {
  6814. done();
  6815. }
  6816. };
  6817. img.src = url;
  6818. }
  6819. while (l--) {
  6820. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  6821. }return x || done();
  6822. };
  6823. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  6824. //check if we can found a <footer> element
  6825. var footer = elem.getElementsByTagName("footer");
  6826. if (footer.length > 0) {
  6827. footer = footer[0];
  6828. //bad hack to get height of footer
  6829. //creat dummy out and check new y after fake rendering
  6830. var oldOut = renderer.pdf.internal.write;
  6831. var oldY = renderer.y;
  6832. renderer.pdf.internal.write = function () {};
  6833. _DrillForContent(footer, renderer, elementHandlers);
  6834. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  6835. renderer.y = oldY;
  6836. renderer.pdf.internal.write = oldOut;
  6837. //add 20% to prevent overlapping
  6838. renderer.pdf.margins_doc.bottom += footerHeight;
  6839. //Create function render header on every page
  6840. var renderFooter = function renderFooter(pageInfo) {
  6841. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
  6842. //set current y position to old margin
  6843. var oldPosition = renderer.y;
  6844. //render all child nodes of the header element
  6845. renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
  6846. renderer.pdf.margins_doc.bottom -= footerHeight;
  6847. //check if we have to add page numbers
  6848. var spans = footer.getElementsByTagName('span');
  6849. for (var i = 0; i < spans.length; ++i) {
  6850. //if we find some span element with class pageCounter, set the page
  6851. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  6852. spans[i].innerHTML = pageNumber;
  6853. }
  6854. //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  6855. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6856. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  6857. }
  6858. }
  6859. //render footer content
  6860. _DrillForContent(footer, renderer, elementHandlers);
  6861. //set bottom margin to previous height including the footer height
  6862. renderer.pdf.margins_doc.bottom += footerHeight;
  6863. //important for other plugins (e.g. table) to start rendering at correct position after header
  6864. renderer.y = oldPosition;
  6865. };
  6866. //check if footer contains totalPages which should be replace at the disoposal of the document
  6867. var spans = footer.getElementsByTagName('span');
  6868. for (var i = 0; i < spans.length; ++i) {
  6869. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6870. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  6871. }
  6872. }
  6873. //register event to render footer on every new page
  6874. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
  6875. //render footer on first page
  6876. renderFooter();
  6877. //prevent footer rendering
  6878. SkipNode['FOOTER'] = 1;
  6879. }
  6880. };
  6881. process = function process(pdf, element, x, y, settings, callback) {
  6882. if (!element) return false;
  6883. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  6884. if (typeof element === "string") {
  6885. element = function (element) {
  6886. var $frame, $hiddendiv, framename, visuallyhidden;
  6887. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  6888. visuallyhidden = "position: absolute !important;" + "clip: rect(1px 1px 1px 1px); /* IE6, IE7 */" + "clip: rect(1px, 1px, 1px, 1px);" + "padding:0 !important;" + "border:0 !important;" + "height: 1px !important;" + "width: 1px !important; " + "top:auto;" + "left:-100px;" + "overflow: hidden;";
  6889. $hiddendiv = document.createElement('div');
  6890. $hiddendiv.style.cssText = visuallyhidden;
  6891. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  6892. document.body.appendChild($hiddendiv);
  6893. $frame = window.frames[framename];
  6894. $frame.document.open();
  6895. $frame.document.writeln(element);
  6896. $frame.document.close();
  6897. return $frame.document.body;
  6898. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  6899. }
  6900. var r = new Renderer(pdf, x, y, settings),
  6901. out;
  6902. // 1. load images
  6903. // 2. prepare optional footer elements
  6904. // 3. render content
  6905. loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
  6906. checkForFooter(element, r, settings.elementHandlers);
  6907. _DrillForContent(element, r, settings.elementHandlers);
  6908. //send event dispose for final taks (e.g. footer totalpage replacement)
  6909. r.pdf.internal.events.publish('htmlRenderingFinished');
  6910. out = r.dispose();
  6911. if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  6912. });
  6913. return out || { x: r.x, y: r.y };
  6914. };
  6915. Renderer.prototype.init = function () {
  6916. this.paragraph = {
  6917. text: [],
  6918. style: []
  6919. };
  6920. return this.pdf.internal.write("q");
  6921. };
  6922. Renderer.prototype.dispose = function () {
  6923. this.pdf.internal.write("Q");
  6924. return {
  6925. x: this.x,
  6926. y: this.y,
  6927. ready: true
  6928. };
  6929. };
  6930. //Checks if we have to execute some watcher functions
  6931. //e.g. to end text floating around an image
  6932. Renderer.prototype.executeWatchFunctions = function (el) {
  6933. var ret = false;
  6934. var narray = [];
  6935. if (this.watchFunctions.length > 0) {
  6936. for (var i = 0; i < this.watchFunctions.length; ++i) {
  6937. if (this.watchFunctions[i](el) === true) {
  6938. ret = true;
  6939. } else {
  6940. narray.push(this.watchFunctions[i]);
  6941. }
  6942. }
  6943. this.watchFunctions = narray;
  6944. }
  6945. return ret;
  6946. };
  6947. Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
  6948. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  6949. defaultFontSize = 12;
  6950. k = this.pdf.internal.scaleFactor;
  6951. fontMetricsCache = {};
  6952. ff = void 0;
  6953. fs = void 0;
  6954. fontMetrics = void 0;
  6955. fragment = void 0;
  6956. style = void 0;
  6957. fragmentSpecificMetrics = void 0;
  6958. fragmentLength = void 0;
  6959. fragmentChopped = void 0;
  6960. line = [];
  6961. lines = [line];
  6962. currentLineLength = 0;
  6963. maxLineLength = this.settings.width;
  6964. while (fragments.length) {
  6965. fragment = fragments.shift();
  6966. style = styles.shift();
  6967. if (fragment) {
  6968. ff = style["font-family"];
  6969. fs = style["font-style"];
  6970. fontMetrics = fontMetricsCache[ff + fs];
  6971. if (!fontMetrics) {
  6972. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  6973. fontMetricsCache[ff + fs] = fontMetrics;
  6974. }
  6975. fragmentSpecificMetrics = {
  6976. widths: fontMetrics.widths,
  6977. kerning: fontMetrics.kerning,
  6978. fontSize: style["font-size"] * defaultFontSize,
  6979. textIndent: currentLineLength
  6980. };
  6981. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6982. if (fragment == "\u2028") {
  6983. line = [];
  6984. lines.push(line);
  6985. } else if (currentLineLength + fragmentLength > maxLineLength) {
  6986. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  6987. line.push([fragmentChopped.shift(), style]);
  6988. while (fragmentChopped.length) {
  6989. line = [[fragmentChopped.shift(), style]];
  6990. lines.push(line);
  6991. }
  6992. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6993. } else {
  6994. line.push([fragment, style]);
  6995. currentLineLength += fragmentLength;
  6996. }
  6997. }
  6998. }
  6999. //if text alignment was set, set margin/indent of each line
  7000. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  7001. for (var i = 0; i < lines.length; ++i) {
  7002. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  7003. //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  7004. if (i > 0) {
  7005. lines[i][0][1] = clone(lines[i][0][1]);
  7006. }
  7007. var space = maxLineLength - length;
  7008. if (style['text-align'] === 'right') {
  7009. lines[i][0][1]['margin-left'] = space;
  7010. //if alignment is not right, it has to be center so split the space to the left and the right
  7011. } else if (style['text-align'] === 'center') {
  7012. lines[i][0][1]['margin-left'] = space / 2;
  7013. //if justify was set, calculate the word spacing and define in by using the css property
  7014. } else if (style['text-align'] === 'justify') {
  7015. var countSpaces = lines[i][0][0].split(' ').length - 1;
  7016. lines[i][0][1]['word-spacing'] = space / countSpaces;
  7017. //ignore the last line in justify mode
  7018. if (i === lines.length - 1) {
  7019. lines[i][0][1]['word-spacing'] = 0;
  7020. }
  7021. }
  7022. }
  7023. }
  7024. return lines;
  7025. };
  7026. Renderer.prototype.RenderTextFragment = function (text, style) {
  7027. var defaultFontSize, font, maxLineHeight;
  7028. maxLineHeight = 0;
  7029. defaultFontSize = 12;
  7030. if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  7031. this.pdf.internal.write("ET", "Q");
  7032. this.pdf.addPage();
  7033. this.y = this.pdf.margins_doc.top;
  7034. this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
  7035. //move cursor by one line on new page
  7036. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  7037. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7038. }
  7039. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  7040. // text color
  7041. var pdfTextColor = this.getPdfColor(style["color"]);
  7042. if (pdfTextColor !== this.lastTextColor) {
  7043. this.pdf.internal.write(pdfTextColor);
  7044. this.lastTextColor = pdfTextColor;
  7045. }
  7046. //set the word spacing for e.g. justify style
  7047. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  7048. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  7049. }
  7050. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  7051. //set the word spacing back to neutral => 0
  7052. if (style['word-spacing'] !== undefined) {
  7053. this.pdf.internal.write(0, "Tw");
  7054. }
  7055. };
  7056. // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  7057. Renderer.prototype.getPdfColor = function (style) {
  7058. var textColor;
  7059. var r, g, b;
  7060. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  7061. var m = rx.exec(style);
  7062. if (m != null) {
  7063. r = parseInt(m[1]);
  7064. g = parseInt(m[2]);
  7065. b = parseInt(m[3]);
  7066. } else {
  7067. if (style.charAt(0) != '#') {
  7068. style = CssColors.colorNameToHex(style);
  7069. if (!style) {
  7070. style = '#000000';
  7071. }
  7072. }
  7073. r = style.substring(1, 3);
  7074. r = parseInt(r, 16);
  7075. g = style.substring(3, 5);
  7076. g = parseInt(g, 16);
  7077. b = style.substring(5, 7);
  7078. b = parseInt(b, 16);
  7079. }
  7080. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  7081. var hex = parseInt(r.substr(1), 16);
  7082. r = hex >> 16 & 255;
  7083. g = hex >> 8 & 255;
  7084. b = hex & 255;
  7085. }
  7086. var f3 = this.f3;
  7087. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  7088. textColor = f3(r / 255) + ' g';
  7089. } else {
  7090. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  7091. }
  7092. return textColor;
  7093. };
  7094. Renderer.prototype.f3 = function (number) {
  7095. return number.toFixed(3); // Ie, %.3f
  7096. }, Renderer.prototype.renderParagraph = function (cb) {
  7097. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  7098. fragments = PurgeWhiteSpace(this.paragraph.text);
  7099. styles = this.paragraph.style;
  7100. blockstyle = this.paragraph.blockstyle;
  7101. priorblockstyle = this.paragraph.priorblockstyle || {};
  7102. this.paragraph = {
  7103. text: [],
  7104. style: [],
  7105. blockstyle: {},
  7106. priorblockstyle: blockstyle
  7107. };
  7108. if (!fragments.join("").trim()) {
  7109. return;
  7110. }
  7111. lines = this.splitFragmentsIntoLines(fragments, styles);
  7112. line = void 0;
  7113. maxLineHeight = void 0;
  7114. defaultFontSize = 12;
  7115. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  7116. this.priorMarginBottom = this.priorMarginBottom || 0;
  7117. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7118. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  7119. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  7120. if (blockstyle['page-break-before'] === 'always') {
  7121. this.pdf.addPage();
  7122. this.y = 0;
  7123. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7124. }
  7125. out = this.pdf.internal.write;
  7126. i = void 0;
  7127. l = void 0;
  7128. this.y += paragraphspacing_before;
  7129. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7130. //stores the current indent of cursor position
  7131. var currentIndent = 0;
  7132. while (lines.length) {
  7133. line = lines.shift();
  7134. maxLineHeight = 0;
  7135. i = 0;
  7136. l = line.length;
  7137. while (i !== l) {
  7138. if (line[i][0].trim()) {
  7139. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  7140. fontSize = line[i][1]["font-size"] * 7;
  7141. }
  7142. i++;
  7143. }
  7144. //if we have to move the cursor to adapt the indent
  7145. var indentMove = 0;
  7146. var wantedIndent = 0;
  7147. //if a margin was added (by e.g. a text-alignment), move the cursor
  7148. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  7149. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  7150. indentMove = wantedIndent - currentIndent;
  7151. currentIndent = wantedIndent;
  7152. }
  7153. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
  7154. //move the cursor
  7155. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7156. i = 0;
  7157. l = line.length;
  7158. while (i !== l) {
  7159. if (line[i][0]) {
  7160. this.RenderTextFragment(line[i][0], line[i][1]);
  7161. }
  7162. i++;
  7163. }
  7164. this.y += maxLineHeight * fontToUnitRatio;
  7165. //if some watcher function was executed successful, so e.g. margin and widths were changed,
  7166. //reset line drawing and calculate position and lines again
  7167. //e.g. to stop text floating around an image
  7168. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  7169. var localFragments = [];
  7170. var localStyles = [];
  7171. //create fragment array of
  7172. lines.forEach(function (localLine) {
  7173. var i = 0;
  7174. var l = localLine.length;
  7175. while (i !== l) {
  7176. if (localLine[i][0]) {
  7177. localFragments.push(localLine[i][0] + ' ');
  7178. localStyles.push(localLine[i][1]);
  7179. }
  7180. ++i;
  7181. }
  7182. });
  7183. //split lines again due to possible coordinate changes
  7184. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
  7185. //reposition the current cursor
  7186. out("ET", "Q");
  7187. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7188. }
  7189. }
  7190. if (cb && typeof cb === "function") {
  7191. cb.call(this, this.x - 9, this.y - fontSize / 2);
  7192. }
  7193. out("ET", "Q");
  7194. return this.y += paragraphspacing_after;
  7195. };
  7196. Renderer.prototype.setBlockBoundary = function (cb) {
  7197. return this.renderParagraph(cb);
  7198. };
  7199. Renderer.prototype.setBlockStyle = function (css) {
  7200. return this.paragraph.blockstyle = css;
  7201. };
  7202. Renderer.prototype.addText = function (text, css) {
  7203. this.paragraph.text.push(text);
  7204. return this.paragraph.style.push(css);
  7205. };
  7206. FontNameDB = {
  7207. helvetica: "helvetica",
  7208. "sans-serif": "helvetica",
  7209. "times new roman": "times",
  7210. serif: "times",
  7211. times: "times",
  7212. monospace: "courier",
  7213. courier: "courier"
  7214. };
  7215. FontWeightMap = {
  7216. 100: "normal",
  7217. 200: "normal",
  7218. 300: "normal",
  7219. 400: "normal",
  7220. 500: "bold",
  7221. 600: "bold",
  7222. 700: "bold",
  7223. 800: "bold",
  7224. 900: "bold",
  7225. normal: "normal",
  7226. bold: "bold",
  7227. bolder: "bold",
  7228. lighter: "normal"
  7229. };
  7230. FontStyleMap = {
  7231. normal: "normal",
  7232. italic: "italic",
  7233. oblique: "italic"
  7234. };
  7235. TextAlignMap = {
  7236. left: "left",
  7237. right: "right",
  7238. center: "center",
  7239. justify: "justify"
  7240. };
  7241. FloatMap = {
  7242. none: 'none',
  7243. right: 'right',
  7244. left: 'left'
  7245. };
  7246. ClearMap = {
  7247. none: 'none',
  7248. both: 'both'
  7249. };
  7250. UnitedNumberMap = {
  7251. normal: 1
  7252. };
  7253. /**
  7254. * Converts HTML-formatted text into formatted PDF text.
  7255. *
  7256. * Notes:
  7257. * 2012-07-18
  7258. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  7259. * Plugin relies on jQuery for CSS extraction.
  7260. * Targeting HTML output from Markdown templating, which is a very simple
  7261. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  7262. * Images, tables are NOT supported.
  7263. *
  7264. * @public
  7265. * @function
  7266. * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  7267. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  7268. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  7269. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  7270. * @returns {Object} jsPDF instance
  7271. */
  7272. jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
  7273. "use strict";
  7274. this.margins_doc = margins || {
  7275. top: 0,
  7276. bottom: 0
  7277. };
  7278. if (!settings) settings = {};
  7279. if (!settings.elementHandlers) settings.elementHandlers = {};
  7280. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  7281. };
  7282. })(jsPDF.API);
  7283. /** ====================================================================
  7284. * jsPDF JavaScript plugin
  7285. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  7286. *
  7287. *
  7288. * ====================================================================
  7289. */
  7290. /*global jsPDF */
  7291. (function (jsPDFAPI) {
  7292. 'use strict';
  7293. var jsNamesObj, jsJsObj, text;
  7294. jsPDFAPI.addJS = function (txt) {
  7295. text = txt;
  7296. this.internal.events.subscribe('postPutResources', function (txt) {
  7297. jsNamesObj = this.internal.newObject();
  7298. this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
  7299. jsJsObj = this.internal.newObject();
  7300. this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
  7301. });
  7302. this.internal.events.subscribe('putCatalog', function () {
  7303. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  7304. this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  7305. }
  7306. });
  7307. return this;
  7308. };
  7309. })(jsPDF.API);
  7310. /**
  7311. * jsPDF Outline PlugIn
  7312. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7313. *
  7314. * Licensed under the MIT License.
  7315. * http://opensource.org/licenses/mit-license
  7316. */
  7317. /**
  7318. * Generates a PDF Outline
  7319. */
  7320. (function (jsPDFAPI) {
  7321. 'use strict';
  7322. jsPDFAPI.events.push(['postPutResources', function () {
  7323. var pdf = this;
  7324. var rx = /^(\d+) 0 obj$/;
  7325. // Write action goto objects for each page
  7326. // this.outline.destsGoto = [];
  7327. // for (var i = 0; i < totalPages; i++) {
  7328. // var id = pdf.internal.newObject();
  7329. // this.outline.destsGoto.push(id);
  7330. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  7331. // null null]/S/GoTo>> endobj");
  7332. // }
  7333. //
  7334. // for (var i = 0; i < dests.length; i++) {
  7335. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  7336. // R");
  7337. // }
  7338. //
  7339. if (this.outline.root.children.length > 0) {
  7340. var lines = pdf.outline.render().split(/\r\n/);
  7341. for (var i = 0; i < lines.length; i++) {
  7342. var line = lines[i];
  7343. var m = rx.exec(line);
  7344. if (m != null) {
  7345. var oid = m[1];
  7346. pdf.internal.newObjectDeferredBegin(oid);
  7347. }
  7348. pdf.internal.write(line);
  7349. }
  7350. }
  7351. // This code will write named destination for each page reference
  7352. // (page_1, etc)
  7353. if (this.outline.createNamedDestinations) {
  7354. var totalPages = this.internal.pages.length;
  7355. // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  7356. // follow 5, 7, 9, etc
  7357. // Write destination objects for each page
  7358. var dests = [];
  7359. for (var i = 0; i < totalPages; i++) {
  7360. var id = pdf.internal.newObject();
  7361. dests.push(id);
  7362. var info = pdf.internal.getPageInfo(i + 1);
  7363. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  7364. }
  7365. // assign a name for each destination
  7366. var names2Oid = pdf.internal.newObject();
  7367. pdf.internal.write('<< /Names [ ');
  7368. for (var i = 0; i < dests.length; i++) {
  7369. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  7370. }
  7371. pdf.internal.write(' ] >>', 'endobj');
  7372. // var kids = pdf.internal.newObject();
  7373. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  7374. // pdf.internal.write(' ] >>', 'endobj');
  7375. var namesOid = pdf.internal.newObject();
  7376. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  7377. pdf.internal.write('>>', 'endobj');
  7378. }
  7379. }]);
  7380. jsPDFAPI.events.push(['putCatalog', function () {
  7381. var pdf = this;
  7382. if (pdf.outline.root.children.length > 0) {
  7383. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  7384. if (this.outline.createNamedDestinations) {
  7385. pdf.internal.write("/Names " + namesOid + " 0 R");
  7386. }
  7387. // Open with Bookmarks showing
  7388. // pdf.internal.write("/PageMode /UseOutlines");
  7389. }
  7390. }]);
  7391. jsPDFAPI.events.push(['initialized', function () {
  7392. var pdf = this;
  7393. pdf.outline = {
  7394. createNamedDestinations: false,
  7395. root: {
  7396. children: []
  7397. }
  7398. };
  7399. var namesOid;
  7400. var destsGoto = [];
  7401. /**
  7402. * Options: pageNumber
  7403. */
  7404. pdf.outline.add = function (parent, title, options) {
  7405. var item = {
  7406. title: title,
  7407. options: options,
  7408. children: []
  7409. };
  7410. if (parent == null) {
  7411. parent = this.root;
  7412. }
  7413. parent.children.push(item);
  7414. return item;
  7415. };
  7416. pdf.outline.render = function () {
  7417. this.ctx = {};
  7418. this.ctx.val = '';
  7419. this.ctx.pdf = pdf;
  7420. this.genIds_r(this.root);
  7421. this.renderRoot(this.root);
  7422. this.renderItems(this.root);
  7423. return this.ctx.val;
  7424. };
  7425. pdf.outline.genIds_r = function (node) {
  7426. node.id = pdf.internal.newObjectDeferred();
  7427. for (var i = 0; i < node.children.length; i++) {
  7428. this.genIds_r(node.children[i]);
  7429. }
  7430. };
  7431. pdf.outline.renderRoot = function (node) {
  7432. this.objStart(node);
  7433. this.line('/Type /Outlines');
  7434. if (node.children.length > 0) {
  7435. this.line('/First ' + this.makeRef(node.children[0]));
  7436. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  7437. }
  7438. this.line('/Count ' + this.count_r({
  7439. count: 0
  7440. }, node));
  7441. this.objEnd();
  7442. };
  7443. pdf.outline.renderItems = function (node) {
  7444. for (var i = 0; i < node.children.length; i++) {
  7445. var item = node.children[i];
  7446. this.objStart(item);
  7447. this.line('/Title ' + this.makeString(item.title));
  7448. this.line('/Parent ' + this.makeRef(node));
  7449. if (i > 0) {
  7450. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  7451. }
  7452. if (i < node.children.length - 1) {
  7453. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  7454. }
  7455. if (item.children.length > 0) {
  7456. this.line('/First ' + this.makeRef(item.children[0]));
  7457. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  7458. }
  7459. var count = this.count = this.count_r({
  7460. count: 0
  7461. }, item);
  7462. if (count > 0) {
  7463. this.line('/Count ' + count);
  7464. }
  7465. if (item.options) {
  7466. if (item.options.pageNumber) {
  7467. // Explicit Destination
  7468. //WARNING this assumes page ids are 3,5,7, etc.
  7469. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  7470. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7471. // this line does not work on all clients (pageNumber instead of page ref)
  7472. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7473. // Named Destination
  7474. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  7475. // Action Destination
  7476. // var id = pdf.internal.newObject();
  7477. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  7478. // this.line('/A ' + id + ' 0 R' );
  7479. }
  7480. }
  7481. this.objEnd();
  7482. }
  7483. for (var i = 0; i < node.children.length; i++) {
  7484. var item = node.children[i];
  7485. this.renderItems(item);
  7486. }
  7487. };
  7488. pdf.outline.line = function (text) {
  7489. this.ctx.val += text + '\r\n';
  7490. };
  7491. pdf.outline.makeRef = function (node) {
  7492. return node.id + ' 0 R';
  7493. };
  7494. pdf.outline.makeString = function (val) {
  7495. return '(' + pdf.internal.pdfEscape(val) + ')';
  7496. };
  7497. pdf.outline.objStart = function (node) {
  7498. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  7499. };
  7500. pdf.outline.objEnd = function (node) {
  7501. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  7502. };
  7503. pdf.outline.count_r = function (ctx, node) {
  7504. for (var i = 0; i < node.children.length; i++) {
  7505. ctx.count++;
  7506. this.count_r(ctx, node.children[i]);
  7507. }
  7508. return ctx.count;
  7509. };
  7510. }]);
  7511. return this;
  7512. })(jsPDF.API);
  7513. /**@preserve
  7514. * ====================================================================
  7515. * jsPDF PNG PlugIn
  7516. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  7517. *
  7518. *
  7519. * ====================================================================
  7520. */
  7521. (function (jsPDFAPI) {
  7522. 'use strict';
  7523. /*
  7524. * @see http://www.w3.org/TR/PNG-Chunks.html
  7525. *
  7526. Color Allowed Interpretation
  7527. Type Bit Depths
  7528. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  7529. 2 8,16 Each pixel is an R,G,B triple.
  7530. 3 1,2,4,8 Each pixel is a palette index;
  7531. a PLTE chunk must appear.
  7532. 4 8,16 Each pixel is a grayscale sample,
  7533. followed by an alpha sample.
  7534. 6 8,16 Each pixel is an R,G,B triple,
  7535. followed by an alpha sample.
  7536. */
  7537. /*
  7538. * PNG filter method types
  7539. *
  7540. * @see http://www.w3.org/TR/PNG-Filters.html
  7541. * @see http://www.libpng.org/pub/png/book/chapter09.html
  7542. *
  7543. * This is what the value 'Predictor' in decode params relates to
  7544. *
  7545. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  7546. * In that case, you actually have to read the first byte off each line for the prediction algorthim (which should be 0-4, corresponding to PDF 10-14) and select the appropriate unprediction algorithm based on that byte.
  7547. *
  7548. 0 None
  7549. 1 Sub
  7550. 2 Up
  7551. 3 Average
  7552. 4 Paeth
  7553. */
  7554. var doesNotHavePngJS = function doesNotHavePngJS() {
  7555. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  7556. },
  7557. canCompress = function canCompress(value) {
  7558. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  7559. },
  7560. hasCompressionJS = function hasCompressionJS() {
  7561. var inst = typeof Deflater === 'function';
  7562. if (!inst) throw new Error("requires deflate.js for compression");
  7563. return inst;
  7564. },
  7565. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  7566. var level = 5,
  7567. filter_method = filterUp;
  7568. switch (compression) {
  7569. case jsPDFAPI.image_compression.FAST:
  7570. level = 3;
  7571. filter_method = filterSub;
  7572. break;
  7573. case jsPDFAPI.image_compression.MEDIUM:
  7574. level = 6;
  7575. filter_method = filterAverage;
  7576. break;
  7577. case jsPDFAPI.image_compression.SLOW:
  7578. level = 9;
  7579. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  7580. break;
  7581. }
  7582. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  7583. var header = new Uint8Array(createZlibHeader(level));
  7584. var checksum = adler32(bytes);
  7585. var deflate = new Deflater(level);
  7586. var a = deflate.append(bytes);
  7587. var cBytes = deflate.flush();
  7588. var len = header.length + a.length + cBytes.length;
  7589. var cmpd = new Uint8Array(len + 4);
  7590. cmpd.set(header);
  7591. cmpd.set(a, header.length);
  7592. cmpd.set(cBytes, header.length + a.length);
  7593. cmpd[len++] = checksum >>> 24 & 0xff;
  7594. cmpd[len++] = checksum >>> 16 & 0xff;
  7595. cmpd[len++] = checksum >>> 8 & 0xff;
  7596. cmpd[len++] = checksum & 0xff;
  7597. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  7598. },
  7599. createZlibHeader = function createZlibHeader(bytes, level) {
  7600. /*
  7601. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  7602. */
  7603. var cm = 8;
  7604. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  7605. var cmf = cinfo << 4 | cm;
  7606. var hdr = cmf << 8;
  7607. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  7608. hdr |= flevel << 6;
  7609. hdr |= 0; //FDICT
  7610. hdr += 31 - hdr % 31;
  7611. return [cmf, hdr & 0xff & 0xff];
  7612. },
  7613. adler32 = function adler32(array, param) {
  7614. var adler = 1;
  7615. var s1 = adler & 0xffff,
  7616. s2 = adler >>> 16 & 0xffff;
  7617. var len = array.length;
  7618. var tlen;
  7619. var i = 0;
  7620. while (len > 0) {
  7621. tlen = len > param ? param : len;
  7622. len -= tlen;
  7623. do {
  7624. s1 += array[i++];
  7625. s2 += s1;
  7626. } while (--tlen);
  7627. s1 %= 65521;
  7628. s2 %= 65521;
  7629. }
  7630. return (s2 << 16 | s1) >>> 0;
  7631. },
  7632. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  7633. var lines = bytes.length / lineLength,
  7634. result = new Uint8Array(bytes.length + lines),
  7635. filter_methods = getFilterMethods(),
  7636. i = 0,
  7637. line,
  7638. prevLine,
  7639. offset;
  7640. for (; i < lines; i++) {
  7641. offset = i * lineLength;
  7642. line = bytes.subarray(offset, offset + lineLength);
  7643. if (filter_method) {
  7644. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  7645. } else {
  7646. var j = 0,
  7647. len = filter_methods.length,
  7648. results = [];
  7649. for (; j < len; j++) {
  7650. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  7651. }var ind = getIndexOfSmallestSum(results.concat());
  7652. result.set(results[ind], offset + i);
  7653. }
  7654. prevLine = line;
  7655. }
  7656. return result;
  7657. },
  7658. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  7659. /*var result = new Uint8Array(line.length + 1);
  7660. result[0] = 0;
  7661. result.set(line, 1);*/
  7662. var result = Array.apply([], line);
  7663. result.unshift(0);
  7664. return result;
  7665. },
  7666. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  7667. var result = [],
  7668. i = 0,
  7669. len = line.length,
  7670. left;
  7671. result[0] = 1;
  7672. for (; i < len; i++) {
  7673. left = line[i - colorsPerPixel] || 0;
  7674. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  7675. }
  7676. return result;
  7677. },
  7678. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  7679. var result = [],
  7680. i = 0,
  7681. len = line.length,
  7682. up;
  7683. result[0] = 2;
  7684. for (; i < len; i++) {
  7685. up = prevLine && prevLine[i] || 0;
  7686. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  7687. }
  7688. return result;
  7689. },
  7690. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  7691. var result = [],
  7692. i = 0,
  7693. len = line.length,
  7694. left,
  7695. up;
  7696. result[0] = 3;
  7697. for (; i < len; i++) {
  7698. left = line[i - colorsPerPixel] || 0;
  7699. up = prevLine && prevLine[i] || 0;
  7700. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  7701. }
  7702. return result;
  7703. },
  7704. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  7705. var result = [],
  7706. i = 0,
  7707. len = line.length,
  7708. left,
  7709. up,
  7710. upLeft,
  7711. paeth;
  7712. result[0] = 4;
  7713. for (; i < len; i++) {
  7714. left = line[i - colorsPerPixel] || 0;
  7715. up = prevLine && prevLine[i] || 0;
  7716. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  7717. paeth = paethPredictor(left, up, upLeft);
  7718. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  7719. }
  7720. return result;
  7721. },
  7722. paethPredictor = function paethPredictor(left, up, upLeft) {
  7723. var p = left + up - upLeft,
  7724. pLeft = Math.abs(p - left),
  7725. pUp = Math.abs(p - up),
  7726. pUpLeft = Math.abs(p - upLeft);
  7727. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  7728. },
  7729. getFilterMethods = function getFilterMethods() {
  7730. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  7731. },
  7732. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  7733. var i = 0,
  7734. len = arrays.length,
  7735. sum,
  7736. min,
  7737. ind;
  7738. while (i < len) {
  7739. sum = absSum(arrays[i].slice(1));
  7740. if (sum < min || !min) {
  7741. min = sum;
  7742. ind = i;
  7743. }
  7744. i++;
  7745. }
  7746. return ind;
  7747. },
  7748. absSum = function absSum(array) {
  7749. var i = 0,
  7750. len = array.length,
  7751. sum = 0;
  7752. while (i < len) {
  7753. sum += Math.abs(array[i++]);
  7754. }return sum;
  7755. },
  7756. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  7757. var predictor;
  7758. switch (compression) {
  7759. case jsPDFAPI.image_compression.FAST:
  7760. predictor = 11;
  7761. break;
  7762. case jsPDFAPI.image_compression.MEDIUM:
  7763. predictor = 13;
  7764. break;
  7765. case jsPDFAPI.image_compression.SLOW:
  7766. predictor = 14;
  7767. break;
  7768. default:
  7769. predictor = 12;
  7770. break;
  7771. }
  7772. return predictor;
  7773. },
  7774. logImg = function logImg(img) {
  7775. console.log("width: " + img.width);
  7776. console.log("height: " + img.height);
  7777. console.log("bits: " + img.bits);
  7778. console.log("colorType: " + img.colorType);
  7779. console.log("transparency:");
  7780. console.log(img.transparency);
  7781. console.log("text:");
  7782. console.log(img.text);
  7783. console.log("compressionMethod: " + img.compressionMethod);
  7784. console.log("filterMethod: " + img.filterMethod);
  7785. console.log("interlaceMethod: " + img.interlaceMethod);
  7786. console.log("imgData:");
  7787. console.log(img.imgData);
  7788. console.log("palette:");
  7789. console.log(img.palette);
  7790. console.log("colors: " + img.colors);
  7791. console.log("colorSpace: " + img.colorSpace);
  7792. console.log("pixelBitlength: " + img.pixelBitlength);
  7793. console.log("hasAlphaChannel: " + img.hasAlphaChannel);
  7794. };
  7795. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  7796. 'use strict';
  7797. var colorSpace = this.color_spaces.DEVICE_RGB,
  7798. decode = this.decode.FLATE_DECODE,
  7799. bpc = 8,
  7800. img,
  7801. dp,
  7802. trns,
  7803. colors,
  7804. pal,
  7805. smask;
  7806. /* if(this.isString(imageData)) {
  7807. }*/
  7808. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  7809. if (this.isArrayBufferView(imageData)) {
  7810. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  7811. img = new PNG(imageData);
  7812. imageData = img.imgData;
  7813. bpc = img.bits;
  7814. colorSpace = img.colorSpace;
  7815. colors = img.colors;
  7816. //logImg(img);
  7817. /*
  7818. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  7819. *
  7820. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  7821. *
  7822. * Extract alpha to create two separate images, using the alpha as a sMask
  7823. */
  7824. if ([4, 6].indexOf(img.colorType) !== -1) {
  7825. /*
  7826. * processes 8 bit RGBA and grayscale + alpha images
  7827. */
  7828. if (img.bits === 8) {
  7829. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  7830. len = pixels.length,
  7831. imgData = new Uint8Array(len * img.colors),
  7832. alphaData = new Uint8Array(len),
  7833. pDiff = img.pixelBitlength - img.bits,
  7834. i = 0,
  7835. n = 0,
  7836. pixel,
  7837. pbl;
  7838. for (; i < len; i++) {
  7839. pixel = pixels[i];
  7840. pbl = 0;
  7841. while (pbl < pDiff) {
  7842. imgData[n++] = pixel >>> pbl & 0xff;
  7843. pbl = pbl + img.bits;
  7844. }
  7845. alphaData[i] = pixel >>> pbl & 0xff;
  7846. }
  7847. }
  7848. /*
  7849. * processes 16 bit RGBA and grayscale + alpha images
  7850. */
  7851. if (img.bits === 16) {
  7852. var pixels = new Uint32Array(img.decodePixels().buffer),
  7853. len = pixels.length,
  7854. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  7855. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  7856. hasColors = img.colors > 1,
  7857. i = 0,
  7858. n = 0,
  7859. a = 0,
  7860. pixel;
  7861. while (i < len) {
  7862. pixel = pixels[i++];
  7863. imgData[n++] = pixel >>> 0 & 0xFF;
  7864. if (hasColors) {
  7865. imgData[n++] = pixel >>> 16 & 0xFF;
  7866. pixel = pixels[i++];
  7867. imgData[n++] = pixel >>> 0 & 0xFF;
  7868. }
  7869. alphaData[a++] = pixel >>> 16 & 0xFF;
  7870. }
  7871. bpc = 8;
  7872. }
  7873. if (canCompress(compression)) {
  7874. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  7875. smask = compressBytes(alphaData, img.width, 1, compression);
  7876. } else {
  7877. imageData = imgData;
  7878. smask = alphaData;
  7879. decode = null;
  7880. }
  7881. }
  7882. /*
  7883. * Indexed png. Each pixel is a palette index.
  7884. */
  7885. if (img.colorType === 3) {
  7886. colorSpace = this.color_spaces.INDEXED;
  7887. pal = img.palette;
  7888. if (img.transparency.indexed) {
  7889. var trans = img.transparency.indexed;
  7890. var total = 0,
  7891. i = 0,
  7892. len = trans.length;
  7893. for (; i < len; ++i) {
  7894. total += trans[i];
  7895. }total = total / 255;
  7896. /*
  7897. * a single color is specified as 100% transparent (0),
  7898. * so we set trns to use a /Mask with that index
  7899. */
  7900. if (total === len - 1 && trans.indexOf(0) !== -1) {
  7901. trns = [trans.indexOf(0)];
  7902. /*
  7903. * there's more than one colour within the palette that specifies
  7904. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  7905. */
  7906. } else if (total !== len) {
  7907. var pixels = img.decodePixels(),
  7908. alphaData = new Uint8Array(pixels.length),
  7909. i = 0,
  7910. len = pixels.length;
  7911. for (; i < len; i++) {
  7912. alphaData[i] = trans[pixels[i]];
  7913. }smask = compressBytes(alphaData, img.width, 1);
  7914. }
  7915. }
  7916. }
  7917. var predictor = getPredictorFromCompression(compression);
  7918. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
  7919. //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  7920. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  7921. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  7922. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  7923. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  7924. }
  7925. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  7926. };
  7927. })(jsPDF.API);
  7928. /**
  7929. * jsPDF Autoprint Plugin
  7930. *
  7931. * Licensed under the MIT License.
  7932. * http://opensource.org/licenses/mit-license
  7933. */
  7934. (function (jsPDFAPI) {
  7935. 'use strict';
  7936. jsPDFAPI.autoPrint = function () {
  7937. 'use strict';
  7938. var refAutoPrintTag;
  7939. this.internal.events.subscribe('postPutResources', function () {
  7940. refAutoPrintTag = this.internal.newObject();
  7941. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  7942. });
  7943. this.internal.events.subscribe("putCatalog", function () {
  7944. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  7945. });
  7946. return this;
  7947. };
  7948. })(jsPDF.API);
  7949. /** @preserve
  7950. * jsPDF split_text_to_size plugin - MIT license.
  7951. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7952. * 2014 Diego Casorran, https://github.com/diegocr
  7953. */
  7954. /**
  7955. *
  7956. * ====================================================================
  7957. */
  7958. (function (API) {
  7959. 'use strict';
  7960. /**
  7961. Returns an array of length matching length of the 'word' string, with each
  7962. cell ocupied by the width of the char in that position.
  7963. @function
  7964. @param word {String}
  7965. @param widths {Object}
  7966. @param kerning {Object}
  7967. @returns {Array}
  7968. */
  7969. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  7970. if (!options) {
  7971. options = {};
  7972. }
  7973. var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
  7974. widthsFractionOf = widths.fof ? widths.fof : 1,
  7975. kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
  7976. kerningFractionOf = kerning.fof ? kerning.fof : 1;
  7977. // console.log("widths, kergnings", widths, kerning)
  7978. var i,
  7979. l,
  7980. char_code,
  7981. prior_char_code = 0 // for kerning
  7982. ,
  7983. default_char_width = widths[0] || widthsFractionOf,
  7984. output = [];
  7985. for (i = 0, l = text.length; i < l; i++) {
  7986. char_code = text.charCodeAt(i);
  7987. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  7988. prior_char_code = char_code;
  7989. }
  7990. return output;
  7991. };
  7992. var getArraySum = function getArraySum(array) {
  7993. var i = array.length,
  7994. output = 0;
  7995. while (i) {
  7996. i--;
  7997. output += array[i];
  7998. }
  7999. return output;
  8000. };
  8001. /**
  8002. Returns a widths of string in a given font, if the font size is set as 1 point.
  8003. In other words, this is "proportional" value. For 1 unit of font size, the length
  8004. of the string will be that much.
  8005. Multiply by font size to get actual width in *points*
  8006. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  8007. @public
  8008. @function
  8009. @param
  8010. @returns {Type}
  8011. */
  8012. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  8013. return getArraySum(getCharWidthsArray.call(this, text, options));
  8014. };
  8015. /**
  8016. returns array of lines
  8017. */
  8018. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  8019. var answer = [];
  8020. // 1st, chop off the piece that can fit on the hanging line.
  8021. var i = 0,
  8022. l = word.length,
  8023. workingLen = 0;
  8024. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  8025. workingLen += widths_array[i];i++;
  8026. }
  8027. // this is first line.
  8028. answer.push(word.slice(0, i));
  8029. // 2nd. Split the rest into maxLen pieces.
  8030. var startOfLine = i;
  8031. workingLen = 0;
  8032. while (i !== l) {
  8033. if (workingLen + widths_array[i] > maxLen) {
  8034. answer.push(word.slice(startOfLine, i));
  8035. workingLen = 0;
  8036. startOfLine = i;
  8037. }
  8038. workingLen += widths_array[i];i++;
  8039. }
  8040. if (startOfLine !== i) {
  8041. answer.push(word.slice(startOfLine, i));
  8042. }
  8043. return answer;
  8044. };
  8045. // Note, all sizing inputs for this function must be in "font measurement units"
  8046. // By default, for PDF, it's "point".
  8047. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  8048. // at this time works only on Western scripts, ones with space char
  8049. // separating the words. Feel free to expand.
  8050. if (!options) {
  8051. options = {};
  8052. }
  8053. var line = [],
  8054. lines = [line],
  8055. line_length = options.textIndent || 0,
  8056. separator_length = 0,
  8057. current_word_length = 0,
  8058. word,
  8059. widths_array,
  8060. words = text.split(' '),
  8061. spaceCharWidth = getCharWidthsArray(' ', options)[0],
  8062. i,
  8063. l,
  8064. tmp,
  8065. lineIndent;
  8066. if (options.lineIndent === -1) {
  8067. lineIndent = words[0].length + 2;
  8068. } else {
  8069. lineIndent = options.lineIndent || 0;
  8070. }
  8071. if (lineIndent) {
  8072. var pad = Array(lineIndent).join(" "),
  8073. wrds = [];
  8074. words.map(function (wrd) {
  8075. wrd = wrd.split(/\s*\n/);
  8076. if (wrd.length > 1) {
  8077. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  8078. return (idx && wrd.length ? "\n" : "") + wrd;
  8079. }));
  8080. } else {
  8081. wrds.push(wrd[0]);
  8082. }
  8083. });
  8084. words = wrds;
  8085. lineIndent = getStringUnitWidth(pad, options);
  8086. }
  8087. for (i = 0, l = words.length; i < l; i++) {
  8088. var force = 0;
  8089. word = words[i];
  8090. if (lineIndent && word[0] == "\n") {
  8091. word = word.substr(1);
  8092. force = 1;
  8093. }
  8094. widths_array = getCharWidthsArray(word, options);
  8095. current_word_length = getArraySum(widths_array);
  8096. if (line_length + separator_length + current_word_length > maxlen || force) {
  8097. if (current_word_length > maxlen) {
  8098. // this happens when you have space-less long URLs for example.
  8099. // we just chop these to size. We do NOT insert hiphens
  8100. tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
  8101. // first line we add to existing line object
  8102. line.push(tmp.shift()); // it's ok to have extra space indicator there
  8103. // last line we make into new line object
  8104. line = [tmp.pop()];
  8105. // lines in the middle we apped to lines object as whole lines
  8106. while (tmp.length) {
  8107. lines.push([tmp.shift()]); // single fragment occupies whole line
  8108. }
  8109. current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
  8110. } else {
  8111. // just put it on a new line
  8112. line = [word];
  8113. }
  8114. // now we attach new line to lines
  8115. lines.push(line);
  8116. line_length = current_word_length + lineIndent;
  8117. separator_length = spaceCharWidth;
  8118. } else {
  8119. line.push(word);
  8120. line_length += separator_length + current_word_length;
  8121. separator_length = spaceCharWidth;
  8122. }
  8123. }
  8124. if (lineIndent) {
  8125. var postProcess = function postProcess(ln, idx) {
  8126. return (idx ? pad : '') + ln.join(" ");
  8127. };
  8128. } else {
  8129. var postProcess = function postProcess(ln) {
  8130. return ln.join(" ");
  8131. };
  8132. }
  8133. return lines.map(postProcess);
  8134. };
  8135. /**
  8136. Splits a given string into an array of strings. Uses 'size' value
  8137. (in measurement units declared as default for the jsPDF instance)
  8138. and the font's "widths" and "Kerning" tables, where available, to
  8139. determine display length of a given string for a given font.
  8140. We use character's 100% of unit size (height) as width when Width
  8141. table or other default width is not available.
  8142. @public
  8143. @function
  8144. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  8145. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  8146. @param options {Object} Optional flags needed for chopper to do the right thing.
  8147. @returns {Array} with strings chopped to size.
  8148. */
  8149. API.splitTextToSize = function (text, maxlen, options) {
  8150. 'use strict';
  8151. if (!options) {
  8152. options = {};
  8153. }
  8154. var fsize = options.fontSize || this.internal.getFontSize(),
  8155. newOptions = function (options) {
  8156. var widths = { 0: 1 },
  8157. kerning = {};
  8158. if (!options.widths || !options.kerning) {
  8159. var f = this.internal.getFont(options.fontName, options.fontStyle),
  8160. encoding = 'Unicode';
  8161. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  8162. // Actual JavaScript-native String's 16bit char codes used.
  8163. // no multi-byte logic here
  8164. if (f.metadata[encoding]) {
  8165. return {
  8166. widths: f.metadata[encoding].widths || widths,
  8167. kerning: f.metadata[encoding].kerning || kerning
  8168. };
  8169. }
  8170. } else {
  8171. return {
  8172. widths: options.widths,
  8173. kerning: options.kerning
  8174. };
  8175. }
  8176. // then use default values
  8177. return {
  8178. widths: widths,
  8179. kerning: kerning
  8180. };
  8181. }.call(this, options);
  8182. // first we split on end-of-line chars
  8183. var paragraphs;
  8184. if (Array.isArray(text)) {
  8185. paragraphs = text;
  8186. } else {
  8187. paragraphs = text.split(/\r?\n/);
  8188. }
  8189. // now we convert size (max length of line) into "font size units"
  8190. // at present time, the "font size unit" is always 'point'
  8191. // 'proportional' means, "in proportion to font size"
  8192. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
  8193. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  8194. // this may change in the future?
  8195. // until then, proportional_maxlen is likely to be in 'points'
  8196. // If first line is to be indented (shorter or longer) than maxLen
  8197. // we indicate that by using CSS-style "text-indent" option.
  8198. // here it's in font units too (which is likely 'points')
  8199. // it can be negative (which makes the first line longer than maxLen)
  8200. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  8201. newOptions.lineIndent = options.lineIndent;
  8202. var i,
  8203. l,
  8204. output = [];
  8205. for (i = 0, l = paragraphs.length; i < l; i++) {
  8206. output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
  8207. }
  8208. return output;
  8209. };
  8210. })(jsPDF.API);
  8211. /** @preserve
  8212. jsPDF standard_fonts_metrics plugin
  8213. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8214. MIT license.
  8215. */
  8216. /**
  8217. *
  8218. * ====================================================================
  8219. */
  8220. (function (API) {
  8221. 'use strict';
  8222. /*
  8223. # reference (Python) versions of 'compress' and 'uncompress'
  8224. # only 'uncompress' function is featured lower as JavaScript
  8225. # if you want to unit test "roundtrip", just transcribe the reference
  8226. # 'compress' function from Python into JavaScript
  8227. def compress(data):
  8228. keys = '0123456789abcdef'
  8229. values = 'klmnopqrstuvwxyz'
  8230. mapping = dict(zip(keys, values))
  8231. vals = []
  8232. for key in data.keys():
  8233. value = data[key]
  8234. try:
  8235. keystring = hex(key)[2:]
  8236. keystring = keystring[:-1] + mapping[keystring[-1:]]
  8237. except:
  8238. keystring = key.join(["'","'"])
  8239. #print('Keystring is %s' % keystring)
  8240. try:
  8241. if value < 0:
  8242. valuestring = hex(value)[3:]
  8243. numberprefix = '-'
  8244. else:
  8245. valuestring = hex(value)[2:]
  8246. numberprefix = ''
  8247. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  8248. except:
  8249. if type(value) == dict:
  8250. valuestring = compress(value)
  8251. else:
  8252. raise Exception("Don't know what to do with value type %s" % type(value))
  8253. vals.append(keystring+valuestring)
  8254. return '{' + ''.join(vals) + '}'
  8255. def uncompress(data):
  8256. decoded = '0123456789abcdef'
  8257. encoded = 'klmnopqrstuvwxyz'
  8258. mapping = dict(zip(encoded, decoded))
  8259. sign = +1
  8260. stringmode = False
  8261. stringparts = []
  8262. output = {}
  8263. activeobject = output
  8264. parentchain = []
  8265. keyparts = ''
  8266. valueparts = ''
  8267. key = None
  8268. ending = set(encoded)
  8269. i = 1
  8270. l = len(data) - 1 # stripping starting, ending {}
  8271. while i != l: # stripping {}
  8272. # -, {, }, ' are special.
  8273. ch = data[i]
  8274. i += 1
  8275. if ch == "'":
  8276. if stringmode:
  8277. # end of string mode
  8278. stringmode = False
  8279. key = ''.join(stringparts)
  8280. else:
  8281. # start of string mode
  8282. stringmode = True
  8283. stringparts = []
  8284. elif stringmode == True:
  8285. #print("Adding %s to stringpart" % ch)
  8286. stringparts.append(ch)
  8287. elif ch == '{':
  8288. # start of object
  8289. parentchain.append( [activeobject, key] )
  8290. activeobject = {}
  8291. key = None
  8292. #DEBUG = True
  8293. elif ch == '}':
  8294. # end of object
  8295. parent, key = parentchain.pop()
  8296. parent[key] = activeobject
  8297. key = None
  8298. activeobject = parent
  8299. #DEBUG = False
  8300. elif ch == '-':
  8301. sign = -1
  8302. else:
  8303. # must be number
  8304. if key == None:
  8305. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  8306. if ch in ending:
  8307. #debug("End of key")
  8308. keyparts += mapping[ch]
  8309. key = int(keyparts, 16) * sign
  8310. sign = +1
  8311. keyparts = ''
  8312. else:
  8313. keyparts += ch
  8314. else:
  8315. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  8316. if ch in ending:
  8317. #debug("End of value")
  8318. valueparts += mapping[ch]
  8319. activeobject[key] = int(valueparts, 16) * sign
  8320. sign = +1
  8321. key = None
  8322. valueparts = ''
  8323. else:
  8324. valueparts += ch
  8325. #debug(activeobject)
  8326. return output
  8327. */
  8328. /**
  8329. Uncompresses data compressed into custom, base16-like format.
  8330. @public
  8331. @function
  8332. @param
  8333. @returns {Type}
  8334. */
  8335. var uncompress = function uncompress(data) {
  8336. var decoded = '0123456789abcdef',
  8337. encoded = 'klmnopqrstuvwxyz',
  8338. mapping = {};
  8339. for (var i = 0; i < encoded.length; i++) {
  8340. mapping[encoded[i]] = decoded[i];
  8341. }
  8342. var undef,
  8343. output = {},
  8344. sign = 1,
  8345. stringparts // undef. will be [] in string mode
  8346. ,
  8347. activeobject = output,
  8348. parentchain = [],
  8349. parent_key_pair,
  8350. keyparts = '',
  8351. valueparts = '',
  8352. key // undef. will be Truthy when Key is resolved.
  8353. ,
  8354. datalen = data.length - 1 // stripping ending }
  8355. ,
  8356. ch;
  8357. i = 1; // stripping starting {
  8358. while (i != datalen) {
  8359. // - { } ' are special.
  8360. ch = data[i];
  8361. i += 1;
  8362. if (ch == "'") {
  8363. if (stringparts) {
  8364. // end of string mode
  8365. key = stringparts.join('');
  8366. stringparts = undef;
  8367. } else {
  8368. // start of string mode
  8369. stringparts = [];
  8370. }
  8371. } else if (stringparts) {
  8372. stringparts.push(ch);
  8373. } else if (ch == '{') {
  8374. // start of object
  8375. parentchain.push([activeobject, key]);
  8376. activeobject = {};
  8377. key = undef;
  8378. } else if (ch == '}') {
  8379. // end of object
  8380. parent_key_pair = parentchain.pop();
  8381. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  8382. key = undef;
  8383. activeobject = parent_key_pair[0];
  8384. } else if (ch == '-') {
  8385. sign = -1;
  8386. } else {
  8387. // must be number
  8388. if (key === undef) {
  8389. if (mapping.hasOwnProperty(ch)) {
  8390. keyparts += mapping[ch];
  8391. key = parseInt(keyparts, 16) * sign;
  8392. sign = +1;
  8393. keyparts = '';
  8394. } else {
  8395. keyparts += ch;
  8396. }
  8397. } else {
  8398. if (mapping.hasOwnProperty(ch)) {
  8399. valueparts += mapping[ch];
  8400. activeobject[key] = parseInt(valueparts, 16) * sign;
  8401. sign = +1;
  8402. key = undef;
  8403. valueparts = '';
  8404. } else {
  8405. valueparts += ch;
  8406. }
  8407. }
  8408. }
  8409. } // end while
  8410. return output;
  8411. };
  8412. // encoding = 'Unicode'
  8413. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  8414. // Actual 16bit char codes used.
  8415. // no multi-byte logic here
  8416. // Unicode characters to WinAnsiEncoding:
  8417. // {402: 131, 8211: 150, 8212: 151, 8216: 145, 8217: 146, 8218: 130, 8220: 147, 8221: 148, 8222: 132, 8224: 134, 8225: 135, 8226: 149, 8230: 133, 8364: 128, 8240:137, 8249: 139, 8250: 155, 710: 136, 8482: 153, 338: 140, 339: 156, 732: 152, 352: 138, 353: 154, 376: 159, 381: 142, 382: 158}
  8418. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  8419. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  8420. // as well as give strings with some (supported by these fonts) Unicode characters and
  8421. // these will be mapped to win cp1252
  8422. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  8423. var encodingBlock = {
  8424. 'codePages': ['WinAnsiEncoding'],
  8425. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  8426. },
  8427. encodings = { 'Unicode': {
  8428. 'Courier': encodingBlock,
  8429. 'Courier-Bold': encodingBlock,
  8430. 'Courier-BoldOblique': encodingBlock,
  8431. 'Courier-Oblique': encodingBlock,
  8432. 'Helvetica': encodingBlock,
  8433. 'Helvetica-Bold': encodingBlock,
  8434. 'Helvetica-BoldOblique': encodingBlock,
  8435. 'Helvetica-Oblique': encodingBlock,
  8436. 'Times-Roman': encodingBlock,
  8437. 'Times-Bold': encodingBlock,
  8438. 'Times-BoldItalic': encodingBlock,
  8439. 'Times-Italic': encodingBlock
  8440. // , 'Symbol'
  8441. // , 'ZapfDingbats'
  8442. } }
  8443. /**
  8444. Resources:
  8445. Font metrics data is reprocessed derivative of contents of
  8446. "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
  8447. Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
  8448. This file and the 14 PostScript(R) AFM files it accompanies may be used,
  8449. copied, and distributed for any purpose and without charge, with or without
  8450. modification, provided that all copyright notices are retained; that the AFM
  8451. files are not distributed without this file; that all modifications to this
  8452. file or any of the AFM files are prominently noted in the modified file(s);
  8453. and that this paragraph is not modified. Adobe Systems has no responsibility
  8454. or obligation to support the use of the AFM files.
  8455. */
  8456. ,
  8457. fontMetrics = { 'Unicode': {
  8458. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  8459. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  8460. // width is 476/1000 or 47.6% of its height (regardless of font size)
  8461. // At this time this value applies to "widths" and "kerning" numbers.
  8462. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  8463. // key 'fof' represents the "fontMetricsFractionOf" value
  8464. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8465. 'Times-BoldItalic': uncompress("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),
  8466. 'Helvetica-Bold': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),
  8467. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8468. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8469. 'Times-Bold': uncompress("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}")
  8470. //, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
  8471. , 'Helvetica': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),
  8472. 'Helvetica-BoldOblique': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}")
  8473. //, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
  8474. , 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8475. 'Times-Italic': uncompress("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}fv{17su5tu5qs}fw{17su5tu5qs}}}"),
  8476. 'Times-Roman': uncompress("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),
  8477. 'Helvetica-Oblique': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")
  8478. } };
  8479. /*
  8480. This event handler is fired when a new jsPDF object is initialized
  8481. This event handler appends metrics data to standard fonts within
  8482. that jsPDF instance. The metrics are mapped over Unicode character
  8483. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  8484. standard PDF fonts.
  8485. Future:
  8486. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  8487. char codes to StandardEncoding character codes. The encoding table is to be used
  8488. somewhere around "pdfEscape" call.
  8489. */
  8490. API.events.push(['addFont', function (font) {
  8491. var metrics,
  8492. unicode_section,
  8493. encoding = 'Unicode',
  8494. encodingBlock;
  8495. metrics = fontMetrics[encoding][font.PostScriptName];
  8496. if (metrics) {
  8497. if (font.metadata[encoding]) {
  8498. unicode_section = font.metadata[encoding];
  8499. } else {
  8500. unicode_section = font.metadata[encoding] = {};
  8501. }
  8502. unicode_section.widths = metrics.widths;
  8503. unicode_section.kerning = metrics.kerning;
  8504. }
  8505. encodingBlock = encodings[encoding][font.PostScriptName];
  8506. if (encodingBlock) {
  8507. if (font.metadata[encoding]) {
  8508. unicode_section = font.metadata[encoding];
  8509. } else {
  8510. unicode_section = font.metadata[encoding] = {};
  8511. }
  8512. unicode_section.encoding = encodingBlock;
  8513. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  8514. font.encoding = encodingBlock.codePages[0];
  8515. }
  8516. }
  8517. }]); // end of adding event handler
  8518. })(jsPDF.API);
  8519. /** @preserve
  8520. jsPDF SVG plugin
  8521. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8522. */
  8523. /**
  8524. *
  8525. * ====================================================================
  8526. */
  8527. (function (jsPDFAPI) {
  8528. 'use strict';
  8529. /**
  8530. Parses SVG XML and converts only some of the SVG elements into
  8531. PDF elements.
  8532. Supports:
  8533. paths
  8534. @public
  8535. @function
  8536. @param
  8537. @returns {Type}
  8538. */
  8539. jsPDFAPI.addSVG = function (svgtext, x, y, w, h) {
  8540. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  8541. var undef;
  8542. if (x === undef || y === undef) {
  8543. throw new Error("addSVG needs values for 'x' and 'y'");
  8544. }
  8545. function InjectCSS(cssbody, document) {
  8546. var styletag = document.createElement('style');
  8547. styletag.type = 'text/css';
  8548. if (styletag.styleSheet) {
  8549. // ie
  8550. styletag.styleSheet.cssText = cssbody;
  8551. } else {
  8552. // others
  8553. styletag.appendChild(document.createTextNode(cssbody));
  8554. }
  8555. document.getElementsByTagName("head")[0].appendChild(styletag);
  8556. }
  8557. function createWorkerNode(document) {
  8558. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  8559. ,
  8560. frame = document.createElement('iframe');
  8561. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  8562. frame.name = frameID;
  8563. frame.setAttribute("width", 0);
  8564. frame.setAttribute("height", 0);
  8565. frame.setAttribute("frameborder", "0");
  8566. frame.setAttribute("scrolling", "no");
  8567. frame.setAttribute("seamless", "seamless");
  8568. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  8569. document.body.appendChild(frame);
  8570. return frame;
  8571. }
  8572. function attachSVGToWorkerNode(svgtext, frame) {
  8573. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  8574. framedoc.write(svgtext);
  8575. framedoc.close();
  8576. return framedoc.getElementsByTagName('svg')[0];
  8577. }
  8578. function convertPathToPDFLinesArgs(path) {
  8579. 'use strict';
  8580. // we will use 'lines' method call. it needs:
  8581. // - starting coordinate pair
  8582. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  8583. // - scale array [horizontal, vertical] ratios
  8584. // - style (stroke, fill, both)
  8585. var x = parseFloat(path[1]),
  8586. y = parseFloat(path[2]),
  8587. vectors = [],
  8588. position = 3,
  8589. len = path.length;
  8590. while (position < len) {
  8591. if (path[position] === 'c') {
  8592. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2]), parseFloat(path[position + 3]), parseFloat(path[position + 4]), parseFloat(path[position + 5]), parseFloat(path[position + 6])]);
  8593. position += 7;
  8594. } else if (path[position] === 'l') {
  8595. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  8596. position += 3;
  8597. } else {
  8598. position += 1;
  8599. }
  8600. }
  8601. return [x, y, vectors];
  8602. }
  8603. var workernode = createWorkerNode(document),
  8604. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  8605. scale = [1, 1],
  8606. svgw = parseFloat(svgnode.getAttribute('width')),
  8607. svgh = parseFloat(svgnode.getAttribute('height'));
  8608. if (svgw && svgh) {
  8609. // setting both w and h makes image stretch to size.
  8610. // this may distort the image, but fits your demanded size
  8611. if (w && h) {
  8612. scale = [w / svgw, h / svgh];
  8613. }
  8614. // if only one is set, that value is set as max and SVG
  8615. // is scaled proportionately.
  8616. else if (w) {
  8617. scale = [w / svgw, w / svgw];
  8618. } else if (h) {
  8619. scale = [h / svgh, h / svgh];
  8620. }
  8621. }
  8622. var i,
  8623. l,
  8624. tmp,
  8625. linesargs,
  8626. items = svgnode.childNodes;
  8627. for (i = 0, l = items.length; i < l; i++) {
  8628. tmp = items[i];
  8629. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  8630. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
  8631. // path start x coordinate
  8632. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  8633. // path start y coordinate
  8634. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  8635. // the rest of lines are vectors. these will adjust with scale value auto.
  8636. this.lines.call(this, linesargs[2] // lines
  8637. , linesargs[0] // starting x
  8638. , linesargs[1] // starting y
  8639. , scale);
  8640. }
  8641. }
  8642. // clean up
  8643. // workernode.parentNode.removeChild(workernode)
  8644. return this;
  8645. };
  8646. })(jsPDF.API);
  8647. /** ====================================================================
  8648. * jsPDF total_pages plugin
  8649. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  8650. *
  8651. *
  8652. * ====================================================================
  8653. */
  8654. (function (jsPDFAPI) {
  8655. 'use strict';
  8656. jsPDFAPI.putTotalPages = function (pageExpression) {
  8657. 'use strict';
  8658. var replaceExpression = new RegExp(pageExpression, 'g');
  8659. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  8660. for (var i = 0; i < this.internal.pages[n].length; i++) {
  8661. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
  8662. }
  8663. }
  8664. return this;
  8665. };
  8666. })(jsPDF.API);
  8667. /** ====================================================================
  8668. * jsPDF XMP metadata plugin
  8669. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  8670. *
  8671. *
  8672. * ====================================================================
  8673. */
  8674. /*global jsPDF */
  8675. /**
  8676. * Adds XMP formatted metadata to PDF
  8677. *
  8678. * @param {String} metadata The actual metadata to be added. The metadata shall be stored as XMP simple value. Note that if the metadata string contains XML markup characters "<", ">" or "&", those characters should be written using XML entities.
  8679. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  8680. * @function
  8681. * @returns {jsPDF}
  8682. * @methodOf jsPDF#
  8683. * @name addMetadata
  8684. */
  8685. (function (jsPDFAPI) {
  8686. 'use strict';
  8687. var xmpmetadata = "";
  8688. var xmpnamespaceuri = "";
  8689. var metadata_object_number = "";
  8690. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  8691. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  8692. xmpmetadata = metadata;
  8693. this.internal.events.subscribe('postPutResources', function () {
  8694. if (!xmpmetadata) {
  8695. metadata_object_number = "";
  8696. } else {
  8697. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  8698. var rdf_beginning = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="' + xmpnamespaceuri + '"><jspdf:metadata>';
  8699. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  8700. var xmpmeta_ending = '</x:xmpmeta>';
  8701. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  8702. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  8703. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  8704. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  8705. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  8706. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  8707. metadata_object_number = this.internal.newObject();
  8708. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  8709. this.internal.write('stream');
  8710. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  8711. this.internal.write('endstream');
  8712. this.internal.write('endobj');
  8713. }
  8714. });
  8715. this.internal.events.subscribe('putCatalog', function () {
  8716. if (metadata_object_number) {
  8717. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  8718. }
  8719. });
  8720. return this;
  8721. };
  8722. })(jsPDF.API);
  8723. /* Blob.js
  8724. * A Blob implementation.
  8725. * 2014-07-24
  8726. *
  8727. * By Eli Grey, http://eligrey.com
  8728. * By Devin Samarin, https://github.com/dsamarin
  8729. * License: X11/MIT
  8730. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  8731. */
  8732. /*global self, unescape */
  8733. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  8734. plusplus: true */
  8735. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  8736. (function (view) {
  8737. "use strict";
  8738. view.URL = view.URL || view.webkitURL;
  8739. if (view.Blob && view.URL) {
  8740. try {
  8741. new Blob;
  8742. return;
  8743. } catch (e) {}
  8744. }
  8745. // Internally we use a BlobBuilder implementation to base Blob off of
  8746. // in order to support older browsers that only have BlobBuilder
  8747. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  8748. var
  8749. get_class = function(object) {
  8750. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  8751. }
  8752. , FakeBlobBuilder = function BlobBuilder() {
  8753. this.data = [];
  8754. }
  8755. , FakeBlob = function Blob(data, type, encoding) {
  8756. this.data = data;
  8757. this.size = data.length;
  8758. this.type = type;
  8759. this.encoding = encoding;
  8760. }
  8761. , FBB_proto = FakeBlobBuilder.prototype
  8762. , FB_proto = FakeBlob.prototype
  8763. , FileReaderSync = view.FileReaderSync
  8764. , FileException = function(type) {
  8765. this.code = this[this.name = type];
  8766. }
  8767. , file_ex_codes = (
  8768. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
  8769. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  8770. ).split(" ")
  8771. , file_ex_code = file_ex_codes.length
  8772. , real_URL = view.URL || view.webkitURL || view
  8773. , real_create_object_URL = real_URL.createObjectURL
  8774. , real_revoke_object_URL = real_URL.revokeObjectURL
  8775. , URL = real_URL
  8776. , btoa = view.btoa
  8777. , atob = view.atob
  8778. , ArrayBuffer = view.ArrayBuffer
  8779. , Uint8Array = view.Uint8Array
  8780. , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;
  8781. FakeBlob.fake = FB_proto.fake = true;
  8782. while (file_ex_code--) {
  8783. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  8784. }
  8785. // Polyfill URL
  8786. if (!real_URL.createObjectURL) {
  8787. URL = view.URL = function(uri) {
  8788. var
  8789. uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8790. , uri_origin;
  8791. uri_info.href = uri;
  8792. if (!("origin" in uri_info)) {
  8793. if (uri_info.protocol.toLowerCase() === "data:") {
  8794. uri_info.origin = null;
  8795. } else {
  8796. uri_origin = uri.match(origin);
  8797. uri_info.origin = uri_origin && uri_origin[1];
  8798. }
  8799. }
  8800. return uri_info;
  8801. };
  8802. }
  8803. URL.createObjectURL = function(blob) {
  8804. var
  8805. type = blob.type
  8806. , data_URI_header;
  8807. if (type === null) {
  8808. type = "application/octet-stream";
  8809. }
  8810. if (blob instanceof FakeBlob) {
  8811. data_URI_header = "data:" + type;
  8812. if (blob.encoding === "base64") {
  8813. return data_URI_header + ";base64," + blob.data;
  8814. } else if (blob.encoding === "URI") {
  8815. return data_URI_header + "," + decodeURIComponent(blob.data);
  8816. } if (btoa) {
  8817. return data_URI_header + ";base64," + btoa(blob.data);
  8818. } else {
  8819. return data_URI_header + "," + encodeURIComponent(blob.data);
  8820. }
  8821. } else if (real_create_object_URL) {
  8822. return real_create_object_URL.call(real_URL, blob);
  8823. }
  8824. };
  8825. URL.revokeObjectURL = function(object_URL) {
  8826. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  8827. real_revoke_object_URL.call(real_URL, object_URL);
  8828. }
  8829. };
  8830. FBB_proto.append = function(data/*, endings*/) {
  8831. var bb = this.data;
  8832. // decode data to a binary string
  8833. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  8834. var
  8835. str = ""
  8836. , buf = new Uint8Array(data)
  8837. , i = 0
  8838. , buf_len = buf.length;
  8839. for (; i < buf_len; i++) {
  8840. str += String.fromCharCode(buf[i]);
  8841. }
  8842. bb.push(str);
  8843. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  8844. if (FileReaderSync) {
  8845. var fr = new FileReaderSync;
  8846. bb.push(fr.readAsBinaryString(data));
  8847. } else {
  8848. // async FileReader won't work as BlobBuilder is sync
  8849. throw new FileException("NOT_READABLE_ERR");
  8850. }
  8851. } else if (data instanceof FakeBlob) {
  8852. if (data.encoding === "base64" && atob) {
  8853. bb.push(atob(data.data));
  8854. } else if (data.encoding === "URI") {
  8855. bb.push(decodeURIComponent(data.data));
  8856. } else if (data.encoding === "raw") {
  8857. bb.push(data.data);
  8858. }
  8859. } else {
  8860. if (typeof data !== "string") {
  8861. data += ""; // convert unsupported types to strings
  8862. }
  8863. // decode UTF-16 to binary string
  8864. bb.push(unescape(encodeURIComponent(data)));
  8865. }
  8866. };
  8867. FBB_proto.getBlob = function(type) {
  8868. if (!arguments.length) {
  8869. type = null;
  8870. }
  8871. return new FakeBlob(this.data.join(""), type, "raw");
  8872. };
  8873. FBB_proto.toString = function() {
  8874. return "[object BlobBuilder]";
  8875. };
  8876. FB_proto.slice = function(start, end, type) {
  8877. var args = arguments.length;
  8878. if (args < 3) {
  8879. type = null;
  8880. }
  8881. return new FakeBlob(
  8882. this.data.slice(start, args > 1 ? end : this.data.length)
  8883. , type
  8884. , this.encoding
  8885. );
  8886. };
  8887. FB_proto.toString = function() {
  8888. return "[object Blob]";
  8889. };
  8890. FB_proto.close = function() {
  8891. this.size = 0;
  8892. delete this.data;
  8893. };
  8894. return FakeBlobBuilder;
  8895. }(view));
  8896. view.Blob = function(blobParts, options) {
  8897. var type = options ? (options.type || "") : "";
  8898. var builder = new BlobBuilder();
  8899. if (blobParts) {
  8900. for (var i = 0, len = blobParts.length; i < len; i++) {
  8901. if (Uint8Array && blobParts[i] instanceof Uint8Array) {
  8902. builder.append(blobParts[i].buffer);
  8903. }
  8904. else {
  8905. builder.append(blobParts[i]);
  8906. }
  8907. }
  8908. }
  8909. var blob = builder.getBlob(type);
  8910. if (!blob.slice && blob.webkitSlice) {
  8911. blob.slice = blob.webkitSlice;
  8912. }
  8913. return blob;
  8914. };
  8915. var getPrototypeOf = Object.getPrototypeOf || function(object) {
  8916. return object.__proto__;
  8917. };
  8918. view.Blob.prototype = getPrototypeOf(new view.Blob());
  8919. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
  8920. /* FileSaver.js
  8921. * A saveAs() FileSaver implementation.
  8922. * 1.1.20151003
  8923. *
  8924. * By Eli Grey, http://eligrey.com
  8925. * License: MIT
  8926. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  8927. */
  8928. /*global self */
  8929. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  8930. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  8931. var saveAs = saveAs || (function(view) {
  8932. "use strict";
  8933. // IE <10 is explicitly unsupported
  8934. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  8935. return;
  8936. }
  8937. var
  8938. doc = view.document
  8939. // only get URL when necessary in case Blob.js hasn't overridden it yet
  8940. , get_URL = function() {
  8941. return view.URL || view.webkitURL || view;
  8942. }
  8943. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8944. , can_use_save_link = "download" in save_link
  8945. , click = function(node) {
  8946. var event = new MouseEvent("click");
  8947. node.dispatchEvent(event);
  8948. }
  8949. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  8950. , webkit_req_fs = view.webkitRequestFileSystem
  8951. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  8952. , throw_outside = function(ex) {
  8953. (view.setImmediate || view.setTimeout)(function() {
  8954. throw ex;
  8955. }, 0);
  8956. }
  8957. , force_saveable_type = "application/octet-stream"
  8958. , fs_min_size = 0
  8959. // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  8960. // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  8961. // for the reasoning behind the timeout and revocation flow
  8962. , arbitrary_revoke_timeout = 500 // in ms
  8963. , revoke = function(file) {
  8964. var revoker = function() {
  8965. if (typeof file === "string") { // file is an object URL
  8966. get_URL().revokeObjectURL(file);
  8967. } else { // file is a File
  8968. file.remove();
  8969. }
  8970. };
  8971. if (view.chrome) {
  8972. revoker();
  8973. } else {
  8974. setTimeout(revoker, arbitrary_revoke_timeout);
  8975. }
  8976. }
  8977. , dispatch = function(filesaver, event_types, event) {
  8978. event_types = [].concat(event_types);
  8979. var i = event_types.length;
  8980. while (i--) {
  8981. var listener = filesaver["on" + event_types[i]];
  8982. if (typeof listener === "function") {
  8983. try {
  8984. listener.call(filesaver, event || filesaver);
  8985. } catch (ex) {
  8986. throw_outside(ex);
  8987. }
  8988. }
  8989. }
  8990. }
  8991. , auto_bom = function(blob) {
  8992. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  8993. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  8994. return new Blob(["\ufeff", blob], {type: blob.type});
  8995. }
  8996. return blob;
  8997. }
  8998. , FileSaver = function(blob, name, no_auto_bom) {
  8999. if (!no_auto_bom) {
  9000. blob = auto_bom(blob);
  9001. }
  9002. // First try a.download, then web filesystem, then object URLs
  9003. var
  9004. filesaver = this
  9005. , type = blob.type
  9006. , blob_changed = false
  9007. , object_url
  9008. , target_view
  9009. , dispatch_all = function() {
  9010. dispatch(filesaver, "writestart progress write writeend".split(" "));
  9011. }
  9012. // on any filesys errors revert to saving with object URLs
  9013. , fs_error = function() {
  9014. if (target_view && is_safari && typeof FileReader !== "undefined") {
  9015. // Safari doesn't allow downloading of blob urls
  9016. var reader = new FileReader();
  9017. reader.onloadend = function() {
  9018. var base64Data = reader.result;
  9019. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  9020. filesaver.readyState = filesaver.DONE;
  9021. dispatch_all();
  9022. };
  9023. reader.readAsDataURL(blob);
  9024. filesaver.readyState = filesaver.INIT;
  9025. return;
  9026. }
  9027. // don't create more object URLs than needed
  9028. if (blob_changed || !object_url) {
  9029. object_url = get_URL().createObjectURL(blob);
  9030. }
  9031. if (target_view) {
  9032. target_view.location.href = object_url;
  9033. } else {
  9034. var new_tab = view.open(object_url, "_blank");
  9035. if (new_tab == undefined && is_safari) {
  9036. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  9037. view.location.href = object_url;
  9038. }
  9039. }
  9040. filesaver.readyState = filesaver.DONE;
  9041. dispatch_all();
  9042. revoke(object_url);
  9043. }
  9044. , abortable = function(func) {
  9045. return function() {
  9046. if (filesaver.readyState !== filesaver.DONE) {
  9047. return func.apply(this, arguments);
  9048. }
  9049. };
  9050. }
  9051. , create_if_not_found = {create: true, exclusive: false}
  9052. , slice;
  9053. filesaver.readyState = filesaver.INIT;
  9054. if (!name) {
  9055. name = "download";
  9056. }
  9057. if (can_use_save_link) {
  9058. object_url = get_URL().createObjectURL(blob);
  9059. setTimeout(function() {
  9060. save_link.href = object_url;
  9061. save_link.download = name;
  9062. click(save_link);
  9063. dispatch_all();
  9064. revoke(object_url);
  9065. filesaver.readyState = filesaver.DONE;
  9066. });
  9067. return;
  9068. }
  9069. // Object and web filesystem URLs have a problem saving in Google Chrome when
  9070. // viewed in a tab, so I force save with application/octet-stream
  9071. // http://code.google.com/p/chromium/issues/detail?id=91158
  9072. // Update: Google errantly closed 91158, I submitted it again:
  9073. // https://code.google.com/p/chromium/issues/detail?id=389642
  9074. if (view.chrome && type && type !== force_saveable_type) {
  9075. slice = blob.slice || blob.webkitSlice;
  9076. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  9077. blob_changed = true;
  9078. }
  9079. // Since I can't be sure that the guessed media type will trigger a download
  9080. // in WebKit, I append .download to the filename.
  9081. // https://bugs.webkit.org/show_bug.cgi?id=65440
  9082. if (webkit_req_fs && name !== "download") {
  9083. name += ".download";
  9084. }
  9085. if (type === force_saveable_type || webkit_req_fs) {
  9086. target_view = view;
  9087. }
  9088. if (!req_fs) {
  9089. fs_error();
  9090. return;
  9091. }
  9092. fs_min_size += blob.size;
  9093. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  9094. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  9095. var save = function() {
  9096. dir.getFile(name, create_if_not_found, abortable(function(file) {
  9097. file.createWriter(abortable(function(writer) {
  9098. writer.onwriteend = function(event) {
  9099. target_view.location.href = file.toURL();
  9100. filesaver.readyState = filesaver.DONE;
  9101. dispatch(filesaver, "writeend", event);
  9102. revoke(file);
  9103. };
  9104. writer.onerror = function() {
  9105. var error = writer.error;
  9106. if (error.code !== error.ABORT_ERR) {
  9107. fs_error();
  9108. }
  9109. };
  9110. "writestart progress write abort".split(" ").forEach(function(event) {
  9111. writer["on" + event] = filesaver["on" + event];
  9112. });
  9113. writer.write(blob);
  9114. filesaver.abort = function() {
  9115. writer.abort();
  9116. filesaver.readyState = filesaver.DONE;
  9117. };
  9118. filesaver.readyState = filesaver.WRITING;
  9119. }), fs_error);
  9120. }), fs_error);
  9121. };
  9122. dir.getFile(name, {create: false}, abortable(function(file) {
  9123. // delete file if it already exists
  9124. file.remove();
  9125. save();
  9126. }), abortable(function(ex) {
  9127. if (ex.code === ex.NOT_FOUND_ERR) {
  9128. save();
  9129. } else {
  9130. fs_error();
  9131. }
  9132. }));
  9133. }), fs_error);
  9134. }), fs_error);
  9135. }
  9136. , FS_proto = FileSaver.prototype
  9137. , saveAs = function(blob, name, no_auto_bom) {
  9138. return new FileSaver(blob, name, no_auto_bom);
  9139. };
  9140. // IE 10+ (native saveAs)
  9141. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  9142. return function(blob, name, no_auto_bom) {
  9143. if (!no_auto_bom) {
  9144. blob = auto_bom(blob);
  9145. }
  9146. return navigator.msSaveOrOpenBlob(blob, name || "download");
  9147. };
  9148. }
  9149. FS_proto.abort = function() {
  9150. var filesaver = this;
  9151. filesaver.readyState = filesaver.DONE;
  9152. dispatch(filesaver, "abort");
  9153. };
  9154. FS_proto.readyState = FS_proto.INIT = 0;
  9155. FS_proto.WRITING = 1;
  9156. FS_proto.DONE = 2;
  9157. FS_proto.error =
  9158. FS_proto.onwritestart =
  9159. FS_proto.onprogress =
  9160. FS_proto.onwrite =
  9161. FS_proto.onabort =
  9162. FS_proto.onerror =
  9163. FS_proto.onwriteend =
  9164. null;
  9165. return saveAs;
  9166. }(
  9167. typeof self !== "undefined" && self
  9168. || typeof window !== "undefined" && window
  9169. || undefined.content
  9170. ));
  9171. // `self` is undefined in Firefox for Android content script context
  9172. // while `this` is nsIContentFrameMessageManager
  9173. // with an attribute `content` that corresponds to the window
  9174. if (typeof module !== "undefined" && module.exports) {
  9175. module.exports.saveAs = saveAs;
  9176. } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  9177. define([], function() {
  9178. return saveAs;
  9179. });
  9180. }
  9181. /*
  9182. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  9183. *
  9184. * Licensed under the MIT License.
  9185. * http://opensource.org/licenses/mit-license
  9186. */
  9187. void function(global, callback) {
  9188. if (typeof module === 'object') {
  9189. module.exports = callback();
  9190. } else if (typeof define === 'function') {
  9191. define(callback);
  9192. } else {
  9193. global.adler32cs = callback();
  9194. }
  9195. }(jsPDF, function() {
  9196. var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
  9197. typeof Uint8Array === 'function';
  9198. var _Buffer = null, _isBuffer = (function() {
  9199. if (!_hasArrayBuffer)
  9200. return function _isBuffer() { return false };
  9201. try {
  9202. var buffer = {};
  9203. if (typeof buffer.Buffer === 'function')
  9204. _Buffer = buffer.Buffer;
  9205. } catch (error) {}
  9206. return function _isBuffer(value) {
  9207. return value instanceof ArrayBuffer ||
  9208. _Buffer !== null && value instanceof _Buffer;
  9209. };
  9210. }());
  9211. var _utf8ToBinary = (function() {
  9212. if (_Buffer !== null) {
  9213. return function _utf8ToBinary(utf8String) {
  9214. return new _Buffer(utf8String, 'utf8').toString('binary');
  9215. };
  9216. } else {
  9217. return function _utf8ToBinary(utf8String) {
  9218. return unescape(encodeURIComponent(utf8String));
  9219. };
  9220. }
  9221. }());
  9222. var MOD = 65521;
  9223. var _update = function _update(checksum, binaryString) {
  9224. var a = checksum & 0xFFFF, b = checksum >>> 16;
  9225. for (var i = 0, length = binaryString.length; i < length; i++) {
  9226. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  9227. b = (b + a) % MOD;
  9228. }
  9229. return (b << 16 | a) >>> 0;
  9230. };
  9231. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  9232. var a = checksum & 0xFFFF, b = checksum >>> 16;
  9233. for (var i = 0, length = uint8Array.length, x; i < length; i++) {
  9234. a = (a + uint8Array[i]) % MOD;
  9235. b = (b + a) % MOD;
  9236. }
  9237. return (b << 16 | a) >>> 0
  9238. };
  9239. var exports = {};
  9240. var Adler32 = exports.Adler32 = (function() {
  9241. var ctor = function Adler32(checksum) {
  9242. if (!(this instanceof ctor)) {
  9243. throw new TypeError(
  9244. 'Constructor cannot called be as a function.');
  9245. }
  9246. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  9247. throw new Error(
  9248. 'First arguments needs to be a finite number.');
  9249. }
  9250. this.checksum = checksum >>> 0;
  9251. };
  9252. var proto = ctor.prototype = {};
  9253. proto.constructor = ctor;
  9254. ctor.from = function(from) {
  9255. from.prototype = proto;
  9256. return from;
  9257. }(function from(binaryString) {
  9258. if (!(this instanceof ctor)) {
  9259. throw new TypeError(
  9260. 'Constructor cannot called be as a function.');
  9261. }
  9262. if (binaryString == null)
  9263. throw new Error('First argument needs to be a string.');
  9264. this.checksum = _update(1, binaryString.toString());
  9265. });
  9266. ctor.fromUtf8 = function(fromUtf8) {
  9267. fromUtf8.prototype = proto;
  9268. return fromUtf8;
  9269. }(function fromUtf8(utf8String) {
  9270. if (!(this instanceof ctor)) {
  9271. throw new TypeError(
  9272. 'Constructor cannot called be as a function.');
  9273. }
  9274. if (utf8String == null)
  9275. throw new Error('First argument needs to be a string.');
  9276. var binaryString = _utf8ToBinary(utf8String.toString());
  9277. this.checksum = _update(1, binaryString);
  9278. });
  9279. if (_hasArrayBuffer) {
  9280. ctor.fromBuffer = function(fromBuffer) {
  9281. fromBuffer.prototype = proto;
  9282. return fromBuffer;
  9283. }(function fromBuffer(buffer) {
  9284. if (!(this instanceof ctor)) {
  9285. throw new TypeError(
  9286. 'Constructor cannot called be as a function.');
  9287. }
  9288. if (!_isBuffer(buffer))
  9289. throw new Error('First argument needs to be ArrayBuffer.');
  9290. var array = new Uint8Array(buffer);
  9291. return this.checksum = _updateUint8Array(1, array);
  9292. });
  9293. }
  9294. proto.update = function update(binaryString) {
  9295. if (binaryString == null)
  9296. throw new Error('First argument needs to be a string.');
  9297. binaryString = binaryString.toString();
  9298. return this.checksum = _update(this.checksum, binaryString);
  9299. };
  9300. proto.updateUtf8 = function updateUtf8(utf8String) {
  9301. if (utf8String == null)
  9302. throw new Error('First argument needs to be a string.');
  9303. var binaryString = _utf8ToBinary(utf8String.toString());
  9304. return this.checksum = _update(this.checksum, binaryString);
  9305. };
  9306. if (_hasArrayBuffer) {
  9307. proto.updateBuffer = function updateBuffer(buffer) {
  9308. if (!_isBuffer(buffer))
  9309. throw new Error('First argument needs to be ArrayBuffer.');
  9310. var array = new Uint8Array(buffer);
  9311. return this.checksum = _updateUint8Array(this.checksum, array);
  9312. };
  9313. }
  9314. proto.clone = function clone() {
  9315. return new Adler32(this.checksum);
  9316. };
  9317. return ctor;
  9318. }());
  9319. exports.from = function from(binaryString) {
  9320. if (binaryString == null)
  9321. throw new Error('First argument needs to be a string.');
  9322. return _update(1, binaryString.toString());
  9323. };
  9324. exports.fromUtf8 = function fromUtf8(utf8String) {
  9325. if (utf8String == null)
  9326. throw new Error('First argument needs to be a string.');
  9327. var binaryString = _utf8ToBinary(utf8String.toString());
  9328. return _update(1, binaryString);
  9329. };
  9330. if (_hasArrayBuffer) {
  9331. exports.fromBuffer = function fromBuffer(buffer) {
  9332. if (!_isBuffer(buffer))
  9333. throw new Error('First argument need to be ArrayBuffer.');
  9334. var array = new Uint8Array(buffer);
  9335. return _updateUint8Array(1, array);
  9336. };
  9337. }
  9338. return exports;
  9339. });
  9340. /**
  9341. * CssColors
  9342. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  9343. *
  9344. * Licensed under the MIT License.
  9345. * http://opensource.org/licenses/mit-license
  9346. */
  9347. /**
  9348. * Usage CssColors('red');
  9349. * Returns RGB hex color with '#' prefix
  9350. */
  9351. var CssColors = {};
  9352. CssColors._colorsTable = {
  9353. "aliceblue" : "#f0f8ff",
  9354. "antiquewhite" : "#faebd7",
  9355. "aqua" : "#00ffff",
  9356. "aquamarine" : "#7fffd4",
  9357. "azure" : "#f0ffff",
  9358. "beige" : "#f5f5dc",
  9359. "bisque" : "#ffe4c4",
  9360. "black" : "#000000",
  9361. "blanchedalmond" : "#ffebcd",
  9362. "blue" : "#0000ff",
  9363. "blueviolet" : "#8a2be2",
  9364. "brown" : "#a52a2a",
  9365. "burlywood" : "#deb887",
  9366. "cadetblue" : "#5f9ea0",
  9367. "chartreuse" : "#7fff00",
  9368. "chocolate" : "#d2691e",
  9369. "coral" : "#ff7f50",
  9370. "cornflowerblue" : "#6495ed",
  9371. "cornsilk" : "#fff8dc",
  9372. "crimson" : "#dc143c",
  9373. "cyan" : "#00ffff",
  9374. "darkblue" : "#00008b",
  9375. "darkcyan" : "#008b8b",
  9376. "darkgoldenrod" : "#b8860b",
  9377. "darkgray" : "#a9a9a9",
  9378. "darkgreen" : "#006400",
  9379. "darkkhaki" : "#bdb76b",
  9380. "darkmagenta" : "#8b008b",
  9381. "darkolivegreen" : "#556b2f",
  9382. "darkorange" : "#ff8c00",
  9383. "darkorchid" : "#9932cc",
  9384. "darkred" : "#8b0000",
  9385. "darksalmon" : "#e9967a",
  9386. "darkseagreen" : "#8fbc8f",
  9387. "darkslateblue" : "#483d8b",
  9388. "darkslategray" : "#2f4f4f",
  9389. "darkturquoise" : "#00ced1",
  9390. "darkviolet" : "#9400d3",
  9391. "deeppink" : "#ff1493",
  9392. "deepskyblue" : "#00bfff",
  9393. "dimgray" : "#696969",
  9394. "dodgerblue" : "#1e90ff",
  9395. "firebrick" : "#b22222",
  9396. "floralwhite" : "#fffaf0",
  9397. "forestgreen" : "#228b22",
  9398. "fuchsia" : "#ff00ff",
  9399. "gainsboro" : "#dcdcdc",
  9400. "ghostwhite" : "#f8f8ff",
  9401. "gold" : "#ffd700",
  9402. "goldenrod" : "#daa520",
  9403. "gray" : "#808080",
  9404. "green" : "#008000",
  9405. "greenyellow" : "#adff2f",
  9406. "honeydew" : "#f0fff0",
  9407. "hotpink" : "#ff69b4",
  9408. "indianred " : "#cd5c5c",
  9409. "indigo" : "#4b0082",
  9410. "ivory" : "#fffff0",
  9411. "khaki" : "#f0e68c",
  9412. "lavender" : "#e6e6fa",
  9413. "lavenderblush" : "#fff0f5",
  9414. "lawngreen" : "#7cfc00",
  9415. "lemonchiffon" : "#fffacd",
  9416. "lightblue" : "#add8e6",
  9417. "lightcoral" : "#f08080",
  9418. "lightcyan" : "#e0ffff",
  9419. "lightgoldenrodyellow" : "#fafad2",
  9420. "lightgrey" : "#d3d3d3",
  9421. "lightgreen" : "#90ee90",
  9422. "lightpink" : "#ffb6c1",
  9423. "lightsalmon" : "#ffa07a",
  9424. "lightseagreen" : "#20b2aa",
  9425. "lightskyblue" : "#87cefa",
  9426. "lightslategray" : "#778899",
  9427. "lightsteelblue" : "#b0c4de",
  9428. "lightyellow" : "#ffffe0",
  9429. "lime" : "#00ff00",
  9430. "limegreen" : "#32cd32",
  9431. "linen" : "#faf0e6",
  9432. "magenta" : "#ff00ff",
  9433. "maroon" : "#800000",
  9434. "mediumaquamarine" : "#66cdaa",
  9435. "mediumblue" : "#0000cd",
  9436. "mediumorchid" : "#ba55d3",
  9437. "mediumpurple" : "#9370d8",
  9438. "mediumseagreen" : "#3cb371",
  9439. "mediumslateblue" : "#7b68ee",
  9440. "mediumspringgreen" : "#00fa9a",
  9441. "mediumturquoise" : "#48d1cc",
  9442. "mediumvioletred" : "#c71585",
  9443. "midnightblue" : "#191970",
  9444. "mintcream" : "#f5fffa",
  9445. "mistyrose" : "#ffe4e1",
  9446. "moccasin" : "#ffe4b5",
  9447. "navajowhite" : "#ffdead",
  9448. "navy" : "#000080",
  9449. "oldlace" : "#fdf5e6",
  9450. "olive" : "#808000",
  9451. "olivedrab" : "#6b8e23",
  9452. "orange" : "#ffa500",
  9453. "orangered" : "#ff4500",
  9454. "orchid" : "#da70d6",
  9455. "palegoldenrod" : "#eee8aa",
  9456. "palegreen" : "#98fb98",
  9457. "paleturquoise" : "#afeeee",
  9458. "palevioletred" : "#d87093",
  9459. "papayawhip" : "#ffefd5",
  9460. "peachpuff" : "#ffdab9",
  9461. "peru" : "#cd853f",
  9462. "pink" : "#ffc0cb",
  9463. "plum" : "#dda0dd",
  9464. "powderblue" : "#b0e0e6",
  9465. "purple" : "#800080",
  9466. "red" : "#ff0000",
  9467. "rosybrown" : "#bc8f8f",
  9468. "royalblue" : "#4169e1",
  9469. "saddlebrown" : "#8b4513",
  9470. "salmon" : "#fa8072",
  9471. "sandybrown" : "#f4a460",
  9472. "seagreen" : "#2e8b57",
  9473. "seashell" : "#fff5ee",
  9474. "sienna" : "#a0522d",
  9475. "silver" : "#c0c0c0",
  9476. "skyblue" : "#87ceeb",
  9477. "slateblue" : "#6a5acd",
  9478. "slategray" : "#708090",
  9479. "snow" : "#fffafa",
  9480. "springgreen" : "#00ff7f",
  9481. "steelblue" : "#4682b4",
  9482. "tan" : "#d2b48c",
  9483. "teal" : "#008080",
  9484. "thistle" : "#d8bfd8",
  9485. "tomato" : "#ff6347",
  9486. "turquoise" : "#40e0d0",
  9487. "violet" : "#ee82ee",
  9488. "wheat" : "#f5deb3",
  9489. "white" : "#ffffff",
  9490. "whitesmoke" : "#f5f5f5",
  9491. "yellow" : "#ffff00",
  9492. "yellowgreen" : "#9acd32"
  9493. };
  9494. CssColors.colorNameToHex = function(color) {
  9495. color = color.toLowerCase();
  9496. if (typeof this._colorsTable[color] != 'undefined')
  9497. return this._colorsTable[color];
  9498. return false;
  9499. };
  9500. /*
  9501. Deflate.js - https://github.com/gildas-lormeau/zip.js
  9502. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  9503. Redistribution and use in source and binary forms, with or without
  9504. modification, are permitted provided that the following conditions are met:
  9505. 1. Redistributions of source code must retain the above copyright notice,
  9506. this list of conditions and the following disclaimer.
  9507. 2. Redistributions in binary form must reproduce the above copyright
  9508. notice, this list of conditions and the following disclaimer in
  9509. the documentation and/or other materials provided with the distribution.
  9510. 3. The names of the authors may not be used to endorse or promote products
  9511. derived from this software without specific prior written permission.
  9512. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  9513. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9514. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  9515. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  9516. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9517. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  9518. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  9519. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  9520. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  9521. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9522. */
  9523. /*
  9524. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  9525. * JZlib is based on zlib-1.1.3, so all credit should go authors
  9526. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  9527. * and contributors of zlib.
  9528. */
  9529. var Deflater = (function(obj) {
  9530. // Global
  9531. var MAX_BITS = 15;
  9532. var D_CODES = 30;
  9533. var BL_CODES = 19;
  9534. var LENGTH_CODES = 29;
  9535. var LITERALS = 256;
  9536. var L_CODES = (LITERALS + 1 + LENGTH_CODES);
  9537. var HEAP_SIZE = (2 * L_CODES + 1);
  9538. var END_BLOCK = 256;
  9539. // Bit length codes must not exceed MAX_BL_BITS bits
  9540. var MAX_BL_BITS = 7;
  9541. // repeat previous bit length 3-6 times (2 bits of repeat count)
  9542. var REP_3_6 = 16;
  9543. // repeat a zero length 3-10 times (3 bits of repeat count)
  9544. var REPZ_3_10 = 17;
  9545. // repeat a zero length 11-138 times (7 bits of repeat count)
  9546. var REPZ_11_138 = 18;
  9547. // The lengths of the bit length codes are sent in order of decreasing
  9548. // probability, to avoid transmitting the lengths for unused bit
  9549. // length codes.
  9550. var Buf_size = 8 * 2;
  9551. // JZlib version : "1.0.2"
  9552. var Z_DEFAULT_COMPRESSION = -1;
  9553. // compression strategy
  9554. var Z_FILTERED = 1;
  9555. var Z_HUFFMAN_ONLY = 2;
  9556. var Z_DEFAULT_STRATEGY = 0;
  9557. var Z_NO_FLUSH = 0;
  9558. var Z_PARTIAL_FLUSH = 1;
  9559. var Z_FULL_FLUSH = 3;
  9560. var Z_FINISH = 4;
  9561. var Z_OK = 0;
  9562. var Z_STREAM_END = 1;
  9563. var Z_NEED_DICT = 2;
  9564. var Z_STREAM_ERROR = -2;
  9565. var Z_DATA_ERROR = -3;
  9566. var Z_BUF_ERROR = -5;
  9567. // Tree
  9568. // see definition of array dist_code below
  9569. var _dist_code = [ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  9570. 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  9571. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  9572. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  9573. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  9574. 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  9575. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19,
  9576. 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  9577. 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  9578. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  9579. 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  9580. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29,
  9581. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  9582. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 ];
  9583. function Tree() {
  9584. var that = this;
  9585. // dyn_tree; // the dynamic tree
  9586. // max_code; // largest code with non zero frequency
  9587. // stat_desc; // the corresponding static tree
  9588. // Compute the optimal bit lengths for a tree and update the total bit
  9589. // length
  9590. // for the current block.
  9591. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  9592. // above are the tree nodes sorted by increasing frequency.
  9593. // OUT assertions: the field len is set to the optimal bit length, the
  9594. // array bl_count contains the frequencies for each bit length.
  9595. // The length opt_len is updated; static_len is also updated if stree is
  9596. // not null.
  9597. function gen_bitlen(s) {
  9598. var tree = that.dyn_tree;
  9599. var stree = that.stat_desc.static_tree;
  9600. var extra = that.stat_desc.extra_bits;
  9601. var base = that.stat_desc.extra_base;
  9602. var max_length = that.stat_desc.max_length;
  9603. var h; // heap index
  9604. var n, m; // iterate over the tree elements
  9605. var bits; // bit length
  9606. var xbits; // extra bits
  9607. var f; // frequency
  9608. var overflow = 0; // number of elements with bit length too large
  9609. for (bits = 0; bits <= MAX_BITS; bits++)
  9610. s.bl_count[bits] = 0;
  9611. // In a first pass, compute the optimal bit lengths (which may
  9612. // overflow in the case of the bit length tree).
  9613. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  9614. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9615. n = s.heap[h];
  9616. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  9617. if (bits > max_length) {
  9618. bits = max_length;
  9619. overflow++;
  9620. }
  9621. tree[n * 2 + 1] = bits;
  9622. // We overwrite tree[n*2+1] which is no longer needed
  9623. if (n > that.max_code)
  9624. continue; // not a leaf node
  9625. s.bl_count[bits]++;
  9626. xbits = 0;
  9627. if (n >= base)
  9628. xbits = extra[n - base];
  9629. f = tree[n * 2];
  9630. s.opt_len += f * (bits + xbits);
  9631. if (stree)
  9632. s.static_len += f * (stree[n * 2 + 1] + xbits);
  9633. }
  9634. if (overflow === 0)
  9635. return;
  9636. // This happens for example on obj2 and pic of the Calgary corpus
  9637. // Find the first bit length which could increase:
  9638. do {
  9639. bits = max_length - 1;
  9640. while (s.bl_count[bits] === 0)
  9641. bits--;
  9642. s.bl_count[bits]--; // move one leaf down the tree
  9643. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  9644. s.bl_count[max_length]--;
  9645. // The brother of the overflow item also moves one step up,
  9646. // but this does not affect bl_count[max_length]
  9647. overflow -= 2;
  9648. } while (overflow > 0);
  9649. for (bits = max_length; bits !== 0; bits--) {
  9650. n = s.bl_count[bits];
  9651. while (n !== 0) {
  9652. m = s.heap[--h];
  9653. if (m > that.max_code)
  9654. continue;
  9655. if (tree[m * 2 + 1] != bits) {
  9656. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  9657. tree[m * 2 + 1] = bits;
  9658. }
  9659. n--;
  9660. }
  9661. }
  9662. }
  9663. // Reverse the first len bits of a code, using straightforward code (a
  9664. // faster
  9665. // method would use a table)
  9666. // IN assertion: 1 <= len <= 15
  9667. function bi_reverse(code, // the value to invert
  9668. len // its bit length
  9669. ) {
  9670. var res = 0;
  9671. do {
  9672. res |= code & 1;
  9673. code >>>= 1;
  9674. res <<= 1;
  9675. } while (--len > 0);
  9676. return res >>> 1;
  9677. }
  9678. // Generate the codes for a given tree and bit counts (which need not be
  9679. // optimal).
  9680. // IN assertion: the array bl_count contains the bit length statistics for
  9681. // the given tree and the field len is set for all tree elements.
  9682. // OUT assertion: the field code is set for all tree elements of non
  9683. // zero code length.
  9684. function gen_codes(tree, // the tree to decorate
  9685. max_code, // largest code with non zero frequency
  9686. bl_count // number of codes at each bit length
  9687. ) {
  9688. var next_code = []; // next code value for each
  9689. // bit length
  9690. var code = 0; // running code value
  9691. var bits; // bit index
  9692. var n; // code index
  9693. var len;
  9694. // The distribution counts are first used to generate the code values
  9695. // without bit reversal.
  9696. for (bits = 1; bits <= MAX_BITS; bits++) {
  9697. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  9698. }
  9699. // Check that the bit counts in bl_count are consistent. The last code
  9700. // must be all ones.
  9701. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9702. // "inconsistent bit counts");
  9703. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9704. for (n = 0; n <= max_code; n++) {
  9705. len = tree[n * 2 + 1];
  9706. if (len === 0)
  9707. continue;
  9708. // Now reverse the bits
  9709. tree[n * 2] = bi_reverse(next_code[len]++, len);
  9710. }
  9711. }
  9712. // Construct one Huffman tree and assigns the code bit strings and lengths.
  9713. // Update the total bit length for the current block.
  9714. // IN assertion: the field freq is set for all tree elements.
  9715. // OUT assertions: the fields len and code are set to the optimal bit length
  9716. // and corresponding code. The length opt_len is updated; static_len is
  9717. // also updated if stree is not null. The field max_code is set.
  9718. that.build_tree = function(s) {
  9719. var tree = that.dyn_tree;
  9720. var stree = that.stat_desc.static_tree;
  9721. var elems = that.stat_desc.elems;
  9722. var n, m; // iterate over heap elements
  9723. var max_code = -1; // largest code with non zero frequency
  9724. var node; // new node being created
  9725. // Construct the initial heap, with least frequent element in
  9726. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9727. // heap[0] is not used.
  9728. s.heap_len = 0;
  9729. s.heap_max = HEAP_SIZE;
  9730. for (n = 0; n < elems; n++) {
  9731. if (tree[n * 2] !== 0) {
  9732. s.heap[++s.heap_len] = max_code = n;
  9733. s.depth[n] = 0;
  9734. } else {
  9735. tree[n * 2 + 1] = 0;
  9736. }
  9737. }
  9738. // The pkzip format requires that at least one distance code exists,
  9739. // and that at least one bit should be sent even if there is only one
  9740. // possible code. So to avoid special checks later on we force at least
  9741. // two codes of non zero frequency.
  9742. while (s.heap_len < 2) {
  9743. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  9744. tree[node * 2] = 1;
  9745. s.depth[node] = 0;
  9746. s.opt_len--;
  9747. if (stree)
  9748. s.static_len -= stree[node * 2 + 1];
  9749. // node is 0 or 1 so it does not have extra bits
  9750. }
  9751. that.max_code = max_code;
  9752. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9753. // establish sub-heaps of increasing lengths:
  9754. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  9755. s.pqdownheap(tree, n);
  9756. // Construct the Huffman tree by repeatedly combining the least two
  9757. // frequent nodes.
  9758. node = elems; // next internal node of the tree
  9759. do {
  9760. // n = node of least frequency
  9761. n = s.heap[1];
  9762. s.heap[1] = s.heap[s.heap_len--];
  9763. s.pqdownheap(tree, 1);
  9764. m = s.heap[1]; // m = node of next least frequency
  9765. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  9766. s.heap[--s.heap_max] = m;
  9767. // Create a new node father of n and m
  9768. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  9769. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  9770. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  9771. // and insert the new node in the heap
  9772. s.heap[1] = node++;
  9773. s.pqdownheap(tree, 1);
  9774. } while (s.heap_len >= 2);
  9775. s.heap[--s.heap_max] = s.heap[1];
  9776. // At this point, the fields freq and dad are set. We can now
  9777. // generate the bit lengths.
  9778. gen_bitlen(s);
  9779. // The field len is now set, we can generate the bit codes
  9780. gen_codes(tree, that.max_code, s.bl_count);
  9781. };
  9782. }
  9783. Tree._length_code = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
  9784. 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  9785. 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
  9786. 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  9787. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  9788. 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  9789. 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 ];
  9790. Tree.base_length = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 ];
  9791. Tree.base_dist = [ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
  9792. 24576 ];
  9793. // Mapping from a distance to a distance code. dist is the distance - 1 and
  9794. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  9795. // used.
  9796. Tree.d_code = function(dist) {
  9797. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  9798. };
  9799. // extra bits for each length code
  9800. Tree.extra_lbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ];
  9801. // extra bits for each distance code
  9802. Tree.extra_dbits = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ];
  9803. // extra bits for each bit length code
  9804. Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
  9805. Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9806. // StaticTree
  9807. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  9808. var that = this;
  9809. that.static_tree = static_tree;
  9810. that.extra_bits = extra_bits;
  9811. that.extra_base = extra_base;
  9812. that.elems = elems;
  9813. that.max_length = max_length;
  9814. }
  9815. StaticTree.static_ltree = [ 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8,
  9816. 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42,
  9817. 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
  9818. 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
  9819. 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113,
  9820. 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8,
  9821. 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8,
  9822. 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
  9823. 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9,
  9824. 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379,
  9825. 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23,
  9826. 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9,
  9827. 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9,
  9828. 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7,
  9829. 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8,
  9830. 99, 8, 227, 8 ];
  9831. StaticTree.static_dtree = [ 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5,
  9832. 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
  9833. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9834. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  9835. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9836. // Deflate
  9837. var MAX_MEM_LEVEL = 9;
  9838. var DEF_MEM_LEVEL = 8;
  9839. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  9840. var that = this;
  9841. that.good_length = good_length;
  9842. that.max_lazy = max_lazy;
  9843. that.nice_length = nice_length;
  9844. that.max_chain = max_chain;
  9845. that.func = func;
  9846. }
  9847. var STORED = 0;
  9848. var FAST = 1;
  9849. var SLOW = 2;
  9850. var config_table = [ new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST),
  9851. new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW),
  9852. new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
  9853. var z_errmsg = [ "need dictionary", // Z_NEED_DICT
  9854. // 2
  9855. "stream end", // Z_STREAM_END 1
  9856. "", // Z_OK 0
  9857. "", // Z_ERRNO (-1)
  9858. "stream error", // Z_STREAM_ERROR (-2)
  9859. "data error", // Z_DATA_ERROR (-3)
  9860. "", // Z_MEM_ERROR (-4)
  9861. "buffer error", // Z_BUF_ERROR (-5)
  9862. "",// Z_VERSION_ERROR (-6)
  9863. "" ];
  9864. // block not completed, need more input or more output
  9865. var NeedMore = 0;
  9866. // block flush performed
  9867. var BlockDone = 1;
  9868. // finish started, need only more output at next deflate
  9869. var FinishStarted = 2;
  9870. // finish done, accept no more input or output
  9871. var FinishDone = 3;
  9872. // preset dictionary flag in zlib header
  9873. var PRESET_DICT = 0x20;
  9874. var INIT_STATE = 42;
  9875. var BUSY_STATE = 113;
  9876. var FINISH_STATE = 666;
  9877. // The deflate compression method
  9878. var Z_DEFLATED = 8;
  9879. var STORED_BLOCK = 0;
  9880. var STATIC_TREES = 1;
  9881. var DYN_TREES = 2;
  9882. var MIN_MATCH = 3;
  9883. var MAX_MATCH = 258;
  9884. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  9885. function smaller(tree, n, m, depth) {
  9886. var tn2 = tree[n * 2];
  9887. var tm2 = tree[m * 2];
  9888. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  9889. }
  9890. function Deflate() {
  9891. var that = this;
  9892. var strm; // pointer back to this zlib stream
  9893. var status; // as the name implies
  9894. // pending_buf; // output still pending
  9895. var pending_buf_size; // size of pending_buf
  9896. // pending_out; // next pending byte to output to the stream
  9897. // pending; // nb of bytes in the pending buffer
  9898. var method; // STORED (for zip only) or DEFLATED
  9899. var last_flush; // value of flush param for previous deflate call
  9900. var w_size; // LZ77 window size (32K by default)
  9901. var w_bits; // log2(w_size) (8..16)
  9902. var w_mask; // w_size - 1
  9903. var window;
  9904. // Sliding window. Input bytes are read into the second half of the window,
  9905. // and move to the first half later to keep a dictionary of at least wSize
  9906. // bytes. With this organization, matches are limited to a distance of
  9907. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  9908. // performed with a length multiple of the block size. Also, it limits
  9909. // the window size to 64K, which is quite useful on MSDOS.
  9910. // To do: use the user input buffer as sliding window.
  9911. var window_size;
  9912. // Actual size of window: 2*wSize, except when the user input buffer
  9913. // is directly used as sliding window.
  9914. var prev;
  9915. // Link to older string with same hash index. To limit the size of this
  9916. // array to 64K, this link is maintained only for the last 32K strings.
  9917. // An index in this array is thus a window index modulo 32K.
  9918. var head; // Heads of the hash chains or NIL.
  9919. var ins_h; // hash index of string to be inserted
  9920. var hash_size; // number of elements in hash table
  9921. var hash_bits; // log2(hash_size)
  9922. var hash_mask; // hash_size-1
  9923. // Number of bits by which ins_h must be shifted at each input
  9924. // step. It must be such that after MIN_MATCH steps, the oldest
  9925. // byte no longer takes part in the hash key, that is:
  9926. // hash_shift * MIN_MATCH >= hash_bits
  9927. var hash_shift;
  9928. // Window position at the beginning of the current output block. Gets
  9929. // negative when the window is moved backwards.
  9930. var block_start;
  9931. var match_length; // length of best match
  9932. var prev_match; // previous match
  9933. var match_available; // set if previous match exists
  9934. var strstart; // start of string to insert
  9935. var match_start; // start of matching string
  9936. var lookahead; // number of valid bytes ahead in window
  9937. // Length of the best match at previous step. Matches not greater than this
  9938. // are discarded. This is used in the lazy match evaluation.
  9939. var prev_length;
  9940. // To speed up deflation, hash chains are never searched beyond this
  9941. // length. A higher limit improves compression ratio but degrades the speed.
  9942. var max_chain_length;
  9943. // Attempt to find a better match only when the current match is strictly
  9944. // smaller than this value. This mechanism is used only for compression
  9945. // levels >= 4.
  9946. var max_lazy_match;
  9947. // Insert new strings in the hash table only if the match length is not
  9948. // greater than this length. This saves time but degrades compression.
  9949. // max_insert_length is used only for compression levels <= 3.
  9950. var level; // compression level (1..9)
  9951. var strategy; // favor or force Huffman coding
  9952. // Use a faster search when the previous match is longer than this
  9953. var good_match;
  9954. // Stop searching when current match exceeds this
  9955. var nice_match;
  9956. var dyn_ltree; // literal and length tree
  9957. var dyn_dtree; // distance tree
  9958. var bl_tree; // Huffman tree for bit lengths
  9959. var l_desc = new Tree(); // desc for literal tree
  9960. var d_desc = new Tree(); // desc for distance tree
  9961. var bl_desc = new Tree(); // desc for bit length tree
  9962. // that.heap_len; // number of elements in the heap
  9963. // that.heap_max; // element of largest frequency
  9964. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  9965. // The same heap array is used to build all trees.
  9966. // Depth of each subtree used as tie breaker for trees of equal frequency
  9967. that.depth = [];
  9968. var l_buf; // index for literals or lengths */
  9969. // Size of match buffer for literals/lengths. There are 4 reasons for
  9970. // limiting lit_bufsize to 64K:
  9971. // - frequencies can be kept in 16 bit counters
  9972. // - if compression is not successful for the first block, all input
  9973. // data is still in the window so we can still emit a stored block even
  9974. // when input comes from standard input. (This can also be done for
  9975. // all blocks if lit_bufsize is not greater than 32K.)
  9976. // - if compression is not successful for a file smaller than 64K, we can
  9977. // even emit a stored file instead of a stored block (saving 5 bytes).
  9978. // This is applicable only for zip (not gzip or zlib).
  9979. // - creating new Huffman trees less frequently may not provide fast
  9980. // adaptation to changes in the input data statistics. (Take for
  9981. // example a binary file with poorly compressible code followed by
  9982. // a highly compressible string table.) Smaller buffer sizes give
  9983. // fast adaptation but have of course the overhead of transmitting
  9984. // trees more frequently.
  9985. // - I can't count above 4
  9986. var lit_bufsize;
  9987. var last_lit; // running index in l_buf
  9988. // Buffer for distances. To simplify the code, d_buf and l_buf have
  9989. // the same number of elements. To use different lengths, an extra flag
  9990. // array would be necessary.
  9991. var d_buf; // index of pendig_buf
  9992. // that.opt_len; // bit length of current block with optimal trees
  9993. // that.static_len; // bit length of current block with static trees
  9994. var matches; // number of string matches in current block
  9995. var last_eob_len; // bit length of EOB code for last block
  9996. // Output buffer. bits are inserted starting at the bottom (least
  9997. // significant bits).
  9998. var bi_buf;
  9999. // Number of valid bits in bi_buf. All bits above the last valid bit
  10000. // are always zero.
  10001. var bi_valid;
  10002. // number of codes at each bit length for an optimal tree
  10003. that.bl_count = [];
  10004. // heap used to build the Huffman trees
  10005. that.heap = [];
  10006. dyn_ltree = [];
  10007. dyn_dtree = [];
  10008. bl_tree = [];
  10009. function lm_init() {
  10010. var i;
  10011. window_size = 2 * w_size;
  10012. head[hash_size - 1] = 0;
  10013. for (i = 0; i < hash_size - 1; i++) {
  10014. head[i] = 0;
  10015. }
  10016. // Set the default configuration parameters:
  10017. max_lazy_match = config_table[level].max_lazy;
  10018. good_match = config_table[level].good_length;
  10019. nice_match = config_table[level].nice_length;
  10020. max_chain_length = config_table[level].max_chain;
  10021. strstart = 0;
  10022. block_start = 0;
  10023. lookahead = 0;
  10024. match_length = prev_length = MIN_MATCH - 1;
  10025. match_available = 0;
  10026. ins_h = 0;
  10027. }
  10028. function init_block() {
  10029. var i;
  10030. // Initialize the trees.
  10031. for (i = 0; i < L_CODES; i++)
  10032. dyn_ltree[i * 2] = 0;
  10033. for (i = 0; i < D_CODES; i++)
  10034. dyn_dtree[i * 2] = 0;
  10035. for (i = 0; i < BL_CODES; i++)
  10036. bl_tree[i * 2] = 0;
  10037. dyn_ltree[END_BLOCK * 2] = 1;
  10038. that.opt_len = that.static_len = 0;
  10039. last_lit = matches = 0;
  10040. }
  10041. // Initialize the tree data structures for a new zlib stream.
  10042. function tr_init() {
  10043. l_desc.dyn_tree = dyn_ltree;
  10044. l_desc.stat_desc = StaticTree.static_l_desc;
  10045. d_desc.dyn_tree = dyn_dtree;
  10046. d_desc.stat_desc = StaticTree.static_d_desc;
  10047. bl_desc.dyn_tree = bl_tree;
  10048. bl_desc.stat_desc = StaticTree.static_bl_desc;
  10049. bi_buf = 0;
  10050. bi_valid = 0;
  10051. last_eob_len = 8; // enough lookahead for inflate
  10052. // Initialize the first block of the first file:
  10053. init_block();
  10054. }
  10055. // Restore the heap property by moving down the tree starting at node k,
  10056. // exchanging a node with the smallest of its two sons if necessary,
  10057. // stopping
  10058. // when the heap property is re-established (each father smaller than its
  10059. // two sons).
  10060. that.pqdownheap = function(tree, // the tree to restore
  10061. k // node to move down
  10062. ) {
  10063. var heap = that.heap;
  10064. var v = heap[k];
  10065. var j = k << 1; // left son of k
  10066. while (j <= that.heap_len) {
  10067. // Set j to the smallest of the two sons:
  10068. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  10069. j++;
  10070. }
  10071. // Exit if v is smaller than both sons
  10072. if (smaller(tree, v, heap[j], that.depth))
  10073. break;
  10074. // Exchange v with the smallest son
  10075. heap[k] = heap[j];
  10076. k = j;
  10077. // And continue down the tree, setting j to the left son of k
  10078. j <<= 1;
  10079. }
  10080. heap[k] = v;
  10081. };
  10082. // Scan a literal or distance tree to determine the frequencies of the codes
  10083. // in the bit length tree.
  10084. function scan_tree(tree,// the tree to be scanned
  10085. max_code // and its largest code of non zero frequency
  10086. ) {
  10087. var n; // iterates over all tree elements
  10088. var prevlen = -1; // last emitted length
  10089. var curlen; // length of current code
  10090. var nextlen = tree[0 * 2 + 1]; // length of next code
  10091. var count = 0; // repeat count of the current code
  10092. var max_count = 7; // max repeat count
  10093. var min_count = 4; // min repeat count
  10094. if (nextlen === 0) {
  10095. max_count = 138;
  10096. min_count = 3;
  10097. }
  10098. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  10099. for (n = 0; n <= max_code; n++) {
  10100. curlen = nextlen;
  10101. nextlen = tree[(n + 1) * 2 + 1];
  10102. if (++count < max_count && curlen == nextlen) {
  10103. continue;
  10104. } else if (count < min_count) {
  10105. bl_tree[curlen * 2] += count;
  10106. } else if (curlen !== 0) {
  10107. if (curlen != prevlen)
  10108. bl_tree[curlen * 2]++;
  10109. bl_tree[REP_3_6 * 2]++;
  10110. } else if (count <= 10) {
  10111. bl_tree[REPZ_3_10 * 2]++;
  10112. } else {
  10113. bl_tree[REPZ_11_138 * 2]++;
  10114. }
  10115. count = 0;
  10116. prevlen = curlen;
  10117. if (nextlen === 0) {
  10118. max_count = 138;
  10119. min_count = 3;
  10120. } else if (curlen == nextlen) {
  10121. max_count = 6;
  10122. min_count = 3;
  10123. } else {
  10124. max_count = 7;
  10125. min_count = 4;
  10126. }
  10127. }
  10128. }
  10129. // Construct the Huffman tree for the bit lengths and return the index in
  10130. // bl_order of the last bit length code to send.
  10131. function build_bl_tree() {
  10132. var max_blindex; // index of last bit length code of non zero freq
  10133. // Determine the bit length frequencies for literal and distance trees
  10134. scan_tree(dyn_ltree, l_desc.max_code);
  10135. scan_tree(dyn_dtree, d_desc.max_code);
  10136. // Build the bit length tree:
  10137. bl_desc.build_tree(that);
  10138. // opt_len now includes the length of the tree representations, except
  10139. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  10140. // counts.
  10141. // Determine the number of bit length codes to send. The pkzip format
  10142. // requires that at least 4 bit length codes be sent. (appnote.txt says
  10143. // 3 but the actual value used is 4.)
  10144. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  10145. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  10146. break;
  10147. }
  10148. // Update opt_len to include the bit length tree and counts
  10149. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  10150. return max_blindex;
  10151. }
  10152. // Output a byte on the stream.
  10153. // IN assertion: there is enough room in pending_buf.
  10154. function put_byte(p) {
  10155. that.pending_buf[that.pending++] = p;
  10156. }
  10157. function put_short(w) {
  10158. put_byte(w & 0xff);
  10159. put_byte((w >>> 8) & 0xff);
  10160. }
  10161. function putShortMSB(b) {
  10162. put_byte((b >> 8) & 0xff);
  10163. put_byte((b & 0xff) & 0xff);
  10164. }
  10165. function send_bits(value, length) {
  10166. var val, len = length;
  10167. if (bi_valid > Buf_size - len) {
  10168. val = value;
  10169. // bi_buf |= (val << bi_valid);
  10170. bi_buf |= ((val << bi_valid) & 0xffff);
  10171. put_short(bi_buf);
  10172. bi_buf = val >>> (Buf_size - bi_valid);
  10173. bi_valid += len - Buf_size;
  10174. } else {
  10175. // bi_buf |= (value) << bi_valid;
  10176. bi_buf |= (((value) << bi_valid) & 0xffff);
  10177. bi_valid += len;
  10178. }
  10179. }
  10180. function send_code(c, tree) {
  10181. var c2 = c * 2;
  10182. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  10183. }
  10184. // Send a literal or distance tree in compressed form, using the codes in
  10185. // bl_tree.
  10186. function send_tree(tree,// the tree to be sent
  10187. max_code // and its largest code of non zero frequency
  10188. ) {
  10189. var n; // iterates over all tree elements
  10190. var prevlen = -1; // last emitted length
  10191. var curlen; // length of current code
  10192. var nextlen = tree[0 * 2 + 1]; // length of next code
  10193. var count = 0; // repeat count of the current code
  10194. var max_count = 7; // max repeat count
  10195. var min_count = 4; // min repeat count
  10196. if (nextlen === 0) {
  10197. max_count = 138;
  10198. min_count = 3;
  10199. }
  10200. for (n = 0; n <= max_code; n++) {
  10201. curlen = nextlen;
  10202. nextlen = tree[(n + 1) * 2 + 1];
  10203. if (++count < max_count && curlen == nextlen) {
  10204. continue;
  10205. } else if (count < min_count) {
  10206. do {
  10207. send_code(curlen, bl_tree);
  10208. } while (--count !== 0);
  10209. } else if (curlen !== 0) {
  10210. if (curlen != prevlen) {
  10211. send_code(curlen, bl_tree);
  10212. count--;
  10213. }
  10214. send_code(REP_3_6, bl_tree);
  10215. send_bits(count - 3, 2);
  10216. } else if (count <= 10) {
  10217. send_code(REPZ_3_10, bl_tree);
  10218. send_bits(count - 3, 3);
  10219. } else {
  10220. send_code(REPZ_11_138, bl_tree);
  10221. send_bits(count - 11, 7);
  10222. }
  10223. count = 0;
  10224. prevlen = curlen;
  10225. if (nextlen === 0) {
  10226. max_count = 138;
  10227. min_count = 3;
  10228. } else if (curlen == nextlen) {
  10229. max_count = 6;
  10230. min_count = 3;
  10231. } else {
  10232. max_count = 7;
  10233. min_count = 4;
  10234. }
  10235. }
  10236. }
  10237. // Send the header for a block using dynamic Huffman trees: the counts, the
  10238. // lengths of the bit length codes, the literal tree and the distance tree.
  10239. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10240. function send_all_trees(lcodes, dcodes, blcodes) {
  10241. var rank; // index in bl_order
  10242. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  10243. send_bits(dcodes - 1, 5);
  10244. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  10245. for (rank = 0; rank < blcodes; rank++) {
  10246. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  10247. }
  10248. send_tree(dyn_ltree, lcodes - 1); // literal tree
  10249. send_tree(dyn_dtree, dcodes - 1); // distance tree
  10250. }
  10251. // Flush the bit buffer, keeping at most 7 bits in it.
  10252. function bi_flush() {
  10253. if (bi_valid == 16) {
  10254. put_short(bi_buf);
  10255. bi_buf = 0;
  10256. bi_valid = 0;
  10257. } else if (bi_valid >= 8) {
  10258. put_byte(bi_buf & 0xff);
  10259. bi_buf >>>= 8;
  10260. bi_valid -= 8;
  10261. }
  10262. }
  10263. // Send one empty static block to give enough lookahead for inflate.
  10264. // This takes 10 bits, of which 7 may remain in the bit buffer.
  10265. // The current inflate code requires 9 bits of lookahead. If the
  10266. // last two codes for the previous block (real code plus EOB) were coded
  10267. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  10268. // the last real code. In this case we send two empty static blocks instead
  10269. // of one. (There are no problems if the previous block is stored or fixed.)
  10270. // To simplify the code, we assume the worst case of last real code encoded
  10271. // on one bit only.
  10272. function _tr_align() {
  10273. send_bits(STATIC_TREES << 1, 3);
  10274. send_code(END_BLOCK, StaticTree.static_ltree);
  10275. bi_flush();
  10276. // Of the 10 bits for the empty block, we have already sent
  10277. // (10 - bi_valid) bits. The lookahead for the last real code (before
  10278. // the EOB of the previous block) was thus at least one plus the length
  10279. // of the EOB plus what we have just sent of the empty static block.
  10280. if (1 + last_eob_len + 10 - bi_valid < 9) {
  10281. send_bits(STATIC_TREES << 1, 3);
  10282. send_code(END_BLOCK, StaticTree.static_ltree);
  10283. bi_flush();
  10284. }
  10285. last_eob_len = 7;
  10286. }
  10287. // Save the match info and tally the frequency counts. Return true if
  10288. // the current block must be flushed.
  10289. function _tr_tally(dist, // distance of matched string
  10290. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  10291. ) {
  10292. var out_length, in_length, dcode;
  10293. that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
  10294. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  10295. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  10296. last_lit++;
  10297. if (dist === 0) {
  10298. // lc is the unmatched char
  10299. dyn_ltree[lc * 2]++;
  10300. } else {
  10301. matches++;
  10302. // Here, lc is the match length - MIN_MATCH
  10303. dist--; // dist = match distance - 1
  10304. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  10305. dyn_dtree[Tree.d_code(dist) * 2]++;
  10306. }
  10307. if ((last_lit & 0x1fff) === 0 && level > 2) {
  10308. // Compute an upper bound for the compressed length
  10309. out_length = last_lit * 8;
  10310. in_length = strstart - block_start;
  10311. for (dcode = 0; dcode < D_CODES; dcode++) {
  10312. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  10313. }
  10314. out_length >>>= 3;
  10315. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  10316. return true;
  10317. }
  10318. return (last_lit == lit_bufsize - 1);
  10319. // We avoid equality with lit_bufsize because of wraparound at 64K
  10320. // on 16 bit machines and because stored blocks are restricted to
  10321. // 64K-1 bytes.
  10322. }
  10323. // Send the block data compressed using the given Huffman trees
  10324. function compress_block(ltree, dtree) {
  10325. var dist; // distance of matched string
  10326. var lc; // match length or unmatched char (if dist === 0)
  10327. var lx = 0; // running index in l_buf
  10328. var code; // the code to send
  10329. var extra; // number of extra bits to send
  10330. if (last_lit !== 0) {
  10331. do {
  10332. dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
  10333. lc = (that.pending_buf[l_buf + lx]) & 0xff;
  10334. lx++;
  10335. if (dist === 0) {
  10336. send_code(lc, ltree); // send a literal byte
  10337. } else {
  10338. // Here, lc is the match length - MIN_MATCH
  10339. code = Tree._length_code[lc];
  10340. send_code(code + LITERALS + 1, ltree); // send the length
  10341. // code
  10342. extra = Tree.extra_lbits[code];
  10343. if (extra !== 0) {
  10344. lc -= Tree.base_length[code];
  10345. send_bits(lc, extra); // send the extra length bits
  10346. }
  10347. dist--; // dist is now the match distance - 1
  10348. code = Tree.d_code(dist);
  10349. send_code(code, dtree); // send the distance code
  10350. extra = Tree.extra_dbits[code];
  10351. if (extra !== 0) {
  10352. dist -= Tree.base_dist[code];
  10353. send_bits(dist, extra); // send the extra distance bits
  10354. }
  10355. } // literal or match pair ?
  10356. // Check that the overlay between pending_buf and d_buf+l_buf is
  10357. // ok:
  10358. } while (lx < last_lit);
  10359. }
  10360. send_code(END_BLOCK, ltree);
  10361. last_eob_len = ltree[END_BLOCK * 2 + 1];
  10362. }
  10363. // Flush the bit buffer and align the output on a byte boundary
  10364. function bi_windup() {
  10365. if (bi_valid > 8) {
  10366. put_short(bi_buf);
  10367. } else if (bi_valid > 0) {
  10368. put_byte(bi_buf & 0xff);
  10369. }
  10370. bi_buf = 0;
  10371. bi_valid = 0;
  10372. }
  10373. // Copy a stored block, storing first the length and its
  10374. // one's complement if requested.
  10375. function copy_block(buf, // the input data
  10376. len, // its length
  10377. header // true if block header must be written
  10378. ) {
  10379. bi_windup(); // align on byte boundary
  10380. last_eob_len = 8; // enough lookahead for inflate
  10381. if (header) {
  10382. put_short(len);
  10383. put_short(~len);
  10384. }
  10385. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  10386. that.pending += len;
  10387. }
  10388. // Send a stored block
  10389. function _tr_stored_block(buf, // input block
  10390. stored_len, // length of input block
  10391. eof // true if this is the last block for a file
  10392. ) {
  10393. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  10394. copy_block(buf, stored_len, true); // with header
  10395. }
  10396. // Determine the best encoding for the current block: dynamic trees, static
  10397. // trees or store, and output the encoded block to the zip file.
  10398. function _tr_flush_block(buf, // input block, or NULL if too old
  10399. stored_len, // length of input block
  10400. eof // true if this is the last block for a file
  10401. ) {
  10402. var opt_lenb, static_lenb;// opt_len and static_len in bytes
  10403. var max_blindex = 0; // index of last bit length code of non zero freq
  10404. // Build the Huffman trees unless a stored block is forced
  10405. if (level > 0) {
  10406. // Construct the literal and distance trees
  10407. l_desc.build_tree(that);
  10408. d_desc.build_tree(that);
  10409. // At this point, opt_len and static_len are the total bit lengths
  10410. // of
  10411. // the compressed block data, excluding the tree representations.
  10412. // Build the bit length tree for the above two trees, and get the
  10413. // index
  10414. // in bl_order of the last bit length code to send.
  10415. max_blindex = build_bl_tree();
  10416. // Determine the best encoding. Compute first the block length in
  10417. // bytes
  10418. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  10419. static_lenb = (that.static_len + 3 + 7) >>> 3;
  10420. if (static_lenb <= opt_lenb)
  10421. opt_lenb = static_lenb;
  10422. } else {
  10423. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  10424. }
  10425. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  10426. // 4: two words for the lengths
  10427. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10428. // Otherwise we can't have processed more than WSIZE input bytes
  10429. // since
  10430. // the last block flush, because compression would have been
  10431. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10432. // transform a block into a stored block.
  10433. _tr_stored_block(buf, stored_len, eof);
  10434. } else if (static_lenb == opt_lenb) {
  10435. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  10436. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  10437. } else {
  10438. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  10439. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  10440. compress_block(dyn_ltree, dyn_dtree);
  10441. }
  10442. // The above check is made mod 2^32, for files larger than 512 MB
  10443. // and uLong implemented on 32 bits.
  10444. init_block();
  10445. if (eof) {
  10446. bi_windup();
  10447. }
  10448. }
  10449. function flush_block_only(eof) {
  10450. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  10451. block_start = strstart;
  10452. strm.flush_pending();
  10453. }
  10454. // Fill the window when the lookahead becomes insufficient.
  10455. // Updates strstart and lookahead.
  10456. //
  10457. // IN assertion: lookahead < MIN_LOOKAHEAD
  10458. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  10459. // At least one byte has been read, or avail_in === 0; reads are
  10460. // performed for at least two bytes (required for the zip translate_eol
  10461. // option -- not supported here).
  10462. function fill_window() {
  10463. var n, m;
  10464. var p;
  10465. var more; // Amount of free space at the end of the window.
  10466. do {
  10467. more = (window_size - lookahead - strstart);
  10468. // Deal with !@#$% 64K limit:
  10469. if (more === 0 && strstart === 0 && lookahead === 0) {
  10470. more = w_size;
  10471. } else if (more == -1) {
  10472. // Very unlikely, but possible on 16 bit machine if strstart ==
  10473. // 0
  10474. // and lookahead == 1 (input done one byte at time)
  10475. more--;
  10476. // If the window is almost full and there is insufficient
  10477. // lookahead,
  10478. // move the upper half to the lower one to make room in the
  10479. // upper half.
  10480. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  10481. window.set(window.subarray(w_size, w_size + w_size), 0);
  10482. match_start -= w_size;
  10483. strstart -= w_size; // we now have strstart >= MAX_DIST
  10484. block_start -= w_size;
  10485. // Slide the hash table (could be avoided with 32 bit values
  10486. // at the expense of memory usage). We slide even when level ==
  10487. // 0
  10488. // to keep the hash table consistent if we switch back to level
  10489. // > 0
  10490. // later. (Using level 0 permanently is not an optimal usage of
  10491. // zlib, so we don't care about this pathological case.)
  10492. n = hash_size;
  10493. p = n;
  10494. do {
  10495. m = (head[--p] & 0xffff);
  10496. head[p] = (m >= w_size ? m - w_size : 0);
  10497. } while (--n !== 0);
  10498. n = w_size;
  10499. p = n;
  10500. do {
  10501. m = (prev[--p] & 0xffff);
  10502. prev[p] = (m >= w_size ? m - w_size : 0);
  10503. // If n is not on any hash chain, prev[n] is garbage but
  10504. // its value will never be used.
  10505. } while (--n !== 0);
  10506. more += w_size;
  10507. }
  10508. if (strm.avail_in === 0)
  10509. return;
  10510. // If there was no sliding:
  10511. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  10512. // more == window_size - lookahead - strstart
  10513. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  10514. // => more >= window_size - 2*WSIZE + 2
  10515. // In the BIG_MEM or MMAP case (not yet supported),
  10516. // window_size == input_size + MIN_LOOKAHEAD &&
  10517. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  10518. // Otherwise, window_size == 2*WSIZE so more >= 2.
  10519. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  10520. n = strm.read_buf(window, strstart + lookahead, more);
  10521. lookahead += n;
  10522. // Initialize the hash value now that we have some input:
  10523. if (lookahead >= MIN_MATCH) {
  10524. ins_h = window[strstart] & 0xff;
  10525. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10526. }
  10527. // If the whole input has less than MIN_MATCH bytes, ins_h is
  10528. // garbage,
  10529. // but this is not important since only literal bytes will be
  10530. // emitted.
  10531. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  10532. }
  10533. // Copy without compression as much as possible from the input stream,
  10534. // return
  10535. // the current block state.
  10536. // This function does not insert new strings in the dictionary since
  10537. // uncompressible data is probably not useful. This function is used
  10538. // only for the level=0 compression option.
  10539. // NOTE: this function should be optimized to avoid extra copying from
  10540. // window to pending_buf.
  10541. function deflate_stored(flush) {
  10542. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  10543. // to pending_buf_size, and each stored block has a 5 byte header:
  10544. var max_block_size = 0xffff;
  10545. var max_start;
  10546. if (max_block_size > pending_buf_size - 5) {
  10547. max_block_size = pending_buf_size - 5;
  10548. }
  10549. // Copy as much as possible from input to output:
  10550. while (true) {
  10551. // Fill the window as much as possible:
  10552. if (lookahead <= 1) {
  10553. fill_window();
  10554. if (lookahead === 0 && flush == Z_NO_FLUSH)
  10555. return NeedMore;
  10556. if (lookahead === 0)
  10557. break; // flush the current block
  10558. }
  10559. strstart += lookahead;
  10560. lookahead = 0;
  10561. // Emit a stored block if pending_buf will be full:
  10562. max_start = block_start + max_block_size;
  10563. if (strstart === 0 || strstart >= max_start) {
  10564. // strstart === 0 is possible when wraparound on 16-bit machine
  10565. lookahead = (strstart - max_start);
  10566. strstart = max_start;
  10567. flush_block_only(false);
  10568. if (strm.avail_out === 0)
  10569. return NeedMore;
  10570. }
  10571. // Flush if we may have to slide, otherwise block_start may become
  10572. // negative and the data will be gone:
  10573. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  10574. flush_block_only(false);
  10575. if (strm.avail_out === 0)
  10576. return NeedMore;
  10577. }
  10578. }
  10579. flush_block_only(flush == Z_FINISH);
  10580. if (strm.avail_out === 0)
  10581. return (flush == Z_FINISH) ? FinishStarted : NeedMore;
  10582. return flush == Z_FINISH ? FinishDone : BlockDone;
  10583. }
  10584. function longest_match(cur_match) {
  10585. var chain_length = max_chain_length; // max hash chain length
  10586. var scan = strstart; // current string
  10587. var match; // matched string
  10588. var len; // length of current match
  10589. var best_len = prev_length; // best match length so far
  10590. var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  10591. var _nice_match = nice_match;
  10592. // Stop when cur_match becomes <= limit. To simplify the code,
  10593. // we prevent matches with the string of window index 0.
  10594. var wmask = w_mask;
  10595. var strend = strstart + MAX_MATCH;
  10596. var scan_end1 = window[scan + best_len - 1];
  10597. var scan_end = window[scan + best_len];
  10598. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  10599. // 16.
  10600. // It is easy to get rid of this optimization if necessary.
  10601. // Do not waste too much time if we already have a good match:
  10602. if (prev_length >= good_match) {
  10603. chain_length >>= 2;
  10604. }
  10605. // Do not look for matches beyond the end of the input. This is
  10606. // necessary
  10607. // to make deflate deterministic.
  10608. if (_nice_match > lookahead)
  10609. _nice_match = lookahead;
  10610. do {
  10611. match = cur_match;
  10612. // Skip to next match if the match length cannot increase
  10613. // or if the match length is less than 2:
  10614. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
  10615. || window[++match] != window[scan + 1])
  10616. continue;
  10617. // The check at best_len-1 can be removed because it will be made
  10618. // again later. (This heuristic is not always a win.)
  10619. // It is not necessary to compare scan[2] and match[2] since they
  10620. // are always equal when the other bytes match, given that
  10621. // the hash keys are equal and that HASH_BITS >= 8.
  10622. scan += 2;
  10623. match++;
  10624. // We check for insufficient lookahead only every 8th comparison;
  10625. // the 256th check will be made at strstart+258.
  10626. do {
  10627. } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10628. && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10629. && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  10630. len = MAX_MATCH - (strend - scan);
  10631. scan = strend - MAX_MATCH;
  10632. if (len > best_len) {
  10633. match_start = cur_match;
  10634. best_len = len;
  10635. if (len >= _nice_match)
  10636. break;
  10637. scan_end1 = window[scan + best_len - 1];
  10638. scan_end = window[scan + best_len];
  10639. }
  10640. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  10641. if (best_len <= lookahead)
  10642. return best_len;
  10643. return lookahead;
  10644. }
  10645. // Compress as much as possible from the input stream, return the current
  10646. // block state.
  10647. // This function does not perform lazy evaluation of matches and inserts
  10648. // new strings in the dictionary only for unmatched strings or for short
  10649. // matches. It is used only for the fast compression options.
  10650. function deflate_fast(flush) {
  10651. // short hash_head = 0; // head of the hash chain
  10652. var hash_head = 0; // head of the hash chain
  10653. var bflush; // set if current block must be flushed
  10654. while (true) {
  10655. // Make sure that we always have enough lookahead, except
  10656. // at the end of the input file. We need MAX_MATCH bytes
  10657. // for the next match, plus MIN_MATCH bytes to insert the
  10658. // string following the next match.
  10659. if (lookahead < MIN_LOOKAHEAD) {
  10660. fill_window();
  10661. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10662. return NeedMore;
  10663. }
  10664. if (lookahead === 0)
  10665. break; // flush the current block
  10666. }
  10667. // Insert the string window[strstart .. strstart+2] in the
  10668. // dictionary, and set hash_head to the head of the hash chain:
  10669. if (lookahead >= MIN_MATCH) {
  10670. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10671. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10672. hash_head = (head[ins_h] & 0xffff);
  10673. prev[strstart & w_mask] = head[ins_h];
  10674. head[ins_h] = strstart;
  10675. }
  10676. // Find the longest match, discarding those <= prev_length.
  10677. // At this point we have always match_length < MIN_MATCH
  10678. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10679. // To simplify the code, we prevent matches with the string
  10680. // of window index 0 (in particular we have to avoid a match
  10681. // of the string with itself at the start of the input file).
  10682. if (strategy != Z_HUFFMAN_ONLY) {
  10683. match_length = longest_match(hash_head);
  10684. }
  10685. // longest_match() sets match_start
  10686. }
  10687. if (match_length >= MIN_MATCH) {
  10688. // check_match(strstart, match_start, match_length);
  10689. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  10690. lookahead -= match_length;
  10691. // Insert new strings in the hash table only if the match length
  10692. // is not too large. This saves time but degrades compression.
  10693. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  10694. match_length--; // string at strstart already in hash table
  10695. do {
  10696. strstart++;
  10697. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10698. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10699. hash_head = (head[ins_h] & 0xffff);
  10700. prev[strstart & w_mask] = head[ins_h];
  10701. head[ins_h] = strstart;
  10702. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  10703. // always MIN_MATCH bytes ahead.
  10704. } while (--match_length !== 0);
  10705. strstart++;
  10706. } else {
  10707. strstart += match_length;
  10708. match_length = 0;
  10709. ins_h = window[strstart] & 0xff;
  10710. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10711. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  10712. // not
  10713. // matter since it will be recomputed at next deflate call.
  10714. }
  10715. } else {
  10716. // No match, output a literal byte
  10717. bflush = _tr_tally(0, window[strstart] & 0xff);
  10718. lookahead--;
  10719. strstart++;
  10720. }
  10721. if (bflush) {
  10722. flush_block_only(false);
  10723. if (strm.avail_out === 0)
  10724. return NeedMore;
  10725. }
  10726. }
  10727. flush_block_only(flush == Z_FINISH);
  10728. if (strm.avail_out === 0) {
  10729. if (flush == Z_FINISH)
  10730. return FinishStarted;
  10731. else
  10732. return NeedMore;
  10733. }
  10734. return flush == Z_FINISH ? FinishDone : BlockDone;
  10735. }
  10736. // Same as above, but achieves better compression. We use a lazy
  10737. // evaluation for matches: a match is finally adopted only if there is
  10738. // no better match at the next window position.
  10739. function deflate_slow(flush) {
  10740. // short hash_head = 0; // head of hash chain
  10741. var hash_head = 0; // head of hash chain
  10742. var bflush; // set if current block must be flushed
  10743. var max_insert;
  10744. // Process the input block.
  10745. while (true) {
  10746. // Make sure that we always have enough lookahead, except
  10747. // at the end of the input file. We need MAX_MATCH bytes
  10748. // for the next match, plus MIN_MATCH bytes to insert the
  10749. // string following the next match.
  10750. if (lookahead < MIN_LOOKAHEAD) {
  10751. fill_window();
  10752. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10753. return NeedMore;
  10754. }
  10755. if (lookahead === 0)
  10756. break; // flush the current block
  10757. }
  10758. // Insert the string window[strstart .. strstart+2] in the
  10759. // dictionary, and set hash_head to the head of the hash chain:
  10760. if (lookahead >= MIN_MATCH) {
  10761. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10762. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10763. hash_head = (head[ins_h] & 0xffff);
  10764. prev[strstart & w_mask] = head[ins_h];
  10765. head[ins_h] = strstart;
  10766. }
  10767. // Find the longest match, discarding those <= prev_length.
  10768. prev_length = match_length;
  10769. prev_match = match_start;
  10770. match_length = MIN_MATCH - 1;
  10771. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10772. // To simplify the code, we prevent matches with the string
  10773. // of window index 0 (in particular we have to avoid a match
  10774. // of the string with itself at the start of the input file).
  10775. if (strategy != Z_HUFFMAN_ONLY) {
  10776. match_length = longest_match(hash_head);
  10777. }
  10778. // longest_match() sets match_start
  10779. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  10780. // If prev_match is also MIN_MATCH, match_start is garbage
  10781. // but we will ignore the current match anyway.
  10782. match_length = MIN_MATCH - 1;
  10783. }
  10784. }
  10785. // If there was a match at the previous step and the current
  10786. // match is not better, output the previous match:
  10787. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  10788. max_insert = strstart + lookahead - MIN_MATCH;
  10789. // Do not insert strings in hash table beyond this.
  10790. // check_match(strstart-1, prev_match, prev_length);
  10791. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  10792. // Insert in hash table all strings up to the end of the match.
  10793. // strstart-1 and strstart are already inserted. If there is not
  10794. // enough lookahead, the last two strings are not inserted in
  10795. // the hash table.
  10796. lookahead -= prev_length - 1;
  10797. prev_length -= 2;
  10798. do {
  10799. if (++strstart <= max_insert) {
  10800. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10801. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10802. hash_head = (head[ins_h] & 0xffff);
  10803. prev[strstart & w_mask] = head[ins_h];
  10804. head[ins_h] = strstart;
  10805. }
  10806. } while (--prev_length !== 0);
  10807. match_available = 0;
  10808. match_length = MIN_MATCH - 1;
  10809. strstart++;
  10810. if (bflush) {
  10811. flush_block_only(false);
  10812. if (strm.avail_out === 0)
  10813. return NeedMore;
  10814. }
  10815. } else if (match_available !== 0) {
  10816. // If there was no match at the previous position, output a
  10817. // single literal. If there was a match but the current match
  10818. // is longer, truncate the previous match to a single literal.
  10819. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10820. if (bflush) {
  10821. flush_block_only(false);
  10822. }
  10823. strstart++;
  10824. lookahead--;
  10825. if (strm.avail_out === 0)
  10826. return NeedMore;
  10827. } else {
  10828. // There is no previous match to compare with, wait for
  10829. // the next step to decide.
  10830. match_available = 1;
  10831. strstart++;
  10832. lookahead--;
  10833. }
  10834. }
  10835. if (match_available !== 0) {
  10836. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10837. match_available = 0;
  10838. }
  10839. flush_block_only(flush == Z_FINISH);
  10840. if (strm.avail_out === 0) {
  10841. if (flush == Z_FINISH)
  10842. return FinishStarted;
  10843. else
  10844. return NeedMore;
  10845. }
  10846. return flush == Z_FINISH ? FinishDone : BlockDone;
  10847. }
  10848. function deflateReset(strm) {
  10849. strm.total_in = strm.total_out = 0;
  10850. strm.msg = null; //
  10851. that.pending = 0;
  10852. that.pending_out = 0;
  10853. status = BUSY_STATE;
  10854. last_flush = Z_NO_FLUSH;
  10855. tr_init();
  10856. lm_init();
  10857. return Z_OK;
  10858. }
  10859. that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
  10860. if (!_method)
  10861. _method = Z_DEFLATED;
  10862. if (!memLevel)
  10863. memLevel = DEF_MEM_LEVEL;
  10864. if (!_strategy)
  10865. _strategy = Z_DEFAULT_STRATEGY;
  10866. // byte[] my_version=ZLIB_VERSION;
  10867. //
  10868. // if (!version || version[0] != my_version[0]
  10869. // || stream_size != sizeof(z_stream)) {
  10870. // return Z_VERSION_ERROR;
  10871. // }
  10872. strm.msg = null;
  10873. if (_level == Z_DEFAULT_COMPRESSION)
  10874. _level = 6;
  10875. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  10876. || _strategy > Z_HUFFMAN_ONLY) {
  10877. return Z_STREAM_ERROR;
  10878. }
  10879. strm.dstate = that;
  10880. w_bits = bits;
  10881. w_size = 1 << w_bits;
  10882. w_mask = w_size - 1;
  10883. hash_bits = memLevel + 7;
  10884. hash_size = 1 << hash_bits;
  10885. hash_mask = hash_size - 1;
  10886. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  10887. window = new Uint8Array(w_size * 2);
  10888. prev = [];
  10889. head = [];
  10890. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  10891. // We overlay pending_buf and d_buf+l_buf. This works since the average
  10892. // output size for (length,distance) codes is <= 24 bits.
  10893. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  10894. pending_buf_size = lit_bufsize * 4;
  10895. d_buf = Math.floor(lit_bufsize / 2);
  10896. l_buf = (1 + 2) * lit_bufsize;
  10897. level = _level;
  10898. strategy = _strategy;
  10899. method = _method & 0xff;
  10900. return deflateReset(strm);
  10901. };
  10902. that.deflateEnd = function() {
  10903. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  10904. return Z_STREAM_ERROR;
  10905. }
  10906. // Deallocate in reverse order of allocations:
  10907. that.pending_buf = null;
  10908. head = null;
  10909. prev = null;
  10910. window = null;
  10911. // free
  10912. that.dstate = null;
  10913. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  10914. };
  10915. that.deflateParams = function(strm, _level, _strategy) {
  10916. var err = Z_OK;
  10917. if (_level == Z_DEFAULT_COMPRESSION) {
  10918. _level = 6;
  10919. }
  10920. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  10921. return Z_STREAM_ERROR;
  10922. }
  10923. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  10924. // Flush the last buffer:
  10925. err = strm.deflate(Z_PARTIAL_FLUSH);
  10926. }
  10927. if (level != _level) {
  10928. level = _level;
  10929. max_lazy_match = config_table[level].max_lazy;
  10930. good_match = config_table[level].good_length;
  10931. nice_match = config_table[level].nice_length;
  10932. max_chain_length = config_table[level].max_chain;
  10933. }
  10934. strategy = _strategy;
  10935. return err;
  10936. };
  10937. that.deflateSetDictionary = function(strm, dictionary, dictLength) {
  10938. var length = dictLength;
  10939. var n, index = 0;
  10940. if (!dictionary || status != INIT_STATE)
  10941. return Z_STREAM_ERROR;
  10942. if (length < MIN_MATCH)
  10943. return Z_OK;
  10944. if (length > w_size - MIN_LOOKAHEAD) {
  10945. length = w_size - MIN_LOOKAHEAD;
  10946. index = dictLength - length; // use the tail of the dictionary
  10947. }
  10948. window.set(dictionary.subarray(index, index + length), 0);
  10949. strstart = length;
  10950. block_start = length;
  10951. // Insert all strings in the hash table (except for the last two bytes).
  10952. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  10953. // call of fill_window.
  10954. ins_h = window[0] & 0xff;
  10955. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  10956. for (n = 0; n <= length - MIN_MATCH; n++) {
  10957. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10958. prev[n & w_mask] = head[ins_h];
  10959. head[ins_h] = n;
  10960. }
  10961. return Z_OK;
  10962. };
  10963. that.deflate = function(_strm, flush) {
  10964. var i, header, level_flags, old_flush, bstate;
  10965. if (flush > Z_FINISH || flush < 0) {
  10966. return Z_STREAM_ERROR;
  10967. }
  10968. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
  10969. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  10970. return Z_STREAM_ERROR;
  10971. }
  10972. if (_strm.avail_out === 0) {
  10973. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10974. return Z_BUF_ERROR;
  10975. }
  10976. strm = _strm; // just in case
  10977. old_flush = last_flush;
  10978. last_flush = flush;
  10979. // Write the zlib header
  10980. if (status == INIT_STATE) {
  10981. header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  10982. level_flags = ((level - 1) & 0xff) >> 1;
  10983. if (level_flags > 3)
  10984. level_flags = 3;
  10985. header |= (level_flags << 6);
  10986. if (strstart !== 0)
  10987. header |= PRESET_DICT;
  10988. header += 31 - (header % 31);
  10989. status = BUSY_STATE;
  10990. putShortMSB(header);
  10991. }
  10992. // Flush as much pending output as possible
  10993. if (that.pending !== 0) {
  10994. strm.flush_pending();
  10995. if (strm.avail_out === 0) {
  10996. // console.log(" avail_out==0");
  10997. // Since avail_out is 0, deflate will be called again with
  10998. // more output space, but possibly with both pending and
  10999. // avail_in equal to zero. There won't be anything to do,
  11000. // but this is not an error situation so make sure we
  11001. // return OK instead of BUF_ERROR at next call of deflate:
  11002. last_flush = -1;
  11003. return Z_OK;
  11004. }
  11005. // Make sure there is something to do and avoid duplicate
  11006. // consecutive
  11007. // flushes. For repeated and useless calls with Z_FINISH, we keep
  11008. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  11009. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  11010. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  11011. return Z_BUF_ERROR;
  11012. }
  11013. // User must not provide more input after the first FINISH:
  11014. if (status == FINISH_STATE && strm.avail_in !== 0) {
  11015. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  11016. return Z_BUF_ERROR;
  11017. }
  11018. // Start a new block or continue the current one.
  11019. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
  11020. bstate = -1;
  11021. switch (config_table[level].func) {
  11022. case STORED:
  11023. bstate = deflate_stored(flush);
  11024. break;
  11025. case FAST:
  11026. bstate = deflate_fast(flush);
  11027. break;
  11028. case SLOW:
  11029. bstate = deflate_slow(flush);
  11030. break;
  11031. default:
  11032. }
  11033. if (bstate == FinishStarted || bstate == FinishDone) {
  11034. status = FINISH_STATE;
  11035. }
  11036. if (bstate == NeedMore || bstate == FinishStarted) {
  11037. if (strm.avail_out === 0) {
  11038. last_flush = -1; // avoid BUF_ERROR next call, see above
  11039. }
  11040. return Z_OK;
  11041. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  11042. // of deflate should use the same flush parameter to make sure
  11043. // that the flush is complete. So we don't have to output an
  11044. // empty block here, this will be done at next call. This also
  11045. // ensures that for a very small output buffer, we emit at most
  11046. // one empty block.
  11047. }
  11048. if (bstate == BlockDone) {
  11049. if (flush == Z_PARTIAL_FLUSH) {
  11050. _tr_align();
  11051. } else { // FULL_FLUSH or SYNC_FLUSH
  11052. _tr_stored_block(0, 0, false);
  11053. // For a full flush, this empty block will be recognized
  11054. // as a special marker by inflate_sync().
  11055. if (flush == Z_FULL_FLUSH) {
  11056. // state.head[s.hash_size-1]=0;
  11057. for (i = 0; i < hash_size/*-1*/; i++)
  11058. // forget history
  11059. head[i] = 0;
  11060. }
  11061. }
  11062. strm.flush_pending();
  11063. if (strm.avail_out === 0) {
  11064. last_flush = -1; // avoid BUF_ERROR at next call, see above
  11065. return Z_OK;
  11066. }
  11067. }
  11068. }
  11069. if (flush != Z_FINISH)
  11070. return Z_OK;
  11071. return Z_STREAM_END;
  11072. };
  11073. }
  11074. // ZStream
  11075. function ZStream() {
  11076. var that = this;
  11077. that.next_in_index = 0;
  11078. that.next_out_index = 0;
  11079. // that.next_in; // next input byte
  11080. that.avail_in = 0; // number of bytes available at next_in
  11081. that.total_in = 0; // total nb of input bytes read so far
  11082. // that.next_out; // next output byte should be put there
  11083. that.avail_out = 0; // remaining free space at next_out
  11084. that.total_out = 0; // total nb of bytes output so far
  11085. // that.msg;
  11086. // that.dstate;
  11087. }
  11088. ZStream.prototype = {
  11089. deflateInit : function(level, bits) {
  11090. var that = this;
  11091. that.dstate = new Deflate();
  11092. if (!bits)
  11093. bits = MAX_BITS;
  11094. return that.dstate.deflateInit(that, level, bits);
  11095. },
  11096. deflate : function(flush) {
  11097. var that = this;
  11098. if (!that.dstate) {
  11099. return Z_STREAM_ERROR;
  11100. }
  11101. return that.dstate.deflate(that, flush);
  11102. },
  11103. deflateEnd : function() {
  11104. var that = this;
  11105. if (!that.dstate)
  11106. return Z_STREAM_ERROR;
  11107. var ret = that.dstate.deflateEnd();
  11108. that.dstate = null;
  11109. return ret;
  11110. },
  11111. deflateParams : function(level, strategy) {
  11112. var that = this;
  11113. if (!that.dstate)
  11114. return Z_STREAM_ERROR;
  11115. return that.dstate.deflateParams(that, level, strategy);
  11116. },
  11117. deflateSetDictionary : function(dictionary, dictLength) {
  11118. var that = this;
  11119. if (!that.dstate)
  11120. return Z_STREAM_ERROR;
  11121. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  11122. },
  11123. // Read a new buffer from the current input stream, update the
  11124. // total number of bytes read. All deflate() input goes through
  11125. // this function so some applications may wish to modify it to avoid
  11126. // allocating a large strm->next_in buffer and copying from it.
  11127. // (See also flush_pending()).
  11128. read_buf : function(buf, start, size) {
  11129. var that = this;
  11130. var len = that.avail_in;
  11131. if (len > size)
  11132. len = size;
  11133. if (len === 0)
  11134. return 0;
  11135. that.avail_in -= len;
  11136. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  11137. that.next_in_index += len;
  11138. that.total_in += len;
  11139. return len;
  11140. },
  11141. // Flush as much pending output as possible. All deflate() output goes
  11142. // through this function so some applications may wish to modify it
  11143. // to avoid allocating a large strm->next_out buffer and copying into it.
  11144. // (See also read_buf()).
  11145. flush_pending : function() {
  11146. var that = this;
  11147. var len = that.dstate.pending;
  11148. if (len > that.avail_out)
  11149. len = that.avail_out;
  11150. if (len === 0)
  11151. return;
  11152. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  11153. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  11154. // len)) {
  11155. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  11156. // that.next_out_index + ", " + len);
  11157. // console.log("avail_out=" + that.avail_out);
  11158. // }
  11159. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  11160. that.next_out_index += len;
  11161. that.dstate.pending_out += len;
  11162. that.total_out += len;
  11163. that.avail_out -= len;
  11164. that.dstate.pending -= len;
  11165. if (that.dstate.pending === 0) {
  11166. that.dstate.pending_out = 0;
  11167. }
  11168. }
  11169. };
  11170. // Deflater
  11171. return function Deflater(level) {
  11172. var that = this;
  11173. var z = new ZStream();
  11174. var bufsize = 512;
  11175. var flush = Z_NO_FLUSH;
  11176. var buf = new Uint8Array(bufsize);
  11177. if (typeof level == "undefined")
  11178. level = Z_DEFAULT_COMPRESSION;
  11179. z.deflateInit(level);
  11180. z.next_out = buf;
  11181. that.append = function(data, onprogress) {
  11182. var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
  11183. if (!data.length)
  11184. return;
  11185. z.next_in_index = 0;
  11186. z.next_in = data;
  11187. z.avail_in = data.length;
  11188. do {
  11189. z.next_out_index = 0;
  11190. z.avail_out = bufsize;
  11191. err = z.deflate(flush);
  11192. if (err != Z_OK)
  11193. throw "deflating: " + z.msg;
  11194. if (z.next_out_index)
  11195. if (z.next_out_index == bufsize)
  11196. buffers.push(new Uint8Array(buf));
  11197. else
  11198. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11199. bufferSize += z.next_out_index;
  11200. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  11201. onprogress(z.next_in_index);
  11202. lastIndex = z.next_in_index;
  11203. }
  11204. } while (z.avail_in > 0 || z.avail_out === 0);
  11205. array = new Uint8Array(bufferSize);
  11206. buffers.forEach(function(chunk) {
  11207. array.set(chunk, bufferIndex);
  11208. bufferIndex += chunk.length;
  11209. });
  11210. return array;
  11211. };
  11212. that.flush = function() {
  11213. var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
  11214. do {
  11215. z.next_out_index = 0;
  11216. z.avail_out = bufsize;
  11217. err = z.deflate(Z_FINISH);
  11218. if (err != Z_STREAM_END && err != Z_OK)
  11219. throw "deflating: " + z.msg;
  11220. if (bufsize - z.avail_out > 0)
  11221. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11222. bufferSize += z.next_out_index;
  11223. } while (z.avail_in > 0 || z.avail_out === 0);
  11224. z.deflateEnd();
  11225. array = new Uint8Array(bufferSize);
  11226. buffers.forEach(function(chunk) {
  11227. array.set(chunk, bufferIndex);
  11228. bufferIndex += chunk.length;
  11229. });
  11230. return array;
  11231. };
  11232. };
  11233. })(undefined);
  11234. /*
  11235. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  11236. Copyright (c) 2016 Niklas von Hertzen
  11237. Released under License
  11238. */
  11239. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e();}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  11240. (function (global){
  11241. /*! http://mths.be/punycode v1.2.4 by @mathias */
  11242. (function(root) {
  11243. /** Detect free variables */
  11244. var freeExports = typeof exports == 'object' && exports;
  11245. var freeModule = typeof module == 'object' && module &&
  11246. module.exports == freeExports && module;
  11247. var freeGlobal = typeof global == 'object' && global;
  11248. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  11249. root = freeGlobal;
  11250. }
  11251. /**
  11252. * The `punycode` object.
  11253. * @name punycode
  11254. * @type Object
  11255. */
  11256. var punycode,
  11257. /** Highest positive signed 32-bit float value */
  11258. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  11259. /** Bootstring parameters */
  11260. base = 36,
  11261. tMin = 1,
  11262. tMax = 26,
  11263. skew = 38,
  11264. damp = 700,
  11265. initialBias = 72,
  11266. initialN = 128, // 0x80
  11267. delimiter = '-', // '\x2D'
  11268. /** Regular expressions */
  11269. regexPunycode = /^xn--/,
  11270. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  11271. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  11272. /** Error messages */
  11273. errors = {
  11274. 'overflow': 'Overflow: input needs wider integers to process',
  11275. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  11276. 'invalid-input': 'Invalid input'
  11277. },
  11278. /** Convenience shortcuts */
  11279. baseMinusTMin = base - tMin,
  11280. floor = Math.floor,
  11281. stringFromCharCode = String.fromCharCode,
  11282. /** Temporary variable */
  11283. key;
  11284. /*--------------------------------------------------------------------------*/
  11285. /**
  11286. * A generic error utility function.
  11287. * @private
  11288. * @param {String} type The error type.
  11289. * @returns {Error} Throws a `RangeError` with the applicable error message.
  11290. */
  11291. function error(type) {
  11292. throw RangeError(errors[type]);
  11293. }
  11294. /**
  11295. * A generic `Array#map` utility function.
  11296. * @private
  11297. * @param {Array} array The array to iterate over.
  11298. * @param {Function} callback The function that gets called for every array
  11299. * item.
  11300. * @returns {Array} A new array of values returned by the callback function.
  11301. */
  11302. function map(array, fn) {
  11303. var length = array.length;
  11304. while (length--) {
  11305. array[length] = fn(array[length]);
  11306. }
  11307. return array;
  11308. }
  11309. /**
  11310. * A simple `Array#map`-like wrapper to work with domain name strings.
  11311. * @private
  11312. * @param {String} domain The domain name.
  11313. * @param {Function} callback The function that gets called for every
  11314. * character.
  11315. * @returns {Array} A new string of characters returned by the callback
  11316. * function.
  11317. */
  11318. function mapDomain(string, fn) {
  11319. return map(string.split(regexSeparators), fn).join('.');
  11320. }
  11321. /**
  11322. * Creates an array containing the numeric code points of each Unicode
  11323. * character in the string. While JavaScript uses UCS-2 internally,
  11324. * this function will convert a pair of surrogate halves (each of which
  11325. * UCS-2 exposes as separate characters) into a single code point,
  11326. * matching UTF-16.
  11327. * @see `punycode.ucs2.encode`
  11328. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11329. * @memberOf punycode.ucs2
  11330. * @name decode
  11331. * @param {String} string The Unicode input string (UCS-2).
  11332. * @returns {Array} The new array of code points.
  11333. */
  11334. function ucs2decode(string) {
  11335. var output = [],
  11336. counter = 0,
  11337. length = string.length,
  11338. value,
  11339. extra;
  11340. while (counter < length) {
  11341. value = string.charCodeAt(counter++);
  11342. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11343. // high surrogate, and there is a next character
  11344. extra = string.charCodeAt(counter++);
  11345. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11346. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11347. } else {
  11348. // unmatched surrogate; only append this code unit, in case the next
  11349. // code unit is the high surrogate of a surrogate pair
  11350. output.push(value);
  11351. counter--;
  11352. }
  11353. } else {
  11354. output.push(value);
  11355. }
  11356. }
  11357. return output;
  11358. }
  11359. /**
  11360. * Creates a string based on an array of numeric code points.
  11361. * @see `punycode.ucs2.decode`
  11362. * @memberOf punycode.ucs2
  11363. * @name encode
  11364. * @param {Array} codePoints The array of numeric code points.
  11365. * @returns {String} The new Unicode string (UCS-2).
  11366. */
  11367. function ucs2encode(array) {
  11368. return map(array, function(value) {
  11369. var output = '';
  11370. if (value > 0xFFFF) {
  11371. value -= 0x10000;
  11372. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11373. value = 0xDC00 | value & 0x3FF;
  11374. }
  11375. output += stringFromCharCode(value);
  11376. return output;
  11377. }).join('');
  11378. }
  11379. /**
  11380. * Converts a basic code point into a digit/integer.
  11381. * @see `digitToBasic()`
  11382. * @private
  11383. * @param {Number} codePoint The basic numeric code point value.
  11384. * @returns {Number} The numeric value of a basic code point (for use in
  11385. * representing integers) in the range `0` to `base - 1`, or `base` if
  11386. * the code point does not represent a value.
  11387. */
  11388. function basicToDigit(codePoint) {
  11389. if (codePoint - 48 < 10) {
  11390. return codePoint - 22;
  11391. }
  11392. if (codePoint - 65 < 26) {
  11393. return codePoint - 65;
  11394. }
  11395. if (codePoint - 97 < 26) {
  11396. return codePoint - 97;
  11397. }
  11398. return base;
  11399. }
  11400. /**
  11401. * Converts a digit/integer into a basic code point.
  11402. * @see `basicToDigit()`
  11403. * @private
  11404. * @param {Number} digit The numeric value of a basic code point.
  11405. * @returns {Number} The basic code point whose value (when used for
  11406. * representing integers) is `digit`, which needs to be in the range
  11407. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11408. * used; else, the lowercase form is used. The behavior is undefined
  11409. * if `flag` is non-zero and `digit` has no uppercase form.
  11410. */
  11411. function digitToBasic(digit, flag) {
  11412. // 0..25 map to ASCII a..z or A..Z
  11413. // 26..35 map to ASCII 0..9
  11414. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11415. }
  11416. /**
  11417. * Bias adaptation function as per section 3.4 of RFC 3492.
  11418. * http://tools.ietf.org/html/rfc3492#section-3.4
  11419. * @private
  11420. */
  11421. function adapt(delta, numPoints, firstTime) {
  11422. var k = 0;
  11423. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11424. delta += floor(delta / numPoints);
  11425. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  11426. delta = floor(delta / baseMinusTMin);
  11427. }
  11428. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11429. }
  11430. /**
  11431. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11432. * symbols.
  11433. * @memberOf punycode
  11434. * @param {String} input The Punycode string of ASCII-only symbols.
  11435. * @returns {String} The resulting string of Unicode symbols.
  11436. */
  11437. function decode(input) {
  11438. // Don't use UCS-2
  11439. var output = [],
  11440. inputLength = input.length,
  11441. out,
  11442. i = 0,
  11443. n = initialN,
  11444. bias = initialBias,
  11445. basic,
  11446. j,
  11447. index,
  11448. oldi,
  11449. w,
  11450. k,
  11451. digit,
  11452. t,
  11453. /** Cached calculation results */
  11454. baseMinusT;
  11455. // Handle the basic code points: let `basic` be the number of input code
  11456. // points before the last delimiter, or `0` if there is none, then copy
  11457. // the first basic code points to the output.
  11458. basic = input.lastIndexOf(delimiter);
  11459. if (basic < 0) {
  11460. basic = 0;
  11461. }
  11462. for (j = 0; j < basic; ++j) {
  11463. // if it's not a basic code point
  11464. if (input.charCodeAt(j) >= 0x80) {
  11465. error('not-basic');
  11466. }
  11467. output.push(input.charCodeAt(j));
  11468. }
  11469. // Main decoding loop: start just after the last delimiter if any basic code
  11470. // points were copied; start at the beginning otherwise.
  11471. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  11472. // `index` is the index of the next character to be consumed.
  11473. // Decode a generalized variable-length integer into `delta`,
  11474. // which gets added to `i`. The overflow checking is easier
  11475. // if we increase `i` as we go, then subtract off its starting
  11476. // value at the end to obtain `delta`.
  11477. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  11478. if (index >= inputLength) {
  11479. error('invalid-input');
  11480. }
  11481. digit = basicToDigit(input.charCodeAt(index++));
  11482. if (digit >= base || digit > floor((maxInt - i) / w)) {
  11483. error('overflow');
  11484. }
  11485. i += digit * w;
  11486. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11487. if (digit < t) {
  11488. break;
  11489. }
  11490. baseMinusT = base - t;
  11491. if (w > floor(maxInt / baseMinusT)) {
  11492. error('overflow');
  11493. }
  11494. w *= baseMinusT;
  11495. }
  11496. out = output.length + 1;
  11497. bias = adapt(i - oldi, out, oldi == 0);
  11498. // `i` was supposed to wrap around from `out` to `0`,
  11499. // incrementing `n` each time, so we'll fix that now:
  11500. if (floor(i / out) > maxInt - n) {
  11501. error('overflow');
  11502. }
  11503. n += floor(i / out);
  11504. i %= out;
  11505. // Insert `n` at position `i` of the output
  11506. output.splice(i++, 0, n);
  11507. }
  11508. return ucs2encode(output);
  11509. }
  11510. /**
  11511. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  11512. * symbols.
  11513. * @memberOf punycode
  11514. * @param {String} input The string of Unicode symbols.
  11515. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  11516. */
  11517. function encode(input) {
  11518. var n,
  11519. delta,
  11520. handledCPCount,
  11521. basicLength,
  11522. bias,
  11523. j,
  11524. m,
  11525. q,
  11526. k,
  11527. t,
  11528. currentValue,
  11529. output = [],
  11530. /** `inputLength` will hold the number of code points in `input`. */
  11531. inputLength,
  11532. /** Cached calculation results */
  11533. handledCPCountPlusOne,
  11534. baseMinusT,
  11535. qMinusT;
  11536. // Convert the input in UCS-2 to Unicode
  11537. input = ucs2decode(input);
  11538. // Cache the length
  11539. inputLength = input.length;
  11540. // Initialize the state
  11541. n = initialN;
  11542. delta = 0;
  11543. bias = initialBias;
  11544. // Handle the basic code points
  11545. for (j = 0; j < inputLength; ++j) {
  11546. currentValue = input[j];
  11547. if (currentValue < 0x80) {
  11548. output.push(stringFromCharCode(currentValue));
  11549. }
  11550. }
  11551. handledCPCount = basicLength = output.length;
  11552. // `handledCPCount` is the number of code points that have been handled;
  11553. // `basicLength` is the number of basic code points.
  11554. // Finish the basic string - if it is not empty - with a delimiter
  11555. if (basicLength) {
  11556. output.push(delimiter);
  11557. }
  11558. // Main encoding loop:
  11559. while (handledCPCount < inputLength) {
  11560. // All non-basic code points < n have been handled already. Find the next
  11561. // larger one:
  11562. for (m = maxInt, j = 0; j < inputLength; ++j) {
  11563. currentValue = input[j];
  11564. if (currentValue >= n && currentValue < m) {
  11565. m = currentValue;
  11566. }
  11567. }
  11568. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  11569. // but guard against overflow
  11570. handledCPCountPlusOne = handledCPCount + 1;
  11571. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  11572. error('overflow');
  11573. }
  11574. delta += (m - n) * handledCPCountPlusOne;
  11575. n = m;
  11576. for (j = 0; j < inputLength; ++j) {
  11577. currentValue = input[j];
  11578. if (currentValue < n && ++delta > maxInt) {
  11579. error('overflow');
  11580. }
  11581. if (currentValue == n) {
  11582. // Represent delta as a generalized variable-length integer
  11583. for (q = delta, k = base; /* no condition */; k += base) {
  11584. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11585. if (q < t) {
  11586. break;
  11587. }
  11588. qMinusT = q - t;
  11589. baseMinusT = base - t;
  11590. output.push(
  11591. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  11592. );
  11593. q = floor(qMinusT / baseMinusT);
  11594. }
  11595. output.push(stringFromCharCode(digitToBasic(q, 0)));
  11596. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  11597. delta = 0;
  11598. ++handledCPCount;
  11599. }
  11600. }
  11601. ++delta;
  11602. ++n;
  11603. }
  11604. return output.join('');
  11605. }
  11606. /**
  11607. * Converts a Punycode string representing a domain name to Unicode. Only the
  11608. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  11609. * matter if you call it on a string that has already been converted to
  11610. * Unicode.
  11611. * @memberOf punycode
  11612. * @param {String} domain The Punycode domain name to convert to Unicode.
  11613. * @returns {String} The Unicode representation of the given Punycode
  11614. * string.
  11615. */
  11616. function toUnicode(domain) {
  11617. return mapDomain(domain, function(string) {
  11618. return regexPunycode.test(string)
  11619. ? decode(string.slice(4).toLowerCase())
  11620. : string;
  11621. });
  11622. }
  11623. /**
  11624. * Converts a Unicode string representing a domain name to Punycode. Only the
  11625. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  11626. * matter if you call it with a domain that's already in ASCII.
  11627. * @memberOf punycode
  11628. * @param {String} domain The domain name to convert, as a Unicode string.
  11629. * @returns {String} The Punycode representation of the given domain name.
  11630. */
  11631. function toASCII(domain) {
  11632. return mapDomain(domain, function(string) {
  11633. return regexNonASCII.test(string)
  11634. ? 'xn--' + encode(string)
  11635. : string;
  11636. });
  11637. }
  11638. /*--------------------------------------------------------------------------*/
  11639. /** Define the public API */
  11640. punycode = {
  11641. /**
  11642. * A string representing the current Punycode.js version number.
  11643. * @memberOf punycode
  11644. * @type String
  11645. */
  11646. 'version': '1.2.4',
  11647. /**
  11648. * An object of methods to convert from JavaScript's internal character
  11649. * representation (UCS-2) to Unicode code points, and back.
  11650. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11651. * @memberOf punycode
  11652. * @type Object
  11653. */
  11654. 'ucs2': {
  11655. 'decode': ucs2decode,
  11656. 'encode': ucs2encode
  11657. },
  11658. 'decode': decode,
  11659. 'encode': encode,
  11660. 'toASCII': toASCII,
  11661. 'toUnicode': toUnicode
  11662. };
  11663. /** Expose `punycode` */
  11664. // Some AMD build optimizers, like r.js, check for specific condition patterns
  11665. // like the following:
  11666. if (
  11667. typeof define == 'function' &&
  11668. typeof define.amd == 'object' &&
  11669. define.amd
  11670. ) {
  11671. define('punycode', function() {
  11672. return punycode;
  11673. });
  11674. } else if (freeExports && !freeExports.nodeType) {
  11675. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  11676. freeModule.exports = punycode;
  11677. } else { // in Narwhal or RingoJS v0.7.0-
  11678. for (key in punycode) {
  11679. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  11680. }
  11681. }
  11682. } else { // in Rhino or a web browser
  11683. root.punycode = punycode;
  11684. }
  11685. }(this));
  11686. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
  11687. },{}],2:[function(_dereq_,module,exports){
  11688. var log = _dereq_('./log');
  11689. function restoreOwnerScroll(ownerDocument, x, y) {
  11690. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  11691. ownerDocument.defaultView.scrollTo(x, y);
  11692. }
  11693. }
  11694. function cloneCanvasContents(canvas, clonedCanvas) {
  11695. try {
  11696. if (clonedCanvas) {
  11697. clonedCanvas.width = canvas.width;
  11698. clonedCanvas.height = canvas.height;
  11699. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  11700. }
  11701. } catch(e) {
  11702. log("Unable to copy canvas content from", canvas, e);
  11703. }
  11704. }
  11705. function cloneNode(node, javascriptEnabled) {
  11706. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  11707. var child = node.firstChild;
  11708. while(child) {
  11709. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  11710. clone.appendChild(cloneNode(child, javascriptEnabled));
  11711. }
  11712. child = child.nextSibling;
  11713. }
  11714. if (node.nodeType === 1) {
  11715. clone._scrollTop = node.scrollTop;
  11716. clone._scrollLeft = node.scrollLeft;
  11717. if (node.nodeName === "CANVAS") {
  11718. cloneCanvasContents(node, clone);
  11719. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  11720. clone.value = node.value;
  11721. }
  11722. }
  11723. return clone;
  11724. }
  11725. function initNode(node) {
  11726. if (node.nodeType === 1) {
  11727. node.scrollTop = node._scrollTop;
  11728. node.scrollLeft = node._scrollLeft;
  11729. var child = node.firstChild;
  11730. while(child) {
  11731. initNode(child);
  11732. child = child.nextSibling;
  11733. }
  11734. }
  11735. }
  11736. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  11737. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  11738. var container = containerDocument.createElement("iframe");
  11739. container.className = "html2canvas-container";
  11740. container.style.visibility = "hidden";
  11741. container.style.position = "fixed";
  11742. container.style.left = "-10000px";
  11743. container.style.top = "0px";
  11744. container.style.border = "0";
  11745. container.width = width;
  11746. container.height = height;
  11747. container.scrolling = "no"; // ios won't scroll without it
  11748. containerDocument.body.appendChild(container);
  11749. return new Promise(function(resolve) {
  11750. var documentClone = container.contentWindow.document;
  11751. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  11752. if window url is about:blank, we can assign the url to current by writing onto the document
  11753. */
  11754. container.contentWindow.onload = container.onload = function() {
  11755. var interval = setInterval(function() {
  11756. if (documentClone.body.childNodes.length > 0) {
  11757. initNode(documentClone.documentElement);
  11758. clearInterval(interval);
  11759. if (options.type === "view") {
  11760. container.contentWindow.scrollTo(x, y);
  11761. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  11762. documentClone.documentElement.style.top = (-y) + "px";
  11763. documentClone.documentElement.style.left = (-x) + "px";
  11764. documentClone.documentElement.style.position = 'absolute';
  11765. }
  11766. }
  11767. resolve(container);
  11768. }
  11769. }, 50);
  11770. };
  11771. documentClone.open();
  11772. documentClone.write("<!DOCTYPE html><html></html>");
  11773. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  11774. restoreOwnerScroll(ownerDocument, x, y);
  11775. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  11776. documentClone.close();
  11777. });
  11778. };
  11779. },{"./log":13}],3:[function(_dereq_,module,exports){
  11780. // http://dev.w3.org/csswg/css-color/
  11781. function Color(value) {
  11782. this.r = 0;
  11783. this.g = 0;
  11784. this.b = 0;
  11785. this.a = null;
  11786. var result = this.fromArray(value) ||
  11787. this.namedColor(value) ||
  11788. this.rgb(value) ||
  11789. this.rgba(value) ||
  11790. this.hex6(value) ||
  11791. this.hex3(value);
  11792. }
  11793. Color.prototype.darken = function(amount) {
  11794. var a = 1 - amount;
  11795. return new Color([
  11796. Math.round(this.r * a),
  11797. Math.round(this.g * a),
  11798. Math.round(this.b * a),
  11799. this.a
  11800. ]);
  11801. };
  11802. Color.prototype.isTransparent = function() {
  11803. return this.a === 0;
  11804. };
  11805. Color.prototype.isBlack = function() {
  11806. return this.r === 0 && this.g === 0 && this.b === 0;
  11807. };
  11808. Color.prototype.fromArray = function(array) {
  11809. if (Array.isArray(array)) {
  11810. this.r = Math.min(array[0], 255);
  11811. this.g = Math.min(array[1], 255);
  11812. this.b = Math.min(array[2], 255);
  11813. if (array.length > 3) {
  11814. this.a = array[3];
  11815. }
  11816. }
  11817. return (Array.isArray(array));
  11818. };
  11819. var _hex3 = /^#([a-f0-9]{3})$/i;
  11820. Color.prototype.hex3 = function(value) {
  11821. var match = null;
  11822. if ((match = value.match(_hex3)) !== null) {
  11823. this.r = parseInt(match[1][0] + match[1][0], 16);
  11824. this.g = parseInt(match[1][1] + match[1][1], 16);
  11825. this.b = parseInt(match[1][2] + match[1][2], 16);
  11826. }
  11827. return match !== null;
  11828. };
  11829. var _hex6 = /^#([a-f0-9]{6})$/i;
  11830. Color.prototype.hex6 = function(value) {
  11831. var match = null;
  11832. if ((match = value.match(_hex6)) !== null) {
  11833. this.r = parseInt(match[1].substring(0, 2), 16);
  11834. this.g = parseInt(match[1].substring(2, 4), 16);
  11835. this.b = parseInt(match[1].substring(4, 6), 16);
  11836. }
  11837. return match !== null;
  11838. };
  11839. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  11840. Color.prototype.rgb = function(value) {
  11841. var match = null;
  11842. if ((match = value.match(_rgb)) !== null) {
  11843. this.r = Number(match[1]);
  11844. this.g = Number(match[2]);
  11845. this.b = Number(match[3]);
  11846. }
  11847. return match !== null;
  11848. };
  11849. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  11850. Color.prototype.rgba = function(value) {
  11851. var match = null;
  11852. if ((match = value.match(_rgba)) !== null) {
  11853. this.r = Number(match[1]);
  11854. this.g = Number(match[2]);
  11855. this.b = Number(match[3]);
  11856. this.a = Number(match[4]);
  11857. }
  11858. return match !== null;
  11859. };
  11860. Color.prototype.toString = function() {
  11861. return this.a !== null && this.a !== 1 ?
  11862. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  11863. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  11864. };
  11865. Color.prototype.namedColor = function(value) {
  11866. value = value.toLowerCase();
  11867. var color = colors[value];
  11868. if (color) {
  11869. this.r = color[0];
  11870. this.g = color[1];
  11871. this.b = color[2];
  11872. } else if (value === "transparent") {
  11873. this.r = this.g = this.b = this.a = 0;
  11874. return true;
  11875. }
  11876. return !!color;
  11877. };
  11878. Color.prototype.isColor = true;
  11879. // JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
  11880. var colors = {
  11881. "aliceblue": [240, 248, 255],
  11882. "antiquewhite": [250, 235, 215],
  11883. "aqua": [0, 255, 255],
  11884. "aquamarine": [127, 255, 212],
  11885. "azure": [240, 255, 255],
  11886. "beige": [245, 245, 220],
  11887. "bisque": [255, 228, 196],
  11888. "black": [0, 0, 0],
  11889. "blanchedalmond": [255, 235, 205],
  11890. "blue": [0, 0, 255],
  11891. "blueviolet": [138, 43, 226],
  11892. "brown": [165, 42, 42],
  11893. "burlywood": [222, 184, 135],
  11894. "cadetblue": [95, 158, 160],
  11895. "chartreuse": [127, 255, 0],
  11896. "chocolate": [210, 105, 30],
  11897. "coral": [255, 127, 80],
  11898. "cornflowerblue": [100, 149, 237],
  11899. "cornsilk": [255, 248, 220],
  11900. "crimson": [220, 20, 60],
  11901. "cyan": [0, 255, 255],
  11902. "darkblue": [0, 0, 139],
  11903. "darkcyan": [0, 139, 139],
  11904. "darkgoldenrod": [184, 134, 11],
  11905. "darkgray": [169, 169, 169],
  11906. "darkgreen": [0, 100, 0],
  11907. "darkgrey": [169, 169, 169],
  11908. "darkkhaki": [189, 183, 107],
  11909. "darkmagenta": [139, 0, 139],
  11910. "darkolivegreen": [85, 107, 47],
  11911. "darkorange": [255, 140, 0],
  11912. "darkorchid": [153, 50, 204],
  11913. "darkred": [139, 0, 0],
  11914. "darksalmon": [233, 150, 122],
  11915. "darkseagreen": [143, 188, 143],
  11916. "darkslateblue": [72, 61, 139],
  11917. "darkslategray": [47, 79, 79],
  11918. "darkslategrey": [47, 79, 79],
  11919. "darkturquoise": [0, 206, 209],
  11920. "darkviolet": [148, 0, 211],
  11921. "deeppink": [255, 20, 147],
  11922. "deepskyblue": [0, 191, 255],
  11923. "dimgray": [105, 105, 105],
  11924. "dimgrey": [105, 105, 105],
  11925. "dodgerblue": [30, 144, 255],
  11926. "firebrick": [178, 34, 34],
  11927. "floralwhite": [255, 250, 240],
  11928. "forestgreen": [34, 139, 34],
  11929. "fuchsia": [255, 0, 255],
  11930. "gainsboro": [220, 220, 220],
  11931. "ghostwhite": [248, 248, 255],
  11932. "gold": [255, 215, 0],
  11933. "goldenrod": [218, 165, 32],
  11934. "gray": [128, 128, 128],
  11935. "green": [0, 128, 0],
  11936. "greenyellow": [173, 255, 47],
  11937. "grey": [128, 128, 128],
  11938. "honeydew": [240, 255, 240],
  11939. "hotpink": [255, 105, 180],
  11940. "indianred": [205, 92, 92],
  11941. "indigo": [75, 0, 130],
  11942. "ivory": [255, 255, 240],
  11943. "khaki": [240, 230, 140],
  11944. "lavender": [230, 230, 250],
  11945. "lavenderblush": [255, 240, 245],
  11946. "lawngreen": [124, 252, 0],
  11947. "lemonchiffon": [255, 250, 205],
  11948. "lightblue": [173, 216, 230],
  11949. "lightcoral": [240, 128, 128],
  11950. "lightcyan": [224, 255, 255],
  11951. "lightgoldenrodyellow": [250, 250, 210],
  11952. "lightgray": [211, 211, 211],
  11953. "lightgreen": [144, 238, 144],
  11954. "lightgrey": [211, 211, 211],
  11955. "lightpink": [255, 182, 193],
  11956. "lightsalmon": [255, 160, 122],
  11957. "lightseagreen": [32, 178, 170],
  11958. "lightskyblue": [135, 206, 250],
  11959. "lightslategray": [119, 136, 153],
  11960. "lightslategrey": [119, 136, 153],
  11961. "lightsteelblue": [176, 196, 222],
  11962. "lightyellow": [255, 255, 224],
  11963. "lime": [0, 255, 0],
  11964. "limegreen": [50, 205, 50],
  11965. "linen": [250, 240, 230],
  11966. "magenta": [255, 0, 255],
  11967. "maroon": [128, 0, 0],
  11968. "mediumaquamarine": [102, 205, 170],
  11969. "mediumblue": [0, 0, 205],
  11970. "mediumorchid": [186, 85, 211],
  11971. "mediumpurple": [147, 112, 219],
  11972. "mediumseagreen": [60, 179, 113],
  11973. "mediumslateblue": [123, 104, 238],
  11974. "mediumspringgreen": [0, 250, 154],
  11975. "mediumturquoise": [72, 209, 204],
  11976. "mediumvioletred": [199, 21, 133],
  11977. "midnightblue": [25, 25, 112],
  11978. "mintcream": [245, 255, 250],
  11979. "mistyrose": [255, 228, 225],
  11980. "moccasin": [255, 228, 181],
  11981. "navajowhite": [255, 222, 173],
  11982. "navy": [0, 0, 128],
  11983. "oldlace": [253, 245, 230],
  11984. "olive": [128, 128, 0],
  11985. "olivedrab": [107, 142, 35],
  11986. "orange": [255, 165, 0],
  11987. "orangered": [255, 69, 0],
  11988. "orchid": [218, 112, 214],
  11989. "palegoldenrod": [238, 232, 170],
  11990. "palegreen": [152, 251, 152],
  11991. "paleturquoise": [175, 238, 238],
  11992. "palevioletred": [219, 112, 147],
  11993. "papayawhip": [255, 239, 213],
  11994. "peachpuff": [255, 218, 185],
  11995. "peru": [205, 133, 63],
  11996. "pink": [255, 192, 203],
  11997. "plum": [221, 160, 221],
  11998. "powderblue": [176, 224, 230],
  11999. "purple": [128, 0, 128],
  12000. "rebeccapurple": [102, 51, 153],
  12001. "red": [255, 0, 0],
  12002. "rosybrown": [188, 143, 143],
  12003. "royalblue": [65, 105, 225],
  12004. "saddlebrown": [139, 69, 19],
  12005. "salmon": [250, 128, 114],
  12006. "sandybrown": [244, 164, 96],
  12007. "seagreen": [46, 139, 87],
  12008. "seashell": [255, 245, 238],
  12009. "sienna": [160, 82, 45],
  12010. "silver": [192, 192, 192],
  12011. "skyblue": [135, 206, 235],
  12012. "slateblue": [106, 90, 205],
  12013. "slategray": [112, 128, 144],
  12014. "slategrey": [112, 128, 144],
  12015. "snow": [255, 250, 250],
  12016. "springgreen": [0, 255, 127],
  12017. "steelblue": [70, 130, 180],
  12018. "tan": [210, 180, 140],
  12019. "teal": [0, 128, 128],
  12020. "thistle": [216, 191, 216],
  12021. "tomato": [255, 99, 71],
  12022. "turquoise": [64, 224, 208],
  12023. "violet": [238, 130, 238],
  12024. "wheat": [245, 222, 179],
  12025. "white": [255, 255, 255],
  12026. "whitesmoke": [245, 245, 245],
  12027. "yellow": [255, 255, 0],
  12028. "yellowgreen": [154, 205, 50]
  12029. };
  12030. module.exports = Color;
  12031. },{}],4:[function(_dereq_,module,exports){
  12032. var Support = _dereq_('./support');
  12033. var CanvasRenderer = _dereq_('./renderers/canvas');
  12034. var ImageLoader = _dereq_('./imageloader');
  12035. var NodeParser = _dereq_('./nodeparser');
  12036. var NodeContainer = _dereq_('./nodecontainer');
  12037. var log = _dereq_('./log');
  12038. var utils = _dereq_('./utils');
  12039. var createWindowClone = _dereq_('./clone');
  12040. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  12041. var getBounds = utils.getBounds;
  12042. var html2canvasNodeAttribute = "data-html2canvas-node";
  12043. var html2canvasCloneIndex = 0;
  12044. function html2canvas(nodeList, options) {
  12045. var index = html2canvasCloneIndex++;
  12046. options = options || {};
  12047. if (options.logging) {
  12048. log.options.logging = true;
  12049. log.options.start = Date.now();
  12050. }
  12051. options.async = typeof(options.async) === "undefined" ? true : options.async;
  12052. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  12053. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  12054. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  12055. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  12056. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  12057. options.strict = !!options.strict;
  12058. if (typeof(nodeList) === "string") {
  12059. if (typeof(options.proxy) !== "string") {
  12060. return Promise.reject("Proxy must be used when rendering url");
  12061. }
  12062. var width = options.width != null ? options.width : window.innerWidth;
  12063. var height = options.height != null ? options.height : window.innerHeight;
  12064. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  12065. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  12066. });
  12067. }
  12068. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  12069. node.setAttribute(html2canvasNodeAttribute + index, index);
  12070. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  12071. if (typeof(options.onrendered) === "function") {
  12072. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  12073. options.onrendered(canvas);
  12074. }
  12075. return canvas;
  12076. });
  12077. }
  12078. html2canvas.CanvasRenderer = CanvasRenderer;
  12079. html2canvas.NodeContainer = NodeContainer;
  12080. html2canvas.log = log;
  12081. html2canvas.utils = utils;
  12082. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  12083. return Promise.reject("No canvas support");
  12084. } : html2canvas;
  12085. module.exports = html2canvasExport;
  12086. if (typeof(define) === 'function' && define.amd) {
  12087. define('html2canvas', [], function() {
  12088. return html2canvasExport;
  12089. });
  12090. }
  12091. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  12092. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  12093. log("Document cloned");
  12094. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  12095. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  12096. document.querySelector(selector).removeAttribute(attributeName);
  12097. var clonedWindow = container.contentWindow;
  12098. var node = clonedWindow.document.querySelector(selector);
  12099. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  12100. return oncloneHandler.then(function() {
  12101. return renderWindow(node, container, options, windowWidth, windowHeight);
  12102. });
  12103. });
  12104. }
  12105. function renderWindow(node, container, options, windowWidth, windowHeight) {
  12106. var clonedWindow = container.contentWindow;
  12107. var support = new Support(clonedWindow.document);
  12108. var imageLoader = new ImageLoader(options, support);
  12109. var bounds = getBounds(node);
  12110. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  12111. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  12112. var renderer = new options.renderer(width, height, imageLoader, options, document);
  12113. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  12114. return parser.ready.then(function() {
  12115. log("Finished rendering");
  12116. var canvas;
  12117. if (options.type === "view") {
  12118. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  12119. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  12120. canvas = renderer.canvas;
  12121. } else {
  12122. canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
  12123. }
  12124. cleanupContainer(container, options);
  12125. return canvas;
  12126. });
  12127. }
  12128. function cleanupContainer(container, options) {
  12129. if (options.removeContainer) {
  12130. container.parentNode.removeChild(container);
  12131. log("Cleaned up container");
  12132. }
  12133. }
  12134. function crop(canvas, bounds) {
  12135. var croppedCanvas = document.createElement("canvas");
  12136. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  12137. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  12138. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  12139. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  12140. croppedCanvas.width = bounds.width;
  12141. croppedCanvas.height = bounds.height;
  12142. var width = x2-x1;
  12143. var height = y2-y1;
  12144. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  12145. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  12146. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  12147. return croppedCanvas;
  12148. }
  12149. function documentWidth (doc) {
  12150. return Math.max(
  12151. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  12152. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  12153. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  12154. );
  12155. }
  12156. function documentHeight (doc) {
  12157. return Math.max(
  12158. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  12159. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  12160. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  12161. );
  12162. }
  12163. function absoluteUrl(url) {
  12164. var link = document.createElement("a");
  12165. link.href = url;
  12166. link.href = link.href;
  12167. return link;
  12168. }
  12169. },{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
  12170. var log = _dereq_('./log');
  12171. var smallImage = _dereq_('./utils').smallImage;
  12172. function DummyImageContainer(src) {
  12173. this.src = src;
  12174. log("DummyImageContainer for", src);
  12175. if (!this.promise || !this.image) {
  12176. log("Initiating DummyImageContainer");
  12177. DummyImageContainer.prototype.image = new Image();
  12178. var image = this.image;
  12179. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  12180. image.onload = resolve;
  12181. image.onerror = reject;
  12182. image.src = smallImage();
  12183. if (image.complete === true) {
  12184. resolve(image);
  12185. }
  12186. });
  12187. }
  12188. }
  12189. module.exports = DummyImageContainer;
  12190. },{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
  12191. var smallImage = _dereq_('./utils').smallImage;
  12192. function Font(family, size) {
  12193. var container = document.createElement('div'),
  12194. img = document.createElement('img'),
  12195. span = document.createElement('span'),
  12196. sampleText = 'Hidden Text',
  12197. baseline,
  12198. middle;
  12199. container.style.visibility = "hidden";
  12200. container.style.fontFamily = family;
  12201. container.style.fontSize = size;
  12202. container.style.margin = 0;
  12203. container.style.padding = 0;
  12204. document.body.appendChild(container);
  12205. img.src = smallImage();
  12206. img.width = 1;
  12207. img.height = 1;
  12208. img.style.margin = 0;
  12209. img.style.padding = 0;
  12210. img.style.verticalAlign = "baseline";
  12211. span.style.fontFamily = family;
  12212. span.style.fontSize = size;
  12213. span.style.margin = 0;
  12214. span.style.padding = 0;
  12215. span.appendChild(document.createTextNode(sampleText));
  12216. container.appendChild(span);
  12217. container.appendChild(img);
  12218. baseline = (img.offsetTop - span.offsetTop) + 1;
  12219. container.removeChild(span);
  12220. container.appendChild(document.createTextNode(sampleText));
  12221. container.style.lineHeight = "normal";
  12222. img.style.verticalAlign = "super";
  12223. middle = (img.offsetTop-container.offsetTop) + 1;
  12224. document.body.removeChild(container);
  12225. this.baseline = baseline;
  12226. this.lineWidth = 1;
  12227. this.middle = middle;
  12228. }
  12229. module.exports = Font;
  12230. },{"./utils":26}],7:[function(_dereq_,module,exports){
  12231. var Font = _dereq_('./font');
  12232. function FontMetrics() {
  12233. this.data = {};
  12234. }
  12235. FontMetrics.prototype.getMetrics = function(family, size) {
  12236. if (this.data[family + "-" + size] === undefined) {
  12237. this.data[family + "-" + size] = new Font(family, size);
  12238. }
  12239. return this.data[family + "-" + size];
  12240. };
  12241. module.exports = FontMetrics;
  12242. },{"./font":6}],8:[function(_dereq_,module,exports){
  12243. var utils = _dereq_('./utils');
  12244. var getBounds = utils.getBounds;
  12245. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  12246. function FrameContainer(container, sameOrigin, options) {
  12247. this.image = null;
  12248. this.src = container;
  12249. var self = this;
  12250. var bounds = getBounds(container);
  12251. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  12252. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  12253. container.contentWindow.onload = container.onload = function() {
  12254. resolve(container);
  12255. };
  12256. } else {
  12257. resolve(container);
  12258. }
  12259. })).then(function(container) {
  12260. var html2canvas = _dereq_('./core');
  12261. return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
  12262. }).then(function(canvas) {
  12263. return self.image = canvas;
  12264. });
  12265. }
  12266. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  12267. var container = this.src;
  12268. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  12269. };
  12270. module.exports = FrameContainer;
  12271. },{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
  12272. function GradientContainer(imageData) {
  12273. this.src = imageData.value;
  12274. this.colorStops = [];
  12275. this.type = null;
  12276. this.x0 = 0.5;
  12277. this.y0 = 0.5;
  12278. this.x1 = 0.5;
  12279. this.y1 = 0.5;
  12280. this.promise = Promise.resolve(true);
  12281. }
  12282. GradientContainer.TYPES = {
  12283. LINEAR: 1,
  12284. RADIAL: 2
  12285. };
  12286. // TODO: support hsl[a], negative %/length values
  12287. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12288. GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
  12289. module.exports = GradientContainer;
  12290. },{}],10:[function(_dereq_,module,exports){
  12291. function ImageContainer(src, cors) {
  12292. this.src = src;
  12293. this.image = new Image();
  12294. var self = this;
  12295. this.tainted = null;
  12296. this.promise = new Promise(function(resolve, reject) {
  12297. self.image.onload = resolve;
  12298. self.image.onerror = reject;
  12299. if (cors) {
  12300. self.image.crossOrigin = "anonymous";
  12301. }
  12302. self.image.src = src;
  12303. if (self.image.complete === true) {
  12304. resolve(self.image);
  12305. }
  12306. });
  12307. }
  12308. module.exports = ImageContainer;
  12309. },{}],11:[function(_dereq_,module,exports){
  12310. var log = _dereq_('./log');
  12311. var ImageContainer = _dereq_('./imagecontainer');
  12312. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  12313. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  12314. var FrameContainer = _dereq_('./framecontainer');
  12315. var SVGContainer = _dereq_('./svgcontainer');
  12316. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  12317. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  12318. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  12319. var bind = _dereq_('./utils').bind;
  12320. function ImageLoader(options, support) {
  12321. this.link = null;
  12322. this.options = options;
  12323. this.support = support;
  12324. this.origin = this.getOrigin(window.location.href);
  12325. }
  12326. ImageLoader.prototype.findImages = function(nodes) {
  12327. var images = [];
  12328. nodes.reduce(function(imageNodes, container) {
  12329. switch(container.node.nodeName) {
  12330. case "IMG":
  12331. return imageNodes.concat([{
  12332. args: [container.node.src],
  12333. method: "url"
  12334. }]);
  12335. case "svg":
  12336. case "IFRAME":
  12337. return imageNodes.concat([{
  12338. args: [container.node],
  12339. method: container.node.nodeName
  12340. }]);
  12341. }
  12342. return imageNodes;
  12343. }, []).forEach(this.addImage(images, this.loadImage), this);
  12344. return images;
  12345. };
  12346. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  12347. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  12348. return images;
  12349. };
  12350. ImageLoader.prototype.addImage = function(images, callback) {
  12351. return function(newImage) {
  12352. newImage.args.forEach(function(image) {
  12353. if (!this.imageExists(images, image)) {
  12354. images.splice(0, 0, callback.call(this, newImage));
  12355. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  12356. }
  12357. }, this);
  12358. };
  12359. };
  12360. ImageLoader.prototype.hasImageBackground = function(imageData) {
  12361. return imageData.method !== "none";
  12362. };
  12363. ImageLoader.prototype.loadImage = function(imageData) {
  12364. if (imageData.method === "url") {
  12365. var src = imageData.args[0];
  12366. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  12367. return new SVGContainer(src);
  12368. } else if (src.match(/data:image\/.*;base64,/i)) {
  12369. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  12370. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  12371. return new ImageContainer(src, false);
  12372. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  12373. return new ImageContainer(src, true);
  12374. } else if (this.options.proxy) {
  12375. return new ProxyImageContainer(src, this.options.proxy);
  12376. } else {
  12377. return new DummyImageContainer(src);
  12378. }
  12379. } else if (imageData.method === "linear-gradient") {
  12380. return new LinearGradientContainer(imageData);
  12381. } else if (imageData.method === "gradient") {
  12382. return new WebkitGradientContainer(imageData);
  12383. } else if (imageData.method === "svg") {
  12384. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  12385. } else if (imageData.method === "IFRAME") {
  12386. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  12387. } else {
  12388. return new DummyImageContainer(imageData);
  12389. }
  12390. };
  12391. ImageLoader.prototype.isSVG = function(src) {
  12392. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  12393. };
  12394. ImageLoader.prototype.imageExists = function(images, src) {
  12395. return images.some(function(image) {
  12396. return image.src === src;
  12397. });
  12398. };
  12399. ImageLoader.prototype.isSameOrigin = function(url) {
  12400. return (this.getOrigin(url) === this.origin);
  12401. };
  12402. ImageLoader.prototype.getOrigin = function(url) {
  12403. var link = this.link || (this.link = document.createElement("a"));
  12404. link.href = url;
  12405. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  12406. return link.protocol + link.hostname + link.port;
  12407. };
  12408. ImageLoader.prototype.getPromise = function(container) {
  12409. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  12410. var dummy = new DummyImageContainer(container.src);
  12411. return dummy.promise.then(function(image) {
  12412. container.image = image;
  12413. });
  12414. });
  12415. };
  12416. ImageLoader.prototype.get = function(src) {
  12417. var found = null;
  12418. return this.images.some(function(img) {
  12419. return (found = img).src === src;
  12420. }) ? found : null;
  12421. };
  12422. ImageLoader.prototype.fetch = function(nodes) {
  12423. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  12424. this.images.forEach(function(image, index) {
  12425. image.promise.then(function() {
  12426. log("Succesfully loaded image #"+ (index+1), image);
  12427. }, function(e) {
  12428. log("Failed loading image #"+ (index+1), image, e);
  12429. });
  12430. });
  12431. this.ready = Promise.all(this.images.map(this.getPromise, this));
  12432. log("Finished searching images");
  12433. return this;
  12434. };
  12435. ImageLoader.prototype.timeout = function(container, timeout) {
  12436. var timer;
  12437. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  12438. timer = setTimeout(function() {
  12439. log("Timed out loading image", container);
  12440. reject(container);
  12441. }, timeout);
  12442. })]).then(function(container) {
  12443. clearTimeout(timer);
  12444. return container;
  12445. });
  12446. promise['catch'](function() {
  12447. clearTimeout(timer);
  12448. });
  12449. return promise;
  12450. };
  12451. module.exports = ImageLoader;
  12452. },{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./utils":26,"./webkitgradientcontainer":27}],12:[function(_dereq_,module,exports){
  12453. var GradientContainer = _dereq_('./gradientcontainer');
  12454. var Color = _dereq_('./color');
  12455. function LinearGradientContainer(imageData) {
  12456. GradientContainer.apply(this, arguments);
  12457. this.type = GradientContainer.TYPES.LINEAR;
  12458. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
  12459. !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
  12460. if (hasDirection) {
  12461. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  12462. switch(position) {
  12463. case "left":
  12464. this.x0 = 0;
  12465. this.x1 = 1;
  12466. break;
  12467. case "top":
  12468. this.y0 = 0;
  12469. this.y1 = 1;
  12470. break;
  12471. case "right":
  12472. this.x0 = 1;
  12473. this.x1 = 0;
  12474. break;
  12475. case "bottom":
  12476. this.y0 = 1;
  12477. this.y1 = 0;
  12478. break;
  12479. case "to":
  12480. var y0 = this.y0;
  12481. var x0 = this.x0;
  12482. this.y0 = this.y1;
  12483. this.x0 = this.x1;
  12484. this.x1 = x0;
  12485. this.y1 = y0;
  12486. break;
  12487. case "center":
  12488. break; // centered by default
  12489. // Firefox internally converts position keywords to percentages:
  12490. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  12491. default: // percentage or absolute length
  12492. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  12493. var ratio = parseFloat(position, 10) * 1e-2;
  12494. if (isNaN(ratio)) { // invalid or unhandled value
  12495. break;
  12496. }
  12497. if (index === 0) {
  12498. this.y0 = ratio;
  12499. this.y1 = 1 - this.y0;
  12500. } else {
  12501. this.x0 = ratio;
  12502. this.x1 = 1 - this.x0;
  12503. }
  12504. break;
  12505. }
  12506. }, this);
  12507. } else {
  12508. this.y0 = 0;
  12509. this.y1 = 1;
  12510. }
  12511. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  12512. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  12513. var value = +colorStopMatch[2];
  12514. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  12515. return {
  12516. color: new Color(colorStopMatch[1]),
  12517. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  12518. stop: unit === "%" ? value / 100 : null
  12519. };
  12520. });
  12521. if (this.colorStops[0].stop === null) {
  12522. this.colorStops[0].stop = 0;
  12523. }
  12524. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  12525. this.colorStops[this.colorStops.length - 1].stop = 1;
  12526. }
  12527. // calculates and fills-in explicit stop positions when omitted from rule
  12528. this.colorStops.forEach(function(colorStop, index) {
  12529. if (colorStop.stop === null) {
  12530. this.colorStops.slice(index).some(function(find, count) {
  12531. if (find.stop !== null) {
  12532. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  12533. return true;
  12534. } else {
  12535. return false;
  12536. }
  12537. }, this);
  12538. }
  12539. }, this);
  12540. }
  12541. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  12542. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12543. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  12544. module.exports = LinearGradientContainer;
  12545. },{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
  12546. var logger = function() {
  12547. if (logger.options.logging && window.console && window.console.log) {
  12548. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  12549. }
  12550. };
  12551. logger.options = {logging: false};
  12552. module.exports = logger;
  12553. },{}],14:[function(_dereq_,module,exports){
  12554. var Color = _dereq_('./color');
  12555. var utils = _dereq_('./utils');
  12556. var getBounds = utils.getBounds;
  12557. var parseBackgrounds = utils.parseBackgrounds;
  12558. var offsetBounds = utils.offsetBounds;
  12559. function NodeContainer(node, parent) {
  12560. this.node = node;
  12561. this.parent = parent;
  12562. this.stack = null;
  12563. this.bounds = null;
  12564. this.borders = null;
  12565. this.clip = [];
  12566. this.backgroundClip = [];
  12567. this.offsetBounds = null;
  12568. this.visible = null;
  12569. this.computedStyles = null;
  12570. this.colors = {};
  12571. this.styles = {};
  12572. this.backgroundImages = null;
  12573. this.transformData = null;
  12574. this.transformMatrix = null;
  12575. this.isPseudoElement = false;
  12576. this.opacity = null;
  12577. }
  12578. NodeContainer.prototype.cloneTo = function(stack) {
  12579. stack.visible = this.visible;
  12580. stack.borders = this.borders;
  12581. stack.bounds = this.bounds;
  12582. stack.clip = this.clip;
  12583. stack.backgroundClip = this.backgroundClip;
  12584. stack.computedStyles = this.computedStyles;
  12585. stack.styles = this.styles;
  12586. stack.backgroundImages = this.backgroundImages;
  12587. stack.opacity = this.opacity;
  12588. };
  12589. NodeContainer.prototype.getOpacity = function() {
  12590. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  12591. };
  12592. NodeContainer.prototype.assignStack = function(stack) {
  12593. this.stack = stack;
  12594. stack.children.push(this);
  12595. };
  12596. NodeContainer.prototype.isElementVisible = function() {
  12597. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  12598. this.css('display') !== "none" &&
  12599. this.css('visibility') !== "hidden" &&
  12600. !this.node.hasAttribute("data-html2canvas-ignore") &&
  12601. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  12602. );
  12603. };
  12604. NodeContainer.prototype.css = function(attribute) {
  12605. if (!this.computedStyles) {
  12606. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  12607. }
  12608. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  12609. };
  12610. NodeContainer.prototype.prefixedCss = function(attribute) {
  12611. var prefixes = ["webkit", "moz", "ms", "o"];
  12612. var value = this.css(attribute);
  12613. if (value === undefined) {
  12614. prefixes.some(function(prefix) {
  12615. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  12616. return value !== undefined;
  12617. }, this);
  12618. }
  12619. return value === undefined ? null : value;
  12620. };
  12621. NodeContainer.prototype.computedStyle = function(type) {
  12622. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  12623. };
  12624. NodeContainer.prototype.cssInt = function(attribute) {
  12625. var value = parseInt(this.css(attribute), 10);
  12626. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  12627. };
  12628. NodeContainer.prototype.color = function(attribute) {
  12629. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  12630. };
  12631. NodeContainer.prototype.cssFloat = function(attribute) {
  12632. var value = parseFloat(this.css(attribute));
  12633. return (isNaN(value)) ? 0 : value;
  12634. };
  12635. NodeContainer.prototype.fontWeight = function() {
  12636. var weight = this.css("fontWeight");
  12637. switch(parseInt(weight, 10)){
  12638. case 401:
  12639. weight = "bold";
  12640. break;
  12641. case 400:
  12642. weight = "normal";
  12643. break;
  12644. }
  12645. return weight;
  12646. };
  12647. NodeContainer.prototype.parseClip = function() {
  12648. var matches = this.css('clip').match(this.CLIP);
  12649. if (matches) {
  12650. return {
  12651. top: parseInt(matches[1], 10),
  12652. right: parseInt(matches[2], 10),
  12653. bottom: parseInt(matches[3], 10),
  12654. left: parseInt(matches[4], 10)
  12655. };
  12656. }
  12657. return null;
  12658. };
  12659. NodeContainer.prototype.parseBackgroundImages = function() {
  12660. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  12661. };
  12662. NodeContainer.prototype.cssList = function(property, index) {
  12663. var value = (this.css(property) || '').split(',');
  12664. value = value[index || 0] || value[0] || 'auto';
  12665. value = value.trim().split(' ');
  12666. if (value.length === 1) {
  12667. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  12668. }
  12669. return value;
  12670. };
  12671. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  12672. var size = this.cssList("backgroundSize", index);
  12673. var width, height;
  12674. if (isPercentage(size[0])) {
  12675. width = bounds.width * parseFloat(size[0]) / 100;
  12676. } else if (/contain|cover/.test(size[0])) {
  12677. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  12678. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  12679. } else {
  12680. width = parseInt(size[0], 10);
  12681. }
  12682. if (size[0] === 'auto' && size[1] === 'auto') {
  12683. height = image.height;
  12684. } else if (size[1] === 'auto') {
  12685. height = width / image.width * image.height;
  12686. } else if (isPercentage(size[1])) {
  12687. height = bounds.height * parseFloat(size[1]) / 100;
  12688. } else {
  12689. height = parseInt(size[1], 10);
  12690. }
  12691. if (size[0] === 'auto') {
  12692. width = height / image.height * image.width;
  12693. }
  12694. return {width: width, height: height};
  12695. };
  12696. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  12697. var position = this.cssList('backgroundPosition', index);
  12698. var left, top;
  12699. if (isPercentage(position[0])){
  12700. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  12701. } else {
  12702. left = parseInt(position[0], 10);
  12703. }
  12704. if (position[1] === 'auto') {
  12705. top = left / image.width * image.height;
  12706. } else if (isPercentage(position[1])){
  12707. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  12708. } else {
  12709. top = parseInt(position[1], 10);
  12710. }
  12711. if (position[0] === 'auto') {
  12712. left = top / image.height * image.width;
  12713. }
  12714. return {left: left, top: top};
  12715. };
  12716. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  12717. return this.cssList("backgroundRepeat", index)[0];
  12718. };
  12719. NodeContainer.prototype.parseTextShadows = function() {
  12720. var textShadow = this.css("textShadow");
  12721. var results = [];
  12722. if (textShadow && textShadow !== 'none') {
  12723. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  12724. for (var i = 0; shadows && (i < shadows.length); i++) {
  12725. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  12726. results.push({
  12727. color: new Color(s[0]),
  12728. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  12729. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  12730. blur: s[3] ? s[3].replace('px', '') : 0
  12731. });
  12732. }
  12733. }
  12734. return results;
  12735. };
  12736. NodeContainer.prototype.parseTransform = function() {
  12737. if (!this.transformData) {
  12738. if (this.hasTransform()) {
  12739. var offset = this.parseBounds();
  12740. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  12741. origin[0] += offset.left;
  12742. origin[1] += offset.top;
  12743. this.transformData = {
  12744. origin: origin,
  12745. matrix: this.parseTransformMatrix()
  12746. };
  12747. } else {
  12748. this.transformData = {
  12749. origin: [0, 0],
  12750. matrix: [1, 0, 0, 1, 0, 0]
  12751. };
  12752. }
  12753. }
  12754. return this.transformData;
  12755. };
  12756. NodeContainer.prototype.parseTransformMatrix = function() {
  12757. if (!this.transformMatrix) {
  12758. var transform = this.prefixedCss("transform");
  12759. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  12760. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  12761. }
  12762. return this.transformMatrix;
  12763. };
  12764. NodeContainer.prototype.parseBounds = function() {
  12765. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  12766. };
  12767. NodeContainer.prototype.hasTransform = function() {
  12768. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  12769. };
  12770. NodeContainer.prototype.getValue = function() {
  12771. var value = this.node.value || "";
  12772. if (this.node.tagName === "SELECT") {
  12773. value = selectionValue(this.node);
  12774. } else if (this.node.type === "password") {
  12775. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  12776. }
  12777. return value.length === 0 ? (this.node.placeholder || "") : value;
  12778. };
  12779. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  12780. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  12781. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  12782. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  12783. function selectionValue(node) {
  12784. var option = node.options[node.selectedIndex || 0];
  12785. return option ? (option.text || "") : "";
  12786. }
  12787. function parseMatrix(match) {
  12788. if (match && match[1] === "matrix") {
  12789. return match[2].split(",").map(function(s) {
  12790. return parseFloat(s.trim());
  12791. });
  12792. } else if (match && match[1] === "matrix3d") {
  12793. var matrix3d = match[2].split(",").map(function(s) {
  12794. return parseFloat(s.trim());
  12795. });
  12796. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  12797. }
  12798. }
  12799. function isPercentage(value) {
  12800. return value.toString().indexOf("%") !== -1;
  12801. }
  12802. function removePx(str) {
  12803. return str.replace("px", "");
  12804. }
  12805. function asFloat(str) {
  12806. return parseFloat(str);
  12807. }
  12808. module.exports = NodeContainer;
  12809. },{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
  12810. var log = _dereq_('./log');
  12811. var punycode = _dereq_('punycode');
  12812. var NodeContainer = _dereq_('./nodecontainer');
  12813. var TextContainer = _dereq_('./textcontainer');
  12814. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  12815. var FontMetrics = _dereq_('./fontmetrics');
  12816. var Color = _dereq_('./color');
  12817. var StackingContext = _dereq_('./stackingcontext');
  12818. var utils = _dereq_('./utils');
  12819. var bind = utils.bind;
  12820. var getBounds = utils.getBounds;
  12821. var parseBackgrounds = utils.parseBackgrounds;
  12822. var offsetBounds = utils.offsetBounds;
  12823. function NodeParser(element, renderer, support, imageLoader, options) {
  12824. log("Starting NodeParser");
  12825. this.renderer = renderer;
  12826. this.options = options;
  12827. this.range = null;
  12828. this.support = support;
  12829. this.renderQueue = [];
  12830. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  12831. var parent = new NodeContainer(element, null);
  12832. if (options.background) {
  12833. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  12834. }
  12835. if (element === element.ownerDocument.documentElement) {
  12836. // http://www.w3.org/TR/css3-background/#special-backgrounds
  12837. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  12838. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  12839. }
  12840. parent.visibile = parent.isElementVisible();
  12841. this.createPseudoHideStyles(element.ownerDocument);
  12842. this.disableAnimations(element.ownerDocument);
  12843. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  12844. return container.visible = container.isElementVisible();
  12845. }).map(this.getPseudoElements, this));
  12846. this.fontMetrics = new FontMetrics();
  12847. log("Fetched nodes, total:", this.nodes.length);
  12848. log("Calculate overflow clips");
  12849. this.calculateOverflowClips();
  12850. log("Start fetching images");
  12851. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  12852. this.ready = this.images.ready.then(bind(function() {
  12853. log("Images loaded, starting parsing");
  12854. log("Creating stacking contexts");
  12855. this.createStackingContexts();
  12856. log("Sorting stacking contexts");
  12857. this.sortStackingContexts(this.stack);
  12858. this.parse(this.stack);
  12859. log("Render queue created with " + this.renderQueue.length + " items");
  12860. return new Promise(bind(function(resolve) {
  12861. if (!options.async) {
  12862. this.renderQueue.forEach(this.paint, this);
  12863. resolve();
  12864. } else if (typeof(options.async) === "function") {
  12865. options.async.call(this, this.renderQueue, resolve);
  12866. } else if (this.renderQueue.length > 0){
  12867. this.renderIndex = 0;
  12868. this.asyncRenderer(this.renderQueue, resolve);
  12869. } else {
  12870. resolve();
  12871. }
  12872. }, this));
  12873. }, this));
  12874. }
  12875. NodeParser.prototype.calculateOverflowClips = function() {
  12876. this.nodes.forEach(function(container) {
  12877. if (isElement(container)) {
  12878. if (isPseudoElement(container)) {
  12879. container.appendToDOM();
  12880. }
  12881. container.borders = this.parseBorders(container);
  12882. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  12883. var cssClip = container.parseClip();
  12884. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  12885. clip.push([["rect",
  12886. container.bounds.left + cssClip.left,
  12887. container.bounds.top + cssClip.top,
  12888. cssClip.right - cssClip.left,
  12889. cssClip.bottom - cssClip.top
  12890. ]]);
  12891. }
  12892. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  12893. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  12894. if (isPseudoElement(container)) {
  12895. container.cleanDOM();
  12896. }
  12897. } else if (isTextNode(container)) {
  12898. container.clip = hasParentClip(container) ? container.parent.clip : [];
  12899. }
  12900. if (!isPseudoElement(container)) {
  12901. container.bounds = null;
  12902. }
  12903. }, this);
  12904. };
  12905. function hasParentClip(container) {
  12906. return container.parent && container.parent.clip.length;
  12907. }
  12908. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  12909. asyncTimer = asyncTimer || Date.now();
  12910. this.paint(queue[this.renderIndex++]);
  12911. if (queue.length === this.renderIndex) {
  12912. resolve();
  12913. } else if (asyncTimer + 20 > Date.now()) {
  12914. this.asyncRenderer(queue, resolve, asyncTimer);
  12915. } else {
  12916. setTimeout(bind(function() {
  12917. this.asyncRenderer(queue, resolve);
  12918. }, this), 0);
  12919. }
  12920. };
  12921. NodeParser.prototype.createPseudoHideStyles = function(document) {
  12922. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  12923. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  12924. };
  12925. NodeParser.prototype.disableAnimations = function(document) {
  12926. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  12927. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  12928. };
  12929. NodeParser.prototype.createStyles = function(document, styles) {
  12930. var hidePseudoElements = document.createElement('style');
  12931. hidePseudoElements.innerHTML = styles;
  12932. document.body.appendChild(hidePseudoElements);
  12933. };
  12934. NodeParser.prototype.getPseudoElements = function(container) {
  12935. var nodes = [[container]];
  12936. if (container.node.nodeType === Node.ELEMENT_NODE) {
  12937. var before = this.getPseudoElement(container, ":before");
  12938. var after = this.getPseudoElement(container, ":after");
  12939. if (before) {
  12940. nodes.push(before);
  12941. }
  12942. if (after) {
  12943. nodes.push(after);
  12944. }
  12945. }
  12946. return flatten(nodes);
  12947. };
  12948. function toCamelCase(str) {
  12949. return str.replace(/(\-[a-z])/g, function(match){
  12950. return match.toUpperCase().replace('-','');
  12951. });
  12952. }
  12953. NodeParser.prototype.getPseudoElement = function(container, type) {
  12954. var style = container.computedStyle(type);
  12955. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  12956. return null;
  12957. }
  12958. var content = stripQuotes(style.content);
  12959. var isImage = content.substr(0, 3) === 'url';
  12960. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  12961. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  12962. for (var i = style.length-1; i >= 0; i--) {
  12963. var property = toCamelCase(style.item(i));
  12964. pseudoNode.style[property] = style[property];
  12965. }
  12966. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  12967. if (isImage) {
  12968. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  12969. return [pseudoContainer];
  12970. } else {
  12971. var text = document.createTextNode(content);
  12972. pseudoNode.appendChild(text);
  12973. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  12974. }
  12975. };
  12976. NodeParser.prototype.getChildren = function(parentContainer) {
  12977. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  12978. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  12979. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  12980. }, this));
  12981. };
  12982. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  12983. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  12984. container.cloneTo(stack);
  12985. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  12986. parentStack.contexts.push(stack);
  12987. container.stack = stack;
  12988. };
  12989. NodeParser.prototype.createStackingContexts = function() {
  12990. this.nodes.forEach(function(container) {
  12991. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  12992. this.newStackingContext(container, true);
  12993. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  12994. this.newStackingContext(container, false);
  12995. } else {
  12996. container.assignStack(container.parent.stack);
  12997. }
  12998. }, this);
  12999. };
  13000. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  13001. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  13002. };
  13003. NodeParser.prototype.isRootElement = function(container) {
  13004. return container.parent === null;
  13005. };
  13006. NodeParser.prototype.sortStackingContexts = function(stack) {
  13007. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  13008. stack.contexts.forEach(this.sortStackingContexts, this);
  13009. };
  13010. NodeParser.prototype.parseTextBounds = function(container) {
  13011. return function(text, index, textList) {
  13012. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  13013. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  13014. var offset = textList.slice(0, index).join("").length;
  13015. return this.getRangeBounds(container.node, offset, text.length);
  13016. } else if (container.node && typeof(container.node.data) === "string") {
  13017. var replacementNode = container.node.splitText(text.length);
  13018. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  13019. container.node = replacementNode;
  13020. return bounds;
  13021. }
  13022. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  13023. container.node = container.node.splitText(text.length);
  13024. }
  13025. return {};
  13026. };
  13027. };
  13028. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  13029. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  13030. var parent = node.parentNode,
  13031. backupText = node.cloneNode(true);
  13032. wrapper.appendChild(node.cloneNode(true));
  13033. parent.replaceChild(wrapper, node);
  13034. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  13035. parent.replaceChild(backupText, wrapper);
  13036. return bounds;
  13037. };
  13038. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  13039. var range = this.range || (this.range = node.ownerDocument.createRange());
  13040. range.setStart(node, offset);
  13041. range.setEnd(node, offset + length);
  13042. return range.getBoundingClientRect();
  13043. };
  13044. function ClearTransform() {}
  13045. NodeParser.prototype.parse = function(stack) {
  13046. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  13047. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  13048. var descendantElements = stack.children.filter(isElement);
  13049. var descendantNonFloats = descendantElements.filter(not(isFloating));
  13050. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  13051. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  13052. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  13053. var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  13054. var text = stack.children.filter(isTextNode).filter(hasText);
  13055. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  13056. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  13057. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  13058. this.renderQueue.push(container);
  13059. if (isStackingContext(container)) {
  13060. this.parse(container);
  13061. this.renderQueue.push(new ClearTransform());
  13062. }
  13063. }, this);
  13064. };
  13065. NodeParser.prototype.paint = function(container) {
  13066. try {
  13067. if (container instanceof ClearTransform) {
  13068. this.renderer.ctx.restore();
  13069. } else if (isTextNode(container)) {
  13070. if (isPseudoElement(container.parent)) {
  13071. container.parent.appendToDOM();
  13072. }
  13073. this.paintText(container);
  13074. if (isPseudoElement(container.parent)) {
  13075. container.parent.cleanDOM();
  13076. }
  13077. } else {
  13078. this.paintNode(container);
  13079. }
  13080. } catch(e) {
  13081. log(e);
  13082. if (this.options.strict) {
  13083. throw e;
  13084. }
  13085. }
  13086. };
  13087. NodeParser.prototype.paintNode = function(container) {
  13088. if (isStackingContext(container)) {
  13089. this.renderer.setOpacity(container.opacity);
  13090. this.renderer.ctx.save();
  13091. if (container.hasTransform()) {
  13092. this.renderer.setTransform(container.parseTransform());
  13093. }
  13094. }
  13095. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  13096. this.paintCheckbox(container);
  13097. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  13098. this.paintRadio(container);
  13099. } else {
  13100. this.paintElement(container);
  13101. }
  13102. };
  13103. NodeParser.prototype.paintElement = function(container) {
  13104. var bounds = container.parseBounds();
  13105. this.renderer.clip(container.backgroundClip, function() {
  13106. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  13107. }, this);
  13108. this.renderer.clip(container.clip, function() {
  13109. this.renderer.renderBorders(container.borders.borders);
  13110. }, this);
  13111. this.renderer.clip(container.backgroundClip, function() {
  13112. switch (container.node.nodeName) {
  13113. case "svg":
  13114. case "IFRAME":
  13115. var imgContainer = this.images.get(container.node);
  13116. if (imgContainer) {
  13117. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  13118. } else {
  13119. log("Error loading <" + container.node.nodeName + ">", container.node);
  13120. }
  13121. break;
  13122. case "IMG":
  13123. var imageContainer = this.images.get(container.node.src);
  13124. if (imageContainer) {
  13125. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  13126. } else {
  13127. log("Error loading <img>", container.node.src);
  13128. }
  13129. break;
  13130. case "CANVAS":
  13131. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  13132. break;
  13133. case "SELECT":
  13134. case "INPUT":
  13135. case "TEXTAREA":
  13136. this.paintFormValue(container);
  13137. break;
  13138. }
  13139. }, this);
  13140. };
  13141. NodeParser.prototype.paintCheckbox = function(container) {
  13142. var b = container.parseBounds();
  13143. var size = Math.min(b.width, b.height);
  13144. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  13145. var r = [3, 3];
  13146. var radius = [r, r, r, r];
  13147. var borders = [1,1,1,1].map(function(w) {
  13148. return {color: new Color('#A5A5A5'), width: w};
  13149. });
  13150. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  13151. this.renderer.clip(container.backgroundClip, function() {
  13152. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  13153. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  13154. if (container.node.checked) {
  13155. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  13156. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  13157. }
  13158. }, this);
  13159. };
  13160. NodeParser.prototype.paintRadio = function(container) {
  13161. var bounds = container.parseBounds();
  13162. var size = Math.min(bounds.width, bounds.height) - 2;
  13163. this.renderer.clip(container.backgroundClip, function() {
  13164. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  13165. if (container.node.checked) {
  13166. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  13167. }
  13168. }, this);
  13169. };
  13170. NodeParser.prototype.paintFormValue = function(container) {
  13171. var value = container.getValue();
  13172. if (value.length > 0) {
  13173. var document = container.node.ownerDocument;
  13174. var wrapper = document.createElement('html2canvaswrapper');
  13175. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  13176. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  13177. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  13178. 'boxSizing', 'whiteSpace', 'wordWrap'];
  13179. properties.forEach(function(property) {
  13180. try {
  13181. wrapper.style[property] = container.css(property);
  13182. } catch(e) {
  13183. // Older IE has issues with "border"
  13184. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  13185. }
  13186. });
  13187. var bounds = container.parseBounds();
  13188. wrapper.style.position = "fixed";
  13189. wrapper.style.left = bounds.left + "px";
  13190. wrapper.style.top = bounds.top + "px";
  13191. wrapper.textContent = value;
  13192. document.body.appendChild(wrapper);
  13193. this.paintText(new TextContainer(wrapper.firstChild, container));
  13194. document.body.removeChild(wrapper);
  13195. }
  13196. };
  13197. NodeParser.prototype.paintText = function(container) {
  13198. container.applyTextTransform();
  13199. var characters = punycode.ucs2.decode(container.node.data);
  13200. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  13201. return punycode.ucs2.encode([character]);
  13202. });
  13203. var weight = container.parent.fontWeight();
  13204. var size = container.parent.css('fontSize');
  13205. var family = container.parent.css('fontFamily');
  13206. var shadows = container.parent.parseTextShadows();
  13207. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  13208. if (shadows.length) {
  13209. // TODO: support multiple text shadows
  13210. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  13211. } else {
  13212. this.renderer.clearShadow();
  13213. }
  13214. this.renderer.clip(container.parent.clip, function() {
  13215. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  13216. if (bounds) {
  13217. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  13218. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  13219. }
  13220. }, this);
  13221. }, this);
  13222. };
  13223. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  13224. switch(container.css("textDecoration").split(" ")[0]) {
  13225. case "underline":
  13226. // Draws a line at the baseline of the font
  13227. // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
  13228. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13229. break;
  13230. case "overline":
  13231. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  13232. break;
  13233. case "line-through":
  13234. // TODO try and find exact position for line-through
  13235. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13236. break;
  13237. }
  13238. };
  13239. var borderColorTransforms = {
  13240. inset: [
  13241. ["darken", 0.60],
  13242. ["darken", 0.10],
  13243. ["darken", 0.10],
  13244. ["darken", 0.60]
  13245. ]
  13246. };
  13247. NodeParser.prototype.parseBorders = function(container) {
  13248. var nodeBounds = container.parseBounds();
  13249. var radius = getBorderRadiusData(container);
  13250. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  13251. var style = container.css('border' + side + 'Style');
  13252. var color = container.color('border' + side + 'Color');
  13253. if (style === "inset" && color.isBlack()) {
  13254. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  13255. }
  13256. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  13257. return {
  13258. width: container.cssInt('border' + side + 'Width'),
  13259. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  13260. args: null
  13261. };
  13262. });
  13263. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  13264. return {
  13265. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  13266. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  13267. };
  13268. };
  13269. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  13270. return borders.map(function(border, borderSide) {
  13271. if (border.width > 0) {
  13272. var bx = nodeBounds.left;
  13273. var by = nodeBounds.top;
  13274. var bw = nodeBounds.width;
  13275. var bh = nodeBounds.height - (borders[2].width);
  13276. switch(borderSide) {
  13277. case 0:
  13278. // top border
  13279. bh = borders[0].width;
  13280. border.args = drawSide({
  13281. c1: [bx, by],
  13282. c2: [bx + bw, by],
  13283. c3: [bx + bw - borders[1].width, by + bh],
  13284. c4: [bx + borders[3].width, by + bh]
  13285. }, radius[0], radius[1],
  13286. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  13287. break;
  13288. case 1:
  13289. // right border
  13290. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  13291. bw = borders[1].width;
  13292. border.args = drawSide({
  13293. c1: [bx + bw, by],
  13294. c2: [bx + bw, by + bh + borders[2].width],
  13295. c3: [bx, by + bh],
  13296. c4: [bx, by + borders[0].width]
  13297. }, radius[1], radius[2],
  13298. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  13299. break;
  13300. case 2:
  13301. // bottom border
  13302. by = (by + nodeBounds.height) - (borders[2].width);
  13303. bh = borders[2].width;
  13304. border.args = drawSide({
  13305. c1: [bx + bw, by + bh],
  13306. c2: [bx, by + bh],
  13307. c3: [bx + borders[3].width, by],
  13308. c4: [bx + bw - borders[3].width, by]
  13309. }, radius[2], radius[3],
  13310. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  13311. break;
  13312. case 3:
  13313. // left border
  13314. bw = borders[3].width;
  13315. border.args = drawSide({
  13316. c1: [bx, by + bh + borders[2].width],
  13317. c2: [bx, by],
  13318. c3: [bx + bw, by + borders[0].width],
  13319. c4: [bx + bw, by + bh]
  13320. }, radius[3], radius[0],
  13321. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  13322. break;
  13323. }
  13324. }
  13325. return border;
  13326. });
  13327. }
  13328. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  13329. var backgroundClip = container.css('backgroundClip'),
  13330. borderArgs = [];
  13331. switch(backgroundClip) {
  13332. case "content-box":
  13333. case "padding-box":
  13334. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  13335. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  13336. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  13337. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  13338. break;
  13339. default:
  13340. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  13341. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  13342. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  13343. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  13344. break;
  13345. }
  13346. return borderArgs;
  13347. };
  13348. function getCurvePoints(x, y, r1, r2) {
  13349. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  13350. var ox = (r1) * kappa, // control point offset horizontal
  13351. oy = (r2) * kappa, // control point offset vertical
  13352. xm = x + r1, // x-middle
  13353. ym = y + r2; // y-middle
  13354. return {
  13355. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  13356. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  13357. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  13358. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  13359. };
  13360. }
  13361. function calculateCurvePoints(bounds, borderRadius, borders) {
  13362. var x = bounds.left,
  13363. y = bounds.top,
  13364. width = bounds.width,
  13365. height = bounds.height,
  13366. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  13367. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  13368. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  13369. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  13370. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  13371. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  13372. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  13373. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  13374. var topWidth = width - trh,
  13375. rightHeight = height - brv,
  13376. bottomWidth = width - brh,
  13377. leftHeight = height - blv;
  13378. return {
  13379. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  13380. topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
  13381. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  13382. topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
  13383. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  13384. bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
  13385. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  13386. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  13387. };
  13388. }
  13389. function bezierCurve(start, startControl, endControl, end) {
  13390. var lerp = function (a, b, t) {
  13391. return {
  13392. x: a.x + (b.x - a.x) * t,
  13393. y: a.y + (b.y - a.y) * t
  13394. };
  13395. };
  13396. return {
  13397. start: start,
  13398. startControl: startControl,
  13399. endControl: endControl,
  13400. end: end,
  13401. subdivide: function(t) {
  13402. var ab = lerp(start, startControl, t),
  13403. bc = lerp(startControl, endControl, t),
  13404. cd = lerp(endControl, end, t),
  13405. abbc = lerp(ab, bc, t),
  13406. bccd = lerp(bc, cd, t),
  13407. dest = lerp(abbc, bccd, t);
  13408. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  13409. },
  13410. curveTo: function(borderArgs) {
  13411. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  13412. },
  13413. curveToReversed: function(borderArgs) {
  13414. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  13415. }
  13416. };
  13417. }
  13418. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  13419. var borderArgs = [];
  13420. if (radius1[0] > 0 || radius1[1] > 0) {
  13421. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  13422. outer1[1].curveTo(borderArgs);
  13423. } else {
  13424. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  13425. }
  13426. if (radius2[0] > 0 || radius2[1] > 0) {
  13427. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  13428. outer2[0].curveTo(borderArgs);
  13429. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  13430. inner2[0].curveToReversed(borderArgs);
  13431. } else {
  13432. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  13433. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  13434. }
  13435. if (radius1[0] > 0 || radius1[1] > 0) {
  13436. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  13437. inner1[1].curveToReversed(borderArgs);
  13438. } else {
  13439. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  13440. }
  13441. return borderArgs;
  13442. }
  13443. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  13444. if (radius1[0] > 0 || radius1[1] > 0) {
  13445. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  13446. corner1[0].curveTo(borderArgs);
  13447. corner1[1].curveTo(borderArgs);
  13448. } else {
  13449. borderArgs.push(["line", x, y]);
  13450. }
  13451. if (radius2[0] > 0 || radius2[1] > 0) {
  13452. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  13453. }
  13454. }
  13455. function negativeZIndex(container) {
  13456. return container.cssInt("zIndex") < 0;
  13457. }
  13458. function positiveZIndex(container) {
  13459. return container.cssInt("zIndex") > 0;
  13460. }
  13461. function zIndex0(container) {
  13462. return container.cssInt("zIndex") === 0;
  13463. }
  13464. function inlineLevel(container) {
  13465. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13466. }
  13467. function isStackingContext(container) {
  13468. return (container instanceof StackingContext);
  13469. }
  13470. function hasText(container) {
  13471. return container.node.data.trim().length > 0;
  13472. }
  13473. function noLetterSpacing(container) {
  13474. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  13475. }
  13476. function getBorderRadiusData(container) {
  13477. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  13478. var value = container.css('border' + side + 'Radius');
  13479. var arr = value.split(" ");
  13480. if (arr.length <= 1) {
  13481. arr[1] = arr[0];
  13482. }
  13483. return arr.map(asInt);
  13484. });
  13485. }
  13486. function renderableNode(node) {
  13487. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  13488. }
  13489. function isPositionedForStacking(container) {
  13490. var position = container.css("position");
  13491. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  13492. return zIndex !== "auto";
  13493. }
  13494. function isPositioned(container) {
  13495. return container.css("position") !== "static";
  13496. }
  13497. function isFloating(container) {
  13498. return container.css("float") !== "none";
  13499. }
  13500. function isInlineBlock(container) {
  13501. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13502. }
  13503. function not(callback) {
  13504. var context = this;
  13505. return function() {
  13506. return !callback.apply(context, arguments);
  13507. };
  13508. }
  13509. function isElement(container) {
  13510. return container.node.nodeType === Node.ELEMENT_NODE;
  13511. }
  13512. function isPseudoElement(container) {
  13513. return container.isPseudoElement === true;
  13514. }
  13515. function isTextNode(container) {
  13516. return container.node.nodeType === Node.TEXT_NODE;
  13517. }
  13518. function zIndexSort(contexts) {
  13519. return function(a, b) {
  13520. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  13521. };
  13522. }
  13523. function hasOpacity(container) {
  13524. return container.getOpacity() < 1;
  13525. }
  13526. function asInt(value) {
  13527. return parseInt(value, 10);
  13528. }
  13529. function getWidth(border) {
  13530. return border.width;
  13531. }
  13532. function nonIgnoredElement(nodeContainer) {
  13533. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  13534. }
  13535. function flatten(arrays) {
  13536. return [].concat.apply([], arrays);
  13537. }
  13538. function stripQuotes(content) {
  13539. var first = content.substr(0, 1);
  13540. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  13541. }
  13542. function getWords(characters) {
  13543. var words = [], i = 0, onWordBoundary = false, word;
  13544. while(characters.length) {
  13545. if (isWordBoundary(characters[i]) === onWordBoundary) {
  13546. word = characters.splice(0, i);
  13547. if (word.length) {
  13548. words.push(punycode.ucs2.encode(word));
  13549. }
  13550. onWordBoundary =! onWordBoundary;
  13551. i = 0;
  13552. } else {
  13553. i++;
  13554. }
  13555. if (i >= characters.length) {
  13556. word = characters.splice(0, i);
  13557. if (word.length) {
  13558. words.push(punycode.ucs2.encode(word));
  13559. }
  13560. }
  13561. }
  13562. return words;
  13563. }
  13564. function isWordBoundary(characterCode) {
  13565. return [
  13566. 32, // <space>
  13567. 13, // \r
  13568. 10, // \n
  13569. 9, // \t
  13570. 45 // -
  13571. ].indexOf(characterCode) !== -1;
  13572. }
  13573. function hasUnicode(string) {
  13574. return (/[^\u0000-\u00ff]/).test(string);
  13575. }
  13576. module.exports = NodeParser;
  13577. },{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
  13578. var XHR = _dereq_('./xhr');
  13579. var utils = _dereq_('./utils');
  13580. var log = _dereq_('./log');
  13581. var createWindowClone = _dereq_('./clone');
  13582. var decode64 = utils.decode64;
  13583. function Proxy(src, proxyUrl, document) {
  13584. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  13585. if (!proxyUrl) {
  13586. return Promise.reject("No proxy configured");
  13587. }
  13588. var callback = createCallback(supportsCORS);
  13589. var url = createProxyUrl(proxyUrl, src, callback);
  13590. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  13591. return decode64(response.content);
  13592. }));
  13593. }
  13594. var proxyCount = 0;
  13595. function ProxyURL(src, proxyUrl, document) {
  13596. var supportsCORSImage = ('crossOrigin' in new Image());
  13597. var callback = createCallback(supportsCORSImage);
  13598. var url = createProxyUrl(proxyUrl, src, callback);
  13599. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  13600. return "data:" + response.type + ";base64," + response.content;
  13601. }));
  13602. }
  13603. function jsonp(document, url, callback) {
  13604. return new Promise(function(resolve, reject) {
  13605. var s = document.createElement("script");
  13606. var cleanup = function() {
  13607. delete window.html2canvas.proxy[callback];
  13608. document.body.removeChild(s);
  13609. };
  13610. window.html2canvas.proxy[callback] = function(response) {
  13611. cleanup();
  13612. resolve(response);
  13613. };
  13614. s.src = url;
  13615. s.onerror = function(e) {
  13616. cleanup();
  13617. reject(e);
  13618. };
  13619. document.body.appendChild(s);
  13620. });
  13621. }
  13622. function createCallback(useCORS) {
  13623. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  13624. }
  13625. function createProxyUrl(proxyUrl, src, callback) {
  13626. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  13627. }
  13628. function documentFromHTML(src) {
  13629. return function(html) {
  13630. var parser = new DOMParser(), doc;
  13631. try {
  13632. doc = parser.parseFromString(html, "text/html");
  13633. } catch(e) {
  13634. log("DOMParser not supported, falling back to createHTMLDocument");
  13635. doc = document.implementation.createHTMLDocument("");
  13636. try {
  13637. doc.open();
  13638. doc.write(html);
  13639. doc.close();
  13640. } catch(ee) {
  13641. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  13642. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  13643. }
  13644. }
  13645. var b = doc.querySelector("base");
  13646. if (!b || !b.href.host) {
  13647. var base = doc.createElement("base");
  13648. base.href = src;
  13649. doc.head.insertBefore(base, doc.head.firstChild);
  13650. }
  13651. return doc;
  13652. };
  13653. }
  13654. function loadUrlDocument(src, proxy, document, width, height, options) {
  13655. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  13656. return createWindowClone(doc, document, width, height, options, 0, 0);
  13657. });
  13658. }
  13659. exports.Proxy = Proxy;
  13660. exports.ProxyURL = ProxyURL;
  13661. exports.loadUrlDocument = loadUrlDocument;
  13662. },{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
  13663. var ProxyURL = _dereq_('./proxy').ProxyURL;
  13664. function ProxyImageContainer(src, proxy) {
  13665. var link = document.createElement("a");
  13666. link.href = src;
  13667. src = link.href;
  13668. this.src = src;
  13669. this.image = new Image();
  13670. var self = this;
  13671. this.promise = new Promise(function(resolve, reject) {
  13672. self.image.crossOrigin = "Anonymous";
  13673. self.image.onload = resolve;
  13674. self.image.onerror = reject;
  13675. new ProxyURL(src, proxy, document).then(function(url) {
  13676. self.image.src = url;
  13677. })['catch'](reject);
  13678. });
  13679. }
  13680. module.exports = ProxyImageContainer;
  13681. },{"./proxy":16}],18:[function(_dereq_,module,exports){
  13682. var NodeContainer = _dereq_('./nodecontainer');
  13683. function PseudoElementContainer(node, parent, type) {
  13684. NodeContainer.call(this, node, parent);
  13685. this.isPseudoElement = true;
  13686. this.before = type === ":before";
  13687. }
  13688. PseudoElementContainer.prototype.cloneTo = function(stack) {
  13689. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  13690. stack.isPseudoElement = true;
  13691. stack.before = this.before;
  13692. };
  13693. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  13694. PseudoElementContainer.prototype.appendToDOM = function() {
  13695. if (this.before) {
  13696. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  13697. } else {
  13698. this.parent.node.appendChild(this.node);
  13699. }
  13700. this.parent.node.className += " " + this.getHideClass();
  13701. };
  13702. PseudoElementContainer.prototype.cleanDOM = function() {
  13703. this.node.parentNode.removeChild(this.node);
  13704. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  13705. };
  13706. PseudoElementContainer.prototype.getHideClass = function() {
  13707. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  13708. };
  13709. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  13710. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  13711. module.exports = PseudoElementContainer;
  13712. },{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
  13713. var log = _dereq_('./log');
  13714. function Renderer(width, height, images, options, document) {
  13715. this.width = width;
  13716. this.height = height;
  13717. this.images = images;
  13718. this.options = options;
  13719. this.document = document;
  13720. }
  13721. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  13722. var paddingLeft = container.cssInt('paddingLeft'),
  13723. paddingTop = container.cssInt('paddingTop'),
  13724. paddingRight = container.cssInt('paddingRight'),
  13725. paddingBottom = container.cssInt('paddingBottom'),
  13726. borders = borderData.borders;
  13727. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  13728. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  13729. this.drawImage(
  13730. imageContainer,
  13731. 0,
  13732. 0,
  13733. imageContainer.image.width || width,
  13734. imageContainer.image.height || height,
  13735. bounds.left + paddingLeft + borders[3].width,
  13736. bounds.top + paddingTop + borders[0].width,
  13737. width,
  13738. height
  13739. );
  13740. };
  13741. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  13742. if (bounds.height > 0 && bounds.width > 0) {
  13743. this.renderBackgroundColor(container, bounds);
  13744. this.renderBackgroundImage(container, bounds, borderData);
  13745. }
  13746. };
  13747. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  13748. var color = container.color("backgroundColor");
  13749. if (!color.isTransparent()) {
  13750. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  13751. }
  13752. };
  13753. Renderer.prototype.renderBorders = function(borders) {
  13754. borders.forEach(this.renderBorder, this);
  13755. };
  13756. Renderer.prototype.renderBorder = function(data) {
  13757. if (!data.color.isTransparent() && data.args !== null) {
  13758. this.drawShape(data.args, data.color);
  13759. }
  13760. };
  13761. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  13762. var backgroundImages = container.parseBackgroundImages();
  13763. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  13764. switch(backgroundImage.method) {
  13765. case "url":
  13766. var image = this.images.get(backgroundImage.args[0]);
  13767. if (image) {
  13768. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  13769. } else {
  13770. log("Error loading background-image", backgroundImage.args[0]);
  13771. }
  13772. break;
  13773. case "linear-gradient":
  13774. case "gradient":
  13775. var gradientImage = this.images.get(backgroundImage.value);
  13776. if (gradientImage) {
  13777. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  13778. } else {
  13779. log("Error loading background-image", backgroundImage.args[0]);
  13780. }
  13781. break;
  13782. case "none":
  13783. break;
  13784. default:
  13785. log("Unknown background-image type", backgroundImage.args[0]);
  13786. }
  13787. }, this);
  13788. };
  13789. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  13790. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  13791. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  13792. var repeat = container.parseBackgroundRepeat(index);
  13793. switch (repeat) {
  13794. case "repeat-x":
  13795. case "repeat no-repeat":
  13796. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  13797. break;
  13798. case "repeat-y":
  13799. case "no-repeat repeat":
  13800. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  13801. break;
  13802. case "no-repeat":
  13803. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  13804. break;
  13805. default:
  13806. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  13807. break;
  13808. }
  13809. };
  13810. module.exports = Renderer;
  13811. },{"./log":13}],20:[function(_dereq_,module,exports){
  13812. var Renderer = _dereq_('../renderer');
  13813. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  13814. var log = _dereq_('../log');
  13815. function CanvasRenderer(width, height) {
  13816. Renderer.apply(this, arguments);
  13817. this.canvas = this.options.canvas || this.document.createElement("canvas");
  13818. if (!this.options.canvas) {
  13819. this.canvas.width = width;
  13820. this.canvas.height = height;
  13821. }
  13822. this.ctx = this.canvas.getContext("2d");
  13823. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  13824. this.ctx.textBaseline = "bottom";
  13825. this.variables = {};
  13826. log("Initialized CanvasRenderer with size", width, "x", height);
  13827. }
  13828. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  13829. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  13830. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  13831. return this.ctx;
  13832. };
  13833. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  13834. this.setFillStyle(color).fillRect(left, top, width, height);
  13835. };
  13836. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  13837. this.setFillStyle(color);
  13838. this.ctx.beginPath();
  13839. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  13840. this.ctx.closePath();
  13841. this.ctx.fill();
  13842. };
  13843. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  13844. this.circle(left, top, size, color);
  13845. this.ctx.strokeStyle = strokeColor.toString();
  13846. this.ctx.stroke();
  13847. };
  13848. CanvasRenderer.prototype.drawShape = function(shape, color) {
  13849. this.shape(shape);
  13850. this.setFillStyle(color).fill();
  13851. };
  13852. CanvasRenderer.prototype.taints = function(imageContainer) {
  13853. if (imageContainer.tainted === null) {
  13854. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  13855. try {
  13856. this.taintCtx.getImageData(0, 0, 1, 1);
  13857. imageContainer.tainted = false;
  13858. } catch(e) {
  13859. this.taintCtx = document.createElement("canvas").getContext("2d");
  13860. imageContainer.tainted = true;
  13861. }
  13862. }
  13863. return imageContainer.tainted;
  13864. };
  13865. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  13866. if (!this.taints(imageContainer) || this.options.allowTaint) {
  13867. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  13868. }
  13869. };
  13870. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  13871. this.ctx.save();
  13872. shapes.filter(hasEntries).forEach(function(shape) {
  13873. this.shape(shape).clip();
  13874. }, this);
  13875. callback.call(context);
  13876. this.ctx.restore();
  13877. };
  13878. CanvasRenderer.prototype.shape = function(shape) {
  13879. this.ctx.beginPath();
  13880. shape.forEach(function(point, index) {
  13881. if (point[0] === "rect") {
  13882. this.ctx.rect.apply(this.ctx, point.slice(1));
  13883. } else {
  13884. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  13885. }
  13886. }, this);
  13887. this.ctx.closePath();
  13888. return this.ctx;
  13889. };
  13890. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  13891. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  13892. };
  13893. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  13894. this.setVariable("shadowColor", color.toString())
  13895. .setVariable("shadowOffsetY", offsetX)
  13896. .setVariable("shadowOffsetX", offsetY)
  13897. .setVariable("shadowBlur", blur);
  13898. };
  13899. CanvasRenderer.prototype.clearShadow = function() {
  13900. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  13901. };
  13902. CanvasRenderer.prototype.setOpacity = function(opacity) {
  13903. this.ctx.globalAlpha = opacity;
  13904. };
  13905. CanvasRenderer.prototype.setTransform = function(transform) {
  13906. this.ctx.translate(transform.origin[0], transform.origin[1]);
  13907. this.ctx.transform.apply(this.ctx, transform.matrix);
  13908. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  13909. };
  13910. CanvasRenderer.prototype.setVariable = function(property, value) {
  13911. if (this.variables[property] !== value) {
  13912. this.variables[property] = this.ctx[property] = value;
  13913. }
  13914. return this;
  13915. };
  13916. CanvasRenderer.prototype.text = function(text, left, bottom) {
  13917. this.ctx.fillText(text, left, bottom);
  13918. };
  13919. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  13920. var shape = [
  13921. ["line", Math.round(left), Math.round(top)],
  13922. ["line", Math.round(left + width), Math.round(top)],
  13923. ["line", Math.round(left + width), Math.round(height + top)],
  13924. ["line", Math.round(left), Math.round(height + top)]
  13925. ];
  13926. this.clip([shape], function() {
  13927. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  13928. }, this);
  13929. };
  13930. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  13931. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  13932. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  13933. this.ctx.translate(offsetX, offsetY);
  13934. this.ctx.fill();
  13935. this.ctx.translate(-offsetX, -offsetY);
  13936. };
  13937. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  13938. if (gradientImage instanceof LinearGradientContainer) {
  13939. var gradient = this.ctx.createLinearGradient(
  13940. bounds.left + bounds.width * gradientImage.x0,
  13941. bounds.top + bounds.height * gradientImage.y0,
  13942. bounds.left + bounds.width * gradientImage.x1,
  13943. bounds.top + bounds.height * gradientImage.y1);
  13944. gradientImage.colorStops.forEach(function(colorStop) {
  13945. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  13946. });
  13947. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  13948. }
  13949. };
  13950. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  13951. var image = imageContainer.image;
  13952. if(image.width === size.width && image.height === size.height) {
  13953. return image;
  13954. }
  13955. var ctx, canvas = document.createElement('canvas');
  13956. canvas.width = size.width;
  13957. canvas.height = size.height;
  13958. ctx = canvas.getContext("2d");
  13959. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  13960. return canvas;
  13961. };
  13962. function hasEntries(array) {
  13963. return array.length > 0;
  13964. }
  13965. module.exports = CanvasRenderer;
  13966. },{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
  13967. var NodeContainer = _dereq_('./nodecontainer');
  13968. function StackingContext(hasOwnStacking, opacity, element, parent) {
  13969. NodeContainer.call(this, element, parent);
  13970. this.ownStacking = hasOwnStacking;
  13971. this.contexts = [];
  13972. this.children = [];
  13973. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  13974. }
  13975. StackingContext.prototype = Object.create(NodeContainer.prototype);
  13976. StackingContext.prototype.getParentStack = function(context) {
  13977. var parentStack = (this.parent) ? this.parent.stack : null;
  13978. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  13979. };
  13980. module.exports = StackingContext;
  13981. },{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
  13982. function Support(document) {
  13983. this.rangeBounds = this.testRangeBounds(document);
  13984. this.cors = this.testCORS();
  13985. this.svg = this.testSVG();
  13986. }
  13987. Support.prototype.testRangeBounds = function(document) {
  13988. var range, testElement, rangeBounds, rangeHeight, support = false;
  13989. if (document.createRange) {
  13990. range = document.createRange();
  13991. if (range.getBoundingClientRect) {
  13992. testElement = document.createElement('boundtest');
  13993. testElement.style.height = "123px";
  13994. testElement.style.display = "block";
  13995. document.body.appendChild(testElement);
  13996. range.selectNode(testElement);
  13997. rangeBounds = range.getBoundingClientRect();
  13998. rangeHeight = rangeBounds.height;
  13999. if (rangeHeight === 123) {
  14000. support = true;
  14001. }
  14002. document.body.removeChild(testElement);
  14003. }
  14004. }
  14005. return support;
  14006. };
  14007. Support.prototype.testCORS = function() {
  14008. return typeof((new Image()).crossOrigin) !== "undefined";
  14009. };
  14010. Support.prototype.testSVG = function() {
  14011. var img = new Image();
  14012. var canvas = document.createElement("canvas");
  14013. var ctx = canvas.getContext("2d");
  14014. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  14015. try {
  14016. ctx.drawImage(img, 0, 0);
  14017. canvas.toDataURL();
  14018. } catch(e) {
  14019. return false;
  14020. }
  14021. return true;
  14022. };
  14023. module.exports = Support;
  14024. },{}],23:[function(_dereq_,module,exports){
  14025. var XHR = _dereq_('./xhr');
  14026. var decode64 = _dereq_('./utils').decode64;
  14027. function SVGContainer(src) {
  14028. this.src = src;
  14029. this.image = null;
  14030. var self = this;
  14031. this.promise = this.hasFabric().then(function() {
  14032. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  14033. }).then(function(svg) {
  14034. return new Promise(function(resolve) {
  14035. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  14036. });
  14037. });
  14038. }
  14039. SVGContainer.prototype.hasFabric = function() {
  14040. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  14041. };
  14042. SVGContainer.prototype.inlineFormatting = function(src) {
  14043. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  14044. };
  14045. SVGContainer.prototype.removeContentType = function(src) {
  14046. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  14047. };
  14048. SVGContainer.prototype.isInline = function(src) {
  14049. return (/^data:image\/svg\+xml/i.test(src));
  14050. };
  14051. SVGContainer.prototype.createCanvas = function(resolve) {
  14052. var self = this;
  14053. return function (objects, options) {
  14054. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  14055. self.image = canvas.lowerCanvasEl;
  14056. canvas
  14057. .setWidth(options.width)
  14058. .setHeight(options.height)
  14059. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  14060. .renderAll();
  14061. resolve(canvas.lowerCanvasEl);
  14062. };
  14063. };
  14064. SVGContainer.prototype.decode64 = function(str) {
  14065. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  14066. };
  14067. module.exports = SVGContainer;
  14068. },{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
  14069. var SVGContainer = _dereq_('./svgcontainer');
  14070. function SVGNodeContainer(node, _native) {
  14071. this.src = node;
  14072. this.image = null;
  14073. var self = this;
  14074. this.promise = _native ? new Promise(function(resolve, reject) {
  14075. self.image = new Image();
  14076. self.image.onload = resolve;
  14077. self.image.onerror = reject;
  14078. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  14079. if (self.image.complete === true) {
  14080. resolve(self.image);
  14081. }
  14082. }) : this.hasFabric().then(function() {
  14083. return new Promise(function(resolve) {
  14084. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  14085. });
  14086. });
  14087. }
  14088. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  14089. module.exports = SVGNodeContainer;
  14090. },{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
  14091. var NodeContainer = _dereq_('./nodecontainer');
  14092. function TextContainer(node, parent) {
  14093. NodeContainer.call(this, node, parent);
  14094. }
  14095. TextContainer.prototype = Object.create(NodeContainer.prototype);
  14096. TextContainer.prototype.applyTextTransform = function() {
  14097. this.node.data = this.transform(this.parent.css("textTransform"));
  14098. };
  14099. TextContainer.prototype.transform = function(transform) {
  14100. var text = this.node.data;
  14101. switch(transform){
  14102. case "lowercase":
  14103. return text.toLowerCase();
  14104. case "capitalize":
  14105. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  14106. case "uppercase":
  14107. return text.toUpperCase();
  14108. default:
  14109. return text;
  14110. }
  14111. };
  14112. function capitalize(m, p1, p2) {
  14113. if (m.length > 0) {
  14114. return p1 + p2.toUpperCase();
  14115. }
  14116. }
  14117. module.exports = TextContainer;
  14118. },{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
  14119. exports.smallImage = function smallImage() {
  14120. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  14121. };
  14122. exports.bind = function(callback, context) {
  14123. return function() {
  14124. return callback.apply(context, arguments);
  14125. };
  14126. };
  14127. /*
  14128. * base64-arraybuffer
  14129. * https://github.com/niklasvh/base64-arraybuffer
  14130. *
  14131. * Copyright (c) 2012 Niklas von Hertzen
  14132. * Licensed under the MIT license.
  14133. */
  14134. exports.decode64 = function(base64) {
  14135. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  14136. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  14137. var output = "";
  14138. for (i = 0; i < len; i+=4) {
  14139. encoded1 = chars.indexOf(base64[i]);
  14140. encoded2 = chars.indexOf(base64[i+1]);
  14141. encoded3 = chars.indexOf(base64[i+2]);
  14142. encoded4 = chars.indexOf(base64[i+3]);
  14143. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  14144. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  14145. byte3 = ((encoded3 & 3) << 6) | encoded4;
  14146. if (encoded3 === 64) {
  14147. output += String.fromCharCode(byte1);
  14148. } else if (encoded4 === 64 || encoded4 === -1) {
  14149. output += String.fromCharCode(byte1, byte2);
  14150. } else{
  14151. output += String.fromCharCode(byte1, byte2, byte3);
  14152. }
  14153. }
  14154. return output;
  14155. };
  14156. exports.getBounds = function(node) {
  14157. if (node.getBoundingClientRect) {
  14158. var clientRect = node.getBoundingClientRect();
  14159. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  14160. return {
  14161. top: clientRect.top,
  14162. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  14163. right: clientRect.left + width,
  14164. left: clientRect.left,
  14165. width: width,
  14166. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  14167. };
  14168. }
  14169. return {};
  14170. };
  14171. exports.offsetBounds = function(node) {
  14172. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  14173. return {
  14174. top: node.offsetTop + parent.top,
  14175. bottom: node.offsetTop + node.offsetHeight + parent.top,
  14176. right: node.offsetLeft + parent.left + node.offsetWidth,
  14177. left: node.offsetLeft + parent.left,
  14178. width: node.offsetWidth,
  14179. height: node.offsetHeight
  14180. };
  14181. };
  14182. exports.parseBackgrounds = function(backgroundImage) {
  14183. var whitespace = ' \r\n\t',
  14184. method, definition, prefix, prefix_i, block, results = [],
  14185. mode = 0, numParen = 0, quote, args;
  14186. var appendResult = function() {
  14187. if(method) {
  14188. if (definition.substr(0, 1) === '"') {
  14189. definition = definition.substr(1, definition.length - 2);
  14190. }
  14191. if (definition) {
  14192. args.push(definition);
  14193. }
  14194. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  14195. prefix = method.substr(0, prefix_i);
  14196. method = method.substr(prefix_i);
  14197. }
  14198. results.push({
  14199. prefix: prefix,
  14200. method: method.toLowerCase(),
  14201. value: block,
  14202. args: args,
  14203. image: null
  14204. });
  14205. }
  14206. args = [];
  14207. method = prefix = definition = block = '';
  14208. };
  14209. args = [];
  14210. method = prefix = definition = block = '';
  14211. backgroundImage.split("").forEach(function(c) {
  14212. if (mode === 0 && whitespace.indexOf(c) > -1) {
  14213. return;
  14214. }
  14215. switch(c) {
  14216. case '"':
  14217. if(!quote) {
  14218. quote = c;
  14219. } else if(quote === c) {
  14220. quote = null;
  14221. }
  14222. break;
  14223. case '(':
  14224. if(quote) {
  14225. break;
  14226. } else if(mode === 0) {
  14227. mode = 1;
  14228. block += c;
  14229. return;
  14230. } else {
  14231. numParen++;
  14232. }
  14233. break;
  14234. case ')':
  14235. if (quote) {
  14236. break;
  14237. } else if(mode === 1) {
  14238. if(numParen === 0) {
  14239. mode = 0;
  14240. block += c;
  14241. appendResult();
  14242. return;
  14243. } else {
  14244. numParen--;
  14245. }
  14246. }
  14247. break;
  14248. case ',':
  14249. if (quote) {
  14250. break;
  14251. } else if(mode === 0) {
  14252. appendResult();
  14253. return;
  14254. } else if (mode === 1) {
  14255. if (numParen === 0 && !method.match(/^url$/i)) {
  14256. args.push(definition);
  14257. definition = '';
  14258. block += c;
  14259. return;
  14260. }
  14261. }
  14262. break;
  14263. }
  14264. block += c;
  14265. if (mode === 0) {
  14266. method += c;
  14267. } else {
  14268. definition += c;
  14269. }
  14270. });
  14271. appendResult();
  14272. return results;
  14273. };
  14274. },{}],27:[function(_dereq_,module,exports){
  14275. var GradientContainer = _dereq_('./gradientcontainer');
  14276. function WebkitGradientContainer(imageData) {
  14277. GradientContainer.apply(this, arguments);
  14278. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  14279. }
  14280. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  14281. module.exports = WebkitGradientContainer;
  14282. },{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
  14283. function XHR(url) {
  14284. return new Promise(function(resolve, reject) {
  14285. var xhr = new XMLHttpRequest();
  14286. xhr.open('GET', url);
  14287. xhr.onload = function() {
  14288. if (xhr.status === 200) {
  14289. resolve(xhr.responseText);
  14290. } else {
  14291. reject(new Error(xhr.statusText));
  14292. }
  14293. };
  14294. xhr.onerror = function() {
  14295. reject(new Error("Network Error"));
  14296. };
  14297. xhr.send();
  14298. });
  14299. }
  14300. module.exports = XHR;
  14301. },{}]},{},[4])(4)
  14302. });
  14303. // Generated by CoffeeScript 1.4.0
  14304. /*
  14305. # PNG.js
  14306. # Copyright (c) 2011 Devon Govett
  14307. # MIT LICENSE
  14308. #
  14309. #
  14310. */
  14311. (function(global) {
  14312. var PNG;
  14313. PNG = (function() {
  14314. var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  14315. PNG.load = function(url, canvas, callback) {
  14316. var xhr,
  14317. _this = this;
  14318. if (typeof canvas === 'function') {
  14319. callback = canvas;
  14320. }
  14321. xhr = new XMLHttpRequest;
  14322. xhr.open("GET", url, true);
  14323. xhr.responseType = "arraybuffer";
  14324. xhr.onload = function() {
  14325. var data, png;
  14326. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  14327. png = new PNG(data);
  14328. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  14329. png.render(canvas);
  14330. }
  14331. return typeof callback === "function" ? callback(png) : void 0;
  14332. };
  14333. return xhr.send(null);
  14334. };
  14335. APNG_DISPOSE_OP_NONE = 0;
  14336. APNG_DISPOSE_OP_BACKGROUND = 1;
  14337. APNG_DISPOSE_OP_PREVIOUS = 2;
  14338. APNG_BLEND_OP_SOURCE = 0;
  14339. APNG_BLEND_OP_OVER = 1;
  14340. function PNG(data) {
  14341. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  14342. this.data = data;
  14343. this.pos = 8;
  14344. this.palette = [];
  14345. this.imgData = [];
  14346. this.transparency = {};
  14347. this.animation = null;
  14348. this.text = {};
  14349. frame = null;
  14350. while (true) {
  14351. chunkSize = this.readUInt32();
  14352. section = ((function() {
  14353. var _i, _results;
  14354. _results = [];
  14355. for (i = _i = 0; _i < 4; i = ++_i) {
  14356. _results.push(String.fromCharCode(this.data[this.pos++]));
  14357. }
  14358. return _results;
  14359. }).call(this)).join('');
  14360. switch (section) {
  14361. case 'IHDR':
  14362. this.width = this.readUInt32();
  14363. this.height = this.readUInt32();
  14364. this.bits = this.data[this.pos++];
  14365. this.colorType = this.data[this.pos++];
  14366. this.compressionMethod = this.data[this.pos++];
  14367. this.filterMethod = this.data[this.pos++];
  14368. this.interlaceMethod = this.data[this.pos++];
  14369. break;
  14370. case 'acTL':
  14371. this.animation = {
  14372. numFrames: this.readUInt32(),
  14373. numPlays: this.readUInt32() || Infinity,
  14374. frames: []
  14375. };
  14376. break;
  14377. case 'PLTE':
  14378. this.palette = this.read(chunkSize);
  14379. break;
  14380. case 'fcTL':
  14381. if (frame) {
  14382. this.animation.frames.push(frame);
  14383. }
  14384. this.pos += 4;
  14385. frame = {
  14386. width: this.readUInt32(),
  14387. height: this.readUInt32(),
  14388. xOffset: this.readUInt32(),
  14389. yOffset: this.readUInt32()
  14390. };
  14391. delayNum = this.readUInt16();
  14392. delayDen = this.readUInt16() || 100;
  14393. frame.delay = 1000 * delayNum / delayDen;
  14394. frame.disposeOp = this.data[this.pos++];
  14395. frame.blendOp = this.data[this.pos++];
  14396. frame.data = [];
  14397. break;
  14398. case 'IDAT':
  14399. case 'fdAT':
  14400. if (section === 'fdAT') {
  14401. this.pos += 4;
  14402. chunkSize -= 4;
  14403. }
  14404. data = (frame != null ? frame.data : void 0) || this.imgData;
  14405. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  14406. data.push(this.data[this.pos++]);
  14407. }
  14408. break;
  14409. case 'tRNS':
  14410. this.transparency = {};
  14411. switch (this.colorType) {
  14412. case 3:
  14413. palLen = this.palette.length/3;
  14414. this.transparency.indexed = this.read(chunkSize);
  14415. if(this.transparency.indexed.length > palLen)
  14416. throw new Error('More transparent colors than palette size');
  14417. /*
  14418. * According to the PNG spec trns should be increased to the same size as palette if shorter
  14419. */
  14420. //palShort = 255 - this.transparency.indexed.length;
  14421. palShort = palLen - this.transparency.indexed.length;
  14422. if (palShort > 0) {
  14423. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  14424. this.transparency.indexed.push(255);
  14425. }
  14426. }
  14427. break;
  14428. case 0:
  14429. this.transparency.grayscale = this.read(chunkSize)[0];
  14430. break;
  14431. case 2:
  14432. this.transparency.rgb = this.read(chunkSize);
  14433. }
  14434. break;
  14435. case 'tEXt':
  14436. text = this.read(chunkSize);
  14437. index = text.indexOf(0);
  14438. key = String.fromCharCode.apply(String, text.slice(0, index));
  14439. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  14440. break;
  14441. case 'IEND':
  14442. if (frame) {
  14443. this.animation.frames.push(frame);
  14444. }
  14445. this.colors = (function() {
  14446. switch (this.colorType) {
  14447. case 0:
  14448. case 3:
  14449. case 4:
  14450. return 1;
  14451. case 2:
  14452. case 6:
  14453. return 3;
  14454. }
  14455. }).call(this);
  14456. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  14457. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  14458. this.pixelBitlength = this.bits * colors;
  14459. this.colorSpace = (function() {
  14460. switch (this.colors) {
  14461. case 1:
  14462. return 'DeviceGray';
  14463. case 3:
  14464. return 'DeviceRGB';
  14465. }
  14466. }).call(this);
  14467. this.imgData = new Uint8Array(this.imgData);
  14468. return;
  14469. default:
  14470. this.pos += chunkSize;
  14471. }
  14472. this.pos += 4;
  14473. if (this.pos > this.data.length) {
  14474. throw new Error("Incomplete or corrupt PNG file");
  14475. }
  14476. }
  14477. return;
  14478. }
  14479. PNG.prototype.read = function(bytes) {
  14480. var i, _i, _results;
  14481. _results = [];
  14482. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  14483. _results.push(this.data[this.pos++]);
  14484. }
  14485. return _results;
  14486. };
  14487. PNG.prototype.readUInt32 = function() {
  14488. var b1, b2, b3, b4;
  14489. b1 = this.data[this.pos++] << 24;
  14490. b2 = this.data[this.pos++] << 16;
  14491. b3 = this.data[this.pos++] << 8;
  14492. b4 = this.data[this.pos++];
  14493. return b1 | b2 | b3 | b4;
  14494. };
  14495. PNG.prototype.readUInt16 = function() {
  14496. var b1, b2;
  14497. b1 = this.data[this.pos++] << 8;
  14498. b2 = this.data[this.pos++];
  14499. return b1 | b2;
  14500. };
  14501. PNG.prototype.decodePixels = function(data) {
  14502. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  14503. if (data == null) {
  14504. data = this.imgData;
  14505. }
  14506. if (data.length === 0) {
  14507. return new Uint8Array(0);
  14508. }
  14509. data = new FlateStream(data);
  14510. data = data.getBytes();
  14511. pixelBytes = this.pixelBitlength / 8;
  14512. scanlineLength = pixelBytes * this.width;
  14513. pixels = new Uint8Array(scanlineLength * this.height);
  14514. length = data.length;
  14515. row = 0;
  14516. pos = 0;
  14517. c = 0;
  14518. while (pos < length) {
  14519. switch (data[pos++]) {
  14520. case 0:
  14521. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  14522. pixels[c++] = data[pos++];
  14523. }
  14524. break;
  14525. case 1:
  14526. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  14527. abyte = data[pos++];
  14528. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14529. pixels[c++] = (abyte + left) % 256;
  14530. }
  14531. break;
  14532. case 2:
  14533. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  14534. abyte = data[pos++];
  14535. col = (i - (i % pixelBytes)) / pixelBytes;
  14536. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14537. pixels[c++] = (upper + abyte) % 256;
  14538. }
  14539. break;
  14540. case 3:
  14541. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  14542. abyte = data[pos++];
  14543. col = (i - (i % pixelBytes)) / pixelBytes;
  14544. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14545. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14546. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  14547. }
  14548. break;
  14549. case 4:
  14550. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  14551. abyte = data[pos++];
  14552. col = (i - (i % pixelBytes)) / pixelBytes;
  14553. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14554. if (row === 0) {
  14555. upper = upperLeft = 0;
  14556. } else {
  14557. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14558. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
  14559. }
  14560. p = left + upper - upperLeft;
  14561. pa = Math.abs(p - left);
  14562. pb = Math.abs(p - upper);
  14563. pc = Math.abs(p - upperLeft);
  14564. if (pa <= pb && pa <= pc) {
  14565. paeth = left;
  14566. } else if (pb <= pc) {
  14567. paeth = upper;
  14568. } else {
  14569. paeth = upperLeft;
  14570. }
  14571. pixels[c++] = (abyte + paeth) % 256;
  14572. }
  14573. break;
  14574. default:
  14575. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  14576. }
  14577. row++;
  14578. }
  14579. return pixels;
  14580. };
  14581. PNG.prototype.decodePalette = function() {
  14582. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  14583. palette = this.palette;
  14584. transparency = this.transparency.indexed || [];
  14585. ret = new Uint8Array((transparency.length || 0) + palette.length);
  14586. pos = 0;
  14587. length = palette.length;
  14588. c = 0;
  14589. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  14590. ret[pos++] = palette[i];
  14591. ret[pos++] = palette[i + 1];
  14592. ret[pos++] = palette[i + 2];
  14593. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  14594. }
  14595. return ret;
  14596. };
  14597. PNG.prototype.copyToImageData = function(imageData, pixels) {
  14598. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  14599. colors = this.colors;
  14600. palette = null;
  14601. alpha = this.hasAlphaChannel;
  14602. if (this.palette.length) {
  14603. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  14604. colors = 4;
  14605. alpha = true;
  14606. }
  14607. data = imageData.data || imageData;
  14608. length = data.length;
  14609. input = palette || pixels;
  14610. i = j = 0;
  14611. if (colors === 1) {
  14612. while (i < length) {
  14613. k = palette ? pixels[i / 4] * 4 : j;
  14614. v = input[k++];
  14615. data[i++] = v;
  14616. data[i++] = v;
  14617. data[i++] = v;
  14618. data[i++] = alpha ? input[k++] : 255;
  14619. j = k;
  14620. }
  14621. } else {
  14622. while (i < length) {
  14623. k = palette ? pixels[i / 4] * 4 : j;
  14624. data[i++] = input[k++];
  14625. data[i++] = input[k++];
  14626. data[i++] = input[k++];
  14627. data[i++] = alpha ? input[k++] : 255;
  14628. j = k;
  14629. }
  14630. }
  14631. };
  14632. PNG.prototype.decode = function() {
  14633. var ret;
  14634. ret = new Uint8Array(this.width * this.height * 4);
  14635. this.copyToImageData(ret, this.decodePixels());
  14636. return ret;
  14637. };
  14638. try {
  14639. scratchCanvas = global.document.createElement('canvas');
  14640. scratchCtx = scratchCanvas.getContext('2d');
  14641. } catch(e) {
  14642. return -1;
  14643. }
  14644. makeImage = function(imageData) {
  14645. var img;
  14646. scratchCtx.width = imageData.width;
  14647. scratchCtx.height = imageData.height;
  14648. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  14649. scratchCtx.putImageData(imageData, 0, 0);
  14650. img = new Image;
  14651. img.src = scratchCanvas.toDataURL();
  14652. return img;
  14653. };
  14654. PNG.prototype.decodeFrames = function(ctx) {
  14655. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  14656. if (!this.animation) {
  14657. return;
  14658. }
  14659. _ref = this.animation.frames;
  14660. _results = [];
  14661. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  14662. frame = _ref[i];
  14663. imageData = ctx.createImageData(frame.width, frame.height);
  14664. pixels = this.decodePixels(new Uint8Array(frame.data));
  14665. this.copyToImageData(imageData, pixels);
  14666. frame.imageData = imageData;
  14667. _results.push(frame.image = makeImage(imageData));
  14668. }
  14669. return _results;
  14670. };
  14671. PNG.prototype.renderFrame = function(ctx, number) {
  14672. var frame, frames, prev;
  14673. frames = this.animation.frames;
  14674. frame = frames[number];
  14675. prev = frames[number - 1];
  14676. if (number === 0) {
  14677. ctx.clearRect(0, 0, this.width, this.height);
  14678. }
  14679. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  14680. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  14681. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  14682. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  14683. }
  14684. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  14685. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  14686. }
  14687. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  14688. };
  14689. PNG.prototype.animate = function(ctx) {
  14690. var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
  14691. _this = this;
  14692. frameNumber = 0;
  14693. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  14694. return (doFrame = function() {
  14695. var f, frame;
  14696. f = frameNumber++ % numFrames;
  14697. frame = frames[f];
  14698. _this.renderFrame(ctx, f);
  14699. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  14700. return _this.animation._timeout = setTimeout(doFrame, frame.delay);
  14701. }
  14702. })();
  14703. };
  14704. PNG.prototype.stopAnimation = function() {
  14705. var _ref;
  14706. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  14707. };
  14708. PNG.prototype.render = function(canvas) {
  14709. var ctx, data;
  14710. if (canvas._png) {
  14711. canvas._png.stopAnimation();
  14712. }
  14713. canvas._png = this;
  14714. canvas.width = this.width;
  14715. canvas.height = this.height;
  14716. ctx = canvas.getContext("2d");
  14717. if (this.animation) {
  14718. this.decodeFrames(ctx);
  14719. return this.animate(ctx);
  14720. } else {
  14721. data = ctx.createImageData(this.width, this.height);
  14722. this.copyToImageData(data, this.decodePixels());
  14723. return ctx.putImageData(data, 0, 0);
  14724. }
  14725. };
  14726. return PNG;
  14727. })();
  14728. global.PNG = PNG;
  14729. })(typeof window !== "undefined" && window || undefined);
  14730. /*
  14731. * Extracted from pdf.js
  14732. * https://github.com/andreasgal/pdf.js
  14733. *
  14734. * Copyright (c) 2011 Mozilla Foundation
  14735. *
  14736. * Contributors: Andreas Gal <gal@mozilla.com>
  14737. * Chris G Jones <cjones@mozilla.com>
  14738. * Shaon Barman <shaon.barman@gmail.com>
  14739. * Vivien Nicolas <21@vingtetun.org>
  14740. * Justin D'Arcangelo <justindarc@gmail.com>
  14741. * Yury Delendik
  14742. *
  14743. *
  14744. */
  14745. var DecodeStream = (function() {
  14746. function constructor() {
  14747. this.pos = 0;
  14748. this.bufferLength = 0;
  14749. this.eof = false;
  14750. this.buffer = null;
  14751. }
  14752. constructor.prototype = {
  14753. ensureBuffer: function decodestream_ensureBuffer(requested) {
  14754. var buffer = this.buffer;
  14755. var current = buffer ? buffer.byteLength : 0;
  14756. if (requested < current)
  14757. return buffer;
  14758. var size = 512;
  14759. while (size < requested)
  14760. size <<= 1;
  14761. var buffer2 = new Uint8Array(size);
  14762. for (var i = 0; i < current; ++i)
  14763. buffer2[i] = buffer[i];
  14764. return this.buffer = buffer2;
  14765. },
  14766. getByte: function decodestream_getByte() {
  14767. var pos = this.pos;
  14768. while (this.bufferLength <= pos) {
  14769. if (this.eof)
  14770. return null;
  14771. this.readBlock();
  14772. }
  14773. return this.buffer[this.pos++];
  14774. },
  14775. getBytes: function decodestream_getBytes(length) {
  14776. var pos = this.pos;
  14777. if (length) {
  14778. this.ensureBuffer(pos + length);
  14779. var end = pos + length;
  14780. while (!this.eof && this.bufferLength < end)
  14781. this.readBlock();
  14782. var bufEnd = this.bufferLength;
  14783. if (end > bufEnd)
  14784. end = bufEnd;
  14785. } else {
  14786. while (!this.eof)
  14787. this.readBlock();
  14788. var end = this.bufferLength;
  14789. }
  14790. this.pos = end;
  14791. return this.buffer.subarray(pos, end);
  14792. },
  14793. lookChar: function decodestream_lookChar() {
  14794. var pos = this.pos;
  14795. while (this.bufferLength <= pos) {
  14796. if (this.eof)
  14797. return null;
  14798. this.readBlock();
  14799. }
  14800. return String.fromCharCode(this.buffer[this.pos]);
  14801. },
  14802. getChar: function decodestream_getChar() {
  14803. var pos = this.pos;
  14804. while (this.bufferLength <= pos) {
  14805. if (this.eof)
  14806. return null;
  14807. this.readBlock();
  14808. }
  14809. return String.fromCharCode(this.buffer[this.pos++]);
  14810. },
  14811. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  14812. var end = start + length;
  14813. while (this.bufferLength <= end && !this.eof)
  14814. this.readBlock();
  14815. return new Stream(this.buffer, start, length, dict);
  14816. },
  14817. skip: function decodestream_skip(n) {
  14818. if (!n)
  14819. n = 1;
  14820. this.pos += n;
  14821. },
  14822. reset: function decodestream_reset() {
  14823. this.pos = 0;
  14824. }
  14825. };
  14826. return constructor;
  14827. })();
  14828. var FlateStream = (function() {
  14829. if (typeof Uint32Array === 'undefined') {
  14830. return undefined;
  14831. }
  14832. var codeLenCodeMap = new Uint32Array([
  14833. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  14834. ]);
  14835. var lengthDecode = new Uint32Array([
  14836. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  14837. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  14838. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  14839. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  14840. ]);
  14841. var distDecode = new Uint32Array([
  14842. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  14843. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  14844. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  14845. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  14846. ]);
  14847. var fixedLitCodeTab = [new Uint32Array([
  14848. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  14849. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  14850. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  14851. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  14852. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  14853. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  14854. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  14855. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  14856. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  14857. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  14858. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  14859. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  14860. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  14861. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  14862. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  14863. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  14864. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  14865. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  14866. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  14867. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  14868. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  14869. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  14870. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  14871. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  14872. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  14873. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  14874. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  14875. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  14876. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  14877. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  14878. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  14879. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  14880. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  14881. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  14882. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  14883. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  14884. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  14885. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  14886. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  14887. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  14888. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  14889. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  14890. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  14891. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  14892. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  14893. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  14894. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  14895. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  14896. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  14897. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  14898. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  14899. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  14900. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  14901. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  14902. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  14903. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  14904. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  14905. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  14906. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  14907. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  14908. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  14909. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  14910. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  14911. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  14912. ]), 9];
  14913. var fixedDistCodeTab = [new Uint32Array([
  14914. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  14915. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  14916. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  14917. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  14918. ]), 5];
  14919. function error(e) {
  14920. throw new Error(e)
  14921. }
  14922. function constructor(bytes) {
  14923. //var bytes = stream.getBytes();
  14924. var bytesPos = 0;
  14925. var cmf = bytes[bytesPos++];
  14926. var flg = bytes[bytesPos++];
  14927. if (cmf == -1 || flg == -1)
  14928. error('Invalid header in flate stream');
  14929. if ((cmf & 0x0f) != 0x08)
  14930. error('Unknown compression method in flate stream');
  14931. if ((((cmf << 8) + flg) % 31) != 0)
  14932. error('Bad FCHECK in flate stream');
  14933. if (flg & 0x20)
  14934. error('FDICT bit set in flate stream');
  14935. this.bytes = bytes;
  14936. this.bytesPos = bytesPos;
  14937. this.codeSize = 0;
  14938. this.codeBuf = 0;
  14939. DecodeStream.call(this);
  14940. }
  14941. constructor.prototype = Object.create(DecodeStream.prototype);
  14942. constructor.prototype.getBits = function(bits) {
  14943. var codeSize = this.codeSize;
  14944. var codeBuf = this.codeBuf;
  14945. var bytes = this.bytes;
  14946. var bytesPos = this.bytesPos;
  14947. var b;
  14948. while (codeSize < bits) {
  14949. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14950. error('Bad encoding in flate stream');
  14951. codeBuf |= b << codeSize;
  14952. codeSize += 8;
  14953. }
  14954. b = codeBuf & ((1 << bits) - 1);
  14955. this.codeBuf = codeBuf >> bits;
  14956. this.codeSize = codeSize -= bits;
  14957. this.bytesPos = bytesPos;
  14958. return b;
  14959. };
  14960. constructor.prototype.getCode = function(table) {
  14961. var codes = table[0];
  14962. var maxLen = table[1];
  14963. var codeSize = this.codeSize;
  14964. var codeBuf = this.codeBuf;
  14965. var bytes = this.bytes;
  14966. var bytesPos = this.bytesPos;
  14967. while (codeSize < maxLen) {
  14968. var b;
  14969. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14970. error('Bad encoding in flate stream');
  14971. codeBuf |= (b << codeSize);
  14972. codeSize += 8;
  14973. }
  14974. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  14975. var codeLen = code >> 16;
  14976. var codeVal = code & 0xffff;
  14977. if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
  14978. error('Bad encoding in flate stream');
  14979. this.codeBuf = (codeBuf >> codeLen);
  14980. this.codeSize = (codeSize - codeLen);
  14981. this.bytesPos = bytesPos;
  14982. return codeVal;
  14983. };
  14984. constructor.prototype.generateHuffmanTable = function(lengths) {
  14985. var n = lengths.length;
  14986. // find max code length
  14987. var maxLen = 0;
  14988. for (var i = 0; i < n; ++i) {
  14989. if (lengths[i] > maxLen)
  14990. maxLen = lengths[i];
  14991. }
  14992. // build the table
  14993. var size = 1 << maxLen;
  14994. var codes = new Uint32Array(size);
  14995. for (var len = 1, code = 0, skip = 2;
  14996. len <= maxLen;
  14997. ++len, code <<= 1, skip <<= 1) {
  14998. for (var val = 0; val < n; ++val) {
  14999. if (lengths[val] == len) {
  15000. // bit-reverse the code
  15001. var code2 = 0;
  15002. var t = code;
  15003. for (var i = 0; i < len; ++i) {
  15004. code2 = (code2 << 1) | (t & 1);
  15005. t >>= 1;
  15006. }
  15007. // fill the table entries
  15008. for (var i = code2; i < size; i += skip)
  15009. codes[i] = (len << 16) | val;
  15010. ++code;
  15011. }
  15012. }
  15013. }
  15014. return [codes, maxLen];
  15015. };
  15016. constructor.prototype.readBlock = function() {
  15017. function repeat(stream, array, len, offset, what) {
  15018. var repeat = stream.getBits(len) + offset;
  15019. while (repeat-- > 0)
  15020. array[i++] = what;
  15021. }
  15022. // read block header
  15023. var hdr = this.getBits(3);
  15024. if (hdr & 1)
  15025. this.eof = true;
  15026. hdr >>= 1;
  15027. if (hdr == 0) { // uncompressed block
  15028. var bytes = this.bytes;
  15029. var bytesPos = this.bytesPos;
  15030. var b;
  15031. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15032. error('Bad block header in flate stream');
  15033. var blockLen = b;
  15034. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15035. error('Bad block header in flate stream');
  15036. blockLen |= (b << 8);
  15037. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15038. error('Bad block header in flate stream');
  15039. var check = b;
  15040. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15041. error('Bad block header in flate stream');
  15042. check |= (b << 8);
  15043. if (check != (~blockLen & 0xffff))
  15044. error('Bad uncompressed block length in flate stream');
  15045. this.codeBuf = 0;
  15046. this.codeSize = 0;
  15047. var bufferLength = this.bufferLength;
  15048. var buffer = this.ensureBuffer(bufferLength + blockLen);
  15049. var end = bufferLength + blockLen;
  15050. this.bufferLength = end;
  15051. for (var n = bufferLength; n < end; ++n) {
  15052. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  15053. this.eof = true;
  15054. break;
  15055. }
  15056. buffer[n] = b;
  15057. }
  15058. this.bytesPos = bytesPos;
  15059. return;
  15060. }
  15061. var litCodeTable;
  15062. var distCodeTable;
  15063. if (hdr == 1) { // compressed block, fixed codes
  15064. litCodeTable = fixedLitCodeTab;
  15065. distCodeTable = fixedDistCodeTab;
  15066. } else if (hdr == 2) { // compressed block, dynamic codes
  15067. var numLitCodes = this.getBits(5) + 257;
  15068. var numDistCodes = this.getBits(5) + 1;
  15069. var numCodeLenCodes = this.getBits(4) + 4;
  15070. // build the code lengths code table
  15071. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  15072. var i = 0;
  15073. while (i < numCodeLenCodes)
  15074. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  15075. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  15076. // build the literal and distance code tables
  15077. var len = 0;
  15078. var i = 0;
  15079. var codes = numLitCodes + numDistCodes;
  15080. var codeLengths = new Array(codes);
  15081. while (i < codes) {
  15082. var code = this.getCode(codeLenCodeTab);
  15083. if (code == 16) {
  15084. repeat(this, codeLengths, 2, 3, len);
  15085. } else if (code == 17) {
  15086. repeat(this, codeLengths, 3, 3, len = 0);
  15087. } else if (code == 18) {
  15088. repeat(this, codeLengths, 7, 11, len = 0);
  15089. } else {
  15090. codeLengths[i++] = len = code;
  15091. }
  15092. }
  15093. litCodeTable =
  15094. this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  15095. distCodeTable =
  15096. this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  15097. } else {
  15098. error('Unknown block type in flate stream');
  15099. }
  15100. var buffer = this.buffer;
  15101. var limit = buffer ? buffer.length : 0;
  15102. var pos = this.bufferLength;
  15103. while (true) {
  15104. var code1 = this.getCode(litCodeTable);
  15105. if (code1 < 256) {
  15106. if (pos + 1 >= limit) {
  15107. buffer = this.ensureBuffer(pos + 1);
  15108. limit = buffer.length;
  15109. }
  15110. buffer[pos++] = code1;
  15111. continue;
  15112. }
  15113. if (code1 == 256) {
  15114. this.bufferLength = pos;
  15115. return;
  15116. }
  15117. code1 -= 257;
  15118. code1 = lengthDecode[code1];
  15119. var code2 = code1 >> 16;
  15120. if (code2 > 0)
  15121. code2 = this.getBits(code2);
  15122. var len = (code1 & 0xffff) + code2;
  15123. code1 = this.getCode(distCodeTable);
  15124. code1 = distDecode[code1];
  15125. code2 = code1 >> 16;
  15126. if (code2 > 0)
  15127. code2 = this.getBits(code2);
  15128. var dist = (code1 & 0xffff) + code2;
  15129. if (pos + len >= limit) {
  15130. buffer = this.ensureBuffer(pos + len);
  15131. limit = buffer.length;
  15132. }
  15133. for (var k = 0; k < len; ++k, ++pos)
  15134. buffer[pos] = buffer[pos - dist];
  15135. }
  15136. };
  15137. return constructor;
  15138. })();
  15139. /**
  15140. * JavaScript Polyfill functions for jsPDF
  15141. * Collected from public resources by
  15142. * https://github.com/diegocr
  15143. */
  15144. (function (global) {
  15145. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15146. if (typeof global.btoa === 'undefined') {
  15147. global.btoa = function(data) {
  15148. // discuss at: http://phpjs.org/functions/base64_encode/
  15149. // original by: Tyler Akins (http://rumkin.com)
  15150. // improved by: Bayron Guevara
  15151. // improved by: Thunder.m
  15152. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15153. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15154. // improved by: Rafal Kukawski (http://kukawski.pl)
  15155. // bugfixed by: Pellentesque Malesuada
  15156. // example 1: base64_encode('Kevin van Zonneveld');
  15157. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  15158. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
  15159. if (!data) {
  15160. return data;
  15161. }
  15162. do { // pack three octets into four hexets
  15163. o1 = data.charCodeAt(i++);
  15164. o2 = data.charCodeAt(i++);
  15165. o3 = data.charCodeAt(i++);
  15166. bits = o1 << 16 | o2 << 8 | o3;
  15167. h1 = bits >> 18 & 0x3f;
  15168. h2 = bits >> 12 & 0x3f;
  15169. h3 = bits >> 6 & 0x3f;
  15170. h4 = bits & 0x3f;
  15171. // use hexets to index into b64, and append result to encoded string
  15172. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  15173. } while (i < data.length);
  15174. enc = tmp_arr.join('');
  15175. var r = data.length % 3;
  15176. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  15177. };
  15178. }
  15179. if (typeof global.atob === 'undefined') {
  15180. global.atob = function(data) {
  15181. // discuss at: http://phpjs.org/functions/base64_decode/
  15182. // original by: Tyler Akins (http://rumkin.com)
  15183. // improved by: Thunder.m
  15184. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15185. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15186. // input by: Aman Gupta
  15187. // input by: Brett Zamir (http://brett-zamir.me)
  15188. // bugfixed by: Onno Marsman
  15189. // bugfixed by: Pellentesque Malesuada
  15190. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15191. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  15192. // returns 1: 'Kevin van Zonneveld'
  15193. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
  15194. if (!data) {
  15195. return data;
  15196. }
  15197. data += '';
  15198. do { // unpack four hexets into three octets using index points in b64
  15199. h1 = b64.indexOf(data.charAt(i++));
  15200. h2 = b64.indexOf(data.charAt(i++));
  15201. h3 = b64.indexOf(data.charAt(i++));
  15202. h4 = b64.indexOf(data.charAt(i++));
  15203. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  15204. o1 = bits >> 16 & 0xff;
  15205. o2 = bits >> 8 & 0xff;
  15206. o3 = bits & 0xff;
  15207. if (h3 == 64) {
  15208. tmp_arr[ac++] = String.fromCharCode(o1);
  15209. } else if (h4 == 64) {
  15210. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  15211. } else {
  15212. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  15213. }
  15214. } while (i < data.length);
  15215. dec = tmp_arr.join('');
  15216. return dec;
  15217. };
  15218. }
  15219. if (!Array.prototype.map) {
  15220. Array.prototype.map = function(fun /*, thisArg */) {
  15221. if (this === void 0 || this === null || typeof fun !== "function")
  15222. throw new TypeError();
  15223. var t = Object(this), len = t.length >>> 0, res = new Array(len);
  15224. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  15225. for (var i = 0; i < len; i++) {
  15226. // NOTE: Absolute correctness would demand Object.defineProperty
  15227. // be used. But this method is fairly new, and failure is
  15228. // possible only if Object.prototype or Array.prototype
  15229. // has a property |i| (very unlikely), so use a less-correct
  15230. // but more portable alternative.
  15231. if (i in t)
  15232. res[i] = fun.call(thisArg, t[i], i, t);
  15233. }
  15234. return res;
  15235. };
  15236. }
  15237. if(!Array.isArray) {
  15238. Array.isArray = function(arg) {
  15239. return Object.prototype.toString.call(arg) === '[object Array]';
  15240. };
  15241. }
  15242. if (!Array.prototype.forEach) {
  15243. Array.prototype.forEach = function(fun, thisArg) {
  15244. "use strict";
  15245. if (this === void 0 || this === null || typeof fun !== "function")
  15246. throw new TypeError();
  15247. var t = Object(this), len = t.length >>> 0;
  15248. for (var i = 0; i < len; i++) {
  15249. if (i in t)
  15250. fun.call(thisArg, t[i], i, t);
  15251. }
  15252. };
  15253. }
  15254. if (!Object.keys) {
  15255. Object.keys = (function () {
  15256. 'use strict';
  15257. var hasOwnProperty = Object.prototype.hasOwnProperty,
  15258. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  15259. dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
  15260. 'isPrototypeOf','propertyIsEnumerable','constructor'],
  15261. dontEnumsLength = dontEnums.length;
  15262. return function (obj) {
  15263. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  15264. throw new TypeError();
  15265. }
  15266. var result = [], prop, i;
  15267. for (prop in obj) {
  15268. if (hasOwnProperty.call(obj, prop)) {
  15269. result.push(prop);
  15270. }
  15271. }
  15272. if (hasDontEnumBug) {
  15273. for (i = 0; i < dontEnumsLength; i++) {
  15274. if (hasOwnProperty.call(obj, dontEnums[i])) {
  15275. result.push(dontEnums[i]);
  15276. }
  15277. }
  15278. }
  15279. return result;
  15280. };
  15281. }());
  15282. }
  15283. if (!String.prototype.trim) {
  15284. String.prototype.trim = function () {
  15285. return this.replace(/^\s+|\s+$/g, '');
  15286. };
  15287. }
  15288. if (!String.prototype.trimLeft) {
  15289. String.prototype.trimLeft = function() {
  15290. return this.replace(/^\s+/g, "");
  15291. };
  15292. }
  15293. if (!String.prototype.trimRight) {
  15294. String.prototype.trimRight = function() {
  15295. return this.replace(/\s+$/g, "");
  15296. };
  15297. }
  15298. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  15299. return jsPDF;
  15300. })));