jspdf.debug.js 754 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215
  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() {
  6. 'use strict';
  7. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
  8. return typeof obj;
  9. } : function(obj) {
  10. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  11. };
  12. var asyncGenerator = function() {
  13. function AwaitValue(value) {
  14. this.value = value;
  15. }
  16. function AsyncGenerator(gen) {
  17. var front, back;
  18. function send(key, arg) {
  19. return new Promise(function(resolve, reject) {
  20. var request = {
  21. key: key,
  22. arg: arg,
  23. resolve: resolve,
  24. reject: reject,
  25. next: null
  26. };
  27. if (back) {
  28. back = back.next = request;
  29. } else {
  30. front = back = request;
  31. resume(key, arg);
  32. }
  33. });
  34. }
  35. function resume(key, arg) {
  36. try {
  37. var result = gen[key](arg);
  38. var value = result.value;
  39. if (value instanceof AwaitValue) {
  40. Promise.resolve(value.value).then(function(arg) {
  41. resume("next", arg);
  42. }, function(arg) {
  43. resume("throw", arg);
  44. });
  45. } else {
  46. settle(result.done ? "return" : "normal", result.value);
  47. }
  48. } catch (err) {
  49. settle("throw", err);
  50. }
  51. }
  52. function settle(type, value) {
  53. switch (type) {
  54. case "return":
  55. front.resolve({
  56. value: value,
  57. done: true
  58. });
  59. break;
  60. case "throw":
  61. front.reject(value);
  62. break;
  63. default:
  64. front.resolve({
  65. value: value,
  66. done: false
  67. });
  68. break;
  69. }
  70. front = front.next;
  71. if (front) {
  72. resume(front.key, front.arg);
  73. } else {
  74. back = null;
  75. }
  76. }
  77. this._invoke = send;
  78. if (typeof gen.return !== "function") {
  79. this.return = undefined;
  80. }
  81. }
  82. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  83. AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
  84. return this;
  85. };
  86. }
  87. AsyncGenerator.prototype.next = function(arg) {
  88. return this._invoke("next", arg);
  89. };
  90. AsyncGenerator.prototype.throw = function(arg) {
  91. return this._invoke("throw", arg);
  92. };
  93. AsyncGenerator.prototype.return = function(arg) {
  94. return this._invoke("return", arg);
  95. };
  96. return {
  97. wrap: function(fn) {
  98. return function() {
  99. return new AsyncGenerator(fn.apply(this, arguments));
  100. };
  101. },
  102. await: function(value) {
  103. return new AwaitValue(value);
  104. }
  105. };
  106. }();
  107. /** @preserve
  108. * jsPDF - PDF Document creation from JavaScript
  109. * Version 1.3.5 Built on 2017-09-14T15:10:09.569Z
  110. * CommitID 05dc915baf
  111. *
  112. * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  113. * 2010 Aaron Spike, https://github.com/acspike
  114. * 2012 Willow Systems Corporation, willow-systems.com
  115. * 2012 Pablo Hess, https://github.com/pablohess
  116. * 2012 Florian Jenett, https://github.com/fjenett
  117. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  118. * 2013 Youssef Beddad, https://github.com/lifof
  119. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  120. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  121. * 2013 Jeremy Morel, https://github.com/jmorel
  122. * 2013 Christoph Hartmann, https://github.com/chris-rock
  123. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  124. * 2014 James Makes, https://github.com/dollaruw
  125. * 2014 Diego Casorran, https://github.com/diegocr
  126. * 2014 Steven Spungin, https://github.com/Flamenco
  127. * 2014 Kenneth Glassey, https://github.com/Gavvers
  128. *
  129. * Licensed under the MIT License
  130. *
  131. * Contributor(s):
  132. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  133. * kim3er, mfo, alnorth, Flamenco
  134. */
  135. /**
  136. * Creates new jsPDF document object instance.
  137. * @name jsPDF
  138. * @class
  139. * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l") <br />
  140. * Can also be an options object.
  141. * @param unit Measurement unit to be used when coordinates are specified.
  142. * One of "pt" (points), "mm" (Default), "cm", "in"
  143. * @param format One of 'pageFormats' as shown below, default: a4
  144. * @returns {jsPDF}
  145. * @description
  146. * If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
  147. * ```
  148. * {
  149. * orientation: 'p',
  150. * unit: 'mm',
  151. * format: 'a4',
  152. * hotfixes: [] // an array of hotfix strings to enable
  153. * }
  154. * ```
  155. */
  156. var jsPDF = function(global) {
  157. 'use strict';
  158. var pdfVersion = '1.3',
  159. pageFormats = { // Size in pt of various paper formats
  160. 'a0': [2383.94, 3370.39],
  161. 'a1': [1683.78, 2383.94],
  162. 'a2': [1190.55, 1683.78],
  163. 'a3': [841.89, 1190.55],
  164. 'a4': [595.28, 841.89],
  165. 'a5': [419.53, 595.28],
  166. 'a6': [297.64, 419.53],
  167. 'a7': [209.76, 297.64],
  168. 'a8': [147.40, 209.76],
  169. 'a9': [104.88, 147.40],
  170. 'a10': [73.70, 104.88],
  171. 'b0': [2834.65, 4008.19],
  172. 'b1': [2004.09, 2834.65],
  173. 'b2': [1417.32, 2004.09],
  174. 'b3': [1000.63, 1417.32],
  175. 'b4': [708.66, 1000.63],
  176. 'b5': [498.90, 708.66],
  177. 'b6': [354.33, 498.90],
  178. 'b7': [249.45, 354.33],
  179. 'b8': [175.75, 249.45],
  180. 'b9': [124.72, 175.75],
  181. 'b10': [87.87, 124.72],
  182. 'c0': [2599.37, 3676.54],
  183. 'c1': [1836.85, 2599.37],
  184. 'c2': [1298.27, 1836.85],
  185. 'c3': [918.43, 1298.27],
  186. 'c4': [649.13, 918.43],
  187. 'c5': [459.21, 649.13],
  188. 'c6': [323.15, 459.21],
  189. 'c7': [229.61, 323.15],
  190. 'c8': [161.57, 229.61],
  191. 'c9': [113.39, 161.57],
  192. 'c10': [79.37, 113.39],
  193. 'dl': [311.81, 623.62],
  194. 'letter': [612, 792],
  195. 'government-letter': [576, 756],
  196. 'legal': [612, 1008],
  197. 'junior-legal': [576, 360],
  198. 'ledger': [1224, 792],
  199. 'tabloid': [792, 1224],
  200. 'credit-card': [153, 243]
  201. };
  202. /**
  203. * jsPDF's Internal PubSub Implementation.
  204. * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
  205. * Backward compatible rewritten on 2014 by
  206. * Diego Casorran, https://github.com/diegocr
  207. *
  208. * @class
  209. * @name PubSub
  210. * @ignore This should not be in the public docs.
  211. */
  212. function PubSub(context) {
  213. var topics = {};
  214. this.subscribe = function(topic, callback, once) {
  215. if (typeof callback !== 'function') {
  216. return false;
  217. }
  218. if (!topics.hasOwnProperty(topic)) {
  219. topics[topic] = {};
  220. }
  221. var id = Math.random().toString(35);
  222. topics[topic][id] = [callback, !!once];
  223. return id;
  224. };
  225. this.unsubscribe = function(token) {
  226. for (var topic in topics) {
  227. if (topics[topic][token]) {
  228. delete topics[topic][token];
  229. return true;
  230. }
  231. }
  232. return false;
  233. };
  234. this.publish = function(topic) {
  235. if (topics.hasOwnProperty(topic)) {
  236. var args = Array.prototype.slice.call(arguments, 1),
  237. idr = [];
  238. for (var id in topics[topic]) {
  239. var sub = topics[topic][id];
  240. try {
  241. sub[0].apply(context, args);
  242. } catch (ex) {
  243. if (global.console) {
  244. console.error('jsPDF PubSub Error', ex.message, ex);
  245. }
  246. }
  247. if (sub[1]) idr.push(id);
  248. }
  249. if (idr.length) idr.forEach(this.unsubscribe);
  250. }
  251. };
  252. }
  253. /**
  254. * @constructor
  255. * @private
  256. */
  257. function jsPDF(orientation, unit, format, compressPdf) {
  258. var options = {};
  259. if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
  260. options = orientation;
  261. orientation = options.orientation;
  262. unit = options.unit || unit;
  263. format = options.format || format;
  264. compressPdf = options.compress || options.compressPdf || compressPdf;
  265. }
  266. // Default options
  267. unit = unit || 'mm';
  268. format = format || 'a4';
  269. orientation = ('' + (orientation || 'P')).toLowerCase();
  270. var format_as_string = ('' + format).toLowerCase(),
  271. compress = !!compressPdf && typeof Uint8Array === 'function',
  272. textColor = options.textColor || '0 g',
  273. drawColor = options.drawColor || '0 G',
  274. activeFontSize = options.fontSize || 16,
  275. lineHeightProportion = options.lineHeight || 1.15,
  276. lineWidth = options.lineWidth || 0.200025,
  277. // 2mm
  278. objectNumber = 2,
  279. // 'n' Current object number
  280. outToPages = !1,
  281. // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  282. offsets = [],
  283. // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  284. fonts = {},
  285. // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  286. fontmap = {},
  287. // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  288. activeFontKey,
  289. // will be string representing the KEY of the font as combination of fontName + fontStyle
  290. k,
  291. // Scale factor
  292. tmp,
  293. page = 0,
  294. currentPage,
  295. pages = [],
  296. pagesContext = [],
  297. // same index as pages and pagedim
  298. pagedim = [],
  299. content = [],
  300. additionalObjects = [],
  301. lineCapID = 0,
  302. lineJoinID = 0,
  303. content_length = 0,
  304. pageWidth,
  305. pageHeight,
  306. pageMode,
  307. zoomMode,
  308. layoutMode,
  309. documentProperties = {
  310. 'title': '',
  311. 'subject': '',
  312. 'author': '',
  313. 'keywords': '',
  314. 'creator': ''
  315. },
  316. API = {},
  317. events = new PubSub(API),
  318. hotfixes = options.hotfixes || [],
  319. /////////////////////
  320. // Private functions
  321. /////////////////////
  322. f2 = function f2(number) {
  323. return number.toFixed(2); // Ie, %.2f
  324. },
  325. f3 = function f3(number) {
  326. return number.toFixed(3); // Ie, %.3f
  327. },
  328. padd2 = function padd2(number) {
  329. return ('0' + parseInt(number)).slice(-2);
  330. },
  331. out = function out(string) {
  332. if (outToPages) {
  333. /* set by beginPage */
  334. pages[currentPage].push(string);
  335. } else {
  336. // +1 for '\n' that will be used to join 'content'
  337. content_length += string.length + 1;
  338. content.push(string);
  339. }
  340. },
  341. newObject = function newObject() {
  342. // Begin a new object
  343. objectNumber++;
  344. offsets[objectNumber] = content_length;
  345. out(objectNumber + ' 0 obj');
  346. return objectNumber;
  347. },
  348. // Does not output the object until after the pages have been output.
  349. // Returns an object containing the objectId and content.
  350. // All pages have been added so the object ID can be estimated to start right after.
  351. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  352. newAdditionalObject = function newAdditionalObject() {
  353. var objId = pages.length * 2 + 1;
  354. objId += additionalObjects.length;
  355. var obj = {
  356. objId: objId,
  357. content: ''
  358. };
  359. additionalObjects.push(obj);
  360. return obj;
  361. },
  362. // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  363. newObjectDeferred = function newObjectDeferred() {
  364. objectNumber++;
  365. offsets[objectNumber] = function() {
  366. return content_length;
  367. };
  368. return objectNumber;
  369. },
  370. newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
  371. offsets[oid] = content_length;
  372. },
  373. putStream = function putStream(str) {
  374. out('stream');
  375. out(str);
  376. out('endstream');
  377. },
  378. putPages = function putPages() {
  379. var n,
  380. p,
  381. arr,
  382. i,
  383. deflater,
  384. adler32,
  385. adler32cs,
  386. wPt,
  387. hPt,
  388. pageObjectNumbers = [];
  389. adler32cs = global.adler32cs || jsPDF.adler32cs;
  390. if (compress && typeof adler32cs === 'undefined') {
  391. compress = false;
  392. }
  393. // outToPages = false as set in endDocument(). out() writes to content.
  394. for (n = 1; n <= page; n++) {
  395. pageObjectNumbers.push(newObject());
  396. wPt = (pageWidth = pagedim[n].width) * k;
  397. hPt = (pageHeight = pagedim[n].height) * k;
  398. out('<</Type /Page');
  399. out('/Parent 1 0 R');
  400. out('/Resources 2 0 R');
  401. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  402. // Added for annotation plugin
  403. events.publish('putPage', {
  404. pageNumber: n,
  405. page: pages[n]
  406. });
  407. out('/Contents ' + (objectNumber + 1) + ' 0 R');
  408. out('>>');
  409. out('endobj');
  410. // Page content
  411. p = pages[n].join('\n');
  412. newObject();
  413. if (compress) {
  414. arr = [];
  415. i = p.length;
  416. while (i--) {
  417. arr[i] = p.charCodeAt(i);
  418. }
  419. adler32 = adler32cs.from(p);
  420. deflater = new Deflater(6);
  421. deflater.append(new Uint8Array(arr));
  422. p = deflater.flush();
  423. arr = new Uint8Array(p.length + 6);
  424. arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
  425. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
  426. p = String.fromCharCode.apply(null, arr);
  427. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  428. } else {
  429. out('<</Length ' + p.length + '>>');
  430. }
  431. putStream(p);
  432. out('endobj');
  433. }
  434. offsets[1] = content_length;
  435. out('1 0 obj');
  436. out('<</Type /Pages');
  437. var kids = '/Kids [';
  438. for (i = 0; i < page; i++) {
  439. kids += pageObjectNumbers[i] + ' 0 R ';
  440. }
  441. out(kids + ']');
  442. out('/Count ' + page);
  443. out('>>');
  444. out('endobj');
  445. events.publish('postPutPages');
  446. },
  447. putFont = function putFont(font) {
  448. font.objectNumber = newObject();
  449. out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
  450. if (typeof font.encoding === 'string') {
  451. out('/Encoding/' + font.encoding);
  452. }
  453. out('/Subtype/Type1>>');
  454. out('endobj');
  455. },
  456. putFonts = function putFonts() {
  457. for (var fontKey in fonts) {
  458. if (fonts.hasOwnProperty(fontKey)) {
  459. putFont(fonts[fontKey]);
  460. }
  461. }
  462. },
  463. putXobjectDict = function putXobjectDict() {
  464. // Loop through images, or other data objects
  465. events.publish('putXobjectDict');
  466. },
  467. putResourceDictionary = function putResourceDictionary() {
  468. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  469. out('/Font <<');
  470. // Do this for each font, the '1' bit is the index of the font
  471. for (var fontKey in fonts) {
  472. if (fonts.hasOwnProperty(fontKey)) {
  473. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  474. }
  475. }
  476. out('>>');
  477. out('/XObject <<');
  478. putXobjectDict();
  479. out('>>');
  480. },
  481. putResources = function putResources() {
  482. putFonts();
  483. events.publish('putResources');
  484. // Resource dictionary
  485. offsets[2] = content_length;
  486. out('2 0 obj');
  487. out('<<');
  488. putResourceDictionary();
  489. out('>>');
  490. out('endobj');
  491. events.publish('postPutResources');
  492. },
  493. putAdditionalObjects = function putAdditionalObjects() {
  494. events.publish('putAdditionalObjects');
  495. for (var i = 0; i < additionalObjects.length; i++) {
  496. var obj = additionalObjects[i];
  497. offsets[obj.objId] = content_length;
  498. out(obj.objId + ' 0 obj');
  499. out(obj.content);
  500. out('endobj');
  501. }
  502. objectNumber += additionalObjects.length;
  503. events.publish('postPutAdditionalObjects');
  504. },
  505. addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  506. // this is mapping structure for quick font key lookup.
  507. // returns the KEY of the font (ex: "F1") for a given
  508. // pair of font name and type (ex: "Arial". "Italic")
  509. if (!fontmap.hasOwnProperty(fontName)) {
  510. fontmap[fontName] = {};
  511. }
  512. fontmap[fontName][fontStyle] = fontKey;
  513. },
  514. /**
  515. * FontObject describes a particular font as member of an instnace of jsPDF
  516. *
  517. * It's a collection of properties like 'id' (to be used in PDF stream),
  518. * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  519. *
  520. * @class
  521. * @public
  522. * @property id {String} PDF-document-instance-specific label assinged to the font.
  523. * @property PostScriptName {String} PDF specification full name for the font
  524. * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  525. * @name FontObject
  526. * @ignore This should not be in the public docs.
  527. */
  528. addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
  529. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  530. // This is FontObject
  531. font = fonts[fontKey] = {
  532. 'id': fontKey,
  533. 'PostScriptName': PostScriptName,
  534. 'fontName': fontName,
  535. 'fontStyle': fontStyle,
  536. 'encoding': encoding,
  537. 'metadata': {}
  538. };
  539. addToFontDictionary(fontKey, fontName, fontStyle);
  540. events.publish('addFont', font);
  541. return fontKey;
  542. },
  543. addFonts = function addFonts() {
  544. var HELVETICA = "helvetica",
  545. TIMES = "times",
  546. COURIER = "courier",
  547. NORMAL = "normal",
  548. BOLD = "bold",
  549. ITALIC = "italic",
  550. BOLD_ITALIC = "bolditalic",
  551. encoding = 'StandardEncoding',
  552. ZAPF = "zapfdingbats",
  553. standardFonts = [
  554. ['Helvetica', HELVETICA, NORMAL],
  555. ['Helvetica-Bold', HELVETICA, BOLD],
  556. ['Helvetica-Oblique', HELVETICA, ITALIC],
  557. ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC],
  558. ['Courier', COURIER, NORMAL],
  559. ['Courier-Bold', COURIER, BOLD],
  560. ['Courier-Oblique', COURIER, ITALIC],
  561. ['Courier-BoldOblique', COURIER, BOLD_ITALIC],
  562. ['Times-Roman', TIMES, NORMAL],
  563. ['Times-Bold', TIMES, BOLD],
  564. ['Times-Italic', TIMES, ITALIC],
  565. ['Times-BoldItalic', TIMES, BOLD_ITALIC],
  566. ['ZapfDingbats', ZAPF]
  567. ];
  568. for (var i = 0, l = standardFonts.length; i < l; i++) {
  569. var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
  570. // adding aliases for standard fonts, this time matching the capitalization
  571. var parts = standardFonts[i][0].split('-');
  572. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  573. }
  574. events.publish('addFonts', {
  575. fonts: fonts,
  576. dictionary: fontmap
  577. });
  578. },
  579. SAFE = function __safeCall(fn) {
  580. fn.foo = function __safeCallWrapper() {
  581. try {
  582. return fn.apply(this, arguments);
  583. } catch (e) {
  584. var stack = e.stack || '';
  585. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  586. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  587. if (global.console) {
  588. global.console.error(m, e);
  589. if (global.alert) alert(m);
  590. } else {
  591. throw new Error(m);
  592. }
  593. }
  594. };
  595. fn.foo.bar = fn;
  596. return fn.foo;
  597. },
  598. to8bitStream = function to8bitStream(text, flags) {
  599. /**
  600. * PDF 1.3 spec:
  601. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  602. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  603. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  604. * to be a meaningful beginning of a word or phrase.) The remainder of the
  605. * string consists of Unicode character codes, according to the UTF-16 encoding
  606. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  607. * are represented as 2 bytes per character, with the high-order byte appearing first
  608. * in the string."
  609. *
  610. * In other words, if there are chars in a string with char code above 255, we
  611. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  612. *
  613. * HOWEVER!
  614. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  615. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  616. *
  617. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  618. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  619. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  620. * code page. There, however, all characters in the stream are treated as GIDs,
  621. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  622. * that is tied to a font).
  623. *
  624. * To signal this "special" PDFEscape / to8bitStream handling mode,
  625. * API.text() function sets (unless you overwrite it with manual values
  626. * given to API.text(.., flags) )
  627. * flags.autoencode = true
  628. * flags.noBOM = true
  629. *
  630. * ===================================================================================
  631. * `flags` properties relied upon:
  632. * .sourceEncoding = string with encoding label.
  633. * "Unicode" by default. = encoding of the incoming text.
  634. * pass some non-existing encoding name
  635. * (ex: 'Do not touch my strings! I know what I am doing.')
  636. * to make encoding code skip the encoding step.
  637. * .outputEncoding = Either valid PDF encoding name
  638. * (must be supported by jsPDF font metrics, otherwise no encoding)
  639. * or a JS object, where key = sourceCharCode, value = outputCharCode
  640. * missing keys will be treated as: sourceCharCode === outputCharCode
  641. * .noBOM
  642. * See comment higher above for explanation for why this is important
  643. * .autoencode
  644. * See comment higher above for explanation for why this is important
  645. */
  646. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  647. flags = flags || {};
  648. sourceEncoding = flags.sourceEncoding || 'Unicode';
  649. outputEncoding = flags.outputEncoding;
  650. // This 'encoding' section relies on font metrics format
  651. // attached to font objects by, among others,
  652. // "Willow Systems' standard_font_metrics plugin"
  653. // see jspdf.plugin.standard_font_metrics.js for format
  654. // of the font.metadata.encoding Object.
  655. // It should be something like
  656. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  657. // .widths = {0:width, code:width, ..., 'fof':divisor}
  658. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  659. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  660. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  661. // each font has default encoding. Some have it clearly defined.
  662. if (!outputEncoding && fonts[activeFontKey].encoding) {
  663. outputEncoding = fonts[activeFontKey].encoding;
  664. }
  665. // Hmmm, the above did not work? Let's try again, in different place.
  666. if (!outputEncoding && encodingBlock.codePages) {
  667. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  668. }
  669. if (typeof outputEncoding === 'string') {
  670. outputEncoding = encodingBlock[outputEncoding];
  671. }
  672. // we want output encoding to be a JS Object, where
  673. // key = sourceEncoding's character code and
  674. // value = outputEncoding's character code.
  675. if (outputEncoding) {
  676. isUnicode = false;
  677. newtext = [];
  678. for (i = 0, l = text.length; i < l; i++) {
  679. ch = outputEncoding[text.charCodeAt(i)];
  680. if (ch) {
  681. newtext.push(String.fromCharCode(ch));
  682. } else {
  683. newtext.push(text[i]);
  684. }
  685. // since we are looping over chars anyway, might as well
  686. // check for residual unicodeness
  687. if (newtext[i].charCodeAt(0) >> 8) {
  688. /* more than 255 */
  689. isUnicode = true;
  690. }
  691. }
  692. text = newtext.join('');
  693. }
  694. }
  695. i = text.length;
  696. // isUnicode may be set to false above. Hence the triple-equal to undefined
  697. while (isUnicode === undefined && i !== 0) {
  698. if (text.charCodeAt(i - 1) >> 8) {
  699. /* more than 255 */
  700. isUnicode = true;
  701. }
  702. i--;
  703. }
  704. if (!isUnicode) {
  705. return text;
  706. }
  707. newtext = flags.noBOM ? [] : [254, 255];
  708. for (i = 0, l = text.length; i < l; i++) {
  709. ch = text.charCodeAt(i);
  710. bch = ch >> 8; // divide by 256
  711. if (bch >> 8) {
  712. /* something left after dividing by 256 second time */
  713. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  714. }
  715. newtext.push(bch);
  716. newtext.push(ch - (bch << 8));
  717. }
  718. return String.fromCharCode.apply(undefined, newtext);
  719. },
  720. pdfEscape = function pdfEscape(text, flags) {
  721. /**
  722. * Replace '/', '(', and ')' with pdf-safe versions
  723. *
  724. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  725. * we also need to reference a unicode font and embed it - royal pain in the rear.
  726. *
  727. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  728. * which JavaScript Strings are happy to provide. So, while we still cannot display
  729. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  730. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  731. * is still parseable.
  732. * This will allow immediate support for unicode in document properties strings.
  733. */
  734. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  735. },
  736. putInfo = function putInfo() {
  737. out('/Producer (jsPDF ' + jsPDF.version + ')');
  738. for (var key in documentProperties) {
  739. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  740. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  741. }
  742. }
  743. var created = new Date(),
  744. tzoffset = created.getTimezoneOffset(),
  745. tzsign = tzoffset < 0 ? '+' : '-',
  746. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  747. tzmin = Math.abs(tzoffset % 60),
  748. tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  749. out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
  750. },
  751. putCatalog = function putCatalog() {
  752. out('/Type /Catalog');
  753. out('/Pages 1 0 R');
  754. // PDF13ref Section 7.2.1
  755. if (!zoomMode) zoomMode = 'fullwidth';
  756. switch (zoomMode) {
  757. case 'fullwidth':
  758. out('/OpenAction [3 0 R /FitH null]');
  759. break;
  760. case 'fullheight':
  761. out('/OpenAction [3 0 R /FitV null]');
  762. break;
  763. case 'fullpage':
  764. out('/OpenAction [3 0 R /Fit]');
  765. break;
  766. case 'original':
  767. out('/OpenAction [3 0 R /XYZ null null 1]');
  768. break;
  769. default:
  770. var pcn = '' + zoomMode;
  771. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  772. if (typeof zoomMode === 'number') {
  773. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  774. }
  775. }
  776. if (!layoutMode) layoutMode = 'continuous';
  777. switch (layoutMode) {
  778. case 'continuous':
  779. out('/PageLayout /OneColumn');
  780. break;
  781. case 'single':
  782. out('/PageLayout /SinglePage');
  783. break;
  784. case 'two':
  785. case 'twoleft':
  786. out('/PageLayout /TwoColumnLeft');
  787. break;
  788. case 'tworight':
  789. out('/PageLayout /TwoColumnRight');
  790. break;
  791. }
  792. if (pageMode) {
  793. /**
  794. * A name object specifying how the document should be displayed when opened:
  795. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  796. * UseOutlines : Document outline visible
  797. * UseThumbs : Thumbnail images visible
  798. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  799. */
  800. out('/PageMode /' + pageMode);
  801. }
  802. events.publish('putCatalog');
  803. },
  804. putTrailer = function putTrailer() {
  805. out('/Size ' + (objectNumber + 1));
  806. out('/Root ' + objectNumber + ' 0 R');
  807. out('/Info ' + (objectNumber - 1) + ' 0 R');
  808. },
  809. beginPage = function beginPage(width, height) {
  810. // Dimensions are stored as user units and converted to points on output
  811. var orientation = typeof height === 'string' && height.toLowerCase();
  812. if (typeof width === 'string') {
  813. var format = width.toLowerCase();
  814. if (pageFormats.hasOwnProperty(format)) {
  815. width = pageFormats[format][0] / k;
  816. height = pageFormats[format][1] / k;
  817. }
  818. }
  819. if (Array.isArray(width)) {
  820. height = width[1];
  821. width = width[0];
  822. }
  823. if (orientation) {
  824. switch (orientation.substr(0, 1)) {
  825. case 'l':
  826. if (height > width) orientation = 's';
  827. break;
  828. case 'p':
  829. if (width > height) orientation = 's';
  830. break;
  831. }
  832. if (orientation === 's') {
  833. tmp = width;
  834. width = height;
  835. height = tmp;
  836. }
  837. }
  838. outToPages = true;
  839. pages[++page] = [];
  840. pagedim[page] = {
  841. width: Number(width) || pageWidth,
  842. height: Number(height) || pageHeight
  843. };
  844. pagesContext[page] = {};
  845. _setPage(page);
  846. },
  847. _addPage = function _addPage() {
  848. beginPage.apply(this, arguments);
  849. // Set line width
  850. out(f2(lineWidth * k) + ' w');
  851. // Set draw color
  852. out(drawColor);
  853. // resurrecting non-default line caps, joins
  854. if (lineCapID !== 0) {
  855. out(lineCapID + ' J');
  856. }
  857. if (lineJoinID !== 0) {
  858. out(lineJoinID + ' j');
  859. }
  860. events.publish('addPage', {
  861. pageNumber: page
  862. });
  863. },
  864. _deletePage = function _deletePage(n) {
  865. if (n > 0 && n <= page) {
  866. pages.splice(n, 1);
  867. pagedim.splice(n, 1);
  868. page--;
  869. if (currentPage > page) {
  870. currentPage = page;
  871. }
  872. this.setPage(currentPage);
  873. }
  874. },
  875. _setPage = function _setPage(n) {
  876. if (n > 0 && n <= page) {
  877. currentPage = n;
  878. pageWidth = pagedim[n].width;
  879. pageHeight = pagedim[n].height;
  880. }
  881. },
  882. /**
  883. * Returns a document-specific font key - a label assigned to a
  884. * font name + font type combination at the time the font was added
  885. * to the font inventory.
  886. *
  887. * Font key is used as label for the desired font for a block of text
  888. * to be added to the PDF document stream.
  889. * @private
  890. * @function
  891. * @param fontName {String} can be undefined on "falthy" to indicate "use current"
  892. * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  893. * @returns {String} Font key.
  894. */
  895. _getFont = function _getFont(fontName, fontStyle) {
  896. var key;
  897. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  898. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  899. if (fontName !== undefined) {
  900. fontName = fontName.toLowerCase();
  901. }
  902. switch (fontName) {
  903. case 'sans-serif':
  904. case 'verdana':
  905. case 'arial':
  906. case 'helvetica':
  907. fontName = 'helvetica';
  908. break;
  909. case 'fixed':
  910. case 'monospace':
  911. case 'terminal':
  912. case 'courier':
  913. fontName = 'courier';
  914. break;
  915. case 'serif':
  916. case 'cursive':
  917. case 'fantasy':
  918. default:
  919. fontName = 'times';
  920. break;
  921. }
  922. try {
  923. // get a string like 'F3' - the KEY corresponding tot he font + type combination.
  924. key = fontmap[fontName][fontStyle];
  925. } catch (e) {}
  926. if (!key) {
  927. //throw new Error("Unable to look up font label for font '" + fontName + "', '"
  928. //+ fontStyle + "'. Refer to getFontList() for available fonts.");
  929. key = fontmap['times'][fontStyle];
  930. if (key == null) {
  931. key = fontmap['times']['normal'];
  932. }
  933. }
  934. return key;
  935. },
  936. buildDocument = function buildDocument() {
  937. outToPages = false; // switches out() to content
  938. objectNumber = 2;
  939. content_length = 0;
  940. content = [];
  941. offsets = [];
  942. additionalObjects = [];
  943. // Added for AcroForm
  944. events.publish('buildDocument');
  945. // putHeader()
  946. out('%PDF-' + pdfVersion);
  947. putPages();
  948. // Must happen after putPages
  949. // Modifies current object Id
  950. putAdditionalObjects();
  951. putResources();
  952. // Info
  953. newObject();
  954. out('<<');
  955. putInfo();
  956. out('>>');
  957. out('endobj');
  958. // Catalog
  959. newObject();
  960. out('<<');
  961. putCatalog();
  962. out('>>');
  963. out('endobj');
  964. // Cross-ref
  965. var o = content_length,
  966. i,
  967. p = "0000000000";
  968. out('xref');
  969. out('0 ' + (objectNumber + 1));
  970. out(p + ' 65535 f ');
  971. for (i = 1; i <= objectNumber; i++) {
  972. var offset = offsets[i];
  973. if (typeof offset === 'function') {
  974. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  975. } else {
  976. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  977. }
  978. }
  979. // Trailer
  980. out('trailer');
  981. out('<<');
  982. putTrailer();
  983. out('>>');
  984. out('startxref');
  985. out('' + o);
  986. out('%%EOF');
  987. outToPages = true;
  988. return content.join('\n');
  989. },
  990. getStyle = function getStyle(style) {
  991. // see path-painting operators in PDF spec
  992. var op = 'S'; // stroke
  993. if (style === 'F') {
  994. op = 'f'; // fill
  995. } else if (style === 'FD' || style === 'DF') {
  996. op = 'B'; // both
  997. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  998. /*
  999. Allow direct use of these PDF path-painting operators:
  1000. - f fill using nonzero winding number rule
  1001. - f* fill using even-odd rule
  1002. - B fill then stroke with fill using non-zero winding number rule
  1003. - B* fill then stroke with fill using even-odd rule
  1004. */
  1005. op = style;
  1006. }
  1007. return op;
  1008. },
  1009. getArrayBuffer = function getArrayBuffer() {
  1010. var data = buildDocument(),
  1011. len = data.length,
  1012. ab = new ArrayBuffer(len),
  1013. u8 = new Uint8Array(ab);
  1014. while (len--) {
  1015. u8[len] = data.charCodeAt(len);
  1016. }
  1017. return ab;
  1018. },
  1019. getBlob = function getBlob() {
  1020. return new Blob([getArrayBuffer()], {
  1021. type: "application/pdf"
  1022. });
  1023. },
  1024. /**
  1025. * Generates the PDF document.
  1026. *
  1027. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1028. *
  1029. * @param {String} type A string identifying one of the possible output types.
  1030. * @param {Object} options An object providing some additional signalling to PDF generator.
  1031. * @function
  1032. * @returns {jsPDF}
  1033. * @methodOf jsPDF#
  1034. * @name output
  1035. */
  1036. _output = SAFE(function(type, options) {
  1037. var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
  1038. switch (type) {
  1039. case undefined:
  1040. return buildDocument();
  1041. case 'save':
  1042. if (navigator.getUserMedia) {
  1043. if (global.URL === undefined || global.URL.createObjectURL === undefined) {
  1044. return API.output('dataurlnewwindow');
  1045. }
  1046. }
  1047. saveAs(getBlob(), options);
  1048. if (typeof saveAs.unload === 'function') {
  1049. if (global.setTimeout) {
  1050. setTimeout(saveAs.unload, 911);
  1051. }
  1052. }
  1053. break;
  1054. case 'arraybuffer':
  1055. return getArrayBuffer();
  1056. case 'blob':
  1057. return getBlob();
  1058. case 'bloburi':
  1059. case 'bloburl':
  1060. // User is responsible of calling revokeObjectURL
  1061. return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
  1062. case 'datauristring':
  1063. case 'dataurlstring':
  1064. return datauri;
  1065. case 'dataurlnewwindow':
  1066. var nW = global.open(datauri);
  1067. if (nW || typeof safari === "undefined") return nW;
  1068. /* pass through */
  1069. case 'datauri':
  1070. case 'dataurl':
  1071. return global.document.location.href = datauri;
  1072. default:
  1073. throw new Error('Output type "' + type + '" is not supported.');
  1074. }
  1075. // @TODO: Add different output options
  1076. }),
  1077. /**
  1078. * Used to see if a supplied hotfix was requested when the pdf instance was created.
  1079. * @param {String} hotfixName - The name of the hotfix to check.
  1080. * @returns {boolean}
  1081. */
  1082. hasHotfix = function hasHotfix(hotfixName) {
  1083. return Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1;
  1084. };
  1085. switch (unit) {
  1086. case 'pt':
  1087. k = 1;
  1088. break;
  1089. case 'mm':
  1090. k = 72 / 25.4000508;
  1091. break;
  1092. case 'cm':
  1093. k = 72 / 2.54000508;
  1094. break;
  1095. case 'in':
  1096. k = 72;
  1097. break;
  1098. case 'px':
  1099. if (hasHotfix('px_scaling') == true) {
  1100. k = 72 / 96;
  1101. } else {
  1102. k = 96 / 72;
  1103. }
  1104. break;
  1105. case 'pc':
  1106. k = 12;
  1107. break;
  1108. case 'em':
  1109. k = 12;
  1110. break;
  1111. case 'ex':
  1112. k = 6;
  1113. break;
  1114. default:
  1115. throw 'Invalid unit: ' + unit;
  1116. }
  1117. //---------------------------------------
  1118. // Public API
  1119. /**
  1120. * Object exposing internal API to plugins
  1121. * @public
  1122. */
  1123. API.internal = {
  1124. 'pdfEscape': pdfEscape,
  1125. 'getStyle': getStyle,
  1126. /**
  1127. * Returns {FontObject} describing a particular font.
  1128. * @public
  1129. * @function
  1130. * @param fontName {String} (Optional) Font's family name
  1131. * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  1132. * @returns {FontObject}
  1133. */
  1134. 'getFont': function getFont() {
  1135. return fonts[_getFont.apply(API, arguments)];
  1136. },
  1137. 'getFontSize': function getFontSize() {
  1138. return activeFontSize;
  1139. },
  1140. 'getLineHeight': function getLineHeight() {
  1141. return activeFontSize * lineHeightProportion;
  1142. },
  1143. 'write': function write(string1 /*, string2, string3, etc */ ) {
  1144. out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
  1145. },
  1146. 'getCoordinateString': function getCoordinateString(value) {
  1147. return f2(value * k);
  1148. },
  1149. 'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
  1150. return f2((pageHeight - value) * k);
  1151. },
  1152. 'collections': {},
  1153. 'newObject': newObject,
  1154. 'newAdditionalObject': newAdditionalObject,
  1155. 'newObjectDeferred': newObjectDeferred,
  1156. 'newObjectDeferredBegin': newObjectDeferredBegin,
  1157. 'putStream': putStream,
  1158. 'events': events,
  1159. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  1160. // units of measurement.
  1161. // scaleFactor is set at initialization of the document and calculated against the stated
  1162. // default measurement units for the document.
  1163. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  1164. // through multiplication.
  1165. 'scaleFactor': k,
  1166. 'pageSize': {
  1167. get width() {
  1168. return pageWidth;
  1169. },
  1170. get height() {
  1171. return pageHeight;
  1172. }
  1173. },
  1174. 'output': function output(type, options) {
  1175. return _output(type, options);
  1176. },
  1177. 'getNumberOfPages': function getNumberOfPages() {
  1178. return pages.length - 1;
  1179. },
  1180. 'pages': pages,
  1181. 'out': out,
  1182. 'f2': f2,
  1183. 'getPageInfo': function getPageInfo(pageNumberOneBased) {
  1184. var objId = (pageNumberOneBased - 1) * 2 + 3;
  1185. return {
  1186. objId: objId,
  1187. pageNumber: pageNumberOneBased,
  1188. pageContext: pagesContext[pageNumberOneBased]
  1189. };
  1190. },
  1191. 'getCurrentPageInfo': function getCurrentPageInfo() {
  1192. var objId = (currentPage - 1) * 2 + 3;
  1193. return {
  1194. objId: objId,
  1195. pageNumber: currentPage,
  1196. pageContext: pagesContext[currentPage]
  1197. };
  1198. },
  1199. 'getPDFVersion': function getPDFVersion() {
  1200. return pdfVersion;
  1201. },
  1202. 'hasHotfix': hasHotfix //Expose the hasHotfix check so plugins can also check them.
  1203. };
  1204. /**
  1205. * Adds (and transfers the focus to) new page to the PDF document.
  1206. * @function
  1207. * @returns {jsPDF}
  1208. *
  1209. * @methodOf jsPDF#
  1210. * @name addPage
  1211. */
  1212. API.addPage = function() {
  1213. _addPage.apply(this, arguments);
  1214. return this;
  1215. };
  1216. /**
  1217. * Adds (and transfers the focus to) new page to the PDF document.
  1218. * @function
  1219. * @returns {jsPDF}
  1220. *
  1221. * @methodOf jsPDF#
  1222. * @name setPage
  1223. * @param {Number} page Switch the active page to the page number specified
  1224. * @example
  1225. * doc = jsPDF()
  1226. * doc.addPage()
  1227. * doc.addPage()
  1228. * doc.text('I am on page 3', 10, 10)
  1229. * doc.setPage(1)
  1230. * doc.text('I am on page 1', 10, 10)
  1231. */
  1232. API.setPage = function() {
  1233. _setPage.apply(this, arguments);
  1234. return this;
  1235. };
  1236. API.insertPage = function(beforePage) {
  1237. this.addPage();
  1238. this.movePage(currentPage, beforePage);
  1239. return this;
  1240. };
  1241. API.movePage = function(targetPage, beforePage) {
  1242. if (targetPage > beforePage) {
  1243. var tmpPages = pages[targetPage];
  1244. var tmpPagedim = pagedim[targetPage];
  1245. var tmpPagesContext = pagesContext[targetPage];
  1246. for (var i = targetPage; i > beforePage; i--) {
  1247. pages[i] = pages[i - 1];
  1248. pagedim[i] = pagedim[i - 1];
  1249. pagesContext[i] = pagesContext[i - 1];
  1250. }
  1251. pages[beforePage] = tmpPages;
  1252. pagedim[beforePage] = tmpPagedim;
  1253. pagesContext[beforePage] = tmpPagesContext;
  1254. this.setPage(beforePage);
  1255. } else if (targetPage < beforePage) {
  1256. var tmpPages = pages[targetPage];
  1257. var tmpPagedim = pagedim[targetPage];
  1258. var tmpPagesContext = pagesContext[targetPage];
  1259. for (var i = targetPage; i < beforePage; i++) {
  1260. pages[i] = pages[i + 1];
  1261. pagedim[i] = pagedim[i + 1];
  1262. pagesContext[i] = pagesContext[i + 1];
  1263. }
  1264. pages[beforePage] = tmpPages;
  1265. pagedim[beforePage] = tmpPagedim;
  1266. pagesContext[beforePage] = tmpPagesContext;
  1267. this.setPage(beforePage);
  1268. }
  1269. return this;
  1270. };
  1271. API.deletePage = function() {
  1272. _deletePage.apply(this, arguments);
  1273. return this;
  1274. };
  1275. /**
  1276. * Set the display mode options of the page like zoom and layout.
  1277. *
  1278. * @param {integer|String} zoom You can pass an integer or percentage as
  1279. * a string. 2 will scale the document up 2x, '200%' will scale up by the
  1280. * same amount. You can also set it to 'fullwidth', 'fullheight',
  1281. * 'fullpage', or 'original'.
  1282. *
  1283. * Only certain PDF readers support this, such as Adobe Acrobat
  1284. *
  1285. * @param {String} layout Layout mode can be: 'continuous' - this is the
  1286. * default continuous scroll. 'single' - the single page mode only shows one
  1287. * page at a time. 'twoleft' - two column left mode, first page starts on
  1288. * the left, and 'tworight' - pages are laid out in two columns, with the
  1289. * first page on the right. This would be used for books.
  1290. * @param {String} pmode 'UseOutlines' - it shows the
  1291. * outline of the document on the left. 'UseThumbs' - shows thumbnails along
  1292. * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
  1293. *
  1294. * @function
  1295. * @returns {jsPDF}
  1296. * @name setDisplayMode
  1297. */
  1298. API.setDisplayMode = function(zoom, layout, pmode) {
  1299. zoomMode = zoom;
  1300. layoutMode = layout;
  1301. pageMode = pmode;
  1302. var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
  1303. if (validPageModes.indexOf(pmode) == -1) {
  1304. throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
  1305. }
  1306. return this;
  1307. },
  1308. /**
  1309. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1310. *
  1311. * @function
  1312. * @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.
  1313. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1314. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1315. * @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.
  1316. * @returns {jsPDF}
  1317. * @methodOf jsPDF#
  1318. * @name text
  1319. */
  1320. API.text = function(text, x, y, flags, angle, align) {
  1321. /**
  1322. * Inserts something like this into PDF
  1323. * BT
  1324. * /F1 16 Tf % Font name + size
  1325. * 16 TL % How many units down for next line in multiline text
  1326. * 0 g % color
  1327. * 28.35 813.54 Td % position
  1328. * (line one) Tj
  1329. * T* (line two) Tj
  1330. * T* (line three) Tj
  1331. * ET
  1332. */
  1333. function ESC(s) {
  1334. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1335. return pdfEscape(s, flags);
  1336. }
  1337. // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1338. // in effort to make all calls have similar signature like
  1339. // function(data, coordinates... , miscellaneous)
  1340. // this method had its args flipped.
  1341. // code below allows backward compatibility with old arg order.
  1342. if (typeof text === 'number') {
  1343. tmp = y;
  1344. y = x;
  1345. x = text;
  1346. text = tmp;
  1347. }
  1348. // If there are any newlines in text, we assume
  1349. // the user wanted to print multiple lines, so break the
  1350. // text up into an array. If the text is already an array,
  1351. // we assume the user knows what they are doing.
  1352. // Convert text into an array anyway to simplify
  1353. // later code.
  1354. if (typeof text === 'string') {
  1355. if (text.match(/[\n\r]/)) {
  1356. text = text.split(/\r\n|\r|\n/g);
  1357. } else {
  1358. text = [text];
  1359. }
  1360. }
  1361. if (typeof angle === 'string') {
  1362. align = angle;
  1363. angle = null;
  1364. }
  1365. if (typeof flags === 'string') {
  1366. align = flags;
  1367. flags = null;
  1368. }
  1369. if (typeof flags === 'number') {
  1370. angle = flags;
  1371. flags = null;
  1372. }
  1373. var xtra = '',
  1374. mode = 'Td',
  1375. todo;
  1376. if (angle) {
  1377. angle *= Math.PI / 180;
  1378. var c = Math.cos(angle),
  1379. s = Math.sin(angle);
  1380. xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ");
  1381. mode = 'Tm';
  1382. }
  1383. flags = flags || {};
  1384. if (!('noBOM' in flags)) flags.noBOM = true;
  1385. if (!('autoencode' in flags)) flags.autoencode = true;
  1386. var strokeOption = '';
  1387. var pageContext = this.internal.getCurrentPageInfo().pageContext;
  1388. if (true === flags.stroke) {
  1389. if (pageContext.lastTextWasStroke !== true) {
  1390. strokeOption = '1 Tr\n';
  1391. pageContext.lastTextWasStroke = true;
  1392. }
  1393. } else {
  1394. if (pageContext.lastTextWasStroke) {
  1395. strokeOption = '0 Tr\n';
  1396. }
  1397. pageContext.lastTextWasStroke = false;
  1398. }
  1399. if (typeof this._runningPageHeight === 'undefined') {
  1400. this._runningPageHeight = 0;
  1401. }
  1402. if (typeof text === 'string') {
  1403. text = ESC(text);
  1404. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1405. // we don't want to destroy original text array, so cloning it
  1406. var sa = text.concat(),
  1407. da = [],
  1408. len = sa.length;
  1409. // we do array.join('text that must not be PDFescaped")
  1410. // thus, pdfEscape each component separately
  1411. while (len--) {
  1412. da.push(ESC(sa.shift()));
  1413. }
  1414. if (align) {
  1415. var left,
  1416. prevX,
  1417. maxLineLength,
  1418. leading = activeFontSize * lineHeightProportion,
  1419. lineWidths = text.map(function(v) {
  1420. return this.getStringUnitWidth(v) * activeFontSize / k;
  1421. }, this);
  1422. maxLineLength = Math.max.apply(Math, lineWidths);
  1423. // The first line uses the "main" Td setting,
  1424. // and the subsequent lines are offset by the
  1425. // previous line's x coordinate.
  1426. if (align === "center") {
  1427. // The passed in x coordinate defines
  1428. // the center point.
  1429. left = x - maxLineLength / 2;
  1430. x -= lineWidths[0] / 2;
  1431. } else if (align === "right") {
  1432. // The passed in x coordinate defines the
  1433. // rightmost point of the text.
  1434. left = x - maxLineLength;
  1435. x -= lineWidths[0];
  1436. } else {
  1437. throw new Error('Unrecognized alignment option, use "center" or "right".');
  1438. }
  1439. prevX = x;
  1440. text = da[0];
  1441. for (var i = 1, len = da.length; i < len; i++) {
  1442. var delta = maxLineLength - lineWidths[i];
  1443. if (align === "center") delta /= 2;
  1444. // T* = x-offset leading Td ( text )
  1445. text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
  1446. prevX = left + delta;
  1447. }
  1448. } else {
  1449. text = da.join(") Tj\nT* (");
  1450. }
  1451. } else {
  1452. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1453. }
  1454. // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
  1455. // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
  1456. // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
  1457. // Thus, there is NO useful, *reliable* concept of "default" font for a page.
  1458. // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
  1459. // - readers dealing smartly with brokenness of jsPDF's markup.
  1460. var curY;
  1461. if (todo) {
  1462. //this.addPage();
  1463. //this._runningPageHeight += y - (activeFontSize * 1.7 / k);
  1464. //curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1465. } else {
  1466. curY = f2((pageHeight - y) * k);
  1467. }
  1468. //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
  1469. // if (curY < 0){
  1470. // console.log('auto page break');
  1471. // this.addPage();
  1472. // this._runningPageHeight = y - (activeFontSize * 1.7 / k);
  1473. // curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1474. // }
  1475. out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1476. activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
  1477. strokeOption + // stroke option
  1478. textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
  1479. if (todo) {
  1480. //this.text( todo, x, activeFontSize * 1.7 / k);
  1481. //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
  1482. this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
  1483. }
  1484. return this;
  1485. };
  1486. /**
  1487. * Letter spacing method to print text with gaps
  1488. *
  1489. * @function
  1490. * @param {String|Array} text String to be added to the page.
  1491. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1492. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1493. * @param {Number} spacing Spacing (in units declared at inception)
  1494. * @returns {jsPDF}
  1495. * @methodOf jsPDF#
  1496. * @name lstext
  1497. * @deprecated We'll be removing this function. It doesn't take character width into account.
  1498. */
  1499. API.lstext = function(text, x, y, spacing) {
  1500. console.warn('jsPDF.lstext is deprecated');
  1501. for (var i = 0, len = text.length; i < len; i++, x += spacing) {
  1502. this.text(text[i], x, y);
  1503. }
  1504. return this;
  1505. };
  1506. API.line = function(x1, y1, x2, y2) {
  1507. return this.lines([
  1508. [x2 - x1, y2 - y1]
  1509. ], x1, y1);
  1510. };
  1511. API.clip = function() {
  1512. // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
  1513. // Call .clip() after calling .rect() with a style argument of null
  1514. out('W'); // clip
  1515. out('S'); // stroke path; necessary for clip to work
  1516. };
  1517. /**
  1518. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  1519. * We introduce the fixed version so as to not break API.
  1520. * @param fillRule
  1521. */
  1522. API.clip_fixed = function(fillRule) {
  1523. // Call .clip() after calling drawing ops with a style argument of null
  1524. // W is the PDF clipping op
  1525. if ('evenodd' === fillRule) {
  1526. out('W*');
  1527. } else {
  1528. out('W');
  1529. }
  1530. // End the path object without filling or stroking it.
  1531. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  1532. // (see Section 4.4.3, 鈥淐lipping Path Operators鈥�)
  1533. out('n');
  1534. };
  1535. /**
  1536. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1537. * All data points in `lines` are relative to last line origin.
  1538. * `x`, `y` become x1,y1 for first line / curve in the set.
  1539. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1540. * 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.
  1541. *
  1542. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1543. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1544. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1545. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1546. * @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.
  1547. * @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.
  1548. * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1549. * @function
  1550. * @returns {jsPDF}
  1551. * @methodOf jsPDF#
  1552. * @name lines
  1553. */
  1554. API.lines = function(lines, x, y, scale, style, closed) {
  1555. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1556. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1557. // in effort to make all calls have similar signature like
  1558. // function(content, coordinateX, coordinateY , miscellaneous)
  1559. // this method had its args flipped.
  1560. // code below allows backward compatibility with old arg order.
  1561. if (typeof lines === 'number') {
  1562. tmp = y;
  1563. y = x;
  1564. x = lines;
  1565. lines = tmp;
  1566. }
  1567. scale = scale || [1, 1];
  1568. // starting point
  1569. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1570. scalex = scale[0];
  1571. scaley = scale[1];
  1572. l = lines.length;
  1573. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1574. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1575. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1576. x4 = x; // last / ending point = starting point for first item.
  1577. y4 = y; // last / ending point = starting point for first item.
  1578. for (i = 0; i < l; i++) {
  1579. leg = lines[i];
  1580. if (leg.length === 2) {
  1581. // simple line
  1582. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1583. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1584. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1585. } else {
  1586. // bezier curve
  1587. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1588. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1589. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1590. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1591. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1592. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1593. out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
  1594. }
  1595. }
  1596. if (closed) {
  1597. out(' h');
  1598. }
  1599. // stroking / filling / both the path
  1600. if (style !== null) {
  1601. out(getStyle(style));
  1602. }
  1603. return this;
  1604. };
  1605. /**
  1606. * Adds a rectangle to PDF
  1607. *
  1608. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1609. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1610. * @param {Number} w Width (in units declared at inception of PDF document)
  1611. * @param {Number} h Height (in units declared at inception of PDF document)
  1612. * @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.
  1613. * @function
  1614. * @returns {jsPDF}
  1615. * @methodOf jsPDF#
  1616. * @name rect
  1617. */
  1618. API.rect = function(x, y, w, h, style) {
  1619. var op = getStyle(style);
  1620. out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
  1621. if (style !== null) {
  1622. out(getStyle(style));
  1623. }
  1624. return this;
  1625. };
  1626. /**
  1627. * Adds a triangle to PDF
  1628. *
  1629. * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1630. * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1631. * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1632. * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1633. * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1634. * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1635. * @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.
  1636. * @function
  1637. * @returns {jsPDF}
  1638. * @methodOf jsPDF#
  1639. * @name triangle
  1640. */
  1641. API.triangle = function(x1, y1, x2, y2, x3, y3, style) {
  1642. this.lines([
  1643. [x2 - x1, y2 - y1], // vector to point 2
  1644. [x3 - x2, y3 - y2], // vector to point 3
  1645. [x1 - x3, y1 - y3] // closing vector back to point 1
  1646. ], x1, y1, // start of path
  1647. [1, 1], style, true);
  1648. return this;
  1649. };
  1650. /**
  1651. * Adds a rectangle with rounded corners to PDF
  1652. *
  1653. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1654. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1655. * @param {Number} w Width (in units declared at inception of PDF document)
  1656. * @param {Number} h Height (in units declared at inception of PDF document)
  1657. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1658. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1659. * @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.
  1660. * @function
  1661. * @returns {jsPDF}
  1662. * @methodOf jsPDF#
  1663. * @name roundedRect
  1664. */
  1665. API.roundedRect = function(x, y, w, h, rx, ry, style) {
  1666. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  1667. this.lines([
  1668. [w - 2 * rx, 0],
  1669. [rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry],
  1670. [0, h - 2 * ry],
  1671. [0, ry * MyArc, -(rx * MyArc), ry, -rx, ry],
  1672. [-w + 2 * rx, 0],
  1673. [-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry],
  1674. [0, -h + 2 * ry],
  1675. [0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]
  1676. ], x + rx, y, // start of path
  1677. [1, 1], style);
  1678. return this;
  1679. };
  1680. /**
  1681. * Adds an ellipse to PDF
  1682. *
  1683. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1684. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1685. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1686. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1687. * @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.
  1688. * @function
  1689. * @returns {jsPDF}
  1690. * @methodOf jsPDF#
  1691. * @name ellipse
  1692. */
  1693. API.ellipse = function(x, y, rx, ry, style) {
  1694. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1695. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1696. 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(' '));
  1697. 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(' '));
  1698. 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(' '));
  1699. 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(' '));
  1700. if (style !== null) {
  1701. out(getStyle(style));
  1702. }
  1703. return this;
  1704. };
  1705. /**
  1706. * Adds an circle to PDF
  1707. *
  1708. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1709. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1710. * @param {Number} r Radius (in units declared at inception of PDF document)
  1711. * @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.
  1712. * @function
  1713. * @returns {jsPDF}
  1714. * @methodOf jsPDF#
  1715. * @name circle
  1716. */
  1717. API.circle = function(x, y, r, style) {
  1718. return this.ellipse(x, y, r, r, style);
  1719. };
  1720. /**
  1721. * Adds a properties to the PDF document
  1722. *
  1723. * @param {Object} A property_name-to-property_value object structure.
  1724. * @function
  1725. * @returns {jsPDF}
  1726. * @methodOf jsPDF#
  1727. * @name setProperties
  1728. */
  1729. API.setProperties = function(properties) {
  1730. // copying only those properties we can render.
  1731. for (var property in documentProperties) {
  1732. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1733. documentProperties[property] = properties[property];
  1734. }
  1735. }
  1736. return this;
  1737. };
  1738. /**
  1739. * Sets font size for upcoming text elements.
  1740. *
  1741. * @param {Number} size Font size in points.
  1742. * @function
  1743. * @returns {jsPDF}
  1744. * @methodOf jsPDF#
  1745. * @name setFontSize
  1746. */
  1747. API.setFontSize = function(size) {
  1748. activeFontSize = size;
  1749. return this;
  1750. };
  1751. /**
  1752. * Sets text font face, variant for upcoming text elements.
  1753. * See output of jsPDF.getFontList() for possible font names, styles.
  1754. *
  1755. * @param {String} fontName Font name or family. Example: "times"
  1756. * @param {String} fontStyle Font style or variant. Example: "italic"
  1757. * @function
  1758. * @returns {jsPDF}
  1759. * @methodOf jsPDF#
  1760. * @name setFont
  1761. */
  1762. API.setFont = function(fontName, fontStyle) {
  1763. activeFontKey = _getFont(fontName, fontStyle);
  1764. // if font is not found, the above line blows up and we never go further
  1765. return this;
  1766. };
  1767. /**
  1768. * Switches font style or variant for upcoming text elements,
  1769. * while keeping the font face or family same.
  1770. * See output of jsPDF.getFontList() for possible font names, styles.
  1771. *
  1772. * @param {String} style Font style or variant. Example: "italic"
  1773. * @function
  1774. * @returns {jsPDF}
  1775. * @methodOf jsPDF#
  1776. * @name setFontStyle
  1777. */
  1778. API.setFontStyle = API.setFontType = function(style) {
  1779. activeFontKey = _getFont(undefined, style);
  1780. // if font is not found, the above line blows up and we never go further
  1781. return this;
  1782. };
  1783. /**
  1784. * Returns an object - a tree of fontName to fontStyle relationships available to
  1785. * active PDF document.
  1786. *
  1787. * @public
  1788. * @function
  1789. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  1790. * @methodOf jsPDF#
  1791. * @name getFontList
  1792. */
  1793. API.getFontList = function() {
  1794. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  1795. var list = {},
  1796. fontName,
  1797. fontStyle,
  1798. tmp;
  1799. for (fontName in fontmap) {
  1800. if (fontmap.hasOwnProperty(fontName)) {
  1801. list[fontName] = tmp = [];
  1802. for (fontStyle in fontmap[fontName]) {
  1803. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  1804. tmp.push(fontStyle);
  1805. }
  1806. }
  1807. }
  1808. }
  1809. return list;
  1810. };
  1811. /**
  1812. * Add a custom font.
  1813. *
  1814. * @param {String} Postscript name of the Font. Example: "Menlo-Regular"
  1815. * @param {String} Name of font-family from @font-face definition. Example: "Menlo Regular"
  1816. * @param {String} Font style. Example: "normal"
  1817. * @function
  1818. * @returns the {fontKey} (same as the internal method)
  1819. * @methodOf jsPDF#
  1820. * @name addFont
  1821. */
  1822. API.addFont = function(postScriptName, fontName, fontStyle) {
  1823. addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
  1824. };
  1825. /**
  1826. * Sets line width for upcoming lines.
  1827. *
  1828. * @param {Number} width Line width (in units declared at inception of PDF document)
  1829. * @function
  1830. * @returns {jsPDF}
  1831. * @methodOf jsPDF#
  1832. * @name setLineWidth
  1833. */
  1834. API.setLineWidth = function(width) {
  1835. out((width * k).toFixed(2) + ' w');
  1836. return this;
  1837. };
  1838. /**
  1839. * Sets the stroke color for upcoming elements.
  1840. *
  1841. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1842. * color space is implied.
  1843. *
  1844. * When only ch1 is given, "Gray" color space is implied and it
  1845. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1846. * if values are communicated as String types, or in range from 0 (black)
  1847. * to 255 (white) if communicated as Number type.
  1848. * The RGB-like 0-255 range is provided for backward compatibility.
  1849. *
  1850. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1851. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1852. * (max intensity) if values are communicated as String types, or
  1853. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1854. * as Number types.
  1855. * The RGB-like 0-255 range is provided for backward compatibility.
  1856. *
  1857. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1858. * value must be a in the range from 0.00 (0% concentration) to to
  1859. * 1.00 (100% concentration)
  1860. *
  1861. * Because JavaScript treats fixed point numbers badly (rounds to
  1862. * floating point nearest to binary representation) it is highly advised to
  1863. * communicate the fractional numbers as String types, not JavaScript Number type.
  1864. *
  1865. * @param {Number|String} ch1 Color channel value
  1866. * @param {Number|String} ch2 Color channel value
  1867. * @param {Number|String} ch3 Color channel value
  1868. * @param {Number|String} ch4 Color channel value
  1869. *
  1870. * @function
  1871. * @returns {jsPDF}
  1872. * @methodOf jsPDF#
  1873. * @name setDrawColor
  1874. */
  1875. API.setDrawColor = function(ch1, ch2, ch3, ch4) {
  1876. var color;
  1877. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1878. // Gray color space.
  1879. if (typeof ch1 === 'string') {
  1880. color = ch1 + ' G';
  1881. } else {
  1882. color = f2(ch1 / 255) + ' G';
  1883. }
  1884. } else if (ch4 === undefined) {
  1885. // RGB
  1886. if (typeof ch1 === 'string') {
  1887. color = [ch1, ch2, ch3, 'RG'].join(' ');
  1888. } else {
  1889. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
  1890. }
  1891. } else {
  1892. // CMYK
  1893. if (typeof ch1 === 'string') {
  1894. color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
  1895. } else {
  1896. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
  1897. }
  1898. }
  1899. out(color);
  1900. return this;
  1901. };
  1902. /**
  1903. * Sets the fill color for upcoming elements.
  1904. *
  1905. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1906. * color space is implied.
  1907. *
  1908. * When only ch1 is given, "Gray" color space is implied and it
  1909. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1910. * if values are communicated as String types, or in range from 0 (black)
  1911. * to 255 (white) if communicated as Number type.
  1912. * The RGB-like 0-255 range is provided for backward compatibility.
  1913. *
  1914. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1915. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1916. * (max intensity) if values are communicated as String types, or
  1917. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1918. * as Number types.
  1919. * The RGB-like 0-255 range is provided for backward compatibility.
  1920. *
  1921. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1922. * value must be a in the range from 0.00 (0% concentration) to to
  1923. * 1.00 (100% concentration)
  1924. *
  1925. * Because JavaScript treats fixed point numbers badly (rounds to
  1926. * floating point nearest to binary representation) it is highly advised to
  1927. * communicate the fractional numbers as String types, not JavaScript Number type.
  1928. *
  1929. * @param {Number|String} ch1 Color channel value
  1930. * @param {Number|String} ch2 Color channel value
  1931. * @param {Number|String} ch3 Color channel value
  1932. * @param {Number|String} ch4 Color channel value
  1933. *
  1934. * @function
  1935. * @returns {jsPDF}
  1936. * @methodOf jsPDF#
  1937. * @name setFillColor
  1938. */
  1939. API.setFillColor = function(ch1, ch2, ch3, ch4) {
  1940. var color;
  1941. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1942. // Gray color space.
  1943. if (typeof ch1 === 'string') {
  1944. color = ch1 + ' g';
  1945. } else {
  1946. color = f2(ch1 / 255) + ' g';
  1947. }
  1948. } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
  1949. // RGB
  1950. if (typeof ch1 === 'string') {
  1951. color = [ch1, ch2, ch3, 'rg'].join(' ');
  1952. } else {
  1953. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
  1954. }
  1955. if (ch4 && ch4.a === 0) {
  1956. //TODO Implement transparency.
  1957. //WORKAROUND use white for now
  1958. color = ['255', '255', '255', 'rg'].join(' ');
  1959. }
  1960. } else {
  1961. // CMYK
  1962. if (typeof ch1 === 'string') {
  1963. color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
  1964. } else {
  1965. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
  1966. }
  1967. }
  1968. out(color);
  1969. return this;
  1970. };
  1971. /**
  1972. * Sets the text color for upcoming elements.
  1973. * If only one, first argument is given,
  1974. * treats the value as gray-scale color value.
  1975. *
  1976. * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
  1977. * @param {Number} g Green channel color value in range 0-255
  1978. * @param {Number} b Blue channel color value in range 0-255
  1979. * @function
  1980. * @returns {jsPDF}
  1981. * @methodOf jsPDF#
  1982. * @name setTextColor
  1983. */
  1984. API.setTextColor = function(r, g, b) {
  1985. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  1986. var hex = parseInt(r.substr(1), 16);
  1987. r = hex >> 16 & 255;
  1988. g = hex >> 8 & 255;
  1989. b = hex & 255;
  1990. }
  1991. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  1992. textColor = f3(r / 255) + ' g';
  1993. } else {
  1994. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  1995. }
  1996. return this;
  1997. };
  1998. /**
  1999. * Is an Object providing a mapping from human-readable to
  2000. * integer flag values designating the varieties of line cap
  2001. * and join styles.
  2002. *
  2003. * @returns {Object}
  2004. * @fieldOf jsPDF#
  2005. * @name CapJoinStyles
  2006. */
  2007. API.CapJoinStyles = {
  2008. 0: 0,
  2009. 'butt': 0,
  2010. 'but': 0,
  2011. 'miter': 0,
  2012. 1: 1,
  2013. 'round': 1,
  2014. 'rounded': 1,
  2015. 'circle': 1,
  2016. 2: 2,
  2017. 'projecting': 2,
  2018. 'project': 2,
  2019. 'square': 2,
  2020. 'bevel': 2
  2021. };
  2022. /**
  2023. * Sets the line cap styles
  2024. * See {jsPDF.CapJoinStyles} for variants
  2025. *
  2026. * @param {String|Number} style A string or number identifying the type of line cap
  2027. * @function
  2028. * @returns {jsPDF}
  2029. * @methodOf jsPDF#
  2030. * @name setLineCap
  2031. */
  2032. API.setLineCap = function(style) {
  2033. var id = this.CapJoinStyles[style];
  2034. if (id === undefined) {
  2035. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2036. }
  2037. lineCapID = id;
  2038. out(id + ' J');
  2039. return this;
  2040. };
  2041. /**
  2042. * Sets the line join styles
  2043. * See {jsPDF.CapJoinStyles} for variants
  2044. *
  2045. * @param {String|Number} style A string or number identifying the type of line join
  2046. * @function
  2047. * @returns {jsPDF}
  2048. * @methodOf jsPDF#
  2049. * @name setLineJoin
  2050. */
  2051. API.setLineJoin = function(style) {
  2052. var id = this.CapJoinStyles[style];
  2053. if (id === undefined) {
  2054. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2055. }
  2056. lineJoinID = id;
  2057. out(id + ' j');
  2058. return this;
  2059. };
  2060. // Output is both an internal (for plugins) and external function
  2061. API.output = _output;
  2062. /**
  2063. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  2064. * @param {String} filename The filename including extension.
  2065. *
  2066. * @function
  2067. * @returns {jsPDF}
  2068. * @methodOf jsPDF#
  2069. * @name save
  2070. */
  2071. API.save = function(filename) {
  2072. API.output('save', filename);
  2073. };
  2074. // applying plugins (more methods) ON TOP of built-in API.
  2075. // this is intentional as we allow plugins to override
  2076. // built-ins
  2077. for (var plugin in jsPDF.API) {
  2078. if (jsPDF.API.hasOwnProperty(plugin)) {
  2079. if (plugin === 'events' && jsPDF.API.events.length) {
  2080. (function(events, newEvents) {
  2081. // jsPDF.API.events is a JS Array of Arrays
  2082. // where each Array is a pair of event name, handler
  2083. // Events were added by plugins to the jsPDF instantiator.
  2084. // These are always added to the new instance and some ran
  2085. // during instantiation.
  2086. var eventname, handler_and_args, i;
  2087. for (i = newEvents.length - 1; i !== -1; i--) {
  2088. // subscribe takes 3 args: 'topic', function, runonce_flag
  2089. // if undefined, runonce is false.
  2090. // users can attach callback directly,
  2091. // or they can attach an array with [callback, runonce_flag]
  2092. // that's what the "apply" magic is for below.
  2093. eventname = newEvents[i][0];
  2094. handler_and_args = newEvents[i][1];
  2095. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  2096. }
  2097. })(events, jsPDF.API.events);
  2098. } else {
  2099. API[plugin] = jsPDF.API[plugin];
  2100. }
  2101. }
  2102. }
  2103. //////////////////////////////////////////////////////
  2104. // continuing initialization of jsPDF Document object
  2105. //////////////////////////////////////////////////////
  2106. // Add the first page automatically
  2107. addFonts();
  2108. activeFontKey = 'F1';
  2109. _addPage(format, orientation);
  2110. events.publish('initialized');
  2111. return API;
  2112. }
  2113. /**
  2114. * jsPDF.API is a STATIC property of jsPDF class.
  2115. * jsPDF.API is an object you can add methods and properties to.
  2116. * The methods / properties you add will show up in new jsPDF objects.
  2117. *
  2118. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  2119. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  2120. * Examples:
  2121. * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  2122. * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  2123. *
  2124. * @static
  2125. * @public
  2126. * @memberOf jsPDF
  2127. * @name API
  2128. *
  2129. * @example
  2130. * jsPDF.API.mymethod = function(){
  2131. * // 'this' will be ref to internal API object. see jsPDF source
  2132. * // , so you can refer to built-in methods like so:
  2133. * // this.line(....)
  2134. * // this.text(....)
  2135. * }
  2136. * var pdfdoc = new jsPDF()
  2137. * pdfdoc.mymethod() // <- !!!!!!
  2138. */
  2139. jsPDF.API = {
  2140. events: []
  2141. };
  2142. jsPDF.version = "1.x-master";
  2143. if (typeof define === 'function' && define.amd) {
  2144. define('jsPDF', function() {
  2145. return jsPDF;
  2146. });
  2147. } else if (typeof module !== 'undefined' && module.exports) {
  2148. module.exports = jsPDF;
  2149. } else {
  2150. global.jsPDF = jsPDF;
  2151. }
  2152. return jsPDF;
  2153. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  2154. /**
  2155. * jsPDF AcroForm Plugin
  2156. * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
  2157. *
  2158. * Licensed under the MIT License.
  2159. * http://opensource.org/licenses/mit-license
  2160. */
  2161. (window.AcroForm = function(jsPDFAPI) {
  2162. 'use strict';
  2163. var AcroForm = window.AcroForm;
  2164. AcroForm.scale = function(x) {
  2165. return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
  2166. };
  2167. AcroForm.antiScale = function(x) {
  2168. return 1 / acroformPlugin.internal.scaleFactor * x;
  2169. };
  2170. var acroformPlugin = {
  2171. fields: [],
  2172. xForms: [],
  2173. /**
  2174. * acroFormDictionaryRoot contains information about the AcroForm Dictionary
  2175. * 0: The Event-Token, the AcroFormDictionaryCallback has
  2176. * 1: The Object ID of the Root
  2177. */
  2178. acroFormDictionaryRoot: null,
  2179. /**
  2180. * After the PDF gets evaluated, the reference to the root has to be reset,
  2181. * this indicates, whether the root has already been printed out
  2182. */
  2183. printedOut: false,
  2184. internal: null
  2185. };
  2186. jsPDF.API.acroformPlugin = acroformPlugin;
  2187. var annotReferenceCallback = function annotReferenceCallback() {
  2188. for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
  2189. var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
  2190. // add Annot Reference!
  2191. if (formObject.hasAnnotation) {
  2192. // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
  2193. createAnnotationReference.call(this, formObject);
  2194. }
  2195. }
  2196. };
  2197. var createAcroForm = function createAcroForm() {
  2198. if (this.acroformPlugin.acroFormDictionaryRoot) {
  2199. //return;
  2200. throw new Error("Exception while creating AcroformDictionary");
  2201. }
  2202. // The Object Number of the AcroForm Dictionary
  2203. this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
  2204. this.acroformPlugin.internal = this.internal;
  2205. // add Callback for creating the AcroForm Dictionary
  2206. this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  2207. this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
  2208. // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
  2209. this.internal.events.subscribe('putCatalog', putCatalogCallback);
  2210. // Register event, that creates all Fields
  2211. this.internal.events.subscribe('postPutPages', createFieldCallback);
  2212. };
  2213. /**
  2214. * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
  2215. * (Requires the Annotation Plugin)
  2216. */
  2217. var createAnnotationReference = function createAnnotationReference(object) {
  2218. var options = {
  2219. type: 'reference',
  2220. object: object
  2221. };
  2222. jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
  2223. };
  2224. var putForm = function putForm(formObject) {
  2225. if (this.acroformPlugin.printedOut) {
  2226. this.acroformPlugin.printedOut = false;
  2227. this.acroformPlugin.acroFormDictionaryRoot = null;
  2228. }
  2229. if (!this.acroformPlugin.acroFormDictionaryRoot) {
  2230. createAcroForm.call(this);
  2231. }
  2232. this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  2233. };
  2234. // Callbacks
  2235. var putCatalogCallback = function putCatalogCallback() {
  2236. //Put reference to AcroForm to DocumentCatalog
  2237. if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  2238. // for safety, shouldn't normally be the case
  2239. this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  2240. } else {
  2241. console.log('Root missing...');
  2242. }
  2243. };
  2244. /**
  2245. * Adds /Acroform X 0 R to Document Catalog,
  2246. * and creates the AcroForm Dictionary
  2247. */
  2248. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  2249. // Remove event
  2250. this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
  2251. delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
  2252. this.acroformPlugin.printedOut = true;
  2253. };
  2254. /**
  2255. * Creates the single Fields and writes them into the Document
  2256. *
  2257. * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
  2258. * (for the FormXObjects...)
  2259. */
  2260. var createFieldCallback = function createFieldCallback(fieldArray) {
  2261. var standardFields = !fieldArray;
  2262. if (!fieldArray) {
  2263. // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
  2264. // Print out Root
  2265. this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
  2266. this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
  2267. }
  2268. var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
  2269. for (var i in fieldArray) {
  2270. var form = fieldArray[i];
  2271. var oldRect = form.Rect;
  2272. if (form.Rect) {
  2273. form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
  2274. }
  2275. // Start Writing the Object
  2276. this.internal.newObjectDeferredBegin(form.objId);
  2277. var content = "";
  2278. content += form.objId + " 0 obj\n";
  2279. content += "<<\n" + form.getContent();
  2280. form.Rect = oldRect;
  2281. if (form.hasAppearanceStream && !form.appearanceStreamContent) {
  2282. // Calculate Appearance
  2283. var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
  2284. content += "/AP << /N " + appearance + " >>\n";
  2285. this.acroformPlugin.xForms.push(appearance);
  2286. }
  2287. // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
  2288. if (form.appearanceStreamContent) {
  2289. content += "/AP << ";
  2290. // Iterate over N,R and D
  2291. for (var k in form.appearanceStreamContent) {
  2292. var value = form.appearanceStreamContent[k];
  2293. content += "/" + k + " ";
  2294. content += "<< ";
  2295. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  2296. // appearanceStream is an Array or Object!
  2297. for (var i in value) {
  2298. var obj = value[i];
  2299. if (typeof obj === 'function') {
  2300. // if Function is referenced, call it in order to get the FormXObject
  2301. obj = obj.call(this, form);
  2302. }
  2303. content += "/" + i + " " + obj + " ";
  2304. // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
  2305. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2306. }
  2307. } else {
  2308. var obj = value;
  2309. if (typeof obj === 'function') {
  2310. // if Function is referenced, call it in order to get the FormXObject
  2311. obj = obj.call(this, form);
  2312. }
  2313. content += "/" + i + " " + obj + " \n";
  2314. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2315. }
  2316. content += " >>\n";
  2317. }
  2318. // appearance stream is a normal Object..
  2319. content += ">>\n";
  2320. }
  2321. content += ">>\nendobj\n";
  2322. this.internal.out(content);
  2323. }
  2324. if (standardFields) {
  2325. createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
  2326. }
  2327. };
  2328. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  2329. for (var i in fieldArray) {
  2330. var key = i;
  2331. var form = fieldArray[i];
  2332. // Start Writing the Object
  2333. this.internal.newObjectDeferredBegin(form && form.objId);
  2334. var content = "";
  2335. content += form ? form.getString() : '';
  2336. this.internal.out(content);
  2337. delete fieldArray[key];
  2338. }
  2339. };
  2340. // Public:
  2341. jsPDFAPI.addField = function(fieldObject) {
  2342. //var opt = parseOptions(fieldObject);
  2343. if (fieldObject instanceof AcroForm.TextField) {
  2344. addTextField.call(this, fieldObject);
  2345. } else if (fieldObject instanceof AcroForm.ChoiceField) {
  2346. addChoiceField.call(this, fieldObject);
  2347. } else if (fieldObject instanceof AcroForm.Button) {
  2348. addButton.call(this, fieldObject);
  2349. } else if (fieldObject instanceof AcroForm.ChildClass) {
  2350. putForm.call(this, fieldObject);
  2351. } else if (fieldObject) {
  2352. // try to put..
  2353. putForm.call(this, fieldObject);
  2354. }
  2355. fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
  2356. return this;
  2357. };
  2358. // ############### sort in:
  2359. /**
  2360. * Button
  2361. * FT = Btn
  2362. */
  2363. var addButton = function addButton(options) {
  2364. var options = options || new AcroForm.Field();
  2365. options.FT = '/Btn';
  2366. /**
  2367. * Calculating the Ff entry:
  2368. *
  2369. * The Ff entry contains flags, that have to be set bitwise
  2370. * In the Following the number in the Comment is the BitPosition
  2371. */
  2372. var flags = options.Ff || 0;
  2373. // 17, Pushbutton
  2374. if (options.pushbutton) {
  2375. // Options.pushbutton should be 1 or 0
  2376. flags = AcroForm.internal.setBitPosition(flags, 17);
  2377. delete options.pushbutton;
  2378. }
  2379. //16, Radio
  2380. if (options.radio) {
  2381. //flags = options.Ff | options.radio << 15;
  2382. flags = AcroForm.internal.setBitPosition(flags, 16);
  2383. delete options.radio;
  2384. }
  2385. // 15, NoToggleToOff (Radio buttons only
  2386. if (options.noToggleToOff) {
  2387. //flags = options.Ff | options.noToggleToOff << 14;
  2388. flags = AcroForm.internal.setBitPosition(flags, 15);
  2389. //delete options.noToggleToOff;
  2390. }
  2391. // In case, there is no Flag set, it is a check-box
  2392. options.Ff = flags;
  2393. putForm.call(this, options);
  2394. };
  2395. var addTextField = function addTextField(options) {
  2396. var options = options || new AcroForm.Field();
  2397. options.FT = '/Tx';
  2398. /**
  2399. * Calculating the Ff entry:
  2400. *
  2401. * The Ff entry contains flags, that have to be set bitwise
  2402. * In the Following the number in the Comment is the BitPosition
  2403. */
  2404. var flags = options.Ff || 0;
  2405. // 13, multiline
  2406. if (options.multiline) {
  2407. // Set Flag
  2408. flags = flags | 1 << 12;
  2409. // Remove multiline from FieldObject
  2410. //delete options.multiline;
  2411. }
  2412. // 14, Password
  2413. if (options.password) {
  2414. flags = flags | 1 << 13;
  2415. //delete options.password;
  2416. }
  2417. // 21, FileSelect, PDF 1.4...
  2418. if (options.fileSelect) {
  2419. flags = flags | 1 << 20;
  2420. //delete options.fileSelect;
  2421. }
  2422. // 23, DoNotSpellCheck, PDF 1.4...
  2423. if (options.doNotSpellCheck) {
  2424. flags = flags | 1 << 22;
  2425. //delete options.doNotSpellCheck;
  2426. }
  2427. // 24, DoNotScroll, PDF 1.4...
  2428. if (options.doNotScroll) {
  2429. flags = flags | 1 << 23;
  2430. //delete options.doNotScroll;
  2431. }
  2432. options.Ff = options.Ff || flags;
  2433. // Add field
  2434. putForm.call(this, options);
  2435. };
  2436. var addChoiceField = function addChoiceField(opt) {
  2437. var options = opt || new AcroForm.Field();
  2438. options.FT = '/Ch';
  2439. /**
  2440. * Calculating the Ff entry:
  2441. *
  2442. * The Ff entry contains flags, that have to be set bitwise
  2443. * In the Following the number in the Comment is the BitPosition
  2444. */
  2445. var flags = options.Ff || 0;
  2446. // 18, Combo (If not set, the choiceField is a listBox!!)
  2447. if (options.combo) {
  2448. // Set Flag
  2449. flags = AcroForm.internal.setBitPosition(flags, 18);
  2450. // Remove combo from FieldObject
  2451. delete options.combo;
  2452. }
  2453. // 19, Edit
  2454. if (options.edit) {
  2455. flags = AcroForm.internal.setBitPosition(flags, 19);
  2456. delete options.edit;
  2457. }
  2458. // 20, Sort
  2459. if (options.sort) {
  2460. flags = AcroForm.internal.setBitPosition(flags, 20);
  2461. delete options.sort;
  2462. }
  2463. // 22, MultiSelect (PDF 1.4)
  2464. if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
  2465. flags = AcroForm.internal.setBitPosition(flags, 22);
  2466. delete options.multiSelect;
  2467. }
  2468. // 23, DoNotSpellCheck (PDF 1.4)
  2469. if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
  2470. flags = AcroForm.internal.setBitPosition(flags, 23);
  2471. delete options.doNotSpellCheck;
  2472. }
  2473. options.Ff = flags;
  2474. //options.hasAnnotation = true;
  2475. // Add field
  2476. putForm.call(this, options);
  2477. };
  2478. })(jsPDF.API);
  2479. var AcroForm = window.AcroForm;
  2480. AcroForm.internal = {};
  2481. AcroForm.createFormXObject = function(formObject) {
  2482. var xobj = new AcroForm.FormXObject();
  2483. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  2484. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  2485. xobj.BBox = [0, 0, width, height];
  2486. return xobj;
  2487. };
  2488. // Contains Methods for creating standard appearances
  2489. AcroForm.Appearance = {
  2490. CheckBox: {
  2491. createAppearanceStream: function createAppearanceStream() {
  2492. var appearance = {
  2493. N: {
  2494. On: AcroForm.Appearance.CheckBox.YesNormal
  2495. },
  2496. D: {
  2497. On: AcroForm.Appearance.CheckBox.YesPushDown,
  2498. Off: AcroForm.Appearance.CheckBox.OffPushDown
  2499. }
  2500. };
  2501. return appearance;
  2502. },
  2503. /**
  2504. * If any other icons are needed, the number between the brackets can be changed
  2505. * @returns {string}
  2506. */
  2507. createMK: function createMK() {
  2508. // 3-> Hook
  2509. return "<< /CA (3)>>";
  2510. },
  2511. /**
  2512. * Returns the standard On Appearance for a CheckBox
  2513. * @returns {AcroForm.FormXObject}
  2514. */
  2515. YesPushDown: function YesPushDown(formObject) {
  2516. var xobj = AcroForm.createFormXObject(formObject);
  2517. var stream = "";
  2518. // F13 is ZapfDingbats (Symbolic)
  2519. formObject.Q = 1; // set text-alignment as centered
  2520. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
  2521. stream += "0.749023 g\n\
  2522. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2523. f\n\
  2524. BMC\n\
  2525. q\n\
  2526. 0 0 1 rg\n\
  2527. /F13 " + calcRes.fontSize + " Tf 0 g\n\
  2528. BT\n";
  2529. stream += calcRes.text;
  2530. stream += "ET\n\
  2531. Q\n\
  2532. EMC\n";
  2533. xobj.stream = stream;
  2534. return xobj;
  2535. },
  2536. YesNormal: function YesNormal(formObject) {
  2537. var xobj = AcroForm.createFormXObject(formObject);
  2538. var stream = "";
  2539. formObject.Q = 1; // set text-alignment as centered
  2540. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formObject) * 0.9);
  2541. stream += "1 g\n\
  2542. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2543. f\n\
  2544. q\n\
  2545. 0 0 1 rg\n\
  2546. 0 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
  2547. W\n\
  2548. n\n\
  2549. 0 g\n\
  2550. BT\n\
  2551. /F13 " + calcRes.fontSize + " Tf 0 g\n";
  2552. stream += calcRes.text;
  2553. stream += "ET\n\
  2554. Q\n";
  2555. xobj.stream = stream;
  2556. return xobj;
  2557. },
  2558. /**
  2559. * Returns the standard Off Appearance for a CheckBox
  2560. * @returns {AcroForm.FormXObject}
  2561. */
  2562. OffPushDown: function OffPushDown(formObject) {
  2563. var xobj = AcroForm.createFormXObject(formObject);
  2564. var stream = "";
  2565. stream += "0.749023 g\n\
  2566. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2567. f\n";
  2568. xobj.stream = stream;
  2569. return xobj;
  2570. }
  2571. },
  2572. RadioButton: {
  2573. Circle: {
  2574. createAppearanceStream: function createAppearanceStream(name) {
  2575. var appearanceStreamContent = {
  2576. D: {
  2577. 'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
  2578. },
  2579. N: {}
  2580. };
  2581. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
  2582. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
  2583. return appearanceStreamContent;
  2584. },
  2585. createMK: function createMK() {
  2586. return "<< /CA (l)>>";
  2587. },
  2588. YesNormal: function YesNormal(formObject) {
  2589. var xobj = AcroForm.createFormXObject(formObject);
  2590. var stream = "";
  2591. // Make the Radius of the Circle relative to min(height, width) of formObject
  2592. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2593. // The Borderpadding...
  2594. DotRadius *= 0.9;
  2595. var c = AcroForm.Appearance.internal.Bezier_C;
  2596. /*
  2597. The Following is a Circle created with Bezier-Curves.
  2598. */
  2599. stream += "q\n\
  2600. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2601. " + DotRadius + " 0 m\n\
  2602. " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2603. -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2604. -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2605. " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2606. f\n\
  2607. Q\n";
  2608. xobj.stream = stream;
  2609. return xobj;
  2610. },
  2611. YesPushDown: function YesPushDown(formObject) {
  2612. var xobj = AcroForm.createFormXObject(formObject);
  2613. var stream = "";
  2614. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2615. // The Borderpadding...
  2616. DotRadius *= 0.9;
  2617. // Save results for later use; no need to waste processor ticks on doing math
  2618. var k = DotRadius * 2;
  2619. // var c = AcroForm.Appearance.internal.Bezier_C;
  2620. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2621. var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
  2622. // stream += "0.749023 g\n\
  2623. // q\n\
  2624. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2625. // " + DotRadius * 2 + " 0 m\n\
  2626. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2627. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2628. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2629. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2630. // f\n\
  2631. // Q\n\
  2632. // 0 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. // " + DotRadius + " 0 m\n\
  2636. // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2637. // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2638. // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2639. // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2640. // f\n\
  2641. // Q\n";
  2642. // FASTER VERSION with less processor ticks spent on math operations
  2643. stream += "0.749023 g\n\
  2644. q\n\
  2645. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2646. " + k + " 0 m\n\
  2647. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2648. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2649. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2650. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2651. f\n\
  2652. Q\n\
  2653. 0 g\n\
  2654. q\n\
  2655. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2656. " + DotRadius + " 0 m\n\
  2657. " + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2658. -" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
  2659. -" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2660. " + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
  2661. f\n\
  2662. Q\n";
  2663. xobj.stream = stream;
  2664. return xobj;
  2665. },
  2666. OffPushDown: function OffPushDown(formObject) {
  2667. var xobj = AcroForm.createFormXObject(formObject);
  2668. var stream = "";
  2669. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2670. // The Borderpadding...
  2671. DotRadius *= 0.9;
  2672. // Save results for later use; no need to waste processor ticks on doing math
  2673. var k = DotRadius * 2;
  2674. // var c = AcroForm.Appearance.internal.Bezier_C;
  2675. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  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. // " + DotRadius * 2 + " 0 m\n\
  2680. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2681. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2682. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2683. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2684. // f\n\
  2685. // Q\n";
  2686. // FASTER VERSION with less processor ticks spent on math operations
  2687. stream += "0.749023 g\n\
  2688. q\n\
  2689. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2690. " + k + " 0 m\n\
  2691. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2692. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2693. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2694. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2695. f\n\
  2696. Q\n";
  2697. xobj.stream = stream;
  2698. return xobj;
  2699. }
  2700. },
  2701. Cross: {
  2702. /**
  2703. * Creates the Actual AppearanceDictionary-References
  2704. * @param name
  2705. * @returns
  2706. */
  2707. createAppearanceStream: function createAppearanceStream(name) {
  2708. var appearanceStreamContent = {
  2709. D: {
  2710. 'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
  2711. },
  2712. N: {}
  2713. };
  2714. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
  2715. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
  2716. return appearanceStreamContent;
  2717. },
  2718. createMK: function createMK() {
  2719. return "<< /CA (8)>>";
  2720. },
  2721. YesNormal: function YesNormal(formObject) {
  2722. var xobj = AcroForm.createFormXObject(formObject);
  2723. var stream = "";
  2724. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2725. stream += "q\n\
  2726. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2727. W\n\
  2728. n\n\
  2729. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2730. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2731. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2732. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2733. s\n\
  2734. Q\n";
  2735. xobj.stream = stream;
  2736. return xobj;
  2737. },
  2738. YesPushDown: function YesPushDown(formObject) {
  2739. var xobj = AcroForm.createFormXObject(formObject);
  2740. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2741. var stream = "";
  2742. stream += "0.749023 g\n\
  2743. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2744. f\n\
  2745. q\n\
  2746. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2747. W\n\
  2748. n\n\
  2749. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2750. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2751. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2752. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2753. s\n\
  2754. Q\n";
  2755. xobj.stream = stream;
  2756. return xobj;
  2757. },
  2758. OffPushDown: function OffPushDown(formObject) {
  2759. var xobj = AcroForm.createFormXObject(formObject);
  2760. var stream = "";
  2761. stream += "0.749023 g\n\
  2762. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2763. f\n";
  2764. xobj.stream = stream;
  2765. return xobj;
  2766. }
  2767. }
  2768. },
  2769. /**
  2770. * Returns the standard Appearance
  2771. * @returns {AcroForm.FormXObject}
  2772. */
  2773. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  2774. var stream = "";
  2775. // Set Helvetica to Standard Font (size: auto)
  2776. // Color: Black
  2777. stream += "/Helv 0 Tf 0 g";
  2778. return stream;
  2779. }
  2780. };
  2781. AcroForm.Appearance.internal = {
  2782. Bezier_C: 0.551915024494,
  2783. calculateCross: function calculateCross(formObject) {
  2784. var min = function min(x, y) {
  2785. return x > y ? y : x;
  2786. };
  2787. var width = AcroForm.Appearance.internal.getWidth(formObject);
  2788. var height = AcroForm.Appearance.internal.getHeight(formObject);
  2789. var a = min(width, height);
  2790. var cross = {
  2791. x1: { // upperLeft
  2792. x: (width - a) / 2,
  2793. y: (height - a) / 2 + a //height - borderPadding
  2794. },
  2795. x2: { // lowerRight
  2796. x: (width - a) / 2 + a,
  2797. y: (height - a) / 2 //borderPadding
  2798. },
  2799. x3: { // lowerLeft
  2800. x: (width - a) / 2,
  2801. y: (height - a) / 2 //borderPadding
  2802. },
  2803. x4: { // upperRight
  2804. x: (width - a) / 2 + a,
  2805. y: (height - a) / 2 + a //height - borderPadding
  2806. }
  2807. };
  2808. return cross;
  2809. }
  2810. };
  2811. AcroForm.Appearance.internal.getWidth = function(formObject) {
  2812. return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
  2813. };
  2814. AcroForm.Appearance.internal.getHeight = function(formObject) {
  2815. return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
  2816. };
  2817. // ##########################
  2818. //### For inheritance:
  2819. AcroForm.internal.inherit = function(child, parent) {
  2820. child.prototype = Object.create(parent.prototype);
  2821. child.prototype.constructor = child;
  2822. };
  2823. // ### Handy Functions:
  2824. AcroForm.internal.arrayToPdfArray = function(array) {
  2825. if (Array.isArray(array)) {
  2826. var content = ' [';
  2827. for (var i in array) {
  2828. var element = array[i].toString();
  2829. content += element;
  2830. content += i < array.length - 1 ? ' ' : '';
  2831. }
  2832. content += ']';
  2833. return content;
  2834. }
  2835. };
  2836. AcroForm.internal.toPdfString = function(string) {
  2837. string = string || "";
  2838. // put Bracket at the Beginning of the String
  2839. if (string.indexOf('(') !== 0) {
  2840. string = '(' + string;
  2841. }
  2842. if (string.substring(string.length - 1) != ')') {
  2843. string += '(';
  2844. }
  2845. return string;
  2846. };
  2847. // ##########################
  2848. // Classes
  2849. // ##########################
  2850. AcroForm.PDFObject = function() {
  2851. // The Object ID in the PDF Object Model
  2852. // todo
  2853. var _objId;
  2854. Object.defineProperty(this, 'objId', {
  2855. get: function get() {
  2856. if (!_objId) {
  2857. if (this.internal) {
  2858. _objId = this.internal.newObjectDeferred();
  2859. } else if (jsPDF.API.acroformPlugin.internal) {
  2860. // todo - find better option, that doesn't rely on a Global Static var
  2861. _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
  2862. }
  2863. }
  2864. if (!_objId) {
  2865. console.log("Couldn't create Object ID");
  2866. }
  2867. return _objId;
  2868. },
  2869. configurable: false
  2870. });
  2871. };
  2872. AcroForm.PDFObject.prototype.toString = function() {
  2873. return this.objId + " 0 R";
  2874. };
  2875. AcroForm.PDFObject.prototype.getString = function() {
  2876. var res = this.objId + " 0 obj\n<<";
  2877. var content = this.getContent();
  2878. res += content + ">>\n";
  2879. if (this.stream) {
  2880. res += "stream\n";
  2881. res += this.stream;
  2882. res += "endstream\n";
  2883. }
  2884. res += "endobj\n";
  2885. return res;
  2886. };
  2887. AcroForm.PDFObject.prototype.getContent = function() {
  2888. /**
  2889. * Prints out all enumerable Variables from the Object
  2890. * @param fieldObject
  2891. * @returns {string}
  2892. */
  2893. var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
  2894. var content = '';
  2895. var keys = Object.keys(fieldObject).filter(function(key) {
  2896. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  2897. });
  2898. for (var i in keys) {
  2899. var key = keys[i];
  2900. var value = fieldObject[key];
  2901. /*if (key == 'Rect' && value) {
  2902. value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
  2903. }*/
  2904. if (value) {
  2905. if (Array.isArray(value)) {
  2906. content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
  2907. } else if (value instanceof AcroForm.PDFObject) {
  2908. // In case it is a reference to another PDFObject, take the referennce number
  2909. content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
  2910. } else {
  2911. content += '/' + key + ' ' + value + '\n';
  2912. }
  2913. }
  2914. }
  2915. return content;
  2916. };
  2917. var object = "";
  2918. object += createContentFromFieldObject(this);
  2919. return object;
  2920. };
  2921. AcroForm.FormXObject = function() {
  2922. AcroForm.PDFObject.call(this);
  2923. this.Type = "/XObject";
  2924. this.Subtype = "/Form";
  2925. this.FormType = 1;
  2926. this.BBox;
  2927. this.Matrix;
  2928. this.Resources = "2 0 R";
  2929. this.PieceInfo;
  2930. var _stream;
  2931. Object.defineProperty(this, 'Length', {
  2932. enumerable: true,
  2933. get: function get() {
  2934. return _stream !== undefined ? _stream.length : 0;
  2935. }
  2936. });
  2937. Object.defineProperty(this, 'stream', {
  2938. enumerable: false,
  2939. set: function set(val) {
  2940. _stream = val;
  2941. },
  2942. get: function get() {
  2943. if (_stream) {
  2944. return _stream;
  2945. } else {
  2946. return null;
  2947. }
  2948. }
  2949. });
  2950. };
  2951. AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
  2952. AcroForm.AcroFormDictionary = function() {
  2953. AcroForm.PDFObject.call(this);
  2954. var _Kids = [];
  2955. Object.defineProperty(this, 'Kids', {
  2956. enumerable: false,
  2957. configurable: true,
  2958. get: function get() {
  2959. if (_Kids.length > 0) {
  2960. return _Kids;
  2961. } else {
  2962. return;
  2963. }
  2964. }
  2965. });
  2966. Object.defineProperty(this, 'Fields', {
  2967. enumerable: true,
  2968. configurable: true,
  2969. get: function get() {
  2970. return _Kids;
  2971. }
  2972. });
  2973. // Default Appearance
  2974. this.DA;
  2975. };
  2976. AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
  2977. // ##### The Objects, the User can Create:
  2978. // The Field Object contains the Variables, that every Field needs
  2979. // Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
  2980. AcroForm.Field = function() {
  2981. 'use strict';
  2982. AcroForm.PDFObject.call(this);
  2983. var _Rect;
  2984. Object.defineProperty(this, 'Rect', {
  2985. enumerable: true,
  2986. configurable: false,
  2987. get: function get() {
  2988. if (!_Rect) {
  2989. return;
  2990. }
  2991. var tmp = _Rect;
  2992. //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
  2993. return tmp;
  2994. },
  2995. set: function set(val) {
  2996. _Rect = val;
  2997. }
  2998. });
  2999. var _FT = "";
  3000. Object.defineProperty(this, 'FT', {
  3001. enumerable: true,
  3002. set: function set(val) {
  3003. _FT = val;
  3004. },
  3005. get: function get() {
  3006. return _FT;
  3007. }
  3008. });
  3009. /**
  3010. * The Partial name of the Field Object.
  3011. * It has to be unique.
  3012. */
  3013. var _T;
  3014. Object.defineProperty(this, 'T', {
  3015. enumerable: true,
  3016. configurable: false,
  3017. set: function set(val) {
  3018. _T = val;
  3019. },
  3020. get: function get() {
  3021. if (!_T || _T.length < 1) {
  3022. if (this instanceof AcroForm.ChildClass) {
  3023. // In case of a Child from a Radio麓Group, you don't need a FieldName!!!
  3024. return;
  3025. }
  3026. return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
  3027. }
  3028. if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
  3029. return _T;
  3030. }
  3031. return "(" + _T + ")";
  3032. }
  3033. });
  3034. var _DA;
  3035. // Defines the default appearance (Needed for variable Text)
  3036. Object.defineProperty(this, 'DA', {
  3037. enumerable: true,
  3038. get: function get() {
  3039. if (!_DA) {
  3040. return;
  3041. }
  3042. return '(' + _DA + ')';
  3043. },
  3044. set: function set(val) {
  3045. _DA = val;
  3046. }
  3047. });
  3048. var _DV;
  3049. // Defines the default value
  3050. Object.defineProperty(this, 'DV', {
  3051. enumerable: true,
  3052. configurable: true,
  3053. get: function get() {
  3054. if (!_DV) {
  3055. return;
  3056. }
  3057. return _DV;
  3058. },
  3059. set: function set(val) {
  3060. _DV = val;
  3061. }
  3062. });
  3063. //this.Type = "/Annot";
  3064. //this.Subtype = "/Widget";
  3065. Object.defineProperty(this, 'Type', {
  3066. enumerable: true,
  3067. get: function get() {
  3068. return this.hasAnnotation ? "/Annot" : null;
  3069. }
  3070. });
  3071. Object.defineProperty(this, 'Subtype', {
  3072. enumerable: true,
  3073. get: function get() {
  3074. return this.hasAnnotation ? "/Widget" : null;
  3075. }
  3076. });
  3077. /**
  3078. *
  3079. * @type {Array}
  3080. */
  3081. this.BG;
  3082. Object.defineProperty(this, 'hasAnnotation', {
  3083. enumerable: false,
  3084. get: function get() {
  3085. if (this.Rect || this.BC || this.BG) {
  3086. return true;
  3087. }
  3088. return false;
  3089. }
  3090. });
  3091. Object.defineProperty(this, 'hasAppearanceStream', {
  3092. enumerable: false,
  3093. configurable: true,
  3094. writable: true
  3095. });
  3096. Object.defineProperty(this, 'page', {
  3097. enumerable: false,
  3098. configurable: true,
  3099. writable: true
  3100. });
  3101. };
  3102. AcroForm.Field.FieldNum = 0;
  3103. AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
  3104. AcroForm.ChoiceField = function() {
  3105. AcroForm.Field.call(this);
  3106. // Field Type = Choice Field
  3107. this.FT = "/Ch";
  3108. // options
  3109. this.Opt = [];
  3110. this.V = '()';
  3111. // Top Index
  3112. this.TI = 0;
  3113. /**
  3114. * Defines, whether the
  3115. * @type {boolean}
  3116. */
  3117. this.combo = false;
  3118. /**
  3119. * Defines, whether the Choice Field is an Edit Field.
  3120. * An Edit Field is automatically an Combo Field.
  3121. */
  3122. Object.defineProperty(this, 'edit', {
  3123. enumerable: true,
  3124. set: function set(val) {
  3125. if (val == true) {
  3126. this._edit = true;
  3127. // ComboBox has to be true
  3128. this.combo = true;
  3129. } else {
  3130. this._edit = false;
  3131. }
  3132. },
  3133. get: function get() {
  3134. if (!this._edit) {
  3135. return false;
  3136. }
  3137. return this._edit;
  3138. },
  3139. configurable: false
  3140. });
  3141. this.hasAppearanceStream = true;
  3142. Object.defineProperty(this, 'V', {
  3143. get: function get() {
  3144. AcroForm.internal.toPdfString();
  3145. }
  3146. });
  3147. };
  3148. AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
  3149. window["ChoiceField"] = AcroForm.ChoiceField;
  3150. AcroForm.ListBox = function() {
  3151. AcroForm.ChoiceField.call(this);
  3152. //var combo = true;
  3153. };
  3154. AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
  3155. window["ListBox"] = AcroForm.ListBox;
  3156. AcroForm.ComboBox = function() {
  3157. AcroForm.ListBox.call(this);
  3158. this.combo = true;
  3159. };
  3160. AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
  3161. window["ComboBox"] = AcroForm.ComboBox;
  3162. AcroForm.EditBox = function() {
  3163. AcroForm.ComboBox.call(this);
  3164. this.edit = true;
  3165. };
  3166. AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
  3167. window["EditBox"] = AcroForm.EditBox;
  3168. AcroForm.Button = function() {
  3169. AcroForm.Field.call(this);
  3170. this.FT = "/Btn";
  3171. //this.hasAnnotation = true;
  3172. };
  3173. AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
  3174. window["Button"] = AcroForm.Button;
  3175. AcroForm.PushButton = function() {
  3176. AcroForm.Button.call(this);
  3177. this.pushbutton = true;
  3178. };
  3179. AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
  3180. window["PushButton"] = AcroForm.PushButton;
  3181. AcroForm.RadioButton = function() {
  3182. AcroForm.Button.call(this);
  3183. this.radio = true;
  3184. var _Kids = [];
  3185. Object.defineProperty(this, 'Kids', {
  3186. enumerable: true,
  3187. get: function get() {
  3188. if (_Kids.length > 0) {
  3189. return _Kids;
  3190. }
  3191. }
  3192. });
  3193. Object.defineProperty(this, '__Kids', {
  3194. get: function get() {
  3195. return _Kids;
  3196. }
  3197. });
  3198. var _noToggleToOff;
  3199. Object.defineProperty(this, 'noToggleToOff', {
  3200. enumerable: false,
  3201. get: function get() {
  3202. return _noToggleToOff;
  3203. },
  3204. set: function set(val) {
  3205. _noToggleToOff = val;
  3206. }
  3207. });
  3208. //this.hasAnnotation = false;
  3209. };
  3210. AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
  3211. window["RadioButton"] = AcroForm.RadioButton;
  3212. /*
  3213. * The Child classs of a RadioButton (the radioGroup)
  3214. * -> The single Buttons
  3215. */
  3216. AcroForm.ChildClass = function(parent, name) {
  3217. AcroForm.Field.call(this);
  3218. this.Parent = parent;
  3219. // todo: set AppearanceType as variable that can be set from the outside...
  3220. this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
  3221. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  3222. // Set Print in the Annot Flag
  3223. this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
  3224. // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
  3225. this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
  3226. // Default Appearance is Off
  3227. this.AS = "/Off"; // + name;
  3228. this._Name = name;
  3229. };
  3230. AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
  3231. AcroForm.RadioButton.prototype.setAppearance = function(appearance) {
  3232. if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
  3233. console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  3234. return;
  3235. }
  3236. for (var i in this.__Kids) {
  3237. var child = this.__Kids[i];
  3238. child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
  3239. child.MK = appearance.createMK();
  3240. }
  3241. };
  3242. AcroForm.RadioButton.prototype.createOption = function(name) {
  3243. var parent = this;
  3244. var child = new AcroForm.ChildClass(parent, name);
  3245. // Add to Parent
  3246. this.__Kids.push(child);
  3247. jsPDF.API.addField(child);
  3248. return child;
  3249. };
  3250. AcroForm.CheckBox = function() {
  3251. Button.call(this);
  3252. this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
  3253. this.MK = AcroForm.Appearance.CheckBox.createMK();
  3254. this.AS = "/On";
  3255. this.V = "/On";
  3256. };
  3257. AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
  3258. window["CheckBox"] = AcroForm.CheckBox;
  3259. AcroForm.TextField = function() {
  3260. AcroForm.Field.call(this);
  3261. this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
  3262. this.F = 4;
  3263. var _V;
  3264. Object.defineProperty(this, 'V', {
  3265. get: function get() {
  3266. if (_V) {
  3267. return "(" + _V + ")";
  3268. } else {
  3269. return _V;
  3270. }
  3271. },
  3272. enumerable: true,
  3273. set: function set(val) {
  3274. _V = val;
  3275. }
  3276. });
  3277. var _DV;
  3278. Object.defineProperty(this, 'DV', {
  3279. get: function get() {
  3280. if (_DV) {
  3281. return "(" + _DV + ")";
  3282. } else {
  3283. return _DV;
  3284. }
  3285. },
  3286. enumerable: true,
  3287. set: function set(val) {
  3288. _DV = val;
  3289. }
  3290. });
  3291. var _multiline = false;
  3292. Object.defineProperty(this, 'multiline', {
  3293. enumerable: false,
  3294. get: function get() {
  3295. return _multiline;
  3296. },
  3297. set: function set(val) {
  3298. _multiline = val;
  3299. }
  3300. });
  3301. //this.multiline = false;
  3302. //this.password = false;
  3303. /**
  3304. * For PDF 1.4
  3305. * @type {boolean}
  3306. */
  3307. //this.fileSelect = false;
  3308. /**
  3309. * For PDF 1.4
  3310. * @type {boolean}
  3311. */
  3312. //this.doNotSpellCheck = false;
  3313. /**
  3314. * For PDF 1.4
  3315. * @type {boolean}
  3316. */
  3317. //this.doNotScroll = false;
  3318. var _MaxLen = false;
  3319. Object.defineProperty(this, 'MaxLen', {
  3320. enumerable: true,
  3321. get: function get() {
  3322. return _MaxLen;
  3323. },
  3324. set: function set(val) {
  3325. _MaxLen = val;
  3326. }
  3327. });
  3328. Object.defineProperty(this, 'hasAppearanceStream', {
  3329. enumerable: false,
  3330. get: function get() {
  3331. return this.V || this.DV;
  3332. }
  3333. });
  3334. };
  3335. AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
  3336. window["TextField"] = AcroForm.TextField;
  3337. AcroForm.PasswordField = function() {
  3338. TextField.call(this);
  3339. Object.defineProperty(this, 'password', {
  3340. value: true,
  3341. enumerable: false,
  3342. configurable: false,
  3343. writable: false
  3344. });
  3345. };
  3346. AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
  3347. window["PasswordField"] = AcroForm.PasswordField;
  3348. // ############ internal functions
  3349. /*
  3350. * small workaround for calculating the TextMetric approximately
  3351. * @param text
  3352. * @param fontsize
  3353. * @returns {TextMetrics} (Has Height and Width)
  3354. */
  3355. AcroForm.internal.calculateFontSpace = function(text, fontsize, fonttype) {
  3356. var fonttype = fonttype || "helvetica";
  3357. //re-use canvas object for speed improvements
  3358. var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
  3359. var context = canvas.getContext('2d');
  3360. context.save();
  3361. var newFont = fontsize + " " + fonttype;
  3362. context.font = newFont;
  3363. var res = context.measureText(text);
  3364. context.fontcolor = 'black';
  3365. // Calculate height:
  3366. var context = canvas.getContext('2d');
  3367. res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
  3368. context.restore();
  3369. return res;
  3370. };
  3371. AcroForm.internal.calculateX = function(formObject, text, font, maxFontSize) {
  3372. var maxFontSize = maxFontSize || 12;
  3373. var font = font || "helvetica";
  3374. var returnValue = {
  3375. text: "",
  3376. fontSize: ""
  3377. };
  3378. // Remove Brackets
  3379. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  3380. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
  3381. // split into array of words
  3382. var textSplit = text.split(' ');
  3383. /**
  3384. * the color could be ((alpha)||(r,g,b)||(c,m,y,k))
  3385. * @type {string}
  3386. */
  3387. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3388. var lineSpacing = 2;
  3389. var borderPadding = 2;
  3390. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  3391. height = height < 0 ? -height : height;
  3392. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  3393. width = width < 0 ? -width : width;
  3394. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3395. if (i + 1 < textSplit.length) {
  3396. var tmp = lastLine + " " + textSplit[i + 1];
  3397. var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
  3398. var FieldWidth = width - 2 * borderPadding;
  3399. return TextWidth <= FieldWidth;
  3400. } else {
  3401. return false;
  3402. }
  3403. };
  3404. fontSize++;
  3405. FontSize: while (true) {
  3406. var text = "";
  3407. fontSize--;
  3408. var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
  3409. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3410. startY += lineSpacing;
  3411. var startX = -borderPadding;
  3412. var lastX = startX,
  3413. lastY = startY;
  3414. var firstWordInLine = 0,
  3415. lastWordInLine = 0;
  3416. var lastLength = 0;
  3417. if (fontSize == 0) {
  3418. // In case, the Text doesn't fit at all
  3419. fontSize = 12;
  3420. text = "(...) Tj\n";
  3421. text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
  3422. break;
  3423. }
  3424. lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
  3425. var lastLine = "";
  3426. var lineCount = 0;
  3427. Line: for (var i in textSplit) {
  3428. lastLine += textSplit[i] + " ";
  3429. // Remove last blank
  3430. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3431. var key = parseInt(i);
  3432. lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
  3433. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3434. var isLastWord = i >= textSplit.length - 1;
  3435. if (nextLineIsSmaller && !isLastWord) {
  3436. lastLine += " ";
  3437. continue; // Line
  3438. } else if (!nextLineIsSmaller && !isLastWord) {
  3439. if (!formObject.multiline) {
  3440. continue FontSize;
  3441. } else {
  3442. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3443. // If the Text is higher than the FieldObject
  3444. continue FontSize;
  3445. }
  3446. lastWordInLine = key;
  3447. // go on
  3448. }
  3449. } else if (isLastWord) {
  3450. lastWordInLine = key;
  3451. } else {
  3452. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3453. // If the Text is higher than the FieldObject
  3454. continue FontSize;
  3455. }
  3456. }
  3457. var line = '';
  3458. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3459. line += textSplit[x] + ' ';
  3460. }
  3461. // Remove last blank
  3462. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
  3463. //lastLength -= blankSpace.width;
  3464. lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
  3465. // Calculate startX
  3466. switch (formObject.Q) {
  3467. case 2:
  3468. // Right justified
  3469. startX = width - lastLength - borderPadding;
  3470. break;
  3471. case 1:
  3472. // Q = 1 := Text-Alignment: Center
  3473. startX = (width - lastLength) / 2;
  3474. break;
  3475. case 0:
  3476. default:
  3477. startX = borderPadding;
  3478. break;
  3479. }
  3480. text += startX + ' ' + lastY + ' Td\n';
  3481. text += '(' + line + ') Tj\n';
  3482. // reset X in PDF
  3483. text += -startX + ' 0 Td\n';
  3484. // After a Line, adjust y position
  3485. lastY = -(fontSize + lineSpacing);
  3486. lastLength = 0;
  3487. firstWordInLine = lastWordInLine + 1;
  3488. lineCount++;
  3489. lastLine = "";
  3490. continue Line;
  3491. }
  3492. break;
  3493. }
  3494. returnValue.text = text;
  3495. returnValue.fontSize = fontSize;
  3496. return returnValue;
  3497. };
  3498. AcroForm.internal.calculateAppearanceStream = function(formObject) {
  3499. if (formObject.appearanceStreamContent) {
  3500. // If appearanceStream is already set, use it
  3501. return formObject.appearanceStreamContent;
  3502. }
  3503. if (!formObject.V && !formObject.DV) {
  3504. return;
  3505. }
  3506. // else calculate it
  3507. var stream = '';
  3508. var text = formObject.V || formObject.DV;
  3509. var calcRes = AcroForm.internal.calculateX(formObject, text);
  3510. stream += '/Tx BMC\n' + 'q\n' +
  3511. //color + '\n' +
  3512. '/F1 ' + calcRes.fontSize + ' Tf\n' +
  3513. // Text Matrix
  3514. '1 0 0 1 0 0 Tm\n';
  3515. // Begin Text
  3516. stream += 'BT\n';
  3517. stream += calcRes.text;
  3518. // End Text
  3519. stream += 'ET\n';
  3520. stream += 'Q\n' + 'EMC\n';
  3521. var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
  3522. appearanceStreamContent.stream = stream;
  3523. return appearanceStreamContent;
  3524. };
  3525. /*
  3526. * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
  3527. * @param x
  3528. * @param y
  3529. * @param w
  3530. * @param h
  3531. * @returns {*[]}
  3532. */
  3533. AcroForm.internal.calculateCoordinates = function(x, y, w, h) {
  3534. var coordinates = {};
  3535. if (this.internal) {
  3536. var mmtopx = function mmtopx(x) {
  3537. return x * this.internal.scaleFactor;
  3538. };
  3539. if (Array.isArray(x)) {
  3540. x[0] = AcroForm.scale(x[0]);
  3541. x[1] = AcroForm.scale(x[1]);
  3542. x[2] = AcroForm.scale(x[2]);
  3543. x[3] = AcroForm.scale(x[3]);
  3544. coordinates.lowerLeft_X = x[0] || 0;
  3545. coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
  3546. coordinates.upperRight_X = x[0] + x[2] || 0;
  3547. coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
  3548. } else {
  3549. x = AcroForm.scale(x);
  3550. y = AcroForm.scale(y);
  3551. w = AcroForm.scale(w);
  3552. h = AcroForm.scale(h);
  3553. coordinates.lowerLeft_X = x || 0;
  3554. coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
  3555. coordinates.upperRight_X = x + w || 0;
  3556. coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
  3557. }
  3558. } else {
  3559. // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
  3560. if (Array.isArray(x)) {
  3561. coordinates.lowerLeft_X = x[0] || 0;
  3562. coordinates.lowerLeft_Y = x[1] || 0;
  3563. coordinates.upperRight_X = x[0] + x[2] || 0;
  3564. coordinates.upperRight_Y = x[1] + x[3] || 0;
  3565. } else {
  3566. coordinates.lowerLeft_X = x || 0;
  3567. coordinates.lowerLeft_Y = y || 0;
  3568. coordinates.upperRight_X = x + w || 0;
  3569. coordinates.upperRight_Y = y + h || 0;
  3570. }
  3571. }
  3572. return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
  3573. };
  3574. AcroForm.internal.calculateColor = function(r, g, b) {
  3575. var color = new Array(3);
  3576. color.r = r | 0;
  3577. color.g = g | 0;
  3578. color.b = b | 0;
  3579. return color;
  3580. };
  3581. AcroForm.internal.getBitPosition = function(variable, position) {
  3582. variable = variable || 0;
  3583. var bitMask = 1;
  3584. bitMask = bitMask << position - 1;
  3585. return variable | bitMask;
  3586. };
  3587. AcroForm.internal.setBitPosition = function(variable, position, value) {
  3588. variable = variable || 0;
  3589. value = value || 1;
  3590. var bitMask = 1;
  3591. bitMask = bitMask << position - 1;
  3592. if (value == 1) {
  3593. // Set the Bit to 1
  3594. var variable = variable | bitMask;
  3595. } else {
  3596. // Set the Bit to 0
  3597. var variable = variable & ~bitMask;
  3598. }
  3599. return variable;
  3600. };
  3601. /**
  3602. * jsPDF addHTML PlugIn
  3603. * Copyright (c) 2014 Diego Casorran
  3604. *
  3605. * Licensed under the MIT License.
  3606. * http://opensource.org/licenses/mit-license
  3607. */
  3608. (function(jsPDFAPI) {
  3609. 'use strict';
  3610. /**
  3611. * Renders an HTML element to canvas object which added to the PDF
  3612. *
  3613. * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
  3614. * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
  3615. *
  3616. * @returns {jsPDF}
  3617. * @name addHTML
  3618. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  3619. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  3620. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  3621. * @param options {Object} Additional options, check the code below.
  3622. * @param callback {Function} to call when the rendering has finished.
  3623. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  3624. * case the image is positioned at 0x0 covering the whole PDF document
  3625. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  3626. * @deprecated This is being replace with a vector-supporting API. See
  3627. * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
  3628. */
  3629. jsPDFAPI.addHTML = function(element, x, y, options, callback) {
  3630. 'use strict';
  3631. 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');
  3632. if (typeof x !== 'number') {
  3633. options = x;
  3634. callback = y;
  3635. }
  3636. if (typeof options === 'function') {
  3637. callback = options;
  3638. options = null;
  3639. }
  3640. var I = this.internal,
  3641. K = I.scaleFactor,
  3642. W = I.pageSize.width,
  3643. H = I.pageSize.height;
  3644. options = options || {};
  3645. options.onrendered = function(obj) {
  3646. x = parseInt(x) || 0;
  3647. y = parseInt(y) || 0;
  3648. var dim = options.dim || {};
  3649. var h = dim.h || 0;
  3650. var w = dim.w || Math.min(W, obj.width / K) - x;
  3651. var format = 'JPEG';
  3652. if (options.format) format = options.format;
  3653. if (obj.height > H && options.pagesplit) {
  3654. var crop = function() {
  3655. var cy = 0;
  3656. while (1) {
  3657. var canvas = document.createElement('canvas');
  3658. canvas.width = Math.min(W * K, obj.width);
  3659. canvas.height = Math.min(H * K, obj.height - cy);
  3660. var ctx = canvas.getContext('2d');
  3661. ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
  3662. var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
  3663. this.addImage.apply(this, args);
  3664. cy += canvas.height;
  3665. if (cy >= obj.height) break;
  3666. this.addPage();
  3667. }
  3668. callback(w, cy, null, args);
  3669. }.bind(this);
  3670. if (obj.nodeName === 'CANVAS') {
  3671. var img = new Image();
  3672. img.onload = crop;
  3673. img.src = obj.toDataURL("image/png");
  3674. obj = img;
  3675. } else {
  3676. crop();
  3677. }
  3678. } else {
  3679. var alias = Math.random().toString(35);
  3680. var args = [obj, x, y, w, h, format, alias, 'SLOW'];
  3681. this.addImage.apply(this, args);
  3682. callback(w, h, alias, args);
  3683. }
  3684. }.bind(this);
  3685. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  3686. return html2canvas(element, options);
  3687. }
  3688. if (typeof rasterizeHTML !== 'undefined') {
  3689. var meth = 'drawDocument';
  3690. if (typeof element === 'string') {
  3691. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  3692. }
  3693. options.width = options.width || W * K;
  3694. return rasterizeHTML[meth](element, void 0, options).then(function(r) {
  3695. options.onrendered(r.image);
  3696. }, function(e) {
  3697. callback(null, e);
  3698. });
  3699. }
  3700. return null;
  3701. };
  3702. })(jsPDF.API);
  3703. /** @preserve
  3704. * jsPDF addImage plugin
  3705. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  3706. * 2013 Chris Dowling, https://github.com/gingerchris
  3707. * 2013 Trinh Ho, https://github.com/ineedfat
  3708. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  3709. * 2013 Norah Smith, https://github.com/burnburnrocket
  3710. * 2014 Diego Casorran, https://github.com/diegocr
  3711. * 2014 James Robb, https://github.com/jamesbrobb
  3712. *
  3713. *
  3714. */
  3715. (function(jsPDFAPI) {
  3716. 'use strict';
  3717. var namespace = 'addImage_',
  3718. supported_image_types = ['jpeg', 'jpg', 'png'];
  3719. // Image functionality ported from pdf.js
  3720. var putImage = function putImage(img) {
  3721. var objectNumber = this.internal.newObject(),
  3722. out = this.internal.write,
  3723. putStream = this.internal.putStream;
  3724. img['n'] = objectNumber;
  3725. out('<</Type /XObject');
  3726. out('/Subtype /Image');
  3727. out('/Width ' + img['w']);
  3728. out('/Height ' + img['h']);
  3729. if (img['cs'] === this.color_spaces.INDEXED) {
  3730. out('/ColorSpace [/Indexed /DeviceRGB '
  3731. // if an indexed png defines more than one colour with transparency, we've created a smask
  3732. +
  3733. (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
  3734. } else {
  3735. out('/ColorSpace /' + img['cs']);
  3736. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  3737. out('/Decode [1 0 1 0 1 0 1 0]');
  3738. }
  3739. }
  3740. out('/BitsPerComponent ' + img['bpc']);
  3741. if ('f' in img) {
  3742. out('/Filter /' + img['f']);
  3743. }
  3744. if ('dp' in img) {
  3745. out('/DecodeParms <<' + img['dp'] + '>>');
  3746. }
  3747. if ('trns' in img && img['trns'].constructor == Array) {
  3748. var trns = '',
  3749. i = 0,
  3750. len = img['trns'].length;
  3751. for (; i < len; i++) {
  3752. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  3753. }
  3754. out('/Mask [' + trns + ']');
  3755. }
  3756. if ('smask' in img) {
  3757. out('/SMask ' + (objectNumber + 1) + ' 0 R');
  3758. }
  3759. out('/Length ' + img['data'].length + '>>');
  3760. putStream(img['data']);
  3761. out('endobj');
  3762. // Soft mask
  3763. if ('smask' in img) {
  3764. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  3765. var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
  3766. if ('f' in img) smask.f = img['f'];
  3767. putImage.call(this, smask);
  3768. }
  3769. //Palette
  3770. if (img['cs'] === this.color_spaces.INDEXED) {
  3771. this.internal.newObject();
  3772. //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  3773. //putStream(zlib.compress(img['pal']));
  3774. out('<< /Length ' + img['pal'].length + '>>');
  3775. putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
  3776. out('endobj');
  3777. }
  3778. },
  3779. putResourcesCallback = function putResourcesCallback() {
  3780. var images = this.internal.collections[namespace + 'images'];
  3781. for (var i in images) {
  3782. putImage.call(this, images[i]);
  3783. }
  3784. },
  3785. putXObjectsDictCallback = function putXObjectsDictCallback() {
  3786. var images = this.internal.collections[namespace + 'images'],
  3787. out = this.internal.write,
  3788. image;
  3789. for (var i in images) {
  3790. image = images[i];
  3791. out('/I' + image['i'], image['n'], '0', 'R');
  3792. }
  3793. },
  3794. checkCompressValue = function checkCompressValue(value) {
  3795. if (value && typeof value === 'string') value = value.toUpperCase();
  3796. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  3797. },
  3798. getImages = function getImages() {
  3799. var images = this.internal.collections[namespace + 'images'];
  3800. //first run, so initialise stuff
  3801. if (!images) {
  3802. this.internal.collections[namespace + 'images'] = images = {};
  3803. this.internal.events.subscribe('putResources', putResourcesCallback);
  3804. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  3805. }
  3806. return images;
  3807. },
  3808. getImageIndex = function getImageIndex(images) {
  3809. var imageIndex = 0;
  3810. if (images) {
  3811. // this is NOT the first time this method is ran on this instance of jsPDF object.
  3812. imageIndex = Object.keys ? Object.keys(images).length : function(o) {
  3813. var i = 0;
  3814. for (var e in o) {
  3815. if (o.hasOwnProperty(e)) {
  3816. i++;
  3817. }
  3818. }
  3819. return i;
  3820. }(images);
  3821. }
  3822. return imageIndex;
  3823. },
  3824. notDefined = function notDefined(value) {
  3825. return typeof value === 'undefined' || value === null;
  3826. },
  3827. generateAliasFromData = function generateAliasFromData(data) {
  3828. return typeof data === 'string' && jsPDFAPI.sHashCode(data);
  3829. },
  3830. doesNotSupportImageType = function doesNotSupportImageType(type) {
  3831. return supported_image_types.indexOf(type) === -1;
  3832. },
  3833. processMethodNotEnabled = function processMethodNotEnabled(type) {
  3834. return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
  3835. },
  3836. isDOMElement = function isDOMElement(object) {
  3837. return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
  3838. },
  3839. createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
  3840. //if element is an image which uses data url definition, just return the dataurl
  3841. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  3842. var src = '' + element.getAttribute('src');
  3843. if (!angle && src.indexOf('data:image/') === 0) return src;
  3844. // only if the user doesn't care about a format
  3845. if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
  3846. }
  3847. if (element.nodeName === 'CANVAS') {
  3848. var canvas = element;
  3849. } else {
  3850. var canvas = document.createElement('canvas');
  3851. canvas.width = element.clientWidth || element.width;
  3852. canvas.height = element.clientHeight || element.height;
  3853. var ctx = canvas.getContext('2d');
  3854. if (!ctx) {
  3855. throw 'addImage requires canvas to be supported by browser.';
  3856. }
  3857. if (angle) {
  3858. var x,
  3859. y,
  3860. b,
  3861. c,
  3862. s,
  3863. w,
  3864. h,
  3865. to_radians = Math.PI / 180,
  3866. angleInRadians;
  3867. if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
  3868. x = angle.x;
  3869. y = angle.y;
  3870. b = angle.bg;
  3871. angle = angle.angle;
  3872. }
  3873. angleInRadians = angle * to_radians;
  3874. c = Math.abs(Math.cos(angleInRadians));
  3875. s = Math.abs(Math.sin(angleInRadians));
  3876. w = canvas.width;
  3877. h = canvas.height;
  3878. canvas.width = h * s + w * c;
  3879. canvas.height = h * c + w * s;
  3880. if (isNaN(x)) x = canvas.width / 2;
  3881. if (isNaN(y)) y = canvas.height / 2;
  3882. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3883. ctx.fillStyle = b || 'white';
  3884. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3885. ctx.save();
  3886. ctx.translate(x, y);
  3887. ctx.rotate(angleInRadians);
  3888. ctx.drawImage(element, -(w / 2), -(h / 2));
  3889. ctx.rotate(-angleInRadians);
  3890. ctx.translate(-x, -y);
  3891. ctx.restore();
  3892. } else {
  3893. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  3894. }
  3895. }
  3896. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  3897. },
  3898. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  3899. var cached_info;
  3900. if (images) {
  3901. for (var e in images) {
  3902. if (alias === images[e].alias) {
  3903. cached_info = images[e];
  3904. break;
  3905. }
  3906. }
  3907. }
  3908. return cached_info;
  3909. },
  3910. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  3911. if (!w && !h) {
  3912. w = -96;
  3913. h = -96;
  3914. }
  3915. if (w < 0) {
  3916. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  3917. }
  3918. if (h < 0) {
  3919. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  3920. }
  3921. if (w === 0) {
  3922. w = h * info['w'] / info['h'];
  3923. }
  3924. if (h === 0) {
  3925. h = w * info['h'] / info['w'];
  3926. }
  3927. return [w, h];
  3928. },
  3929. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
  3930. var dims = determineWidthAndHeight.call(this, w, h, info),
  3931. coord = this.internal.getCoordinateString,
  3932. vcoord = this.internal.getVerticalCoordinateString;
  3933. w = dims[0];
  3934. h = dims[1];
  3935. images[index] = info;
  3936. this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
  3937. , coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
  3938. };
  3939. /**
  3940. * COLOR SPACES
  3941. */
  3942. jsPDFAPI.color_spaces = {
  3943. DEVICE_RGB: 'DeviceRGB',
  3944. DEVICE_GRAY: 'DeviceGray',
  3945. DEVICE_CMYK: 'DeviceCMYK',
  3946. CAL_GREY: 'CalGray',
  3947. CAL_RGB: 'CalRGB',
  3948. LAB: 'Lab',
  3949. ICC_BASED: 'ICCBased',
  3950. INDEXED: 'Indexed',
  3951. PATTERN: 'Pattern',
  3952. SEPARATION: 'Separation',
  3953. DEVICE_N: 'DeviceN'
  3954. };
  3955. /**
  3956. * DECODE METHODS
  3957. */
  3958. jsPDFAPI.decode = {
  3959. DCT_DECODE: 'DCTDecode',
  3960. FLATE_DECODE: 'FlateDecode',
  3961. LZW_DECODE: 'LZWDecode',
  3962. JPX_DECODE: 'JPXDecode',
  3963. JBIG2_DECODE: 'JBIG2Decode',
  3964. ASCII85_DECODE: 'ASCII85Decode',
  3965. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  3966. RUN_LENGTH_DECODE: 'RunLengthDecode',
  3967. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  3968. };
  3969. /**
  3970. * IMAGE COMPRESSION TYPES
  3971. */
  3972. jsPDFAPI.image_compression = {
  3973. NONE: 'NONE',
  3974. FAST: 'FAST',
  3975. MEDIUM: 'MEDIUM',
  3976. SLOW: 'SLOW'
  3977. };
  3978. jsPDFAPI.sHashCode = function(str) {
  3979. return Array.prototype.reduce && str.split("").reduce(function(a, b) {
  3980. a = (a << 5) - a + b.charCodeAt(0);
  3981. return a & a;
  3982. }, 0);
  3983. };
  3984. jsPDFAPI.isString = function(object) {
  3985. return typeof object === 'string';
  3986. };
  3987. /**
  3988. * Strips out and returns info from a valid base64 data URI
  3989. * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  3990. * @returns an Array containing the following
  3991. * [0] the complete data URI
  3992. * [1] <MIME-type>
  3993. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  3994. * [4] <data>
  3995. */
  3996. jsPDFAPI.extractInfoFromBase64DataURI = function(dataURI) {
  3997. return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI));
  3998. };
  3999. /**
  4000. * Check to see if ArrayBuffer is supported
  4001. */
  4002. jsPDFAPI.supportsArrayBuffer = function() {
  4003. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  4004. };
  4005. /**
  4006. * Tests supplied object to determine if ArrayBuffer
  4007. * @param {Object[object]}
  4008. */
  4009. jsPDFAPI.isArrayBuffer = function(object) {
  4010. if (!this.supportsArrayBuffer()) return false;
  4011. return object instanceof ArrayBuffer;
  4012. };
  4013. /**
  4014. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  4015. * @param {Object[object]}
  4016. */
  4017. jsPDFAPI.isArrayBufferView = function(object) {
  4018. if (!this.supportsArrayBuffer()) return false;
  4019. if (typeof Uint32Array === 'undefined') return false;
  4020. 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;
  4021. };
  4022. /**
  4023. * Exactly what it says on the tin
  4024. */
  4025. jsPDFAPI.binaryStringToUint8Array = function(binary_string) {
  4026. /*
  4027. * not sure how efficient this will be will bigger files. Is there a native method?
  4028. */
  4029. var len = binary_string.length;
  4030. var bytes = new Uint8Array(len);
  4031. for (var i = 0; i < len; i++) {
  4032. bytes[i] = binary_string.charCodeAt(i);
  4033. }
  4034. return bytes;
  4035. };
  4036. /**
  4037. * Convert the Buffer to a Binary String
  4038. */
  4039. jsPDFAPI.arrayBufferToBinaryString = function(buffer) {
  4040. if (typeof window.atob === "function") {
  4041. return atob(this.arrayBufferToBase64(buffer));
  4042. } else {
  4043. var data = this.isArrayBuffer(buffer) ? buffer : new Uint8Array(buffer);
  4044. var chunkSizeForSlice = 0x5000;
  4045. var binary_string = '';
  4046. var slicesCount = Math.round(data.byteLength / chunkSizeForSlice);
  4047. for (var i = 0; i < slicesCount; i++) {
  4048. binary_string += String.fromCharCode.apply(null, data.slice(i * chunkSizeForSlice, i * chunkSizeForSlice + chunkSizeForSlice));
  4049. }
  4050. return binary_string;
  4051. }
  4052. };
  4053. /**
  4054. * Converts an ArrayBuffer directly to base64
  4055. *
  4056. * Taken from here
  4057. *
  4058. * http://jsperf.com/encoding-xhr-image-data/31
  4059. *
  4060. * Need to test if this is a better solution for larger files
  4061. *
  4062. */
  4063. jsPDFAPI.arrayBufferToBase64 = function(arrayBuffer) {
  4064. var base64 = '';
  4065. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  4066. var bytes = new Uint8Array(arrayBuffer);
  4067. var byteLength = bytes.byteLength;
  4068. var byteRemainder = byteLength % 3;
  4069. var mainLength = byteLength - byteRemainder;
  4070. var a, b, c, d;
  4071. var chunk;
  4072. // Main loop deals with bytes in chunks of 3
  4073. for (var i = 0; i < mainLength; i = i + 3) {
  4074. // Combine the three bytes into a single integer
  4075. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
  4076. // Use bitmasks to extract 6-bit segments from the triplet
  4077. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  4078. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  4079. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  4080. d = chunk & 63; // 63 = 2^6 - 1
  4081. // Convert the raw binary segments to the appropriate ASCII encoding
  4082. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  4083. }
  4084. // Deal with the remaining bytes and padding
  4085. if (byteRemainder == 1) {
  4086. chunk = bytes[mainLength];
  4087. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  4088. // Set the 4 least significant bits to zero
  4089. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  4090. base64 += encodings[a] + encodings[b] + '==';
  4091. } else if (byteRemainder == 2) {
  4092. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  4093. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  4094. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  4095. // Set the 2 least significant bits to zero
  4096. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  4097. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  4098. }
  4099. return base64;
  4100. };
  4101. jsPDFAPI.createImageInfo = function(data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  4102. var info = {
  4103. alias: alias,
  4104. w: wd,
  4105. h: ht,
  4106. cs: cs,
  4107. bpc: bpc,
  4108. i: imageIndex,
  4109. data: data
  4110. // n: objectNumber will be added by putImage code
  4111. };
  4112. if (f) info.f = f;
  4113. if (dp) info.dp = dp;
  4114. if (trns) info.trns = trns;
  4115. if (pal) info.pal = pal;
  4116. if (smask) info.smask = smask;
  4117. if (p) info.p = p; // predictor parameter for PNG compression
  4118. return info;
  4119. };
  4120. jsPDFAPI.addImage = function(imageData, format, x, y, w, h, alias, compression, rotation) {
  4121. 'use strict';
  4122. if (typeof format !== 'string') {
  4123. var tmp = h;
  4124. h = w;
  4125. w = y;
  4126. y = x;
  4127. x = format;
  4128. format = tmp;
  4129. }
  4130. if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  4131. var options = imageData;
  4132. imageData = options.imageData;
  4133. format = options.format || format;
  4134. x = options.x || x || 0;
  4135. y = options.y || y || 0;
  4136. w = options.w || w;
  4137. h = options.h || h;
  4138. alias = options.alias || alias;
  4139. compression = options.compression || compression;
  4140. rotation = options.rotation || options.angle || rotation;
  4141. }
  4142. if (isNaN(x) || isNaN(y)) {
  4143. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  4144. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  4145. }
  4146. var images = getImages.call(this),
  4147. info;
  4148. if (!(info = checkImagesForAlias(imageData, images))) {
  4149. var dataAsBinaryString;
  4150. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
  4151. if (notDefined(alias)) alias = generateAliasFromData(imageData);
  4152. if (!(info = checkImagesForAlias(alias, images))) {
  4153. if (this.isString(imageData)) {
  4154. var base64Info = this.extractInfoFromBase64DataURI(imageData);
  4155. if (base64Info) {
  4156. format = base64Info[2];
  4157. imageData = atob(base64Info[3]); //convert to binary string
  4158. } else {
  4159. if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
  4160. }
  4161. }
  4162. format = (format || 'JPEG').toLowerCase();
  4163. if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
  4164. if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
  4165. /**
  4166. * need to test if it's more efficient to convert all binary strings
  4167. * to TypedArray - or should we just leave and process as string?
  4168. */
  4169. if (this.supportsArrayBuffer()) {
  4170. // no need to convert if imageData is already uint8array
  4171. if (!(imageData instanceof Uint8Array)) {
  4172. dataAsBinaryString = imageData;
  4173. imageData = this.binaryStringToUint8Array(imageData);
  4174. }
  4175. }
  4176. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  4177. if (!info) throw new Error('An unkwown error occurred whilst processing the image');
  4178. }
  4179. }
  4180. writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
  4181. return this;
  4182. };
  4183. /**
  4184. * JPEG SUPPORT
  4185. **/
  4186. //takes a string imgData containing the raw bytes of
  4187. //a jpeg image and returns [width, height]
  4188. //Algorithm from: http://www.64lines.com/jpeg-width-height
  4189. var getJpegSize = function getJpegSize(imgData) {
  4190. 'use strict';
  4191. var width, height, numcomponents;
  4192. // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  4193. 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) {
  4194. throw new Error('getJpegSize requires a binary string jpeg file');
  4195. }
  4196. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  4197. var i = 4,
  4198. len = imgData.length;
  4199. while (i < len) {
  4200. i += blockLength;
  4201. if (imgData.charCodeAt(i) !== 0xff) {
  4202. throw new Error('getJpegSize could not find the size of the image');
  4203. }
  4204. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  4205. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  4206. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  4207. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  4208. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  4209. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  4210. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  4211. imgData.charCodeAt(i + 1) === 0xc7) {
  4212. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  4213. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  4214. numcomponents = imgData.charCodeAt(i + 9);
  4215. return [width, height, numcomponents];
  4216. } else {
  4217. i += 2;
  4218. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  4219. }
  4220. }
  4221. },
  4222. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  4223. var hdr = data[0] << 8 | data[1];
  4224. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  4225. var len = data.length,
  4226. block = (data[4] << 8) + data[5],
  4227. pos = 4,
  4228. bytes,
  4229. width,
  4230. height,
  4231. numcomponents;
  4232. while (pos < len) {
  4233. pos += block;
  4234. bytes = readBytes(data, pos);
  4235. block = (bytes[2] << 8) + bytes[3];
  4236. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  4237. bytes = readBytes(data, pos + 5);
  4238. width = (bytes[2] << 8) + bytes[3];
  4239. height = (bytes[0] << 8) + bytes[1];
  4240. numcomponents = bytes[4];
  4241. return { width: width, height: height, numcomponents: numcomponents };
  4242. }
  4243. pos += 2;
  4244. }
  4245. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  4246. },
  4247. readBytes = function readBytes(data, offset) {
  4248. return data.subarray(offset, offset + 5);
  4249. };
  4250. jsPDFAPI.processJPEG = function(data, index, alias, compression, dataAsBinaryString) {
  4251. 'use strict';
  4252. var colorSpace = this.color_spaces.DEVICE_RGB,
  4253. filter = this.decode.DCT_DECODE,
  4254. bpc = 8,
  4255. dims;
  4256. if (this.isString(data)) {
  4257. dims = getJpegSize(data);
  4258. return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4259. }
  4260. if (this.isArrayBuffer(data)) data = new Uint8Array(data);
  4261. if (this.isArrayBufferView(data)) {
  4262. dims = getJpegSizeFromBytes(data);
  4263. // if we already have a stored binary string rep use that
  4264. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  4265. return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4266. }
  4267. return null;
  4268. };
  4269. jsPDFAPI.processJPG = function() /*data, index, alias, compression, dataAsBinaryString*/ {
  4270. return this.processJPEG.apply(this, arguments);
  4271. };
  4272. })(jsPDF.API);
  4273. /**
  4274. * jsPDF Annotations PlugIn
  4275. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4276. *
  4277. * Licensed under the MIT License.
  4278. * http://opensource.org/licenses/mit-license
  4279. */
  4280. /**
  4281. * There are many types of annotations in a PDF document. Annotations are placed
  4282. * on a page at a particular location. They are not 'attached' to an object.
  4283. * <br />
  4284. * This plugin current supports <br />
  4285. * <li> Goto Page (set pageNumber and top in options)
  4286. * <li> Goto Name (set name and top in options)
  4287. * <li> Goto URL (set url in options)
  4288. * <p>
  4289. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  4290. * (set magFactor in options). XYZ is the default.
  4291. * </p>
  4292. * <p>
  4293. * Links, Text, Popup, and FreeText are supported.
  4294. * </p>
  4295. * <p>
  4296. * Options In PDF spec Not Implemented Yet
  4297. * <li> link border
  4298. * <li> named target
  4299. * <li> page coordinates
  4300. * <li> destination page scaling and layout
  4301. * <li> actions other than URL and GotoPage
  4302. * <li> background / hover actions
  4303. * </p>
  4304. */
  4305. /*
  4306. Destination Magnification Factors
  4307. See PDF 1.3 Page 386 for meanings and options
  4308. [supported]
  4309. XYZ (options; left top zoom)
  4310. Fit (no options)
  4311. FitH (options: top)
  4312. FitV (options: left)
  4313. [not supported]
  4314. FitR
  4315. FitB
  4316. FitBH
  4317. FitBV
  4318. */
  4319. (function(jsPDFAPI) {
  4320. 'use strict';
  4321. var annotationPlugin = {
  4322. /**
  4323. * An array of arrays, indexed by <em>pageNumber</em>.
  4324. */
  4325. annotations: [],
  4326. f2: function f2(number) {
  4327. return number.toFixed(2);
  4328. },
  4329. notEmpty: function notEmpty(obj) {
  4330. if (typeof obj != 'undefined') {
  4331. if (obj != '') {
  4332. return true;
  4333. }
  4334. }
  4335. }
  4336. };
  4337. jsPDF.API.annotationPlugin = annotationPlugin;
  4338. jsPDF.API.events.push(['addPage', function(info) {
  4339. this.annotationPlugin.annotations[info.pageNumber] = [];
  4340. }]);
  4341. jsPDFAPI.events.push(['putPage', function(info) {
  4342. //TODO store annotations in pageContext so reorder/remove will not affect them.
  4343. var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
  4344. var found = false;
  4345. for (var a = 0; a < pageAnnos.length && !found; a++) {
  4346. var anno = pageAnnos[a];
  4347. switch (anno.type) {
  4348. case 'link':
  4349. if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
  4350. found = true;
  4351. break;
  4352. }
  4353. case 'reference':
  4354. case 'text':
  4355. case 'freetext':
  4356. found = true;
  4357. break;
  4358. }
  4359. }
  4360. if (found == false) {
  4361. return;
  4362. }
  4363. this.internal.write("/Annots [");
  4364. var f2 = this.annotationPlugin.f2;
  4365. var k = this.internal.scaleFactor;
  4366. var pageHeight = this.internal.pageSize.height;
  4367. var pageInfo = this.internal.getPageInfo(info.pageNumber);
  4368. for (var a = 0; a < pageAnnos.length; a++) {
  4369. var anno = pageAnnos[a];
  4370. switch (anno.type) {
  4371. case 'reference':
  4372. // References to Widget Anotations (for AcroForm Fields)
  4373. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  4374. break;
  4375. case 'text':
  4376. // Create a an object for both the text and the popup
  4377. var objText = this.internal.newAdditionalObject();
  4378. var objPopup = this.internal.newAdditionalObject();
  4379. var title = anno.title || 'Note';
  4380. 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) + "] ";
  4381. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4382. line += ' /Popup ' + objPopup.objId + " 0 R";
  4383. line += ' /P ' + pageInfo.objId + " 0 R";
  4384. line += ' /T (' + title + ') >>';
  4385. objText.content = line;
  4386. var parent = objText.objId + ' 0 R';
  4387. var popoff = 30;
  4388. 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) + "] ";
  4389. //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) + "] ";
  4390. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  4391. if (anno.open) {
  4392. line += ' /Open true';
  4393. }
  4394. line += ' >>';
  4395. objPopup.content = line;
  4396. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  4397. break;
  4398. case 'freetext':
  4399. 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) + "] ";
  4400. var color = anno.color || '#000000';
  4401. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4402. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  4403. line += ' /Border [0 0 0]';
  4404. line += ' >>';
  4405. this.internal.write(line);
  4406. break;
  4407. case 'link':
  4408. if (anno.options.name) {
  4409. var loc = this.annotations._nameMap[anno.options.name];
  4410. anno.options.pageNumber = loc.page;
  4411. anno.options.top = loc.y;
  4412. } else {
  4413. if (!anno.options.top) {
  4414. anno.options.top = 0;
  4415. }
  4416. }
  4417. 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) + "] ";
  4418. var line = '';
  4419. if (anno.options.url) {
  4420. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  4421. } else if (anno.options.pageNumber) {
  4422. // first page is 0
  4423. var info = this.internal.getPageInfo(anno.options.pageNumber);
  4424. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  4425. anno.options.magFactor = anno.options.magFactor || "XYZ";
  4426. switch (anno.options.magFactor) {
  4427. case 'Fit':
  4428. line += ' /Fit]';
  4429. break;
  4430. case 'FitH':
  4431. //anno.options.top = anno.options.top || f2(pageHeight * k);
  4432. line += ' /FitH ' + anno.options.top + ']';
  4433. break;
  4434. case 'FitV':
  4435. anno.options.left = anno.options.left || 0;
  4436. line += ' /FitV ' + anno.options.left + ']';
  4437. break;
  4438. case 'XYZ':
  4439. default:
  4440. var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
  4441. anno.options.left = anno.options.left || 0;
  4442. // 0 or null zoom will not change zoom factor
  4443. if (typeof anno.options.zoom === 'undefined') {
  4444. anno.options.zoom = 0;
  4445. }
  4446. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  4447. break;
  4448. }
  4449. } else {
  4450. // TODO error - should not be here
  4451. }
  4452. if (line != '') {
  4453. line += " >>";
  4454. this.internal.write(line);
  4455. }
  4456. break;
  4457. }
  4458. }
  4459. this.internal.write("]");
  4460. }]);
  4461. jsPDFAPI.createAnnotation = function(options) {
  4462. switch (options.type) {
  4463. case 'link':
  4464. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  4465. break;
  4466. case 'text':
  4467. case 'freetext':
  4468. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
  4469. break;
  4470. }
  4471. };
  4472. /**
  4473. * valid options
  4474. * <li> pageNumber or url [required]
  4475. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4476. */
  4477. jsPDFAPI.link = function(x, y, w, h, options) {
  4478. 'use strict';
  4479. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4480. x: x,
  4481. y: y,
  4482. w: w,
  4483. h: h,
  4484. options: options,
  4485. type: 'link'
  4486. });
  4487. };
  4488. /**
  4489. * Currently only supports single line text.
  4490. * Returns the width of the text/link
  4491. */
  4492. jsPDFAPI.textWithLink = function(text, x, y, options) {
  4493. 'use strict';
  4494. var width = this.getTextWidth(text);
  4495. var height = this.internal.getLineHeight() / this.internal.scaleFactor;
  4496. this.text(text, x, y);
  4497. //TODO We really need the text baseline height to do this correctly.
  4498. // Or ability to draw text on top, bottom, center, or baseline.
  4499. y += height * .2;
  4500. this.link(x, y - height, width, height, options);
  4501. return width;
  4502. };
  4503. //TODO move into external library
  4504. jsPDFAPI.getTextWidth = function(text) {
  4505. 'use strict';
  4506. var fontSize = this.internal.getFontSize();
  4507. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  4508. return txtWidth;
  4509. };
  4510. //TODO move into external library
  4511. jsPDFAPI.getLineHeight = function() {
  4512. return this.internal.getLineHeight();
  4513. };
  4514. return this;
  4515. })(jsPDF.API);
  4516. /**
  4517. * jsPDF Autoprint Plugin
  4518. *
  4519. * Licensed under the MIT License.
  4520. * http://opensource.org/licenses/mit-license
  4521. */
  4522. /**
  4523. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  4524. * Reader.
  4525. *
  4526. * @returns {jsPDF}
  4527. * @name autoPrint
  4528. * @example
  4529. * var doc = new jsPDF()
  4530. * doc.text(10, 10, 'This is a test')
  4531. * doc.autoPrint()
  4532. * doc.save('autoprint.pdf')
  4533. */
  4534. (function(jsPDFAPI) {
  4535. 'use strict';
  4536. jsPDFAPI.autoPrint = function() {
  4537. 'use strict';
  4538. var refAutoPrintTag;
  4539. this.internal.events.subscribe('postPutResources', function() {
  4540. refAutoPrintTag = this.internal.newObject();
  4541. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  4542. });
  4543. this.internal.events.subscribe("putCatalog", function() {
  4544. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  4545. });
  4546. return this;
  4547. };
  4548. })(jsPDF.API);
  4549. /**
  4550. * jsPDF Canvas PlugIn
  4551. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4552. *
  4553. * Licensed under the MIT License.
  4554. * http://opensource.org/licenses/mit-license
  4555. */
  4556. /**
  4557. * This plugin mimics the HTML5 Canvas
  4558. *
  4559. * The goal is to provide a way for current canvas users to print directly to a PDF.
  4560. */
  4561. (function(jsPDFAPI) {
  4562. 'use strict';
  4563. jsPDFAPI.events.push(['initialized', function() {
  4564. this.canvas.pdf = this;
  4565. }]);
  4566. jsPDFAPI.canvas = {
  4567. getContext: function getContext(name) {
  4568. this.pdf.context2d._canvas = this;
  4569. return this.pdf.context2d;
  4570. },
  4571. style: {}
  4572. };
  4573. Object.defineProperty(jsPDFAPI.canvas, 'width', {
  4574. get: function get() {
  4575. return this._width;
  4576. },
  4577. set: function set(value) {
  4578. this._width = value;
  4579. this.getContext('2d').pageWrapX = value + 1;
  4580. }
  4581. });
  4582. Object.defineProperty(jsPDFAPI.canvas, 'height', {
  4583. get: function get() {
  4584. return this._height;
  4585. },
  4586. set: function set(value) {
  4587. this._height = value;
  4588. this.getContext('2d').pageWrapY = value + 1;
  4589. }
  4590. });
  4591. return this;
  4592. })(jsPDF.API);
  4593. /** ====================================================================
  4594. * jsPDF Cell plugin
  4595. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  4596. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  4597. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  4598. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  4599. * 2014 James Hall, james@parall.ax
  4600. * 2014 Diego Casorran, https://github.com/diegocr
  4601. *
  4602. *
  4603. * ====================================================================
  4604. */
  4605. (function(jsPDFAPI) {
  4606. 'use strict';
  4607. /*jslint browser:true */
  4608. /*global document: false, jsPDF */
  4609. var fontName,
  4610. fontSize,
  4611. fontStyle,
  4612. padding = 3,
  4613. margin = 13,
  4614. headerFunction,
  4615. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
  4616. pages = 1,
  4617. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  4618. lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
  4619. },
  4620. getLastCellPosition = function getLastCellPosition() {
  4621. return lastCellPos;
  4622. },
  4623. NO_MARGINS = { left: 0, top: 0, bottom: 0 };
  4624. jsPDFAPI.setHeaderFunction = function(func) {
  4625. headerFunction = func;
  4626. };
  4627. jsPDFAPI.getTextDimensions = function(txt) {
  4628. fontName = this.internal.getFont().fontName;
  4629. fontSize = this.table_font_size || this.internal.getFontSize();
  4630. fontStyle = this.internal.getFont().fontStyle;
  4631. // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
  4632. var px2pt = 0.264583 * 72 / 25.4,
  4633. dimensions,
  4634. text;
  4635. text = document.createElement('font');
  4636. text.id = "jsPDFCell";
  4637. try {
  4638. text.style.fontStyle = fontStyle;
  4639. } catch (e) {
  4640. text.style.fontWeight = fontStyle;
  4641. }
  4642. text.style.fontName = fontName;
  4643. text.style.fontSize = fontSize + 'pt';
  4644. try {
  4645. text.textContent = txt;
  4646. } catch (e) {
  4647. text.innerText = txt;
  4648. }
  4649. document.body.appendChild(text);
  4650. dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
  4651. document.body.removeChild(text);
  4652. return dimensions;
  4653. };
  4654. jsPDFAPI.cellAddPage = function() {
  4655. var margins = this.margins || NO_MARGINS;
  4656. this.addPage();
  4657. setLastCellPosition(margins.left, margins.top, undefined, undefined);
  4658. //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  4659. pages += 1;
  4660. };
  4661. jsPDFAPI.cellInitialize = function() {
  4662. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
  4663. pages = 1;
  4664. };
  4665. jsPDFAPI.cell = function(x, y, w, h, txt, ln, align) {
  4666. var curCell = getLastCellPosition();
  4667. var pgAdded = false;
  4668. // If this is not the first cell, we must change its position
  4669. if (curCell.ln !== undefined) {
  4670. if (curCell.ln === ln) {
  4671. //Same line
  4672. x = curCell.x + curCell.w;
  4673. y = curCell.y;
  4674. } else {
  4675. //New line
  4676. var margins = this.margins || NO_MARGINS;
  4677. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
  4678. this.cellAddPage();
  4679. pgAdded = true;
  4680. if (this.printHeaders && this.tableHeaderRow) {
  4681. this.printHeaderRow(ln, true);
  4682. }
  4683. }
  4684. //We ignore the passed y: the lines may have different heights
  4685. y = getLastCellPosition().y + getLastCellPosition().h;
  4686. if (pgAdded) y = margin + 10;
  4687. }
  4688. }
  4689. if (txt[0] !== undefined) {
  4690. if (this.printingHeaderRow) {
  4691. this.rect(x, y, w, h, 'FD');
  4692. } else {
  4693. this.rect(x, y, w, h);
  4694. }
  4695. if (align === 'right') {
  4696. if (!(txt instanceof Array)) {
  4697. txt = [txt];
  4698. }
  4699. for (var i = 0; i < txt.length; i++) {
  4700. var currentLine = txt[i];
  4701. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
  4702. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  4703. }
  4704. } else {
  4705. this.text(txt, x + padding, y + this.internal.getLineHeight());
  4706. }
  4707. }
  4708. setLastCellPosition(x, y, w, h, ln);
  4709. return this;
  4710. };
  4711. /**
  4712. * Return the maximum value from an array
  4713. * @param array
  4714. * @param comparisonFn
  4715. * @returns {*}
  4716. */
  4717. jsPDFAPI.arrayMax = function(array, comparisonFn) {
  4718. var max = array[0],
  4719. i,
  4720. ln,
  4721. item;
  4722. for (i = 0, ln = array.length; i < ln; i += 1) {
  4723. item = array[i];
  4724. if (comparisonFn) {
  4725. if (comparisonFn(max, item) === -1) {
  4726. max = item;
  4727. }
  4728. } else {
  4729. if (item > max) {
  4730. max = item;
  4731. }
  4732. }
  4733. }
  4734. return max;
  4735. };
  4736. /**
  4737. * Create a table from a set of data.
  4738. * @param {Integer} [x] : left-position for top-left corner of table
  4739. * @param {Integer} [y] top-position for top-left corner of table
  4740. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  4741. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  4742. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  4743. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  4744. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  4745. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  4746. */
  4747. jsPDFAPI.table = function(x, y, data, headers, config) {
  4748. if (!data) {
  4749. throw 'No data for PDF table';
  4750. }
  4751. var headerNames = [],
  4752. headerPrompts = [],
  4753. header,
  4754. i,
  4755. ln,
  4756. cln,
  4757. columnMatrix = {},
  4758. columnWidths = {},
  4759. columnData,
  4760. column,
  4761. columnMinWidths = [],
  4762. j,
  4763. tableHeaderConfigs = [],
  4764. model,
  4765. jln,
  4766. func,
  4767. //set up defaults. If a value is provided in config, defaults will be overwritten:
  4768. autoSize = false,
  4769. printHeaders = true,
  4770. fontSize = 12,
  4771. margins = NO_MARGINS;
  4772. margins.width = this.internal.pageSize.width;
  4773. if (config) {
  4774. //override config defaults if the user has specified non-default behavior:
  4775. if (config.autoSize === true) {
  4776. autoSize = true;
  4777. }
  4778. if (config.printHeaders === false) {
  4779. printHeaders = false;
  4780. }
  4781. if (config.fontSize) {
  4782. fontSize = config.fontSize;
  4783. }
  4784. if (config.css && typeof config.css['font-size'] !== "undefined") {
  4785. fontSize = config.css['font-size'] * 16;
  4786. }
  4787. if (config.margins) {
  4788. margins = config.margins;
  4789. }
  4790. }
  4791. /**
  4792. * @property {Number} lnMod
  4793. * Keep track of the current line number modifier used when creating cells
  4794. */
  4795. this.lnMod = 0;
  4796. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
  4797. this.printHeaders = printHeaders;
  4798. this.margins = margins;
  4799. this.setFontSize(fontSize);
  4800. this.table_font_size = fontSize;
  4801. // Set header values
  4802. if (headers === undefined || headers === null) {
  4803. // No headers defined so we derive from data
  4804. headerNames = Object.keys(data[0]);
  4805. } else if (headers[0] && typeof headers[0] !== 'string') {
  4806. var px2pt = 0.264583 * 72 / 25.4;
  4807. // Split header configs into names and prompts
  4808. for (i = 0, ln = headers.length; i < ln; i += 1) {
  4809. header = headers[i];
  4810. headerNames.push(header.name);
  4811. headerPrompts.push(header.prompt);
  4812. columnWidths[header.name] = header.width * px2pt;
  4813. }
  4814. } else {
  4815. headerNames = headers;
  4816. }
  4817. if (autoSize) {
  4818. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  4819. func = function func(rec) {
  4820. return rec[header];
  4821. };
  4822. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4823. header = headerNames[i];
  4824. columnMatrix[header] = data.map(func);
  4825. // get header width
  4826. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
  4827. column = columnMatrix[header];
  4828. // get cell widths
  4829. for (j = 0, cln = column.length; j < cln; j += 1) {
  4830. columnData = column[j];
  4831. columnMinWidths.push(this.getTextDimensions(columnData).w);
  4832. }
  4833. // get final column width
  4834. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
  4835. //have to reset
  4836. columnMinWidths = [];
  4837. }
  4838. }
  4839. // -- Construct the table
  4840. if (printHeaders) {
  4841. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
  4842. // Construct the header row
  4843. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4844. header = headerNames[i];
  4845. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  4846. }
  4847. // Store the table header config
  4848. this.setTableHeaderRow(tableHeaderConfigs);
  4849. // Print the header for the start of the table
  4850. this.printHeaderRow(1, false);
  4851. }
  4852. // Construct the data rows
  4853. for (i = 0, ln = data.length; i < ln; i += 1) {
  4854. var lineHeight;
  4855. model = data[i];
  4856. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  4857. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  4858. header = headerNames[j];
  4859. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  4860. }
  4861. }
  4862. this.lastCellPos = lastCellPos;
  4863. this.table_x = x;
  4864. this.table_y = y;
  4865. return this;
  4866. };
  4867. /**
  4868. * Calculate the height for containing the highest column
  4869. * @param {String[]} headerNames is the header, used as keys to the data
  4870. * @param {Integer[]} columnWidths is size of each column
  4871. * @param {Object[]} model is the line of data we want to calculate the height of
  4872. */
  4873. jsPDFAPI.calculateLineHeight = function(headerNames, columnWidths, model) {
  4874. var header,
  4875. lineHeight = 0;
  4876. for (var j = 0; j < headerNames.length; j++) {
  4877. header = headerNames[j];
  4878. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  4879. var h = this.internal.getLineHeight() * model[header].length + padding;
  4880. if (h > lineHeight) lineHeight = h;
  4881. }
  4882. return lineHeight;
  4883. };
  4884. /**
  4885. * Store the config for outputting a table header
  4886. * @param {Object[]} config
  4887. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  4888. * except the ln parameter is excluded
  4889. */
  4890. jsPDFAPI.setTableHeaderRow = function(config) {
  4891. this.tableHeaderRow = config;
  4892. };
  4893. /**
  4894. * Output the store header row
  4895. * @param lineNumber The line number to output the header at
  4896. */
  4897. jsPDFAPI.printHeaderRow = function(lineNumber, new_page) {
  4898. if (!this.tableHeaderRow) {
  4899. throw 'Property tableHeaderRow does not exist.';
  4900. }
  4901. var tableHeaderCell, tmpArray, i, ln;
  4902. this.printingHeaderRow = true;
  4903. if (headerFunction !== undefined) {
  4904. var position = headerFunction(this, pages);
  4905. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  4906. }
  4907. this.setFontStyle('bold');
  4908. var tempHeaderConf = [];
  4909. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  4910. this.setFillColor(200, 200, 200);
  4911. tableHeaderCell = this.tableHeaderRow[i];
  4912. if (new_page) {
  4913. this.margins.top = margin;
  4914. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  4915. tempHeaderConf.push(tableHeaderCell);
  4916. }
  4917. tmpArray = [].concat(tableHeaderCell);
  4918. this.cell.apply(this, tmpArray.concat(lineNumber));
  4919. }
  4920. if (tempHeaderConf.length > 0) {
  4921. this.setTableHeaderRow(tempHeaderConf);
  4922. }
  4923. this.setFontStyle('normal');
  4924. this.printingHeaderRow = false;
  4925. };
  4926. })(jsPDF.API);
  4927. /**
  4928. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4929. *
  4930. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  4931. */
  4932. /**
  4933. * This plugin mimics the HTML5 Canvas's context2d.
  4934. *
  4935. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  4936. */
  4937. /**
  4938. * TODO implement stroke opacity (refactor from fill() method )
  4939. * TODO transform angle and radii parameters
  4940. */
  4941. /**
  4942. * require('jspdf.js'); require('lib/css_colors.js');
  4943. */
  4944. (function(jsPDFAPI) {
  4945. 'use strict';
  4946. jsPDFAPI.events.push(['initialized', function() {
  4947. this.context2d.pdf = this;
  4948. this.context2d.internal.pdf = this;
  4949. this.context2d.ctx = new context();
  4950. this.context2d.ctxStack = [];
  4951. this.context2d.path = [];
  4952. }]);
  4953. jsPDFAPI.context2d = {
  4954. pageWrapXEnabled: false,
  4955. pageWrapYEnabled: false,
  4956. pageWrapX: 9999999,
  4957. pageWrapY: 9999999,
  4958. ctx: new context(),
  4959. f2: function f2(number) {
  4960. return number.toFixed(2);
  4961. },
  4962. fillRect: function fillRect(x, y, w, h) {
  4963. if (this._isFillTransparent()) {
  4964. return;
  4965. }
  4966. x = this._wrapX(x);
  4967. y = this._wrapY(y);
  4968. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4969. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  4970. },
  4971. strokeRect: function strokeRect(x, y, w, h) {
  4972. if (this._isStrokeTransparent()) {
  4973. return;
  4974. }
  4975. x = this._wrapX(x);
  4976. y = this._wrapY(y);
  4977. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4978. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
  4979. },
  4980. /**
  4981. * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  4982. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  4983. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  4984. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  4985. * @param x
  4986. * @param y
  4987. * @param w
  4988. * @param h
  4989. */
  4990. clearRect: function clearRect(x, y, w, h) {
  4991. if (this.ctx.ignoreClearRect) {
  4992. return;
  4993. }
  4994. x = this._wrapX(x);
  4995. y = this._wrapY(y);
  4996. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4997. this.save();
  4998. this.setFillStyle('#ffffff');
  4999. //TODO This is hack to fill with white.
  5000. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5001. this.restore();
  5002. },
  5003. save: function save() {
  5004. this.ctx._fontSize = this.pdf.internal.getFontSize();
  5005. var ctx = new context();
  5006. ctx.copy(this.ctx);
  5007. this.ctxStack.push(this.ctx);
  5008. this.ctx = ctx;
  5009. },
  5010. restore: function restore() {
  5011. this.ctx = this.ctxStack.pop();
  5012. this.setFillStyle(this.ctx.fillStyle);
  5013. this.setStrokeStyle(this.ctx.strokeStyle);
  5014. this.setFont(this.ctx.font);
  5015. this.pdf.setFontSize(this.ctx._fontSize);
  5016. this.setLineCap(this.ctx.lineCap);
  5017. this.setLineWidth(this.ctx.lineWidth);
  5018. this.setLineJoin(this.ctx.lineJoin);
  5019. },
  5020. rect: function rect(x, y, w, h) {
  5021. this.moveTo(x, y);
  5022. this.lineTo(x + w, y);
  5023. this.lineTo(x + w, y + h);
  5024. this.lineTo(x, y + h);
  5025. this.lineTo(x, y); //TODO not needed
  5026. this.closePath();
  5027. },
  5028. beginPath: function beginPath() {
  5029. this.path = [];
  5030. },
  5031. closePath: function closePath() {
  5032. this.path.push({
  5033. type: 'close'
  5034. });
  5035. },
  5036. _getRGBA: function _getRGBA(style) {
  5037. // get the decimal values of r, g, and b;
  5038. var r, g, b, a;
  5039. if (!style) {
  5040. return { r: 0, g: 0, b: 0, a: 0, style: style };
  5041. }
  5042. if (this.internal.rxTransparent.test(style)) {
  5043. r = 0;
  5044. g = 0;
  5045. b = 0;
  5046. a = 0;
  5047. } else {
  5048. var m = this.internal.rxRgb.exec(style);
  5049. if (m != null) {
  5050. r = parseInt(m[1]);
  5051. g = parseInt(m[2]);
  5052. b = parseInt(m[3]);
  5053. a = 1;
  5054. } else {
  5055. m = this.internal.rxRgba.exec(style);
  5056. if (m != null) {
  5057. r = parseInt(m[1]);
  5058. g = parseInt(m[2]);
  5059. b = parseInt(m[3]);
  5060. a = parseFloat(m[4]);
  5061. } else {
  5062. a = 1;
  5063. if (style.charAt(0) != '#') {
  5064. style = CssColors.colorNameToHex(style);
  5065. if (!style) {
  5066. style = '#000000';
  5067. }
  5068. } else {}
  5069. if (style.length === 4) {
  5070. r = style.substring(1, 2);
  5071. r += r;
  5072. g = style.substring(2, 3);
  5073. g += g;
  5074. b = style.substring(3, 4);
  5075. b += b;
  5076. } else {
  5077. r = style.substring(1, 3);
  5078. g = style.substring(3, 5);
  5079. b = style.substring(5, 7);
  5080. }
  5081. r = parseInt(r, 16);
  5082. g = parseInt(g, 16);
  5083. b = parseInt(b, 16);
  5084. }
  5085. }
  5086. }
  5087. return { r: r, g: g, b: b, a: a, style: style };
  5088. },
  5089. setFillStyle: function setFillStyle(style) {
  5090. var rgba = this._getRGBA(style);
  5091. this.ctx.fillStyle = style;
  5092. this.ctx._isFillTransparent = rgba.a === 0;
  5093. this.ctx._fillOpacity = rgba.a;
  5094. this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, {
  5095. a: rgba.a
  5096. });
  5097. this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, {
  5098. a: rgba.a
  5099. });
  5100. },
  5101. setStrokeStyle: function setStrokeStyle(style) {
  5102. var rgba = this._getRGBA(style);
  5103. this.ctx.strokeStyle = rgba.style;
  5104. this.ctx._isStrokeTransparent = rgba.a === 0;
  5105. this.ctx._strokeOpacity = rgba.a;
  5106. //TODO jsPDF to handle rgba
  5107. if (rgba.a === 0) {
  5108. this.pdf.setDrawColor(255, 255, 255);
  5109. } else if (rgba.a === 1) {
  5110. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5111. } else {
  5112. //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
  5113. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5114. }
  5115. },
  5116. fillText: function fillText(text, x, y, maxWidth) {
  5117. if (this._isFillTransparent()) {
  5118. return;
  5119. }
  5120. x = this._wrapX(x);
  5121. y = this._wrapY(y);
  5122. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5123. x = xpt[0];
  5124. y = xpt[1];
  5125. var rads = this._matrix_rotation(this.ctx._transform);
  5126. var degs = rads * 57.2958;
  5127. //TODO only push the clip if it has not been applied to the current PDF context
  5128. if (this.ctx._clip_path.length > 0) {
  5129. var lines;
  5130. if (window.outIntercept) {
  5131. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5132. } else {
  5133. lines = this.internal.getCurrentPage();
  5134. }
  5135. lines.push("q");
  5136. var origPath = this.path;
  5137. this.path = this.ctx._clip_path;
  5138. this.ctx._clip_path = [];
  5139. this._fill(null, true);
  5140. this.ctx._clip_path = this.path;
  5141. this.path = origPath;
  5142. }
  5143. // We only use X axis as scale hint
  5144. var scale = 1;
  5145. try {
  5146. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5147. } catch (e) {
  5148. console.warn(e);
  5149. }
  5150. // In some cases the transform was very small (5.715760606202283e-17). Most likely a canvg rounding error.
  5151. if (scale < .01) {
  5152. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5153. } else {
  5154. var oldSize = this.pdf.internal.getFontSize();
  5155. this.pdf.setFontSize(oldSize * scale);
  5156. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5157. this.pdf.setFontSize(oldSize);
  5158. }
  5159. if (this.ctx._clip_path.length > 0) {
  5160. lines.push('Q');
  5161. }
  5162. },
  5163. strokeText: function strokeText(text, x, y, maxWidth) {
  5164. if (this._isStrokeTransparent()) {
  5165. return;
  5166. }
  5167. x = this._wrapX(x);
  5168. y = this._wrapY(y);
  5169. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5170. x = xpt[0];
  5171. y = xpt[1];
  5172. var rads = this._matrix_rotation(this.ctx._transform);
  5173. var degs = rads * 57.2958;
  5174. //TODO only push the clip if it has not been applied to the current PDF context
  5175. if (this.ctx._clip_path.length > 0) {
  5176. var lines;
  5177. if (window.outIntercept) {
  5178. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5179. } else {
  5180. lines = this.internal.getCurrentPage();
  5181. }
  5182. lines.push("q");
  5183. var origPath = this.path;
  5184. this.path = this.ctx._clip_path;
  5185. this.ctx._clip_path = [];
  5186. this._fill(null, true);
  5187. this.ctx._clip_path = this.path;
  5188. this.path = origPath;
  5189. }
  5190. var scale = 1;
  5191. // We only use the X axis as scale hint
  5192. try {
  5193. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5194. } catch (e) {
  5195. console.warn(e);
  5196. }
  5197. if (scale === 1) {
  5198. this.pdf.text(text, x, this._getBaseline(y), {
  5199. stroke: true
  5200. }, degs);
  5201. } else {
  5202. var oldSize = this.pdf.internal.getFontSize();
  5203. this.pdf.setFontSize(oldSize * scale);
  5204. this.pdf.text(text, x, this._getBaseline(y), {
  5205. stroke: true
  5206. }, degs);
  5207. this.pdf.setFontSize(oldSize);
  5208. }
  5209. if (this.ctx._clip_path.length > 0) {
  5210. lines.push('Q');
  5211. }
  5212. },
  5213. setFont: function setFont(font) {
  5214. this.ctx.font = font;
  5215. //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
  5216. var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
  5217. m = rx.exec(font);
  5218. if (m != null) {
  5219. var fontStyle = m[1];
  5220. var fontWeight = m[3];
  5221. var fontSize = m[4];
  5222. var fontSizeUnit = m[5];
  5223. var fontFamily = m[6];
  5224. if ('px' === fontSizeUnit) {
  5225. fontSize = Math.floor(parseFloat(fontSize));
  5226. // fontSize = fontSize * 1.25;
  5227. } else if ('em' === fontSizeUnit) {
  5228. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5229. } else {
  5230. fontSize = Math.floor(parseFloat(fontSize));
  5231. }
  5232. this.pdf.setFontSize(fontSize);
  5233. if (fontWeight === 'bold' || fontWeight === '700') {
  5234. this.pdf.setFontStyle('bold');
  5235. } else {
  5236. if (fontStyle === 'italic') {
  5237. this.pdf.setFontStyle('italic');
  5238. } else {
  5239. this.pdf.setFontStyle('normal');
  5240. }
  5241. }
  5242. var name = fontFamily;
  5243. var parts = name.toLowerCase().split(/\s*,\s*/);
  5244. var jsPdfFontName;
  5245. if (parts.indexOf('arial') != -1) {
  5246. jsPdfFontName = 'Arial';
  5247. } else if (parts.indexOf('verdana') != -1) {
  5248. jsPdfFontName = 'Verdana';
  5249. } else if (parts.indexOf('helvetica') != -1) {
  5250. jsPdfFontName = 'Helvetica';
  5251. } else if (parts.indexOf('sans-serif') != -1) {
  5252. jsPdfFontName = 'sans-serif';
  5253. } else if (parts.indexOf('fixed') != -1) {
  5254. jsPdfFontName = 'Fixed';
  5255. } else if (parts.indexOf('monospace') != -1) {
  5256. jsPdfFontName = 'Monospace';
  5257. } else if (parts.indexOf('terminal') != -1) {
  5258. jsPdfFontName = 'Terminal';
  5259. } else if (parts.indexOf('courier') != -1) {
  5260. jsPdfFontName = 'Courier';
  5261. } else if (parts.indexOf('times') != -1) {
  5262. jsPdfFontName = 'Times';
  5263. } else if (parts.indexOf('cursive') != -1) {
  5264. jsPdfFontName = 'Cursive';
  5265. } else if (parts.indexOf('fantasy') != -1) {
  5266. jsPdfFontName = 'Fantasy';
  5267. } else if (parts.indexOf('serif') != -1) {
  5268. jsPdfFontName = 'Serif';
  5269. } else {
  5270. jsPdfFontName = 'Serif';
  5271. }
  5272. //TODO check more cases
  5273. var style;
  5274. if ('bold' === fontWeight) {
  5275. style = 'bold';
  5276. } else {
  5277. style = 'normal';
  5278. }
  5279. this.pdf.setFont(jsPdfFontName, style);
  5280. } else {
  5281. var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
  5282. var m = rx.exec(font);
  5283. if (m != null) {
  5284. var size = m[1];
  5285. var name = m[3];
  5286. var style = m[4];
  5287. if (!style) {
  5288. style = 'normal';
  5289. }
  5290. if ('em' === fontSizeUnit) {
  5291. size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5292. } else {
  5293. size = Math.floor(parseFloat(size));
  5294. }
  5295. this.pdf.setFontSize(size);
  5296. this.pdf.setFont(name, style);
  5297. }
  5298. }
  5299. },
  5300. setTextBaseline: function setTextBaseline(baseline) {
  5301. this.ctx.textBaseline = baseline;
  5302. },
  5303. getTextBaseline: function getTextBaseline() {
  5304. return this.ctx.textBaseline;
  5305. },
  5306. //TODO implement textAlign
  5307. setTextAlign: function setTextAlign(align) {
  5308. this.ctx.textAlign = align;
  5309. },
  5310. getTextAlign: function getTextAlign() {
  5311. return this.ctx.textAlign;
  5312. },
  5313. setLineWidth: function setLineWidth(width) {
  5314. this.ctx.lineWidth = width;
  5315. this.pdf.setLineWidth(width);
  5316. },
  5317. setLineCap: function setLineCap(style) {
  5318. this.ctx.lineCap = style;
  5319. this.pdf.setLineCap(style);
  5320. },
  5321. setLineJoin: function setLineJoin(style) {
  5322. this.ctx.lineJoin = style;
  5323. this.pdf.setLineJoin(style);
  5324. },
  5325. moveTo: function moveTo(x, y) {
  5326. x = this._wrapX(x);
  5327. y = this._wrapY(y);
  5328. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5329. x = xpt[0];
  5330. y = xpt[1];
  5331. var obj = {
  5332. type: 'mt',
  5333. x: x,
  5334. y: y
  5335. };
  5336. this.path.push(obj);
  5337. },
  5338. _wrapX: function _wrapX(x) {
  5339. if (this.pageWrapXEnabled) {
  5340. return x % this.pageWrapX;
  5341. } else {
  5342. return x;
  5343. }
  5344. },
  5345. _wrapY: function _wrapY(y) {
  5346. if (this.pageWrapYEnabled) {
  5347. this._gotoPage(this._page(y));
  5348. return (y - this.lastBreak) % this.pageWrapY;
  5349. } else {
  5350. return y;
  5351. }
  5352. },
  5353. transform: function transform(a, b, c, d, e, f) {
  5354. //TODO apply to current transformation instead of replacing
  5355. this.ctx._transform = [a, b, c, d, e, f];
  5356. },
  5357. setTransform: function setTransform(a, b, c, d, e, f) {
  5358. this.ctx._transform = [a, b, c, d, e, f];
  5359. },
  5360. _getTransform: function _getTransform() {
  5361. return this.ctx._transform;
  5362. },
  5363. lastBreak: 0,
  5364. // Y Position of page breaks.
  5365. pageBreaks: [],
  5366. // returns: One-based Page Number
  5367. // Should only be used if pageWrapYEnabled is true
  5368. _page: function _page(y) {
  5369. if (this.pageWrapYEnabled) {
  5370. this.lastBreak = 0;
  5371. var manualBreaks = 0;
  5372. var autoBreaks = 0;
  5373. for (var i = 0; i < this.pageBreaks.length; i++) {
  5374. if (y >= this.pageBreaks[i]) {
  5375. manualBreaks++;
  5376. if (this.lastBreak === 0) {
  5377. autoBreaks++;
  5378. }
  5379. var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
  5380. this.lastBreak = this.pageBreaks[i];
  5381. var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
  5382. autoBreaks += pagesSinceLastBreak;
  5383. }
  5384. }
  5385. if (this.lastBreak === 0) {
  5386. var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
  5387. autoBreaks += pagesSinceLastBreak;
  5388. }
  5389. return autoBreaks + manualBreaks;
  5390. } else {
  5391. return this.pdf.internal.getCurrentPageInfo().pageNumber;
  5392. }
  5393. },
  5394. _gotoPage: function _gotoPage(pageOneBased) {
  5395. // This is a stub to be overriden if needed
  5396. },
  5397. lineTo: function lineTo(x, y) {
  5398. x = this._wrapX(x);
  5399. y = this._wrapY(y);
  5400. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5401. x = xpt[0];
  5402. y = xpt[1];
  5403. var obj = {
  5404. type: 'lt',
  5405. x: x,
  5406. y: y
  5407. };
  5408. this.path.push(obj);
  5409. },
  5410. bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
  5411. x1 = this._wrapX(x1);
  5412. y1 = this._wrapY(y1);
  5413. x2 = this._wrapX(x2);
  5414. y2 = this._wrapY(y2);
  5415. x = this._wrapX(x);
  5416. y = this._wrapY(y);
  5417. var xpt;
  5418. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5419. x = xpt[0];
  5420. y = xpt[1];
  5421. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5422. x1 = xpt[0];
  5423. y1 = xpt[1];
  5424. xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
  5425. x2 = xpt[0];
  5426. y2 = xpt[1];
  5427. var obj = {
  5428. type: 'bct',
  5429. x1: x1,
  5430. y1: y1,
  5431. x2: x2,
  5432. y2: y2,
  5433. x: x,
  5434. y: y
  5435. };
  5436. this.path.push(obj);
  5437. },
  5438. quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
  5439. x1 = this._wrapX(x1);
  5440. y1 = this._wrapY(y1);
  5441. x = this._wrapX(x);
  5442. y = this._wrapY(y);
  5443. var xpt;
  5444. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5445. x = xpt[0];
  5446. y = xpt[1];
  5447. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5448. x1 = xpt[0];
  5449. y1 = xpt[1];
  5450. var obj = {
  5451. type: 'qct',
  5452. x1: x1,
  5453. y1: y1,
  5454. x: x,
  5455. y: y
  5456. };
  5457. this.path.push(obj);
  5458. },
  5459. arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
  5460. x = this._wrapX(x);
  5461. y = this._wrapY(y);
  5462. if (!this._matrix_is_identity(this.ctx._transform)) {
  5463. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5464. x = xpt[0];
  5465. y = xpt[1];
  5466. var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
  5467. var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
  5468. radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
  5469. //TODO angles need to be transformed
  5470. }
  5471. var obj = {
  5472. type: 'arc',
  5473. x: x,
  5474. y: y,
  5475. radius: radius,
  5476. startAngle: startAngle,
  5477. endAngle: endAngle,
  5478. anticlockwise: anticlockwise
  5479. };
  5480. this.path.push(obj);
  5481. },
  5482. drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
  5483. if (x2 !== undefined) {
  5484. x = x2;
  5485. y = y2;
  5486. w = w2;
  5487. h = h2;
  5488. }
  5489. x = this._wrapX(x);
  5490. y = this._wrapY(y);
  5491. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5492. var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
  5493. // TODO implement source clipping and image scaling
  5494. var format;
  5495. var rx = /data:image\/(\w+).*/i;
  5496. var m = rx.exec(img);
  5497. if (m != null) {
  5498. format = m[1];
  5499. } else {
  5500. // format = "jpeg";
  5501. format = "png";
  5502. }
  5503. this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
  5504. },
  5505. /**
  5506. * Multiply the first matrix by the second
  5507. * @param m1
  5508. * @param m2
  5509. * @returns {*[]}
  5510. * @private
  5511. */
  5512. _matrix_multiply: function _matrix_multiply(m2, m1) {
  5513. var sx = m1[0];
  5514. var shy = m1[1];
  5515. var shx = m1[2];
  5516. var sy = m1[3];
  5517. var tx = m1[4];
  5518. var ty = m1[5];
  5519. var t0 = sx * m2[0] + shy * m2[2];
  5520. var t2 = shx * m2[0] + sy * m2[2];
  5521. var t4 = tx * m2[0] + ty * m2[2] + m2[4];
  5522. shy = sx * m2[1] + shy * m2[3];
  5523. sy = shx * m2[1] + sy * m2[3];
  5524. ty = tx * m2[1] + ty * m2[3] + m2[5];
  5525. sx = t0;
  5526. shx = t2;
  5527. tx = t4;
  5528. return [sx, shy, shx, sy, tx, ty];
  5529. },
  5530. _matrix_rotation: function _matrix_rotation(m) {
  5531. return Math.atan2(m[2], m[0]);
  5532. },
  5533. _matrix_decompose: function _matrix_decompose(matrix) {
  5534. var a = matrix[0];
  5535. var b = matrix[1];
  5536. var c = matrix[2];
  5537. var d = matrix[3];
  5538. var scaleX = Math.sqrt(a * a + b * b);
  5539. a /= scaleX;
  5540. b /= scaleX;
  5541. var shear = a * c + b * d;
  5542. c -= a * shear;
  5543. d -= b * shear;
  5544. var scaleY = Math.sqrt(c * c + d * d);
  5545. c /= scaleY;
  5546. d /= scaleY;
  5547. shear /= scaleY;
  5548. if (a * d < b * c) {
  5549. a = -a;
  5550. b = -b;
  5551. shear = -shear;
  5552. scaleX = -scaleX;
  5553. }
  5554. return {
  5555. scale: [scaleX, 0, 0, scaleY, 0, 0],
  5556. translate: [1, 0, 0, 1, matrix[4], matrix[5]],
  5557. rotate: [a, b, -b, a, 0, 0],
  5558. skew: [1, 0, shear, 1, 0, 0]
  5559. };
  5560. },
  5561. _matrix_map_point: function _matrix_map_point(m1, pt) {
  5562. var sx = m1[0];
  5563. var shy = m1[1];
  5564. var shx = m1[2];
  5565. var sy = m1[3];
  5566. var tx = m1[4];
  5567. var ty = m1[5];
  5568. var px = pt[0];
  5569. var py = pt[1];
  5570. var x = px * sx + py * shx + tx;
  5571. var y = px * shy + py * sy + ty;
  5572. return [x, y];
  5573. },
  5574. _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
  5575. var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
  5576. return { x: xpt[0], y: xpt[1] };
  5577. },
  5578. _matrix_map_rect: function _matrix_map_rect(m1, rect) {
  5579. var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
  5580. var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
  5581. return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
  5582. },
  5583. _matrix_is_identity: function _matrix_is_identity(m1) {
  5584. if (m1[0] != 1) {
  5585. return false;
  5586. }
  5587. if (m1[1] != 0) {
  5588. return false;
  5589. }
  5590. if (m1[2] != 0) {
  5591. return false;
  5592. }
  5593. if (m1[3] != 1) {
  5594. return false;
  5595. }
  5596. if (m1[4] != 0) {
  5597. return false;
  5598. }
  5599. if (m1[5] != 0) {
  5600. return false;
  5601. }
  5602. return true;
  5603. },
  5604. rotate: function rotate(angle) {
  5605. var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
  5606. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5607. },
  5608. scale: function scale(sx, sy) {
  5609. var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
  5610. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5611. },
  5612. translate: function translate(x, y) {
  5613. var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
  5614. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5615. },
  5616. stroke: function stroke() {
  5617. if (this.ctx._clip_path.length > 0) {
  5618. var lines;
  5619. if (window.outIntercept) {
  5620. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5621. } else {
  5622. lines = this.internal.getCurrentPage();
  5623. }
  5624. lines.push("q");
  5625. var origPath = this.path;
  5626. this.path = this.ctx._clip_path;
  5627. this.ctx._clip_path = [];
  5628. this._stroke(true);
  5629. this.ctx._clip_path = this.path;
  5630. this.path = origPath;
  5631. this._stroke(false);
  5632. lines.push("Q");
  5633. } else {
  5634. this._stroke(false);
  5635. }
  5636. },
  5637. _stroke: function _stroke(isClip) {
  5638. if (!isClip && this._isStrokeTransparent()) {
  5639. return;
  5640. }
  5641. //TODO opacity
  5642. var moves = [];
  5643. var xPath = this.path;
  5644. for (var i = 0; i < xPath.length; i++) {
  5645. var pt = xPath[i];
  5646. switch (pt.type) {
  5647. case 'mt':
  5648. moves.push({ start: pt, deltas: [], abs: [] });
  5649. break;
  5650. case 'lt':
  5651. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5652. moves[moves.length - 1].deltas.push(delta);
  5653. moves[moves.length - 1].abs.push(pt);
  5654. break;
  5655. case 'bct':
  5656. 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];
  5657. moves[moves.length - 1].deltas.push(delta);
  5658. break;
  5659. case 'qct':
  5660. // convert to bezier
  5661. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5662. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5663. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5664. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5665. var x3 = pt.x;
  5666. var y3 = pt.y;
  5667. 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];
  5668. moves[moves.length - 1].deltas.push(delta);
  5669. break;
  5670. case 'arc':
  5671. //TODO this was hack to avoid out-of-bounds issue
  5672. // No move-to before drawing the arc
  5673. if (moves.length == 0) {
  5674. moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
  5675. }
  5676. moves[moves.length - 1].arc = true;
  5677. moves[moves.length - 1].abs.push(pt);
  5678. break;
  5679. case 'close':
  5680. break;
  5681. }
  5682. }
  5683. for (var i = 0; i < moves.length; i++) {
  5684. var style;
  5685. if (i == moves.length - 1) {
  5686. style = 's';
  5687. } else {
  5688. style = null;
  5689. }
  5690. if (moves[i].arc) {
  5691. var arcs = moves[i].abs;
  5692. for (var ii = 0; ii < arcs.length; ii++) {
  5693. var arc = arcs[ii];
  5694. var start = arc.startAngle * 360 / (2 * Math.PI);
  5695. var end = arc.endAngle * 360 / (2 * Math.PI);
  5696. var x = arc.x;
  5697. var y = arc.y;
  5698. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
  5699. }
  5700. } else {
  5701. var x = moves[i].start.x;
  5702. var y = moves[i].start.y;
  5703. if (!isClip) {
  5704. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5705. } else {
  5706. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5707. this.pdf.clip_fixed();
  5708. }
  5709. }
  5710. }
  5711. },
  5712. _isFillTransparent: function _isFillTransparent() {
  5713. return this.ctx._isFillTransparent || this.globalAlpha == 0;
  5714. },
  5715. _isStrokeTransparent: function _isStrokeTransparent() {
  5716. return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
  5717. },
  5718. fill: function fill(fillRule) {
  5719. //evenodd or nonzero (default)
  5720. if (this.ctx._clip_path.length > 0) {
  5721. var lines;
  5722. if (window.outIntercept) {
  5723. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5724. } else {
  5725. lines = this.internal.getCurrentPage();
  5726. }
  5727. lines.push("q");
  5728. var origPath = this.path;
  5729. this.path = this.ctx._clip_path;
  5730. this.ctx._clip_path = [];
  5731. this._fill(fillRule, true);
  5732. this.ctx._clip_path = this.path;
  5733. this.path = origPath;
  5734. this._fill(fillRule, false);
  5735. lines.push('Q');
  5736. } else {
  5737. this._fill(fillRule, false);
  5738. }
  5739. },
  5740. _fill: function _fill(fillRule, isClip) {
  5741. if (this._isFillTransparent()) {
  5742. return;
  5743. }
  5744. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5745. var lines;
  5746. if (window.outIntercept) {
  5747. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5748. } else {
  5749. lines = this.internal.getCurrentPage();
  5750. }
  5751. // if (this.ctx._clip_path.length > 0) {
  5752. // lines.push('q');
  5753. // var oldPath = this.path;
  5754. // this.path = this.ctx._clip_path;
  5755. // this.ctx._clip_path = [];
  5756. // this._fill(fillRule, true);
  5757. // this.ctx._clip_path = this.path;
  5758. // this.path = oldPath;
  5759. // }
  5760. var moves = [];
  5761. var outInterceptOld = window.outIntercept;
  5762. if (v2Support) {
  5763. // Blend and Mask
  5764. switch (this.ctx.globalCompositeOperation) {
  5765. case 'normal':
  5766. case 'source-over':
  5767. break;
  5768. case 'destination-in':
  5769. case 'destination-out':
  5770. //TODO this need to be added to the current group or page
  5771. // define a mask stream
  5772. var obj = this.pdf.internal.newStreamObject();
  5773. // define a mask state
  5774. var obj2 = this.pdf.internal.newObject2();
  5775. obj2.push('<</Type /ExtGState');
  5776. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5777. obj2.push('>>');
  5778. // add mask to page resources
  5779. var gsName = 'MASK' + obj2.objId;
  5780. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5781. var instruction = '/' + gsName + ' gs';
  5782. // add mask to page, group, or stream
  5783. lines.splice(0, 0, 'q');
  5784. lines.splice(1, 0, instruction);
  5785. lines.push('Q');
  5786. window.outIntercept = obj;
  5787. break;
  5788. default:
  5789. var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
  5790. if (dictionaryEntry) {
  5791. this.pdf.internal.out(dictionaryEntry + ' gs');
  5792. }
  5793. break;
  5794. }
  5795. }
  5796. var alpha = this.ctx.globalAlpha;
  5797. if (this.ctx._fillOpacity < 1) {
  5798. // TODO combine this with global opacity
  5799. alpha = this.ctx._fillOpacity;
  5800. }
  5801. //TODO check for an opacity graphics state that was already created
  5802. //TODO do not set opacity if current value is already active
  5803. if (v2Support) {
  5804. var objOpac = this.pdf.internal.newObject2();
  5805. objOpac.push('<</Type /ExtGState');
  5806. //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
  5807. //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
  5808. objOpac.push('/CA ' + alpha); // Stroke
  5809. objOpac.push('/ca ' + alpha); // Not Stroke
  5810. objOpac.push('>>');
  5811. var gsName = 'GS_O_' + objOpac.objId;
  5812. this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
  5813. this.pdf.internal.out('/' + gsName + ' gs');
  5814. }
  5815. var xPath = this.path;
  5816. for (var i = 0; i < xPath.length; i++) {
  5817. var pt = xPath[i];
  5818. switch (pt.type) {
  5819. case 'mt':
  5820. moves.push({ start: pt, deltas: [], abs: [] });
  5821. break;
  5822. case 'lt':
  5823. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5824. moves[moves.length - 1].deltas.push(delta);
  5825. moves[moves.length - 1].abs.push(pt);
  5826. break;
  5827. case 'bct':
  5828. 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];
  5829. moves[moves.length - 1].deltas.push(delta);
  5830. break;
  5831. case 'qct':
  5832. // convert to bezier
  5833. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5834. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5835. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5836. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5837. var x3 = pt.x;
  5838. var y3 = pt.y;
  5839. 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];
  5840. moves[moves.length - 1].deltas.push(delta);
  5841. break;
  5842. case 'arc':
  5843. //TODO this was hack to avoid out-of-bounds issue when drawing circle
  5844. // No move-to before drawing the arc
  5845. if (moves.length === 0) {
  5846. moves.push({ deltas: [], abs: [] });
  5847. }
  5848. moves[moves.length - 1].arc = true;
  5849. moves[moves.length - 1].abs.push(pt);
  5850. break;
  5851. case 'close':
  5852. moves.push({ close: true });
  5853. break;
  5854. }
  5855. }
  5856. for (var i = 0; i < moves.length; i++) {
  5857. var style;
  5858. if (i == moves.length - 1) {
  5859. style = 'f';
  5860. if (fillRule === 'evenodd') {
  5861. style += '*';
  5862. }
  5863. } else {
  5864. style = null;
  5865. }
  5866. if (moves[i].close) {
  5867. this.pdf.internal.out('h');
  5868. this.pdf.internal.out('f');
  5869. } else if (moves[i].arc) {
  5870. if (moves[i].start) {
  5871. this.internal.move2(this, moves[i].start.x, moves[i].start.y);
  5872. }
  5873. var arcs = moves[i].abs;
  5874. for (var ii = 0; ii < arcs.length; ii++) {
  5875. var arc = arcs[ii];
  5876. //TODO lines deltas were getting in here
  5877. if (typeof arc.startAngle !== 'undefined') {
  5878. var start = arc.startAngle * 360 / (2 * Math.PI);
  5879. var end = arc.endAngle * 360 / (2 * Math.PI);
  5880. var x = arc.x;
  5881. var y = arc.y;
  5882. if (ii === 0) {
  5883. this.internal.move2(this, x, y);
  5884. }
  5885. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
  5886. if (ii === arcs.length - 1) {
  5887. // The original arc move did not occur because of the algorithm
  5888. if (moves[i].start) {
  5889. var x = moves[i].start.x;
  5890. var y = moves[i].start.y;
  5891. this.internal.line2(c2d, x, y);
  5892. }
  5893. }
  5894. } else {
  5895. this.internal.line2(c2d, arc.x, arc.y);
  5896. }
  5897. }
  5898. } else {
  5899. var x = moves[i].start.x;
  5900. var y = moves[i].start.y;
  5901. if (!isClip) {
  5902. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5903. } else {
  5904. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5905. this.pdf.clip_fixed();
  5906. }
  5907. }
  5908. }
  5909. window.outIntercept = outInterceptOld;
  5910. // if (this.ctx._clip_path.length > 0) {
  5911. // lines.push('Q');
  5912. // }
  5913. },
  5914. pushMask: function pushMask() {
  5915. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5916. if (!v2Support) {
  5917. console.log('jsPDF v2 not enabled');
  5918. return;
  5919. }
  5920. // define a mask stream
  5921. var obj = this.pdf.internal.newStreamObject();
  5922. // define a mask state
  5923. var obj2 = this.pdf.internal.newObject2();
  5924. obj2.push('<</Type /ExtGState');
  5925. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5926. obj2.push('>>');
  5927. // add mask to page resources
  5928. var gsName = 'MASK' + obj2.objId;
  5929. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5930. var instruction = '/' + gsName + ' gs';
  5931. this.pdf.internal.out(instruction);
  5932. },
  5933. clip: function clip() {
  5934. //TODO do we reset the path, or just copy it?
  5935. if (this.ctx._clip_path.length > 0) {
  5936. for (var i = 0; i < this.path.length; i++) {
  5937. this.ctx._clip_path.push(this.path[i]);
  5938. }
  5939. } else {
  5940. this.ctx._clip_path = this.path;
  5941. }
  5942. this.path = [];
  5943. },
  5944. measureText: function measureText(text) {
  5945. var pdf = this.pdf;
  5946. return {
  5947. getWidth: function getWidth() {
  5948. var fontSize = pdf.internal.getFontSize();
  5949. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  5950. // Convert points to pixels
  5951. txtWidth *= 1.3333;
  5952. return txtWidth;
  5953. },
  5954. get width() {
  5955. return this.getWidth(text);
  5956. }
  5957. };
  5958. },
  5959. _getBaseline: function _getBaseline(y) {
  5960. var height = parseInt(this.pdf.internal.getFontSize());
  5961. // TODO Get descent from font descriptor
  5962. var descent = height * .25;
  5963. switch (this.ctx.textBaseline) {
  5964. case 'bottom':
  5965. return y - descent;
  5966. case 'top':
  5967. return y + height;
  5968. case 'hanging':
  5969. return y + height - descent;
  5970. case 'middle':
  5971. return y + height / 2 - descent;
  5972. case 'ideographic':
  5973. // TODO not implemented
  5974. return y;
  5975. case 'alphabetic':
  5976. default:
  5977. return y;
  5978. }
  5979. }
  5980. };
  5981. var c2d = jsPDFAPI.context2d;
  5982. // accessor methods
  5983. Object.defineProperty(c2d, 'fillStyle', {
  5984. set: function set(value) {
  5985. this.setFillStyle(value);
  5986. },
  5987. get: function get() {
  5988. return this.ctx.fillStyle;
  5989. }
  5990. });
  5991. Object.defineProperty(c2d, 'strokeStyle', {
  5992. set: function set(value) {
  5993. this.setStrokeStyle(value);
  5994. },
  5995. get: function get() {
  5996. return this.ctx.strokeStyle;
  5997. }
  5998. });
  5999. Object.defineProperty(c2d, 'lineWidth', {
  6000. set: function set(value) {
  6001. this.setLineWidth(value);
  6002. },
  6003. get: function get() {
  6004. return this.ctx.lineWidth;
  6005. }
  6006. });
  6007. Object.defineProperty(c2d, 'lineCap', {
  6008. set: function set(val) {
  6009. this.setLineCap(val);
  6010. },
  6011. get: function get() {
  6012. return this.ctx.lineCap;
  6013. }
  6014. });
  6015. Object.defineProperty(c2d, 'lineJoin', {
  6016. set: function set(val) {
  6017. this.setLineJoin(val);
  6018. },
  6019. get: function get() {
  6020. return this.ctx.lineJoin;
  6021. }
  6022. });
  6023. Object.defineProperty(c2d, 'miterLimit', {
  6024. set: function set(val) {
  6025. this.ctx.miterLimit = val;
  6026. },
  6027. get: function get() {
  6028. return this.ctx.miterLimit;
  6029. }
  6030. });
  6031. Object.defineProperty(c2d, 'textBaseline', {
  6032. set: function set(value) {
  6033. this.setTextBaseline(value);
  6034. },
  6035. get: function get() {
  6036. return this.getTextBaseline();
  6037. }
  6038. });
  6039. Object.defineProperty(c2d, 'textAlign', {
  6040. set: function set(value) {
  6041. this.setTextAlign(value);
  6042. },
  6043. get: function get() {
  6044. return this.getTextAlign();
  6045. }
  6046. });
  6047. Object.defineProperty(c2d, 'font', {
  6048. set: function set(value) {
  6049. this.setFont(value);
  6050. },
  6051. get: function get() {
  6052. return this.ctx.font;
  6053. }
  6054. });
  6055. Object.defineProperty(c2d, 'globalCompositeOperation', {
  6056. set: function set(value) {
  6057. this.ctx.globalCompositeOperation = value;
  6058. },
  6059. get: function get() {
  6060. return this.ctx.globalCompositeOperation;
  6061. }
  6062. });
  6063. Object.defineProperty(c2d, 'globalAlpha', {
  6064. set: function set(value) {
  6065. this.ctx.globalAlpha = value;
  6066. },
  6067. get: function get() {
  6068. return this.ctx.globalAlpha;
  6069. }
  6070. });
  6071. // Not HTML API
  6072. Object.defineProperty(c2d, 'ignoreClearRect', {
  6073. set: function set(value) {
  6074. this.ctx.ignoreClearRect = value;
  6075. },
  6076. get: function get() {
  6077. return this.ctx.ignoreClearRect;
  6078. }
  6079. });
  6080. // End Not HTML API
  6081. c2d.internal = {};
  6082. c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  6083. c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  6084. c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  6085. // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
  6086. c2d.internal.arc = function(c2d, xc, yc, r, a1, a2, anticlockwise, style) {
  6087. var includeMove = true;
  6088. var k = this.pdf.internal.scaleFactor;
  6089. var pageHeight = this.pdf.internal.pageSize.height;
  6090. var f2 = this.pdf.internal.f2;
  6091. var a1r = a1 * (Math.PI / 180);
  6092. var a2r = a2 * (Math.PI / 180);
  6093. var curves = this.createArc(r, a1r, a2r, anticlockwise);
  6094. for (var i = 0; i < curves.length; i++) {
  6095. var curve = curves[i];
  6096. if (includeMove && i === 0) {
  6097. 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(' '));
  6098. } else {
  6099. 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(' '));
  6100. }
  6101. //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
  6102. c2d._lastPoint = { x: xc, y: yc };
  6103. // 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'
  6104. }
  6105. if (style !== null) {
  6106. this.pdf.internal.out(this.pdf.internal.getStyle(style));
  6107. }
  6108. };
  6109. /**
  6110. *
  6111. * @param x Edge point X
  6112. * @param y Edge point Y
  6113. * @param r Radius
  6114. * @param a1 start angle
  6115. * @param a2 end angle
  6116. * @param anticlockwise
  6117. * @param style
  6118. * @param isClip
  6119. */
  6120. c2d.internal.arc2 = function(c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
  6121. // we need to convert from cartesian to polar here methinks.
  6122. var centerX = x; // + r;
  6123. var centerY = y;
  6124. if (!isClip) {
  6125. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
  6126. } else {
  6127. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
  6128. this.pdf.clip_fixed();
  6129. }
  6130. };
  6131. c2d.internal.move2 = function(c2d, x, y) {
  6132. var k = this.pdf.internal.scaleFactor;
  6133. var pageHeight = this.pdf.internal.pageSize.height;
  6134. var f2 = this.pdf.internal.f2;
  6135. this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
  6136. c2d._lastPoint = { x: x, y: y };
  6137. };
  6138. c2d.internal.line2 = function(c2d, dx, dy) {
  6139. var k = this.pdf.internal.scaleFactor;
  6140. var pageHeight = this.pdf.internal.pageSize.height;
  6141. var f2 = this.pdf.internal.f2;
  6142. //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
  6143. var pt = { x: dx, y: dy };
  6144. this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
  6145. //this.pdf.internal.out('f');
  6146. c2d._lastPoint = pt;
  6147. };
  6148. /**
  6149. * 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.
  6150. *
  6151. * 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.
  6152. */
  6153. c2d.internal.createArc = function(radius, startAngle, endAngle, anticlockwise) {
  6154. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
  6155. var twoPI = Math.PI * 2;
  6156. var piOverTwo = Math.PI / 2.0;
  6157. // normalize startAngle, endAngle to [0, 2PI]
  6158. var startAngleN = startAngle;
  6159. if (startAngleN < twoPI || startAngleN > twoPI) {
  6160. startAngleN = startAngleN % twoPI;
  6161. }
  6162. if (startAngleN < 0) {
  6163. startAngleN = twoPI + startAngleN;
  6164. }
  6165. while (startAngle > endAngle) {
  6166. startAngle = startAngle - twoPI;
  6167. }
  6168. var totalAngle = Math.abs(endAngle - startAngle);
  6169. if (totalAngle < twoPI) {
  6170. if (anticlockwise) {
  6171. totalAngle = twoPI - totalAngle;
  6172. }
  6173. }
  6174. // Compute the sequence of arc curves, up to PI/2 at a time.
  6175. var curves = [];
  6176. var sgn = anticlockwise ? -1 : +1;
  6177. var a1 = startAngleN;
  6178. for (; totalAngle > EPSILON;) {
  6179. var remain = sgn * Math.min(totalAngle, piOverTwo);
  6180. var a2 = a1 + remain;
  6181. curves.push(this.createSmallArc(radius, a1, a2));
  6182. totalAngle -= Math.abs(a2 - a1);
  6183. a1 = a2;
  6184. }
  6185. return curves;
  6186. };
  6187. c2d.internal.getCurrentPage = function() {
  6188. return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
  6189. };
  6190. /**
  6191. * 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.
  6192. *
  6193. * 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.
  6194. *
  6195. * 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.
  6196. */
  6197. c2d.internal.createSmallArc = function(r, a1, a2) {
  6198. // Compute all four points for an arc that subtends the same total angle
  6199. // but is centered on the X-axis
  6200. var a = (a2 - a1) / 2.0;
  6201. var x4 = r * Math.cos(a);
  6202. var y4 = r * Math.sin(a);
  6203. var x1 = x4;
  6204. var y1 = -y4;
  6205. var q1 = x1 * x1 + y1 * y1;
  6206. var q2 = q1 + x1 * x4 + y1 * y4;
  6207. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  6208. var x2 = x1 - k2 * y1;
  6209. var y2 = y1 + k2 * x1;
  6210. var x3 = x2;
  6211. var y3 = -y2;
  6212. // Find the arc points' actual locations by computing x1,y1 and x4,y4
  6213. // and rotating the control points by a + a1
  6214. var ar = a + a1;
  6215. var cos_ar = Math.cos(ar);
  6216. var sin_ar = Math.sin(ar);
  6217. return {
  6218. x1: r * Math.cos(a1),
  6219. y1: r * Math.sin(a1),
  6220. x2: x2 * cos_ar - y2 * sin_ar,
  6221. y2: x2 * sin_ar + y2 * cos_ar,
  6222. x3: x3 * cos_ar - y3 * sin_ar,
  6223. y3: x3 * sin_ar + y3 * cos_ar,
  6224. x4: r * Math.cos(a2),
  6225. y4: r * Math.sin(a2)
  6226. };
  6227. };
  6228. function context() {
  6229. this._isStrokeTransparent = false;
  6230. this._strokeOpacity = 1;
  6231. this.strokeStyle = '#000000';
  6232. this.fillStyle = '#000000';
  6233. this._isFillTransparent = false;
  6234. this._fillOpacity = 1;
  6235. this.font = "12pt times";
  6236. this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
  6237. this.textAlign = 'start';
  6238. this.lineWidth = 1;
  6239. this.lineJoin = 'miter'; // round, bevel, miter
  6240. this.lineCap = 'butt'; // butt, round, square
  6241. this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
  6242. this.globalCompositeOperation = 'normal';
  6243. this.globalAlpha = 1.0;
  6244. this._clip_path = [];
  6245. // TODO miter limit //default 10
  6246. // Not HTML API
  6247. this.ignoreClearRect = false;
  6248. this.copy = function(ctx) {
  6249. this._isStrokeTransparent = ctx._isStrokeTransparent;
  6250. this._strokeOpacity = ctx._strokeOpacity;
  6251. this.strokeStyle = ctx.strokeStyle;
  6252. this._isFillTransparent = ctx._isFillTransparent;
  6253. this._fillOpacity = ctx._fillOpacity;
  6254. this.fillStyle = ctx.fillStyle;
  6255. this.font = ctx.font;
  6256. this.lineWidth = ctx.lineWidth;
  6257. this.lineJoin = ctx.lineJoin;
  6258. this.lineCap = ctx.lineCap;
  6259. this.textBaseline = ctx.textBaseline;
  6260. this.textAlign = ctx.textAlign;
  6261. this._fontSize = ctx._fontSize;
  6262. this._transform = ctx._transform.slice(0);
  6263. this.globalCompositeOperation = ctx.globalCompositeOperation;
  6264. this.globalAlpha = ctx.globalAlpha;
  6265. this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
  6266. // Not HTML API
  6267. this.ignoreClearRect = ctx.ignoreClearRect;
  6268. };
  6269. }
  6270. return this;
  6271. })(jsPDF.API);
  6272. /** @preserve
  6273. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  6274. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  6275. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  6276. * 2014 Diego Casorran, https://github.com/diegocr
  6277. * 2014 Daniel Husar, https://github.com/danielhusar
  6278. * 2014 Wolfgang Gassler, https://github.com/woolfg
  6279. * 2014 Steven Spungin, https://github.com/flamenco
  6280. *
  6281. *
  6282. * ====================================================================
  6283. */
  6284. (function(jsPDFAPI) {
  6285. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  6286. clone = function() {
  6287. return function(obj) {
  6288. Clone.prototype = obj;
  6289. return new Clone();
  6290. };
  6291. function Clone() {}
  6292. }();
  6293. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  6294. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  6295. i = 0;
  6296. l = array.length;
  6297. fragment = void 0;
  6298. lTrimmed = false;
  6299. rTrimmed = false;
  6300. while (!lTrimmed && i !== l) {
  6301. fragment = array[i] = array[i].trimLeft();
  6302. if (fragment) {
  6303. lTrimmed = true;
  6304. }
  6305. i++;
  6306. }
  6307. i = l - 1;
  6308. while (l && !rTrimmed && i !== -1) {
  6309. fragment = array[i] = array[i].trimRight();
  6310. if (fragment) {
  6311. rTrimmed = true;
  6312. }
  6313. i--;
  6314. }
  6315. r = /\s+$/g;
  6316. trailingSpace = true;
  6317. i = 0;
  6318. while (i !== l) {
  6319. // Leave the line breaks intact
  6320. if (array[i] != "\u2028") {
  6321. fragment = array[i].replace(/\s+/g, " ");
  6322. if (trailingSpace) {
  6323. fragment = fragment.trimLeft();
  6324. }
  6325. if (fragment) {
  6326. trailingSpace = r.test(fragment);
  6327. }
  6328. array[i] = fragment;
  6329. }
  6330. i++;
  6331. }
  6332. return array;
  6333. };
  6334. Renderer = function Renderer(pdf, x, y, settings) {
  6335. this.pdf = pdf;
  6336. this.x = x;
  6337. this.y = y;
  6338. this.settings = settings;
  6339. //list of functions which are called after each element-rendering process
  6340. this.watchFunctions = [];
  6341. this.init();
  6342. return this;
  6343. };
  6344. ResolveFont = function ResolveFont(css_font_family_string) {
  6345. var name, part, parts;
  6346. name = void 0;
  6347. parts = css_font_family_string.split(",");
  6348. part = parts.shift();
  6349. while (!name && part) {
  6350. name = FontNameDB[part.trim().toLowerCase()];
  6351. part = parts.shift();
  6352. }
  6353. return name;
  6354. };
  6355. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  6356. //IE8 issues
  6357. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  6358. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  6359. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  6360. }
  6361. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  6362. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  6363. }
  6364. var normal, undef, value;
  6365. undef = void 0;
  6366. normal = 16.00;
  6367. value = UnitedNumberMap[css_line_height_string];
  6368. if (value) {
  6369. return value;
  6370. }
  6371. value = {
  6372. "xx-small": 9,
  6373. "x-small": 11,
  6374. small: 13,
  6375. medium: 16,
  6376. large: 19,
  6377. "x-large": 23,
  6378. "xx-large": 28,
  6379. auto: 0
  6380. }[{ css_line_height_string: css_line_height_string }];
  6381. if (value !== undef) {
  6382. return UnitedNumberMap[css_line_height_string] = value / normal;
  6383. }
  6384. if (value = parseFloat(css_line_height_string)) {
  6385. return UnitedNumberMap[css_line_height_string] = value / normal;
  6386. }
  6387. value = css_line_height_string.match(/([\d\.]+)(px)/);
  6388. if (value.length === 3) {
  6389. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  6390. }
  6391. return UnitedNumberMap[css_line_height_string] = 1;
  6392. };
  6393. GetCSS = function GetCSS(element) {
  6394. var css, tmp, computedCSSElement;
  6395. computedCSSElement = function(el) {
  6396. var compCSS;
  6397. compCSS = function(el) {
  6398. if (document.defaultView && document.defaultView.getComputedStyle) {
  6399. return document.defaultView.getComputedStyle(el, null);
  6400. } else if (el.currentStyle) {
  6401. return el.currentStyle;
  6402. } else {
  6403. return el.style;
  6404. }
  6405. }(el);
  6406. return function(prop) {
  6407. prop = prop.replace(/-\D/g, function(match) {
  6408. return match.charAt(1).toUpperCase();
  6409. });
  6410. return compCSS[prop];
  6411. };
  6412. }(element);
  6413. css = {};
  6414. tmp = void 0;
  6415. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  6416. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  6417. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  6418. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  6419. if (tmp === "bold") {
  6420. if (css["font-style"] === "normal") {
  6421. css["font-style"] = tmp;
  6422. } else {
  6423. css["font-style"] = tmp + css["font-style"];
  6424. }
  6425. }
  6426. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  6427. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  6428. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  6429. tmp = css["display"] === "block";
  6430. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  6431. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  6432. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  6433. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  6434. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  6435. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  6436. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  6437. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  6438. css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
  6439. //float and clearing of floats
  6440. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  6441. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  6442. css["color"] = computedCSSElement("color");
  6443. return css;
  6444. };
  6445. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  6446. var handlers, i, isHandledElsewhere, l, classNames;
  6447. isHandledElsewhere = false;
  6448. i = void 0;
  6449. l = void 0;
  6450. handlers = elementHandlers["#" + element.id];
  6451. if (handlers) {
  6452. if (typeof handlers === "function") {
  6453. isHandledElsewhere = handlers(element, renderer);
  6454. } else {
  6455. i = 0;
  6456. l = handlers.length;
  6457. while (!isHandledElsewhere && i !== l) {
  6458. isHandledElsewhere = handlers[i](element, renderer);
  6459. i++;
  6460. }
  6461. }
  6462. }
  6463. handlers = elementHandlers[element.nodeName];
  6464. if (!isHandledElsewhere && handlers) {
  6465. if (typeof handlers === "function") {
  6466. isHandledElsewhere = handlers(element, renderer);
  6467. } else {
  6468. i = 0;
  6469. l = handlers.length;
  6470. while (!isHandledElsewhere && i !== l) {
  6471. isHandledElsewhere = handlers[i](element, renderer);
  6472. i++;
  6473. }
  6474. }
  6475. }
  6476. // Try class names
  6477. classNames = element.className ? element.className.split(' ') : [];
  6478. for (i = 0; i < classNames.length; i++) {
  6479. handlers = elementHandlers['.' + classNames[i]];
  6480. if (!isHandledElsewhere && handlers) {
  6481. if (typeof handlers === "function") {
  6482. isHandledElsewhere = handlers(element, renderer);
  6483. } else {
  6484. i = 0;
  6485. l = handlers.length;
  6486. while (!isHandledElsewhere && i !== l) {
  6487. isHandledElsewhere = handlers[i](element, renderer);
  6488. i++;
  6489. }
  6490. }
  6491. }
  6492. }
  6493. return isHandledElsewhere;
  6494. };
  6495. tableToJson = function tableToJson(table, renderer) {
  6496. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  6497. data = [];
  6498. headers = [];
  6499. i = 0;
  6500. l = table.rows[0].cells.length;
  6501. table_with = table.clientWidth;
  6502. while (i < l) {
  6503. cell = table.rows[0].cells[i];
  6504. headers[i] = {
  6505. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  6506. prompt: cell.textContent.replace(/\r?\n/g, ''),
  6507. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
  6508. };
  6509. i++;
  6510. }
  6511. i = 1;
  6512. while (i < table.rows.length) {
  6513. tableRow = table.rows[i];
  6514. rowData = {};
  6515. j = 0;
  6516. while (j < tableRow.cells.length) {
  6517. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  6518. j++;
  6519. }
  6520. data.push(rowData);
  6521. i++;
  6522. }
  6523. return table_obj = {
  6524. rows: data,
  6525. headers: headers
  6526. };
  6527. };
  6528. var SkipNode = {
  6529. SCRIPT: 1,
  6530. STYLE: 1,
  6531. NOSCRIPT: 1,
  6532. OBJECT: 1,
  6533. EMBED: 1,
  6534. SELECT: 1
  6535. };
  6536. var listCount = 1;
  6537. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  6538. var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
  6539. cns = element.childNodes;
  6540. cn = void 0;
  6541. fragmentCSS = GetCSS(element);
  6542. isBlock = fragmentCSS.display === "block";
  6543. if (isBlock) {
  6544. renderer.setBlockBoundary();
  6545. renderer.setBlockStyle(fragmentCSS);
  6546. }
  6547. i = 0;
  6548. l = cns.length;
  6549. while (i < l) {
  6550. cn = cns[i];
  6551. if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
  6552. //execute all watcher functions to e.g. reset floating
  6553. renderer.executeWatchFunctions(cn);
  6554. /*** HEADER rendering **/
  6555. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  6556. var header = cn;
  6557. //store old top margin
  6558. var oldMarginTop = renderer.pdf.margins_doc.top;
  6559. //subscribe for new page event and render header first on every page
  6560. renderer.pdf.internal.events.subscribe('addPage', function(pageInfo) {
  6561. //set current y position to old margin
  6562. renderer.y = oldMarginTop;
  6563. //render all child nodes of the header element
  6564. _DrillForContent(header, renderer, elementHandlers);
  6565. //set margin to old margin + rendered header + 10 space to prevent overlapping
  6566. //important for other plugins (e.g. table) to start rendering at correct position after header
  6567. renderer.pdf.margins_doc.top = renderer.y + 10;
  6568. renderer.y += 10;
  6569. }, false);
  6570. }
  6571. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  6572. if (~cn.textContent.indexOf("ADD_PAGE")) {
  6573. renderer.pdf.addPage();
  6574. renderer.y = renderer.pdf.margins_doc.top;
  6575. }
  6576. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  6577. /*** IMAGE RENDERING ***/
  6578. var cached_image;
  6579. if (cn.nodeName === "IMG") {
  6580. var url = cn.getAttribute("src");
  6581. cached_image = images[renderer.pdf.sHashCode(url) || url];
  6582. }
  6583. if (cached_image) {
  6584. if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  6585. renderer.pdf.addPage();
  6586. renderer.y = renderer.pdf.margins_doc.top;
  6587. //check if we have to set back some values due to e.g. header rendering for new page
  6588. renderer.executeWatchFunctions(cn);
  6589. }
  6590. var imagesCSS = GetCSS(cn);
  6591. var imageX = renderer.x;
  6592. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
  6593. //define additional paddings, margins which have to be taken into account for margin calculations
  6594. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  6595. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  6596. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  6597. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
  6598. //if float is set to right, move the image to the right border
  6599. //add space if margin is set
  6600. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  6601. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  6602. } else {
  6603. imageX += additionalSpaceLeft;
  6604. }
  6605. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  6606. cached_image = undefined;
  6607. //if the float prop is specified we have to float the text around the image
  6608. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  6609. //add functiont to set back coordinates after image rendering
  6610. renderer.watchFunctions.push(function(diffX, thresholdY, diffWidth, el) {
  6611. //undo drawing box adaptions which were set by floating
  6612. if (renderer.y >= thresholdY) {
  6613. renderer.x += diffX;
  6614. renderer.settings.width += diffWidth;
  6615. return true;
  6616. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  6617. renderer.x += diffX;
  6618. renderer.y = thresholdY;
  6619. renderer.settings.width += diffWidth;
  6620. return true;
  6621. } else {
  6622. return false;
  6623. }
  6624. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
  6625. //reset floating by clear:both divs
  6626. //just set cursorY after the floating element
  6627. renderer.watchFunctions.push(function(yPositionAfterFloating, pages, el) {
  6628. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  6629. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  6630. renderer.y = yPositionAfterFloating;
  6631. return true;
  6632. } else {
  6633. return false;
  6634. }
  6635. } else {
  6636. return true;
  6637. }
  6638. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
  6639. //if floating is set we decrease the available width by the image width
  6640. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
  6641. //if left just add the image width to the X coordinate
  6642. if (imagesCSS['float'] === 'left') {
  6643. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  6644. }
  6645. } else {
  6646. //if no floating is set, move the rendering cursor after the image height
  6647. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  6648. }
  6649. /*** TABLE RENDERING ***/
  6650. } else if (cn.nodeName === "TABLE") {
  6651. table2json = tableToJson(cn, renderer);
  6652. renderer.y += 10;
  6653. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  6654. autoSize: false,
  6655. printHeaders: elementHandlers.printHeaders,
  6656. margins: renderer.pdf.margins_doc,
  6657. css: GetCSS(cn)
  6658. });
  6659. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  6660. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  6661. listCount = 1;
  6662. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6663. _DrillForContent(cn, renderer, elementHandlers);
  6664. }
  6665. renderer.y += 10;
  6666. } else if (cn.nodeName === "LI") {
  6667. var temp = renderer.x;
  6668. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  6669. renderer.y += 3;
  6670. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6671. _DrillForContent(cn, renderer, elementHandlers);
  6672. }
  6673. renderer.x = temp;
  6674. } else if (cn.nodeName === "BR") {
  6675. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  6676. renderer.addText("\u2028", clone(fragmentCSS));
  6677. } else {
  6678. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6679. _DrillForContent(cn, renderer, elementHandlers);
  6680. }
  6681. }
  6682. } else if (cn.nodeType === 3) {
  6683. var value = cn.nodeValue;
  6684. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  6685. if (cn.parentNode.parentNode.nodeName === "OL") {
  6686. value = listCount++ + '. ' + value;
  6687. } else {
  6688. var fontSize = fragmentCSS["font-size"];
  6689. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  6690. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  6691. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  6692. cb = function cb(x, y) {
  6693. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  6694. };
  6695. }
  6696. }
  6697. // Only add the text if the text node is in the body element
  6698. // Add compatibility with IE11
  6699. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  6700. renderer.addText(value, fragmentCSS);
  6701. }
  6702. } else if (typeof cn === "string") {
  6703. renderer.addText(cn, fragmentCSS);
  6704. }
  6705. }
  6706. i++;
  6707. }
  6708. elementHandlers.outY = renderer.y;
  6709. if (isBlock) {
  6710. return renderer.setBlockBoundary(cb);
  6711. }
  6712. };
  6713. images = {};
  6714. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  6715. var imgs = element.getElementsByTagName('img'),
  6716. l = imgs.length,
  6717. found_images,
  6718. x = 0;
  6719. function done() {
  6720. renderer.pdf.internal.events.publish('imagesLoaded');
  6721. cb(found_images);
  6722. }
  6723. function loadImage(url, width, height) {
  6724. if (!url) return;
  6725. var img = new Image();
  6726. found_images = ++x;
  6727. img.crossOrigin = '';
  6728. img.onerror = img.onload = function() {
  6729. if (img.complete) {
  6730. //to support data urls in images, set width and height
  6731. //as those values are not recognized automatically
  6732. if (img.src.indexOf('data:image/') === 0) {
  6733. img.width = width || img.width || 0;
  6734. img.height = height || img.height || 0;
  6735. }
  6736. //if valid image add to known images array
  6737. if (img.width + img.height) {
  6738. var hash = renderer.pdf.sHashCode(url) || url;
  6739. images[hash] = images[hash] || img;
  6740. }
  6741. }
  6742. if (!--x) {
  6743. done();
  6744. }
  6745. };
  6746. img.src = url;
  6747. }
  6748. while (l--) {
  6749. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  6750. }
  6751. return x || done();
  6752. };
  6753. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  6754. //check if we can found a <footer> element
  6755. var footer = elem.getElementsByTagName("footer");
  6756. if (footer.length > 0) {
  6757. footer = footer[0];
  6758. //bad hack to get height of footer
  6759. //creat dummy out and check new y after fake rendering
  6760. var oldOut = renderer.pdf.internal.write;
  6761. var oldY = renderer.y;
  6762. renderer.pdf.internal.write = function() {};
  6763. _DrillForContent(footer, renderer, elementHandlers);
  6764. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  6765. renderer.y = oldY;
  6766. renderer.pdf.internal.write = oldOut;
  6767. //add 20% to prevent overlapping
  6768. renderer.pdf.margins_doc.bottom += footerHeight;
  6769. //Create function render header on every page
  6770. var renderFooter = function renderFooter(pageInfo) {
  6771. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
  6772. //set current y position to old margin
  6773. var oldPosition = renderer.y;
  6774. //render all child nodes of the header element
  6775. renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
  6776. renderer.pdf.margins_doc.bottom -= footerHeight;
  6777. //check if we have to add page numbers
  6778. var spans = footer.getElementsByTagName('span');
  6779. for (var i = 0; i < spans.length; ++i) {
  6780. //if we find some span element with class pageCounter, set the page
  6781. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  6782. spans[i].innerHTML = pageNumber;
  6783. }
  6784. //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  6785. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6786. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  6787. }
  6788. }
  6789. //render footer content
  6790. _DrillForContent(footer, renderer, elementHandlers);
  6791. //set bottom margin to previous height including the footer height
  6792. renderer.pdf.margins_doc.bottom += footerHeight;
  6793. //important for other plugins (e.g. table) to start rendering at correct position after header
  6794. renderer.y = oldPosition;
  6795. };
  6796. //check if footer contains totalPages which should be replace at the disoposal of the document
  6797. var spans = footer.getElementsByTagName('span');
  6798. for (var i = 0; i < spans.length; ++i) {
  6799. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6800. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  6801. }
  6802. }
  6803. //register event to render footer on every new page
  6804. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
  6805. //render footer on first page
  6806. renderFooter();
  6807. //prevent footer rendering
  6808. SkipNode['FOOTER'] = 1;
  6809. }
  6810. };
  6811. process = function process(pdf, element, x, y, settings, callback) {
  6812. if (!element) return false;
  6813. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  6814. if (typeof element === "string") {
  6815. element = function(element) {
  6816. var $frame, $hiddendiv, framename, visuallyhidden;
  6817. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  6818. 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;";
  6819. $hiddendiv = document.createElement('div');
  6820. $hiddendiv.style.cssText = visuallyhidden;
  6821. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  6822. document.body.appendChild($hiddendiv);
  6823. $frame = window.frames[framename];
  6824. $frame.document.open();
  6825. $frame.document.writeln(element);
  6826. $frame.document.close();
  6827. return $frame.document.body;
  6828. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  6829. }
  6830. var r = new Renderer(pdf, x, y, settings),
  6831. out;
  6832. // 1. load images
  6833. // 2. prepare optional footer elements
  6834. // 3. render content
  6835. loadImgs.call(this, element, r, settings.elementHandlers, function(found_images) {
  6836. checkForFooter(element, r, settings.elementHandlers);
  6837. _DrillForContent(element, r, settings.elementHandlers);
  6838. //send event dispose for final taks (e.g. footer totalpage replacement)
  6839. r.pdf.internal.events.publish('htmlRenderingFinished');
  6840. out = r.dispose();
  6841. if (typeof callback === 'function') callback(out);
  6842. else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  6843. });
  6844. return out || { x: r.x, y: r.y };
  6845. };
  6846. Renderer.prototype.init = function() {
  6847. this.paragraph = {
  6848. text: [],
  6849. style: []
  6850. };
  6851. return this.pdf.internal.write("q");
  6852. };
  6853. Renderer.prototype.dispose = function() {
  6854. this.pdf.internal.write("Q");
  6855. return {
  6856. x: this.x,
  6857. y: this.y,
  6858. ready: true
  6859. };
  6860. };
  6861. //Checks if we have to execute some watcher functions
  6862. //e.g. to end text floating around an image
  6863. Renderer.prototype.executeWatchFunctions = function(el) {
  6864. var ret = false;
  6865. var narray = [];
  6866. if (this.watchFunctions.length > 0) {
  6867. for (var i = 0; i < this.watchFunctions.length; ++i) {
  6868. if (this.watchFunctions[i](el) === true) {
  6869. ret = true;
  6870. } else {
  6871. narray.push(this.watchFunctions[i]);
  6872. }
  6873. }
  6874. this.watchFunctions = narray;
  6875. }
  6876. return ret;
  6877. };
  6878. Renderer.prototype.splitFragmentsIntoLines = function(fragments, styles) {
  6879. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  6880. defaultFontSize = 12;
  6881. k = this.pdf.internal.scaleFactor;
  6882. fontMetricsCache = {};
  6883. ff = void 0;
  6884. fs = void 0;
  6885. fontMetrics = void 0;
  6886. fragment = void 0;
  6887. style = void 0;
  6888. fragmentSpecificMetrics = void 0;
  6889. fragmentLength = void 0;
  6890. fragmentChopped = void 0;
  6891. line = [];
  6892. lines = [line];
  6893. currentLineLength = 0;
  6894. maxLineLength = this.settings.width;
  6895. while (fragments.length) {
  6896. fragment = fragments.shift();
  6897. style = styles.shift();
  6898. if (fragment) {
  6899. ff = style["font-family"];
  6900. fs = style["font-style"];
  6901. fontMetrics = fontMetricsCache[ff + fs];
  6902. if (!fontMetrics) {
  6903. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  6904. fontMetricsCache[ff + fs] = fontMetrics;
  6905. }
  6906. fragmentSpecificMetrics = {
  6907. widths: fontMetrics.widths,
  6908. kerning: fontMetrics.kerning,
  6909. fontSize: style["font-size"] * defaultFontSize,
  6910. textIndent: currentLineLength
  6911. };
  6912. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6913. if (fragment == "\u2028") {
  6914. line = [];
  6915. lines.push(line);
  6916. } else if (currentLineLength + fragmentLength > maxLineLength) {
  6917. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  6918. line.push([fragmentChopped.shift(), style]);
  6919. while (fragmentChopped.length) {
  6920. line = [
  6921. [fragmentChopped.shift(), style]
  6922. ];
  6923. lines.push(line);
  6924. }
  6925. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6926. } else {
  6927. line.push([fragment, style]);
  6928. currentLineLength += fragmentLength;
  6929. }
  6930. }
  6931. }
  6932. //if text alignment was set, set margin/indent of each line
  6933. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  6934. for (var i = 0; i < lines.length; ++i) {
  6935. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6936. //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  6937. if (i > 0) {
  6938. lines[i][0][1] = clone(lines[i][0][1]);
  6939. }
  6940. var space = maxLineLength - length;
  6941. if (style['text-align'] === 'right') {
  6942. lines[i][0][1]['margin-left'] = space;
  6943. //if alignment is not right, it has to be center so split the space to the left and the right
  6944. } else if (style['text-align'] === 'center') {
  6945. lines[i][0][1]['margin-left'] = space / 2;
  6946. //if justify was set, calculate the word spacing and define in by using the css property
  6947. } else if (style['text-align'] === 'justify') {
  6948. var countSpaces = lines[i][0][0].split(' ').length - 1;
  6949. lines[i][0][1]['word-spacing'] = space / countSpaces;
  6950. //ignore the last line in justify mode
  6951. if (i === lines.length - 1) {
  6952. lines[i][0][1]['word-spacing'] = 0;
  6953. }
  6954. }
  6955. }
  6956. }
  6957. return lines;
  6958. };
  6959. Renderer.prototype.RenderTextFragment = function(text, style) {
  6960. var defaultFontSize, font, maxLineHeight;
  6961. maxLineHeight = 0;
  6962. defaultFontSize = 12;
  6963. if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  6964. this.pdf.internal.write("ET", "Q");
  6965. this.pdf.addPage();
  6966. this.y = this.pdf.margins_doc.top;
  6967. this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
  6968. //move cursor by one line on new page
  6969. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  6970. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  6971. }
  6972. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  6973. // text color
  6974. var pdfTextColor = this.getPdfColor(style["color"]);
  6975. if (pdfTextColor !== this.lastTextColor) {
  6976. this.pdf.internal.write(pdfTextColor);
  6977. this.lastTextColor = pdfTextColor;
  6978. }
  6979. //set the word spacing for e.g. justify style
  6980. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  6981. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  6982. }
  6983. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  6984. //set the word spacing back to neutral => 0
  6985. if (style['word-spacing'] !== undefined) {
  6986. this.pdf.internal.write(0, "Tw");
  6987. }
  6988. };
  6989. // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  6990. Renderer.prototype.getPdfColor = function(style) {
  6991. var textColor;
  6992. var r, g, b;
  6993. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  6994. var m = rx.exec(style);
  6995. if (m != null) {
  6996. r = parseInt(m[1]);
  6997. g = parseInt(m[2]);
  6998. b = parseInt(m[3]);
  6999. } else {
  7000. if (style.charAt(0) != '#') {
  7001. style = CssColors.colorNameToHex(style);
  7002. if (!style) {
  7003. style = '#000000';
  7004. }
  7005. }
  7006. r = style.substring(1, 3);
  7007. r = parseInt(r, 16);
  7008. g = style.substring(3, 5);
  7009. g = parseInt(g, 16);
  7010. b = style.substring(5, 7);
  7011. b = parseInt(b, 16);
  7012. }
  7013. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  7014. var hex = parseInt(r.substr(1), 16);
  7015. r = hex >> 16 & 255;
  7016. g = hex >> 8 & 255;
  7017. b = hex & 255;
  7018. }
  7019. var f3 = this.f3;
  7020. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  7021. textColor = f3(r / 255) + ' g';
  7022. } else {
  7023. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  7024. }
  7025. return textColor;
  7026. };
  7027. Renderer.prototype.f3 = function(number) {
  7028. return number.toFixed(3); // Ie, %.3f
  7029. }, Renderer.prototype.renderParagraph = function(cb) {
  7030. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  7031. fragments = PurgeWhiteSpace(this.paragraph.text);
  7032. styles = this.paragraph.style;
  7033. blockstyle = this.paragraph.blockstyle;
  7034. this.paragraph = {
  7035. text: [],
  7036. style: [],
  7037. blockstyle: {},
  7038. priorblockstyle: blockstyle
  7039. };
  7040. if (!fragments.join("").trim()) {
  7041. return;
  7042. }
  7043. lines = this.splitFragmentsIntoLines(fragments, styles);
  7044. line = void 0;
  7045. maxLineHeight = void 0;
  7046. defaultFontSize = 12;
  7047. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  7048. this.priorMarginBottom = this.priorMarginBottom || 0;
  7049. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7050. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  7051. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  7052. if (blockstyle['page-break-before'] === 'always') {
  7053. this.pdf.addPage();
  7054. this.y = 0;
  7055. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7056. }
  7057. out = this.pdf.internal.write;
  7058. i = void 0;
  7059. l = void 0;
  7060. this.y += paragraphspacing_before;
  7061. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7062. //stores the current indent of cursor position
  7063. var currentIndent = 0;
  7064. while (lines.length) {
  7065. line = lines.shift();
  7066. maxLineHeight = 0;
  7067. i = 0;
  7068. l = line.length;
  7069. while (i !== l) {
  7070. if (line[i][0].trim()) {
  7071. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  7072. fontSize = line[i][1]["font-size"] * 7;
  7073. }
  7074. i++;
  7075. }
  7076. //if we have to move the cursor to adapt the indent
  7077. var indentMove = 0;
  7078. var wantedIndent = 0;
  7079. //if a margin was added (by e.g. a text-alignment), move the cursor
  7080. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  7081. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  7082. indentMove = wantedIndent - currentIndent;
  7083. currentIndent = wantedIndent;
  7084. }
  7085. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
  7086. //move the cursor
  7087. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7088. i = 0;
  7089. l = line.length;
  7090. while (i !== l) {
  7091. if (line[i][0]) {
  7092. this.RenderTextFragment(line[i][0], line[i][1]);
  7093. }
  7094. i++;
  7095. }
  7096. this.y += maxLineHeight * fontToUnitRatio;
  7097. //if some watcher function was executed successful, so e.g. margin and widths were changed,
  7098. //reset line drawing and calculate position and lines again
  7099. //e.g. to stop text floating around an image
  7100. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  7101. var localFragments = [];
  7102. var localStyles = [];
  7103. //create fragment array of
  7104. lines.forEach(function(localLine) {
  7105. var i = 0;
  7106. var l = localLine.length;
  7107. while (i !== l) {
  7108. if (localLine[i][0]) {
  7109. localFragments.push(localLine[i][0] + ' ');
  7110. localStyles.push(localLine[i][1]);
  7111. }
  7112. ++i;
  7113. }
  7114. });
  7115. //split lines again due to possible coordinate changes
  7116. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
  7117. //reposition the current cursor
  7118. out("ET", "Q");
  7119. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7120. }
  7121. }
  7122. if (cb && typeof cb === "function") {
  7123. cb.call(this, this.x - 9, this.y - fontSize / 2);
  7124. }
  7125. out("ET", "Q");
  7126. return this.y += paragraphspacing_after;
  7127. };
  7128. Renderer.prototype.setBlockBoundary = function(cb) {
  7129. return this.renderParagraph(cb);
  7130. };
  7131. Renderer.prototype.setBlockStyle = function(css) {
  7132. return this.paragraph.blockstyle = css;
  7133. };
  7134. Renderer.prototype.addText = function(text, css) {
  7135. this.paragraph.text.push(text);
  7136. return this.paragraph.style.push(css);
  7137. };
  7138. FontNameDB = {
  7139. helvetica: "helvetica",
  7140. "sans-serif": "helvetica",
  7141. "times new roman": "times",
  7142. serif: "times",
  7143. times: "times",
  7144. monospace: "courier",
  7145. courier: "courier"
  7146. };
  7147. FontWeightMap = {
  7148. 100: "normal",
  7149. 200: "normal",
  7150. 300: "normal",
  7151. 400: "normal",
  7152. 500: "bold",
  7153. 600: "bold",
  7154. 700: "bold",
  7155. 800: "bold",
  7156. 900: "bold",
  7157. normal: "normal",
  7158. bold: "bold",
  7159. bolder: "bold",
  7160. lighter: "normal"
  7161. };
  7162. FontStyleMap = {
  7163. normal: "normal",
  7164. italic: "italic",
  7165. oblique: "italic"
  7166. };
  7167. TextAlignMap = {
  7168. left: "left",
  7169. right: "right",
  7170. center: "center",
  7171. justify: "justify"
  7172. };
  7173. FloatMap = {
  7174. none: 'none',
  7175. right: 'right',
  7176. left: 'left'
  7177. };
  7178. ClearMap = {
  7179. none: 'none',
  7180. both: 'both'
  7181. };
  7182. UnitedNumberMap = {
  7183. normal: 1
  7184. };
  7185. /**
  7186. * Converts HTML-formatted text into formatted PDF text.
  7187. *
  7188. * Notes:
  7189. * 2012-07-18
  7190. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  7191. * Plugin relies on jQuery for CSS extraction.
  7192. * Targeting HTML output from Markdown templating, which is a very simple
  7193. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  7194. * Images, tables are NOT supported.
  7195. *
  7196. * @public
  7197. * @function
  7198. * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  7199. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  7200. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  7201. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  7202. * @returns {Object} jsPDF instance
  7203. */
  7204. jsPDFAPI.fromHTML = function(HTML, x, y, settings, callback, margins) {
  7205. "use strict";
  7206. this.margins_doc = margins || {
  7207. top: 0,
  7208. bottom: 0
  7209. };
  7210. if (!settings) settings = {};
  7211. if (!settings.elementHandlers) settings.elementHandlers = {};
  7212. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  7213. };
  7214. })(jsPDF.API);
  7215. /** ====================================================================
  7216. * jsPDF JavaScript plugin
  7217. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  7218. *
  7219. *
  7220. * ====================================================================
  7221. */
  7222. /*global jsPDF */
  7223. (function(jsPDFAPI) {
  7224. 'use strict';
  7225. var jsNamesObj, jsJsObj, text;
  7226. jsPDFAPI.addJS = function(txt) {
  7227. text = txt;
  7228. this.internal.events.subscribe('postPutResources', function(txt) {
  7229. jsNamesObj = this.internal.newObject();
  7230. this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
  7231. jsJsObj = this.internal.newObject();
  7232. this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
  7233. });
  7234. this.internal.events.subscribe('putCatalog', function() {
  7235. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  7236. this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  7237. }
  7238. });
  7239. return this;
  7240. };
  7241. })(jsPDF.API);
  7242. /**
  7243. * jsPDF Outline PlugIn
  7244. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7245. *
  7246. * Licensed under the MIT License.
  7247. * http://opensource.org/licenses/mit-license
  7248. */
  7249. /**
  7250. * Generates a PDF Outline
  7251. */
  7252. (function(jsPDFAPI) {
  7253. 'use strict';
  7254. jsPDFAPI.events.push(['postPutResources', function() {
  7255. var pdf = this;
  7256. var rx = /^(\d+) 0 obj$/;
  7257. // Write action goto objects for each page
  7258. // this.outline.destsGoto = [];
  7259. // for (var i = 0; i < totalPages; i++) {
  7260. // var id = pdf.internal.newObject();
  7261. // this.outline.destsGoto.push(id);
  7262. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  7263. // null null]/S/GoTo>> endobj");
  7264. // }
  7265. //
  7266. // for (var i = 0; i < dests.length; i++) {
  7267. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  7268. // R");
  7269. // }
  7270. //
  7271. if (this.outline.root.children.length > 0) {
  7272. var lines = pdf.outline.render().split(/\r\n/);
  7273. for (var i = 0; i < lines.length; i++) {
  7274. var line = lines[i];
  7275. var m = rx.exec(line);
  7276. if (m != null) {
  7277. var oid = m[1];
  7278. pdf.internal.newObjectDeferredBegin(oid);
  7279. }
  7280. pdf.internal.write(line);
  7281. }
  7282. }
  7283. // This code will write named destination for each page reference
  7284. // (page_1, etc)
  7285. if (this.outline.createNamedDestinations) {
  7286. var totalPages = this.internal.pages.length;
  7287. // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  7288. // follow 5, 7, 9, etc
  7289. // Write destination objects for each page
  7290. var dests = [];
  7291. for (var i = 0; i < totalPages; i++) {
  7292. var id = pdf.internal.newObject();
  7293. dests.push(id);
  7294. var info = pdf.internal.getPageInfo(i + 1);
  7295. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  7296. }
  7297. // assign a name for each destination
  7298. var names2Oid = pdf.internal.newObject();
  7299. pdf.internal.write('<< /Names [ ');
  7300. for (var i = 0; i < dests.length; i++) {
  7301. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  7302. }
  7303. pdf.internal.write(' ] >>', 'endobj');
  7304. // var kids = pdf.internal.newObject();
  7305. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  7306. // pdf.internal.write(' ] >>', 'endobj');
  7307. var namesOid = pdf.internal.newObject();
  7308. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  7309. pdf.internal.write('>>', 'endobj');
  7310. }
  7311. }]);
  7312. jsPDFAPI.events.push(['putCatalog', function() {
  7313. var pdf = this;
  7314. if (pdf.outline.root.children.length > 0) {
  7315. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  7316. if (this.outline.createNamedDestinations) {
  7317. pdf.internal.write("/Names " + namesOid + " 0 R");
  7318. }
  7319. // Open with Bookmarks showing
  7320. // pdf.internal.write("/PageMode /UseOutlines");
  7321. }
  7322. }]);
  7323. jsPDFAPI.events.push(['initialized', function() {
  7324. var pdf = this;
  7325. pdf.outline = {
  7326. createNamedDestinations: false,
  7327. root: {
  7328. children: []
  7329. }
  7330. };
  7331. pdf.outline.add = function(parent, title, options) {
  7332. var item = {
  7333. title: title,
  7334. options: options,
  7335. children: []
  7336. };
  7337. if (parent == null) {
  7338. parent = this.root;
  7339. }
  7340. parent.children.push(item);
  7341. return item;
  7342. };
  7343. pdf.outline.render = function() {
  7344. this.ctx = {};
  7345. this.ctx.val = '';
  7346. this.ctx.pdf = pdf;
  7347. this.genIds_r(this.root);
  7348. this.renderRoot(this.root);
  7349. this.renderItems(this.root);
  7350. return this.ctx.val;
  7351. };
  7352. pdf.outline.genIds_r = function(node) {
  7353. node.id = pdf.internal.newObjectDeferred();
  7354. for (var i = 0; i < node.children.length; i++) {
  7355. this.genIds_r(node.children[i]);
  7356. }
  7357. };
  7358. pdf.outline.renderRoot = function(node) {
  7359. this.objStart(node);
  7360. this.line('/Type /Outlines');
  7361. if (node.children.length > 0) {
  7362. this.line('/First ' + this.makeRef(node.children[0]));
  7363. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  7364. }
  7365. this.line('/Count ' + this.count_r({
  7366. count: 0
  7367. }, node));
  7368. this.objEnd();
  7369. };
  7370. pdf.outline.renderItems = function(node) {
  7371. for (var i = 0; i < node.children.length; i++) {
  7372. var item = node.children[i];
  7373. this.objStart(item);
  7374. this.line('/Title ' + this.makeString(item.title));
  7375. this.line('/Parent ' + this.makeRef(node));
  7376. if (i > 0) {
  7377. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  7378. }
  7379. if (i < node.children.length - 1) {
  7380. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  7381. }
  7382. if (item.children.length > 0) {
  7383. this.line('/First ' + this.makeRef(item.children[0]));
  7384. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  7385. }
  7386. var count = this.count = this.count_r({
  7387. count: 0
  7388. }, item);
  7389. if (count > 0) {
  7390. this.line('/Count ' + count);
  7391. }
  7392. if (item.options) {
  7393. if (item.options.pageNumber) {
  7394. // Explicit Destination
  7395. //WARNING this assumes page ids are 3,5,7, etc.
  7396. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  7397. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7398. // this line does not work on all clients (pageNumber instead of page ref)
  7399. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7400. // Named Destination
  7401. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  7402. // Action Destination
  7403. // var id = pdf.internal.newObject();
  7404. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  7405. // this.line('/A ' + id + ' 0 R' );
  7406. }
  7407. }
  7408. this.objEnd();
  7409. }
  7410. for (var i = 0; i < node.children.length; i++) {
  7411. var item = node.children[i];
  7412. this.renderItems(item);
  7413. }
  7414. };
  7415. pdf.outline.line = function(text) {
  7416. this.ctx.val += text + '\r\n';
  7417. };
  7418. pdf.outline.makeRef = function(node) {
  7419. return node.id + ' 0 R';
  7420. };
  7421. pdf.outline.makeString = function(val) {
  7422. return '(' + pdf.internal.pdfEscape(val) + ')';
  7423. };
  7424. pdf.outline.objStart = function(node) {
  7425. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  7426. };
  7427. pdf.outline.objEnd = function(node) {
  7428. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  7429. };
  7430. pdf.outline.count_r = function(ctx, node) {
  7431. for (var i = 0; i < node.children.length; i++) {
  7432. ctx.count++;
  7433. this.count_r(ctx, node.children[i]);
  7434. }
  7435. return ctx.count;
  7436. };
  7437. }]);
  7438. return this;
  7439. })(jsPDF.API);
  7440. /**@preserve
  7441. * ====================================================================
  7442. * jsPDF PNG PlugIn
  7443. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  7444. *
  7445. *
  7446. * ====================================================================
  7447. */
  7448. (function(jsPDFAPI) {
  7449. 'use strict';
  7450. /*
  7451. * @see http://www.w3.org/TR/PNG-Chunks.html
  7452. *
  7453. Color Allowed Interpretation
  7454. Type Bit Depths
  7455. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  7456. 2 8,16 Each pixel is an R,G,B triple.
  7457. 3 1,2,4,8 Each pixel is a palette index;
  7458. a PLTE chunk must appear.
  7459. 4 8,16 Each pixel is a grayscale sample,
  7460. followed by an alpha sample.
  7461. 6 8,16 Each pixel is an R,G,B triple,
  7462. followed by an alpha sample.
  7463. */
  7464. /*
  7465. * PNG filter method types
  7466. *
  7467. * @see http://www.w3.org/TR/PNG-Filters.html
  7468. * @see http://www.libpng.org/pub/png/book/chapter09.html
  7469. *
  7470. * This is what the value 'Predictor' in decode params relates to
  7471. *
  7472. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  7473. * 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.
  7474. *
  7475. 0 None
  7476. 1 Sub
  7477. 2 Up
  7478. 3 Average
  7479. 4 Paeth
  7480. */
  7481. var doesNotHavePngJS = function doesNotHavePngJS() {
  7482. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  7483. },
  7484. canCompress = function canCompress(value) {
  7485. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  7486. },
  7487. hasCompressionJS = function hasCompressionJS() {
  7488. var inst = typeof Deflater === 'function';
  7489. if (!inst) throw new Error("requires deflate.js for compression");
  7490. return inst;
  7491. },
  7492. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  7493. var level = 5,
  7494. filter_method = filterUp;
  7495. switch (compression) {
  7496. case jsPDFAPI.image_compression.FAST:
  7497. level = 3;
  7498. filter_method = filterSub;
  7499. break;
  7500. case jsPDFAPI.image_compression.MEDIUM:
  7501. level = 6;
  7502. filter_method = filterAverage;
  7503. break;
  7504. case jsPDFAPI.image_compression.SLOW:
  7505. level = 9;
  7506. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  7507. break;
  7508. }
  7509. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  7510. var header = new Uint8Array(createZlibHeader(level));
  7511. var checksum = adler32(bytes);
  7512. var deflate = new Deflater(level);
  7513. var a = deflate.append(bytes);
  7514. var cBytes = deflate.flush();
  7515. var len = header.length + a.length + cBytes.length;
  7516. var cmpd = new Uint8Array(len + 4);
  7517. cmpd.set(header);
  7518. cmpd.set(a, header.length);
  7519. cmpd.set(cBytes, header.length + a.length);
  7520. cmpd[len++] = checksum >>> 24 & 0xff;
  7521. cmpd[len++] = checksum >>> 16 & 0xff;
  7522. cmpd[len++] = checksum >>> 8 & 0xff;
  7523. cmpd[len++] = checksum & 0xff;
  7524. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  7525. },
  7526. createZlibHeader = function createZlibHeader(bytes, level) {
  7527. /*
  7528. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  7529. */
  7530. var cm = 8;
  7531. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  7532. var cmf = cinfo << 4 | cm;
  7533. var hdr = cmf << 8;
  7534. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  7535. hdr |= flevel << 6;
  7536. hdr |= 0; //FDICT
  7537. hdr += 31 - hdr % 31;
  7538. return [cmf, hdr & 0xff & 0xff];
  7539. },
  7540. adler32 = function adler32(array, param) {
  7541. var adler = 1;
  7542. var s1 = adler & 0xffff,
  7543. s2 = adler >>> 16 & 0xffff;
  7544. var len = array.length;
  7545. var tlen;
  7546. var i = 0;
  7547. while (len > 0) {
  7548. tlen = len > param ? param : len;
  7549. len -= tlen;
  7550. do {
  7551. s1 += array[i++];
  7552. s2 += s1;
  7553. } while (--tlen);
  7554. s1 %= 65521;
  7555. s2 %= 65521;
  7556. }
  7557. return (s2 << 16 | s1) >>> 0;
  7558. },
  7559. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  7560. var lines = bytes.length / lineLength,
  7561. result = new Uint8Array(bytes.length + lines),
  7562. filter_methods = getFilterMethods(),
  7563. i = 0,
  7564. line,
  7565. prevLine,
  7566. offset;
  7567. for (; i < lines; i++) {
  7568. offset = i * lineLength;
  7569. line = bytes.subarray(offset, offset + lineLength);
  7570. if (filter_method) {
  7571. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  7572. } else {
  7573. var j = 0,
  7574. len = filter_methods.length,
  7575. results = [];
  7576. for (; j < len; j++) {
  7577. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  7578. }
  7579. var ind = getIndexOfSmallestSum(results.concat());
  7580. result.set(results[ind], offset + i);
  7581. }
  7582. prevLine = line;
  7583. }
  7584. return result;
  7585. },
  7586. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  7587. /*var result = new Uint8Array(line.length + 1);
  7588. result[0] = 0;
  7589. result.set(line, 1);*/
  7590. var result = Array.apply([], line);
  7591. result.unshift(0);
  7592. return result;
  7593. },
  7594. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  7595. var result = [],
  7596. i = 0,
  7597. len = line.length,
  7598. left;
  7599. result[0] = 1;
  7600. for (; i < len; i++) {
  7601. left = line[i - colorsPerPixel] || 0;
  7602. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  7603. }
  7604. return result;
  7605. },
  7606. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  7607. var result = [],
  7608. i = 0,
  7609. len = line.length,
  7610. up;
  7611. result[0] = 2;
  7612. for (; i < len; i++) {
  7613. up = prevLine && prevLine[i] || 0;
  7614. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  7615. }
  7616. return result;
  7617. },
  7618. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  7619. var result = [],
  7620. i = 0,
  7621. len = line.length,
  7622. left,
  7623. up;
  7624. result[0] = 3;
  7625. for (; i < len; i++) {
  7626. left = line[i - colorsPerPixel] || 0;
  7627. up = prevLine && prevLine[i] || 0;
  7628. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  7629. }
  7630. return result;
  7631. },
  7632. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  7633. var result = [],
  7634. i = 0,
  7635. len = line.length,
  7636. left,
  7637. up,
  7638. upLeft,
  7639. paeth;
  7640. result[0] = 4;
  7641. for (; i < len; i++) {
  7642. left = line[i - colorsPerPixel] || 0;
  7643. up = prevLine && prevLine[i] || 0;
  7644. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  7645. paeth = paethPredictor(left, up, upLeft);
  7646. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  7647. }
  7648. return result;
  7649. },
  7650. paethPredictor = function paethPredictor(left, up, upLeft) {
  7651. var p = left + up - upLeft,
  7652. pLeft = Math.abs(p - left),
  7653. pUp = Math.abs(p - up),
  7654. pUpLeft = Math.abs(p - upLeft);
  7655. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  7656. },
  7657. getFilterMethods = function getFilterMethods() {
  7658. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  7659. },
  7660. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  7661. var i = 0,
  7662. len = arrays.length,
  7663. sum,
  7664. min,
  7665. ind;
  7666. while (i < len) {
  7667. sum = absSum(arrays[i].slice(1));
  7668. if (sum < min || !min) {
  7669. min = sum;
  7670. ind = i;
  7671. }
  7672. i++;
  7673. }
  7674. return ind;
  7675. },
  7676. absSum = function absSum(array) {
  7677. var i = 0,
  7678. len = array.length,
  7679. sum = 0;
  7680. while (i < len) {
  7681. sum += Math.abs(array[i++]);
  7682. }
  7683. return sum;
  7684. },
  7685. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  7686. var predictor;
  7687. switch (compression) {
  7688. case jsPDFAPI.image_compression.FAST:
  7689. predictor = 11;
  7690. break;
  7691. case jsPDFAPI.image_compression.MEDIUM:
  7692. predictor = 13;
  7693. break;
  7694. case jsPDFAPI.image_compression.SLOW:
  7695. predictor = 14;
  7696. break;
  7697. default:
  7698. predictor = 12;
  7699. break;
  7700. }
  7701. return predictor;
  7702. };
  7703. jsPDFAPI.processPNG = function(imageData, imageIndex, alias, compression, dataAsBinaryString) {
  7704. 'use strict';
  7705. var colorSpace = this.color_spaces.DEVICE_RGB,
  7706. decode = this.decode.FLATE_DECODE,
  7707. bpc = 8,
  7708. img,
  7709. dp,
  7710. trns,
  7711. colors,
  7712. pal,
  7713. smask;
  7714. /* if(this.isString(imageData)) {
  7715. }*/
  7716. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  7717. if (this.isArrayBufferView(imageData)) {
  7718. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  7719. img = new PNG(imageData);
  7720. imageData = img.imgData;
  7721. bpc = img.bits;
  7722. colorSpace = img.colorSpace;
  7723. colors = img.colors;
  7724. //logImg(img);
  7725. /*
  7726. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  7727. *
  7728. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  7729. *
  7730. * Extract alpha to create two separate images, using the alpha as a sMask
  7731. */
  7732. if ([4, 6].indexOf(img.colorType) !== -1) {
  7733. /*
  7734. * processes 8 bit RGBA and grayscale + alpha images
  7735. */
  7736. if (img.bits === 8) {
  7737. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  7738. len = pixels.length,
  7739. imgData = new Uint8Array(len * img.colors),
  7740. alphaData = new Uint8Array(len),
  7741. pDiff = img.pixelBitlength - img.bits,
  7742. i = 0,
  7743. n = 0,
  7744. pixel,
  7745. pbl;
  7746. for (; i < len; i++) {
  7747. pixel = pixels[i];
  7748. pbl = 0;
  7749. while (pbl < pDiff) {
  7750. imgData[n++] = pixel >>> pbl & 0xff;
  7751. pbl = pbl + img.bits;
  7752. }
  7753. alphaData[i] = pixel >>> pbl & 0xff;
  7754. }
  7755. }
  7756. /*
  7757. * processes 16 bit RGBA and grayscale + alpha images
  7758. */
  7759. if (img.bits === 16) {
  7760. var pixels = new Uint32Array(img.decodePixels().buffer),
  7761. len = pixels.length,
  7762. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  7763. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  7764. hasColors = img.colors > 1,
  7765. i = 0,
  7766. n = 0,
  7767. a = 0,
  7768. pixel;
  7769. while (i < len) {
  7770. pixel = pixels[i++];
  7771. imgData[n++] = pixel >>> 0 & 0xFF;
  7772. if (hasColors) {
  7773. imgData[n++] = pixel >>> 16 & 0xFF;
  7774. pixel = pixels[i++];
  7775. imgData[n++] = pixel >>> 0 & 0xFF;
  7776. }
  7777. alphaData[a++] = pixel >>> 16 & 0xFF;
  7778. }
  7779. bpc = 8;
  7780. }
  7781. if (canCompress(compression)) {
  7782. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  7783. smask = compressBytes(alphaData, img.width, 1, compression);
  7784. } else {
  7785. imageData = imgData;
  7786. smask = alphaData;
  7787. decode = null;
  7788. }
  7789. }
  7790. /*
  7791. * Indexed png. Each pixel is a palette index.
  7792. */
  7793. if (img.colorType === 3) {
  7794. colorSpace = this.color_spaces.INDEXED;
  7795. pal = img.palette;
  7796. if (img.transparency.indexed) {
  7797. var trans = img.transparency.indexed;
  7798. var total = 0,
  7799. i = 0,
  7800. len = trans.length;
  7801. for (; i < len; ++i) {
  7802. total += trans[i];
  7803. }
  7804. total = total / 255;
  7805. /*
  7806. * a single color is specified as 100% transparent (0),
  7807. * so we set trns to use a /Mask with that index
  7808. */
  7809. if (total === len - 1 && trans.indexOf(0) !== -1) {
  7810. trns = [trans.indexOf(0)];
  7811. /*
  7812. * there's more than one colour within the palette that specifies
  7813. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  7814. */
  7815. } else if (total !== len) {
  7816. var pixels = img.decodePixels(),
  7817. alphaData = new Uint8Array(pixels.length),
  7818. i = 0,
  7819. len = pixels.length;
  7820. for (; i < len; i++) {
  7821. alphaData[i] = trans[pixels[i]];
  7822. }
  7823. smask = compressBytes(alphaData, img.width, 1);
  7824. }
  7825. }
  7826. }
  7827. var predictor = getPredictorFromCompression(compression);
  7828. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  7829. else
  7830. //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  7831. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  7832. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  7833. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  7834. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  7835. }
  7836. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  7837. };
  7838. })(jsPDF.API);
  7839. /**
  7840. * jsPDF Autoprint Plugin
  7841. *
  7842. * Licensed under the MIT License.
  7843. * http://opensource.org/licenses/mit-license
  7844. */
  7845. (function(jsPDFAPI) {
  7846. 'use strict';
  7847. jsPDFAPI.autoPrint = function() {
  7848. 'use strict';
  7849. var refAutoPrintTag;
  7850. this.internal.events.subscribe('postPutResources', function() {
  7851. refAutoPrintTag = this.internal.newObject();
  7852. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  7853. });
  7854. this.internal.events.subscribe("putCatalog", function() {
  7855. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  7856. });
  7857. return this;
  7858. };
  7859. })(jsPDF.API);
  7860. /** @preserve
  7861. * jsPDF split_text_to_size plugin - MIT license.
  7862. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7863. * 2014 Diego Casorran, https://github.com/diegocr
  7864. */
  7865. /**
  7866. *
  7867. * ====================================================================
  7868. */
  7869. (function(API) {
  7870. 'use strict';
  7871. /**
  7872. Returns an array of length matching length of the 'word' string, with each
  7873. cell ocupied by the width of the char in that position.
  7874. @function
  7875. @param word {String}
  7876. @param widths {Object}
  7877. @param kerning {Object}
  7878. @returns {Array}
  7879. */
  7880. var getCharWidthsArray = API.getCharWidthsArray = function(text, options) {
  7881. if (!options) {
  7882. options = {};
  7883. }
  7884. var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
  7885. widthsFractionOf = widths.fof ? widths.fof : 1,
  7886. kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
  7887. kerningFractionOf = kerning.fof ? kerning.fof : 1;
  7888. // console.log("widths, kergnings", widths, kerning)
  7889. var i,
  7890. l,
  7891. char_code,
  7892. prior_char_code = 0 // for kerning
  7893. ,
  7894. default_char_width = widths[0] || widthsFractionOf,
  7895. output = [];
  7896. for (i = 0, l = text.length; i < l; i++) {
  7897. char_code = text.charCodeAt(i);
  7898. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  7899. prior_char_code = char_code;
  7900. }
  7901. return output;
  7902. };
  7903. var getArraySum = function getArraySum(array) {
  7904. var i = array.length,
  7905. output = 0;
  7906. while (i) {
  7907. i--;
  7908. output += array[i];
  7909. }
  7910. return output;
  7911. };
  7912. /**
  7913. Returns a widths of string in a given font, if the font size is set as 1 point.
  7914. In other words, this is "proportional" value. For 1 unit of font size, the length
  7915. of the string will be that much.
  7916. Multiply by font size to get actual width in *points*
  7917. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  7918. @public
  7919. @function
  7920. @param
  7921. @returns {Type}
  7922. */
  7923. var getStringUnitWidth = API.getStringUnitWidth = function(text, options) {
  7924. return getArraySum(getCharWidthsArray.call(this, text, options));
  7925. };
  7926. /**
  7927. returns array of lines
  7928. */
  7929. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  7930. var answer = [];
  7931. // 1st, chop off the piece that can fit on the hanging line.
  7932. var i = 0,
  7933. l = word.length,
  7934. workingLen = 0;
  7935. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  7936. workingLen += widths_array[i];
  7937. i++;
  7938. }
  7939. // this is first line.
  7940. answer.push(word.slice(0, i));
  7941. // 2nd. Split the rest into maxLen pieces.
  7942. var startOfLine = i;
  7943. workingLen = 0;
  7944. while (i !== l) {
  7945. if (workingLen + widths_array[i] > maxLen) {
  7946. answer.push(word.slice(startOfLine, i));
  7947. workingLen = 0;
  7948. startOfLine = i;
  7949. }
  7950. workingLen += widths_array[i];
  7951. i++;
  7952. }
  7953. if (startOfLine !== i) {
  7954. answer.push(word.slice(startOfLine, i));
  7955. }
  7956. return answer;
  7957. };
  7958. // Note, all sizing inputs for this function must be in "font measurement units"
  7959. // By default, for PDF, it's "point".
  7960. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  7961. // at this time works only on Western scripts, ones with space char
  7962. // separating the words. Feel free to expand.
  7963. if (!options) {
  7964. options = {};
  7965. }
  7966. var line = [],
  7967. lines = [line],
  7968. line_length = options.textIndent || 0,
  7969. separator_length = 0,
  7970. current_word_length = 0,
  7971. word,
  7972. widths_array,
  7973. words = text.split(' '),
  7974. spaceCharWidth = getCharWidthsArray(' ', options)[0],
  7975. i,
  7976. l,
  7977. tmp,
  7978. lineIndent;
  7979. if (options.lineIndent === -1) {
  7980. lineIndent = words[0].length + 2;
  7981. } else {
  7982. lineIndent = options.lineIndent || 0;
  7983. }
  7984. if (lineIndent) {
  7985. var pad = Array(lineIndent).join(" "),
  7986. wrds = [];
  7987. words.map(function(wrd) {
  7988. wrd = wrd.split(/\s*\n/);
  7989. if (wrd.length > 1) {
  7990. wrds = wrds.concat(wrd.map(function(wrd, idx) {
  7991. return (idx && wrd.length ? "\n" : "") + wrd;
  7992. }));
  7993. } else {
  7994. wrds.push(wrd[0]);
  7995. }
  7996. });
  7997. words = wrds;
  7998. lineIndent = getStringUnitWidth(pad, options);
  7999. }
  8000. for (i = 0, l = words.length; i < l; i++) {
  8001. var force = 0;
  8002. word = words[i];
  8003. if (lineIndent && word[0] == "\n") {
  8004. word = word.substr(1);
  8005. force = 1;
  8006. }
  8007. widths_array = getCharWidthsArray(word, options);
  8008. current_word_length = getArraySum(widths_array);
  8009. if (line_length + separator_length + current_word_length > maxlen || force) {
  8010. if (current_word_length > maxlen) {
  8011. // this happens when you have space-less long URLs for example.
  8012. // we just chop these to size. We do NOT insert hiphens
  8013. tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
  8014. // first line we add to existing line object
  8015. line.push(tmp.shift()); // it's ok to have extra space indicator there
  8016. // last line we make into new line object
  8017. line = [tmp.pop()];
  8018. // lines in the middle we apped to lines object as whole lines
  8019. while (tmp.length) {
  8020. lines.push([tmp.shift()]); // single fragment occupies whole line
  8021. }
  8022. current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
  8023. } else {
  8024. // just put it on a new line
  8025. line = [word];
  8026. }
  8027. // now we attach new line to lines
  8028. lines.push(line);
  8029. line_length = current_word_length + lineIndent;
  8030. separator_length = spaceCharWidth;
  8031. } else {
  8032. line.push(word);
  8033. line_length += separator_length + current_word_length;
  8034. separator_length = spaceCharWidth;
  8035. }
  8036. }
  8037. if (lineIndent) {
  8038. var postProcess = function postProcess(ln, idx) {
  8039. return (idx ? pad : '') + ln.join(" ");
  8040. };
  8041. } else {
  8042. var postProcess = function postProcess(ln) {
  8043. return ln.join(" ");
  8044. };
  8045. }
  8046. return lines.map(postProcess);
  8047. };
  8048. /**
  8049. Splits a given string into an array of strings. Uses 'size' value
  8050. (in measurement units declared as default for the jsPDF instance)
  8051. and the font's "widths" and "Kerning" tables, where available, to
  8052. determine display length of a given string for a given font.
  8053. We use character's 100% of unit size (height) as width when Width
  8054. table or other default width is not available.
  8055. @public
  8056. @function
  8057. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  8058. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  8059. @param options {Object} Optional flags needed for chopper to do the right thing.
  8060. @returns {Array} with strings chopped to size.
  8061. */
  8062. API.splitTextToSize = function(text, maxlen, options) {
  8063. 'use strict';
  8064. if (!options) {
  8065. options = {};
  8066. }
  8067. var fsize = options.fontSize || this.internal.getFontSize(),
  8068. newOptions = function(options) {
  8069. var widths = { 0: 1 },
  8070. kerning = {};
  8071. if (!options.widths || !options.kerning) {
  8072. var f = this.internal.getFont(options.fontName, options.fontStyle),
  8073. encoding = 'Unicode';
  8074. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  8075. // Actual JavaScript-native String's 16bit char codes used.
  8076. // no multi-byte logic here
  8077. if (f.metadata[encoding]) {
  8078. return {
  8079. widths: f.metadata[encoding].widths || widths,
  8080. kerning: f.metadata[encoding].kerning || kerning
  8081. };
  8082. }
  8083. } else {
  8084. return {
  8085. widths: options.widths,
  8086. kerning: options.kerning
  8087. };
  8088. }
  8089. // then use default values
  8090. return {
  8091. widths: widths,
  8092. kerning: kerning
  8093. };
  8094. }.call(this, options);
  8095. // first we split on end-of-line chars
  8096. var paragraphs;
  8097. if (Array.isArray(text)) {
  8098. paragraphs = text;
  8099. } else {
  8100. paragraphs = text.split(/\r?\n/);
  8101. }
  8102. // now we convert size (max length of line) into "font size units"
  8103. // at present time, the "font size unit" is always 'point'
  8104. // 'proportional' means, "in proportion to font size"
  8105. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
  8106. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  8107. // this may change in the future?
  8108. // until then, proportional_maxlen is likely to be in 'points'
  8109. // If first line is to be indented (shorter or longer) than maxLen
  8110. // we indicate that by using CSS-style "text-indent" option.
  8111. // here it's in font units too (which is likely 'points')
  8112. // it can be negative (which makes the first line longer than maxLen)
  8113. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  8114. newOptions.lineIndent = options.lineIndent;
  8115. var i,
  8116. l,
  8117. output = [];
  8118. for (i = 0, l = paragraphs.length; i < l; i++) {
  8119. output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
  8120. }
  8121. return output;
  8122. };
  8123. })(jsPDF.API);
  8124. /** @preserve
  8125. jsPDF standard_fonts_metrics plugin
  8126. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8127. MIT license.
  8128. */
  8129. /**
  8130. *
  8131. * ====================================================================
  8132. */
  8133. (function(API) {
  8134. 'use strict';
  8135. /*
  8136. # reference (Python) versions of 'compress' and 'uncompress'
  8137. # only 'uncompress' function is featured lower as JavaScript
  8138. # if you want to unit test "roundtrip", just transcribe the reference
  8139. # 'compress' function from Python into JavaScript
  8140. def compress(data):
  8141. keys = '0123456789abcdef'
  8142. values = 'klmnopqrstuvwxyz'
  8143. mapping = dict(zip(keys, values))
  8144. vals = []
  8145. for key in data.keys():
  8146. value = data[key]
  8147. try:
  8148. keystring = hex(key)[2:]
  8149. keystring = keystring[:-1] + mapping[keystring[-1:]]
  8150. except:
  8151. keystring = key.join(["'","'"])
  8152. #print('Keystring is %s' % keystring)
  8153. try:
  8154. if value < 0:
  8155. valuestring = hex(value)[3:]
  8156. numberprefix = '-'
  8157. else:
  8158. valuestring = hex(value)[2:]
  8159. numberprefix = ''
  8160. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  8161. except:
  8162. if type(value) == dict:
  8163. valuestring = compress(value)
  8164. else:
  8165. raise Exception("Don't know what to do with value type %s" % type(value))
  8166. vals.append(keystring+valuestring)
  8167. return '{' + ''.join(vals) + '}'
  8168. def uncompress(data):
  8169. decoded = '0123456789abcdef'
  8170. encoded = 'klmnopqrstuvwxyz'
  8171. mapping = dict(zip(encoded, decoded))
  8172. sign = +1
  8173. stringmode = False
  8174. stringparts = []
  8175. output = {}
  8176. activeobject = output
  8177. parentchain = []
  8178. keyparts = ''
  8179. valueparts = ''
  8180. key = None
  8181. ending = set(encoded)
  8182. i = 1
  8183. l = len(data) - 1 # stripping starting, ending {}
  8184. while i != l: # stripping {}
  8185. # -, {, }, ' are special.
  8186. ch = data[i]
  8187. i += 1
  8188. if ch == "'":
  8189. if stringmode:
  8190. # end of string mode
  8191. stringmode = False
  8192. key = ''.join(stringparts)
  8193. else:
  8194. # start of string mode
  8195. stringmode = True
  8196. stringparts = []
  8197. elif stringmode == True:
  8198. #print("Adding %s to stringpart" % ch)
  8199. stringparts.append(ch)
  8200. elif ch == '{':
  8201. # start of object
  8202. parentchain.append( [activeobject, key] )
  8203. activeobject = {}
  8204. key = None
  8205. #DEBUG = True
  8206. elif ch == '}':
  8207. # end of object
  8208. parent, key = parentchain.pop()
  8209. parent[key] = activeobject
  8210. key = None
  8211. activeobject = parent
  8212. #DEBUG = False
  8213. elif ch == '-':
  8214. sign = -1
  8215. else:
  8216. # must be number
  8217. if key == None:
  8218. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  8219. if ch in ending:
  8220. #debug("End of key")
  8221. keyparts += mapping[ch]
  8222. key = int(keyparts, 16) * sign
  8223. sign = +1
  8224. keyparts = ''
  8225. else:
  8226. keyparts += ch
  8227. else:
  8228. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  8229. if ch in ending:
  8230. #debug("End of value")
  8231. valueparts += mapping[ch]
  8232. activeobject[key] = int(valueparts, 16) * sign
  8233. sign = +1
  8234. key = None
  8235. valueparts = ''
  8236. else:
  8237. valueparts += ch
  8238. #debug(activeobject)
  8239. return output
  8240. */
  8241. /**
  8242. Uncompresses data compressed into custom, base16-like format.
  8243. @public
  8244. @function
  8245. @param
  8246. @returns {Type}
  8247. */
  8248. var uncompress = function uncompress(data) {
  8249. var decoded = '0123456789abcdef',
  8250. encoded = 'klmnopqrstuvwxyz',
  8251. mapping = {};
  8252. for (var i = 0; i < encoded.length; i++) {
  8253. mapping[encoded[i]] = decoded[i];
  8254. }
  8255. var undef,
  8256. output = {},
  8257. sign = 1,
  8258. stringparts // undef. will be [] in string mode
  8259. ,
  8260. activeobject = output,
  8261. parentchain = [],
  8262. parent_key_pair,
  8263. keyparts = '',
  8264. valueparts = '',
  8265. key // undef. will be Truthy when Key is resolved.
  8266. ,
  8267. datalen = data.length - 1 // stripping ending }
  8268. ,
  8269. ch;
  8270. i = 1; // stripping starting {
  8271. while (i != datalen) {
  8272. // - { } ' are special.
  8273. ch = data[i];
  8274. i += 1;
  8275. if (ch == "'") {
  8276. if (stringparts) {
  8277. // end of string mode
  8278. key = stringparts.join('');
  8279. stringparts = undef;
  8280. } else {
  8281. // start of string mode
  8282. stringparts = [];
  8283. }
  8284. } else if (stringparts) {
  8285. stringparts.push(ch);
  8286. } else if (ch == '{') {
  8287. // start of object
  8288. parentchain.push([activeobject, key]);
  8289. activeobject = {};
  8290. key = undef;
  8291. } else if (ch == '}') {
  8292. // end of object
  8293. parent_key_pair = parentchain.pop();
  8294. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  8295. key = undef;
  8296. activeobject = parent_key_pair[0];
  8297. } else if (ch == '-') {
  8298. sign = -1;
  8299. } else {
  8300. // must be number
  8301. if (key === undef) {
  8302. if (mapping.hasOwnProperty(ch)) {
  8303. keyparts += mapping[ch];
  8304. key = parseInt(keyparts, 16) * sign;
  8305. sign = +1;
  8306. keyparts = '';
  8307. } else {
  8308. keyparts += ch;
  8309. }
  8310. } else {
  8311. if (mapping.hasOwnProperty(ch)) {
  8312. valueparts += mapping[ch];
  8313. activeobject[key] = parseInt(valueparts, 16) * sign;
  8314. sign = +1;
  8315. key = undef;
  8316. valueparts = '';
  8317. } else {
  8318. valueparts += ch;
  8319. }
  8320. }
  8321. }
  8322. } // end while
  8323. return output;
  8324. };
  8325. // encoding = 'Unicode'
  8326. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  8327. // Actual 16bit char codes used.
  8328. // no multi-byte logic here
  8329. // Unicode characters to WinAnsiEncoding:
  8330. // {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}
  8331. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  8332. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  8333. // as well as give strings with some (supported by these fonts) Unicode characters and
  8334. // these will be mapped to win cp1252
  8335. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  8336. var encodingBlock = {
  8337. 'codePages': ['WinAnsiEncoding'],
  8338. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  8339. },
  8340. encodings = {
  8341. 'Unicode': {
  8342. 'Courier': encodingBlock,
  8343. 'Courier-Bold': encodingBlock,
  8344. 'Courier-BoldOblique': encodingBlock,
  8345. 'Courier-Oblique': encodingBlock,
  8346. 'Helvetica': encodingBlock,
  8347. 'Helvetica-Bold': encodingBlock,
  8348. 'Helvetica-BoldOblique': encodingBlock,
  8349. 'Helvetica-Oblique': encodingBlock,
  8350. 'Times-Roman': encodingBlock,
  8351. 'Times-Bold': encodingBlock,
  8352. 'Times-BoldItalic': encodingBlock,
  8353. 'Times-Italic': encodingBlock
  8354. // , 'Symbol'
  8355. // , 'ZapfDingbats'
  8356. }
  8357. /**
  8358. Resources:
  8359. Font metrics data is reprocessed derivative of contents of
  8360. "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
  8361. Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
  8362. This file and the 14 PostScript(R) AFM files it accompanies may be used,
  8363. copied, and distributed for any purpose and without charge, with or without
  8364. modification, provided that all copyright notices are retained; that the AFM
  8365. files are not distributed without this file; that all modifications to this
  8366. file or any of the AFM files are prominently noted in the modified file(s);
  8367. and that this paragraph is not modified. Adobe Systems has no responsibility
  8368. or obligation to support the use of the AFM files.
  8369. */
  8370. },
  8371. fontMetrics = {
  8372. 'Unicode': {
  8373. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  8374. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  8375. // width is 476/1000 or 47.6% of its height (regardless of font size)
  8376. // At this time this value applies to "widths" and "kerning" numbers.
  8377. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  8378. // key 'fof' represents the "fontMetricsFractionOf" value
  8379. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8380. '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}}}"),
  8381. '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}}}"),
  8382. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8383. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8384. '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}}}")
  8385. //, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
  8386. ,
  8387. '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}}}"),
  8388. '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}}}")
  8389. //, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
  8390. ,
  8391. 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8392. '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}}}"),
  8393. '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}}}"),
  8394. '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}}}")
  8395. }
  8396. };
  8397. /*
  8398. This event handler is fired when a new jsPDF object is initialized
  8399. This event handler appends metrics data to standard fonts within
  8400. that jsPDF instance. The metrics are mapped over Unicode character
  8401. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  8402. standard PDF fonts.
  8403. Future:
  8404. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  8405. char codes to StandardEncoding character codes. The encoding table is to be used
  8406. somewhere around "pdfEscape" call.
  8407. */
  8408. API.events.push(['addFont', function(font) {
  8409. var metrics,
  8410. unicode_section,
  8411. encoding = 'Unicode',
  8412. encodingBlock;
  8413. metrics = fontMetrics[encoding][font.PostScriptName];
  8414. if (metrics) {
  8415. if (font.metadata[encoding]) {
  8416. unicode_section = font.metadata[encoding];
  8417. } else {
  8418. unicode_section = font.metadata[encoding] = {};
  8419. }
  8420. unicode_section.widths = metrics.widths;
  8421. unicode_section.kerning = metrics.kerning;
  8422. }
  8423. encodingBlock = encodings[encoding][font.PostScriptName];
  8424. if (encodingBlock) {
  8425. if (font.metadata[encoding]) {
  8426. unicode_section = font.metadata[encoding];
  8427. } else {
  8428. unicode_section = font.metadata[encoding] = {};
  8429. }
  8430. unicode_section.encoding = encodingBlock;
  8431. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  8432. font.encoding = encodingBlock.codePages[0];
  8433. }
  8434. }
  8435. }]); // end of adding event handler
  8436. })(jsPDF.API);
  8437. /** @preserve
  8438. jsPDF SVG plugin
  8439. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8440. */
  8441. /**
  8442. *
  8443. * ====================================================================
  8444. */
  8445. (function(jsPDFAPI) {
  8446. 'use strict';
  8447. /**
  8448. Parses SVG XML and converts only some of the SVG elements into
  8449. PDF elements.
  8450. Supports:
  8451. paths
  8452. @public
  8453. @function
  8454. @param
  8455. @returns {Type}
  8456. */
  8457. jsPDFAPI.addSVG = function(svgtext, x, y, w, h) {
  8458. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  8459. var undef;
  8460. if (x === undef || y === undef) {
  8461. throw new Error("addSVG needs values for 'x' and 'y'");
  8462. }
  8463. function InjectCSS(cssbody, document) {
  8464. var styletag = document.createElement('style');
  8465. styletag.type = 'text/css';
  8466. if (styletag.styleSheet) {
  8467. // ie
  8468. styletag.styleSheet.cssText = cssbody;
  8469. } else {
  8470. // others
  8471. styletag.appendChild(document.createTextNode(cssbody));
  8472. }
  8473. document.getElementsByTagName("head")[0].appendChild(styletag);
  8474. }
  8475. function createWorkerNode(document) {
  8476. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  8477. ,
  8478. frame = document.createElement('iframe');
  8479. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  8480. frame.name = frameID;
  8481. frame.setAttribute("width", 0);
  8482. frame.setAttribute("height", 0);
  8483. frame.setAttribute("frameborder", "0");
  8484. frame.setAttribute("scrolling", "no");
  8485. frame.setAttribute("seamless", "seamless");
  8486. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  8487. document.body.appendChild(frame);
  8488. return frame;
  8489. }
  8490. function attachSVGToWorkerNode(svgtext, frame) {
  8491. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  8492. framedoc.write(svgtext);
  8493. framedoc.close();
  8494. return framedoc.getElementsByTagName('svg')[0];
  8495. }
  8496. function convertPathToPDFLinesArgs(path) {
  8497. 'use strict';
  8498. // we will use 'lines' method call. it needs:
  8499. // - starting coordinate pair
  8500. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  8501. // - scale array [horizontal, vertical] ratios
  8502. // - style (stroke, fill, both)
  8503. var x = parseFloat(path[1]),
  8504. y = parseFloat(path[2]),
  8505. vectors = [],
  8506. position = 3,
  8507. len = path.length;
  8508. while (position < len) {
  8509. if (path[position] === 'c') {
  8510. 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])]);
  8511. position += 7;
  8512. } else if (path[position] === 'l') {
  8513. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  8514. position += 3;
  8515. } else {
  8516. position += 1;
  8517. }
  8518. }
  8519. return [x, y, vectors];
  8520. }
  8521. var workernode = createWorkerNode(document),
  8522. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  8523. scale = [1, 1],
  8524. svgw = parseFloat(svgnode.getAttribute('width')),
  8525. svgh = parseFloat(svgnode.getAttribute('height'));
  8526. if (svgw && svgh) {
  8527. // setting both w and h makes image stretch to size.
  8528. // this may distort the image, but fits your demanded size
  8529. if (w && h) {
  8530. scale = [w / svgw, h / svgh];
  8531. }
  8532. // if only one is set, that value is set as max and SVG
  8533. // is scaled proportionately.
  8534. else if (w) {
  8535. scale = [w / svgw, w / svgw];
  8536. } else if (h) {
  8537. scale = [h / svgh, h / svgh];
  8538. }
  8539. }
  8540. var i,
  8541. l,
  8542. tmp,
  8543. linesargs,
  8544. items = svgnode.childNodes;
  8545. for (i = 0, l = items.length; i < l; i++) {
  8546. tmp = items[i];
  8547. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  8548. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
  8549. // path start x coordinate
  8550. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  8551. // path start y coordinate
  8552. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  8553. // the rest of lines are vectors. these will adjust with scale value auto.
  8554. this.lines.call(this, linesargs[2] // lines
  8555. , linesargs[0] // starting x
  8556. , linesargs[1] // starting y
  8557. , scale);
  8558. }
  8559. }
  8560. // clean up
  8561. // workernode.parentNode.removeChild(workernode)
  8562. return this;
  8563. };
  8564. })(jsPDF.API);
  8565. /** ====================================================================
  8566. * jsPDF total_pages plugin
  8567. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  8568. *
  8569. *
  8570. * ====================================================================
  8571. */
  8572. (function(jsPDFAPI) {
  8573. 'use strict';
  8574. jsPDFAPI.putTotalPages = function(pageExpression) {
  8575. 'use strict';
  8576. var replaceExpression = new RegExp(pageExpression, 'g');
  8577. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  8578. for (var i = 0; i < this.internal.pages[n].length; i++) {
  8579. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
  8580. }
  8581. }
  8582. return this;
  8583. };
  8584. })(jsPDF.API);
  8585. /** ====================================================================
  8586. * jsPDF XMP metadata plugin
  8587. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  8588. *
  8589. *
  8590. * ====================================================================
  8591. */
  8592. /*global jsPDF */
  8593. /**
  8594. * Adds XMP formatted metadata to PDF
  8595. *
  8596. * @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.
  8597. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  8598. * @function
  8599. * @returns {jsPDF}
  8600. * @methodOf jsPDF#
  8601. * @name addMetadata
  8602. */
  8603. (function(jsPDFAPI) {
  8604. 'use strict';
  8605. var xmpmetadata = "";
  8606. var xmpnamespaceuri = "";
  8607. var metadata_object_number = "";
  8608. jsPDFAPI.addMetadata = function(metadata, namespaceuri) {
  8609. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  8610. xmpmetadata = metadata;
  8611. this.internal.events.subscribe('postPutResources', function() {
  8612. if (!xmpmetadata) {
  8613. metadata_object_number = "";
  8614. } else {
  8615. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  8616. 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>';
  8617. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  8618. var xmpmeta_ending = '</x:xmpmeta>';
  8619. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  8620. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  8621. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  8622. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  8623. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  8624. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  8625. metadata_object_number = this.internal.newObject();
  8626. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  8627. this.internal.write('stream');
  8628. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  8629. this.internal.write('endstream');
  8630. this.internal.write('endobj');
  8631. }
  8632. });
  8633. this.internal.events.subscribe('putCatalog', function() {
  8634. if (metadata_object_number) {
  8635. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  8636. }
  8637. });
  8638. return this;
  8639. };
  8640. })(jsPDF.API);
  8641. /* Blob.js
  8642. * A Blob implementation.
  8643. * 2014-07-24
  8644. *
  8645. * By Eli Grey, http://eligrey.com
  8646. * By Devin Samarin, https://github.com/dsamarin
  8647. * License: X11/MIT
  8648. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  8649. */
  8650. /*global self, unescape */
  8651. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  8652. plusplus: true */
  8653. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  8654. (function(view) {
  8655. "use strict";
  8656. view.URL = view.URL || view.webkitURL;
  8657. if (view.Blob && view.URL) {
  8658. try {
  8659. new Blob;
  8660. return;
  8661. } catch (e) {}
  8662. }
  8663. // Internally we use a BlobBuilder implementation to base Blob off of
  8664. // in order to support older browsers that only have BlobBuilder
  8665. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  8666. var
  8667. get_class = function(object) {
  8668. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  8669. },
  8670. FakeBlobBuilder = function BlobBuilder() {
  8671. this.data = [];
  8672. },
  8673. FakeBlob = function Blob(data, type, encoding) {
  8674. this.data = data;
  8675. this.size = data.length;
  8676. this.type = type;
  8677. this.encoding = encoding;
  8678. },
  8679. FBB_proto = FakeBlobBuilder.prototype,
  8680. FB_proto = FakeBlob.prototype,
  8681. FileReaderSync = view.FileReaderSync,
  8682. FileException = function(type) {
  8683. this.code = this[this.name = type];
  8684. },
  8685. file_ex_codes = (
  8686. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR " +
  8687. "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  8688. ).split(" "),
  8689. file_ex_code = file_ex_codes.length,
  8690. real_URL = view.URL || view.webkitURL || view,
  8691. real_create_object_URL = real_URL.createObjectURL,
  8692. real_revoke_object_URL = real_URL.revokeObjectURL,
  8693. URL = real_URL,
  8694. btoa = view.btoa,
  8695. atob = view.atob
  8696. , ArrayBuffer = view.ArrayBuffer, Uint8Array = view.Uint8Array
  8697. , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;
  8698. FakeBlob.fake = FB_proto.fake = true;
  8699. while (file_ex_code--) {
  8700. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  8701. }
  8702. // Polyfill URL
  8703. if (!real_URL.createObjectURL) {
  8704. URL = view.URL = function(uri) {
  8705. var
  8706. uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a"),
  8707. uri_origin;
  8708. uri_info.href = uri;
  8709. if (!("origin" in uri_info)) {
  8710. if (uri_info.protocol.toLowerCase() === "data:") {
  8711. uri_info.origin = null;
  8712. } else {
  8713. uri_origin = uri.match(origin);
  8714. uri_info.origin = uri_origin && uri_origin[1];
  8715. }
  8716. }
  8717. return uri_info;
  8718. };
  8719. }
  8720. URL.createObjectURL = function(blob) {
  8721. var
  8722. type = blob.type,
  8723. data_URI_header;
  8724. if (type === null) {
  8725. type = "application/octet-stream";
  8726. }
  8727. if (blob instanceof FakeBlob) {
  8728. data_URI_header = "data:" + type;
  8729. if (blob.encoding === "base64") {
  8730. return data_URI_header + ";base64," + blob.data;
  8731. } else if (blob.encoding === "URI") {
  8732. return data_URI_header + "," + decodeURIComponent(blob.data);
  8733. }
  8734. if (btoa) {
  8735. return data_URI_header + ";base64," + btoa(blob.data);
  8736. } else {
  8737. return data_URI_header + "," + encodeURIComponent(blob.data);
  8738. }
  8739. } else if (real_create_object_URL) {
  8740. return real_create_object_URL.call(real_URL, blob);
  8741. }
  8742. };
  8743. URL.revokeObjectURL = function(object_URL) {
  8744. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  8745. real_revoke_object_URL.call(real_URL, object_URL);
  8746. }
  8747. };
  8748. FBB_proto.append = function(data /*, endings*/ ) {
  8749. var bb = this.data;
  8750. // decode data to a binary string
  8751. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  8752. var
  8753. str = "",
  8754. buf = new Uint8Array(data),
  8755. i = 0,
  8756. buf_len = buf.length;
  8757. for (; i < buf_len; i++) {
  8758. str += String.fromCharCode(buf[i]);
  8759. }
  8760. bb.push(str);
  8761. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  8762. if (FileReaderSync) {
  8763. var fr = new FileReaderSync;
  8764. bb.push(fr.readAsBinaryString(data));
  8765. } else {
  8766. // async FileReader won't work as BlobBuilder is sync
  8767. throw new FileException("NOT_READABLE_ERR");
  8768. }
  8769. } else if (data instanceof FakeBlob) {
  8770. if (data.encoding === "base64" && atob) {
  8771. bb.push(atob(data.data));
  8772. } else if (data.encoding === "URI") {
  8773. bb.push(decodeURIComponent(data.data));
  8774. } else if (data.encoding === "raw") {
  8775. bb.push(data.data);
  8776. }
  8777. } else {
  8778. if (typeof data !== "string") {
  8779. data += ""; // convert unsupported types to strings
  8780. }
  8781. // decode UTF-16 to binary string
  8782. bb.push(unescape(encodeURIComponent(data)));
  8783. }
  8784. };
  8785. FBB_proto.getBlob = function(type) {
  8786. if (!arguments.length) {
  8787. type = null;
  8788. }
  8789. return new FakeBlob(this.data.join(""), type, "raw");
  8790. };
  8791. FBB_proto.toString = function() {
  8792. return "[object BlobBuilder]";
  8793. };
  8794. FB_proto.slice = function(start, end, type) {
  8795. var args = arguments.length;
  8796. if (args < 3) {
  8797. type = null;
  8798. }
  8799. return new FakeBlob(
  8800. this.data.slice(start, args > 1 ? end : this.data.length), type, this.encoding
  8801. );
  8802. };
  8803. FB_proto.toString = function() {
  8804. return "[object Blob]";
  8805. };
  8806. FB_proto.close = function() {
  8807. this.size = 0;
  8808. delete this.data;
  8809. };
  8810. return FakeBlobBuilder;
  8811. }(view));
  8812. view.Blob = function(blobParts, options) {
  8813. var type = options ? (options.type || "") : "";
  8814. var builder = new BlobBuilder();
  8815. if (blobParts) {
  8816. for (var i = 0, len = blobParts.length; i < len; i++) {
  8817. if (Uint8Array && blobParts[i] instanceof Uint8Array) {
  8818. builder.append(blobParts[i].buffer);
  8819. } else {
  8820. builder.append(blobParts[i]);
  8821. }
  8822. }
  8823. }
  8824. var blob = builder.getBlob(type);
  8825. if (!blob.slice && blob.webkitSlice) {
  8826. blob.slice = blob.webkitSlice;
  8827. }
  8828. return blob;
  8829. };
  8830. var getPrototypeOf = Object.getPrototypeOf || function(object) {
  8831. return object.__proto__;
  8832. };
  8833. view.Blob.prototype = getPrototypeOf(new view.Blob());
  8834. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
  8835. /* FileSaver.js
  8836. * A saveAs() FileSaver implementation.
  8837. * 1.3.2
  8838. * 2016-06-16 18:25:19
  8839. *
  8840. * By Eli Grey, http://eligrey.com
  8841. * License: MIT
  8842. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  8843. */
  8844. /*global self */
  8845. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  8846. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  8847. var saveAs = saveAs || (function(view) {
  8848. "use strict";
  8849. // IE <10 is explicitly unsupported
  8850. if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  8851. return;
  8852. }
  8853. var
  8854. doc = view.document
  8855. // only get URL when necessary in case Blob.js hasn't overridden it yet
  8856. ,
  8857. get_URL = function() {
  8858. return view.URL || view.webkitURL || view;
  8859. },
  8860. save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
  8861. can_use_save_link = "download" in save_link,
  8862. click = function(node) {
  8863. var event = new MouseEvent("click");
  8864. node.dispatchEvent(event);
  8865. },
  8866. is_safari = /constructor/i.test(view.HTMLElement) || view.safari,
  8867. is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent),
  8868. throw_outside = function(ex) {
  8869. (view.setImmediate || view.setTimeout)(function() {
  8870. throw ex;
  8871. }, 0);
  8872. },
  8873. force_saveable_type = "application/octet-stream"
  8874. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  8875. ,
  8876. arbitrary_revoke_timeout = 1000 * 40 // in ms
  8877. ,
  8878. revoke = function(file) {
  8879. var revoker = function() {
  8880. if (typeof file === "string") { // file is an object URL
  8881. get_URL().revokeObjectURL(file);
  8882. } else { // file is a File
  8883. file.remove();
  8884. }
  8885. };
  8886. setTimeout(revoker, arbitrary_revoke_timeout);
  8887. },
  8888. dispatch = function(filesaver, event_types, event) {
  8889. event_types = [].concat(event_types);
  8890. var i = event_types.length;
  8891. while (i--) {
  8892. var listener = filesaver["on" + event_types[i]];
  8893. if (typeof listener === "function") {
  8894. try {
  8895. listener.call(filesaver, event || filesaver);
  8896. } catch (ex) {
  8897. throw_outside(ex);
  8898. }
  8899. }
  8900. }
  8901. },
  8902. auto_bom = function(blob) {
  8903. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  8904. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  8905. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  8906. return new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type });
  8907. }
  8908. return blob;
  8909. },
  8910. FileSaver = function(blob, name, no_auto_bom) {
  8911. if (!no_auto_bom) {
  8912. blob = auto_bom(blob);
  8913. }
  8914. // First try a.download, then web filesystem, then object URLs
  8915. var
  8916. filesaver = this,
  8917. type = blob.type,
  8918. force = type === force_saveable_type,
  8919. object_url, dispatch_all = function() {
  8920. dispatch(filesaver, "writestart progress write writeend".split(" "));
  8921. }
  8922. // on any filesys errors revert to saving with object URLs
  8923. ,
  8924. fs_error = function() {
  8925. if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
  8926. // Safari doesn't allow downloading of blob urls
  8927. var reader = new FileReader();
  8928. reader.onloadend = function() {
  8929. var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
  8930. var popup = view.open(url, '_blank');
  8931. if (!popup) view.location.href = url;
  8932. url = undefined; // release reference before dispatching
  8933. filesaver.readyState = filesaver.DONE;
  8934. dispatch_all();
  8935. };
  8936. reader.readAsDataURL(blob);
  8937. filesaver.readyState = filesaver.INIT;
  8938. return;
  8939. }
  8940. // don't create more object URLs than needed
  8941. if (!object_url) {
  8942. object_url = get_URL().createObjectURL(blob);
  8943. }
  8944. if (force) {
  8945. view.location.href = object_url;
  8946. } else {
  8947. var opened = view.open(object_url, "_blank");
  8948. if (!opened) {
  8949. // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
  8950. view.location.href = object_url;
  8951. }
  8952. }
  8953. filesaver.readyState = filesaver.DONE;
  8954. dispatch_all();
  8955. revoke(object_url);
  8956. };
  8957. filesaver.readyState = filesaver.INIT;
  8958. if (can_use_save_link) {
  8959. object_url = get_URL().createObjectURL(blob);
  8960. setTimeout(function() {
  8961. save_link.href = object_url;
  8962. save_link.download = name;
  8963. click(save_link);
  8964. dispatch_all();
  8965. revoke(object_url);
  8966. filesaver.readyState = filesaver.DONE;
  8967. });
  8968. return;
  8969. }
  8970. fs_error();
  8971. },
  8972. FS_proto = FileSaver.prototype,
  8973. saveAs = function(blob, name, no_auto_bom) {
  8974. return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
  8975. };
  8976. // IE 10+ (native saveAs)
  8977. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  8978. return function(blob, name, no_auto_bom) {
  8979. name = name || blob.name || "download";
  8980. if (!no_auto_bom) {
  8981. blob = auto_bom(blob);
  8982. }
  8983. return navigator.msSaveOrOpenBlob(blob, name);
  8984. };
  8985. }
  8986. FS_proto.abort = function() {};
  8987. FS_proto.readyState = FS_proto.INIT = 0;
  8988. FS_proto.WRITING = 1;
  8989. FS_proto.DONE = 2;
  8990. FS_proto.error =
  8991. FS_proto.onwritestart =
  8992. FS_proto.onprogress =
  8993. FS_proto.onwrite =
  8994. FS_proto.onabort =
  8995. FS_proto.onerror =
  8996. FS_proto.onwriteend =
  8997. null;
  8998. return saveAs;
  8999. }(
  9000. typeof self !== "undefined" && self ||
  9001. typeof window !== "undefined" && window ||
  9002. undefined.content
  9003. ));
  9004. // `self` is undefined in Firefox for Android content script context
  9005. // while `this` is nsIContentFrameMessageManager
  9006. // with an attribute `content` that corresponds to the window
  9007. if (typeof module !== "undefined" && module.exports) {
  9008. module.exports.saveAs = saveAs;
  9009. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  9010. define("FileSaver.js", function() {
  9011. return saveAs;
  9012. });
  9013. }
  9014. /*
  9015. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  9016. *
  9017. * Licensed under the MIT License.
  9018. * http://opensource.org/licenses/mit-license
  9019. */
  9020. void
  9021. function(global, callback) {
  9022. if (typeof module === 'object') {
  9023. module.exports = callback();
  9024. } else if (typeof define === 'function') {
  9025. define(callback);
  9026. } else {
  9027. global.adler32cs = callback();
  9028. }
  9029. }(jsPDF, function() {
  9030. var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
  9031. typeof Uint8Array === 'function';
  9032. var _Buffer = null,
  9033. _isBuffer = (function() {
  9034. if (!_hasArrayBuffer)
  9035. return function _isBuffer() { return false };
  9036. try {
  9037. var buffer = {};
  9038. if (typeof buffer.Buffer === 'function')
  9039. _Buffer = buffer.Buffer;
  9040. } catch (error) {}
  9041. return function _isBuffer(value) {
  9042. return value instanceof ArrayBuffer ||
  9043. _Buffer !== null && value instanceof _Buffer;
  9044. };
  9045. }());
  9046. var _utf8ToBinary = (function() {
  9047. if (_Buffer !== null) {
  9048. return function _utf8ToBinary(utf8String) {
  9049. return new _Buffer(utf8String, 'utf8').toString('binary');
  9050. };
  9051. } else {
  9052. return function _utf8ToBinary(utf8String) {
  9053. return unescape(encodeURIComponent(utf8String));
  9054. };
  9055. }
  9056. }());
  9057. var MOD = 65521;
  9058. var _update = function _update(checksum, binaryString) {
  9059. var a = checksum & 0xFFFF,
  9060. b = checksum >>> 16;
  9061. for (var i = 0, length = binaryString.length; i < length; i++) {
  9062. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  9063. b = (b + a) % MOD;
  9064. }
  9065. return (b << 16 | a) >>> 0;
  9066. };
  9067. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  9068. var a = checksum & 0xFFFF,
  9069. b = checksum >>> 16;
  9070. for (var i = 0, length = uint8Array.length; i < length; i++) {
  9071. a = (a + uint8Array[i]) % MOD;
  9072. b = (b + a) % MOD;
  9073. }
  9074. return (b << 16 | a) >>> 0
  9075. };
  9076. var exports = {};
  9077. var Adler32 = exports.Adler32 = (function() {
  9078. var ctor = function Adler32(checksum) {
  9079. if (!(this instanceof ctor)) {
  9080. throw new TypeError(
  9081. 'Constructor cannot called be as a function.');
  9082. }
  9083. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  9084. throw new Error(
  9085. 'First arguments needs to be a finite number.');
  9086. }
  9087. this.checksum = checksum >>> 0;
  9088. };
  9089. var proto = ctor.prototype = {};
  9090. proto.constructor = ctor;
  9091. ctor.from = function(from) {
  9092. from.prototype = proto;
  9093. return from;
  9094. }(function from(binaryString) {
  9095. if (!(this instanceof ctor)) {
  9096. throw new TypeError(
  9097. 'Constructor cannot called be as a function.');
  9098. }
  9099. if (binaryString == null)
  9100. throw new Error('First argument needs to be a string.');
  9101. this.checksum = _update(1, binaryString.toString());
  9102. });
  9103. ctor.fromUtf8 = function(fromUtf8) {
  9104. fromUtf8.prototype = proto;
  9105. return fromUtf8;
  9106. }(function fromUtf8(utf8String) {
  9107. if (!(this instanceof ctor)) {
  9108. throw new TypeError(
  9109. 'Constructor cannot called be as a function.');
  9110. }
  9111. if (utf8String == null)
  9112. throw new Error('First argument needs to be a string.');
  9113. var binaryString = _utf8ToBinary(utf8String.toString());
  9114. this.checksum = _update(1, binaryString);
  9115. });
  9116. if (_hasArrayBuffer) {
  9117. ctor.fromBuffer = function(fromBuffer) {
  9118. fromBuffer.prototype = proto;
  9119. return fromBuffer;
  9120. }(function fromBuffer(buffer) {
  9121. if (!(this instanceof ctor)) {
  9122. throw new TypeError(
  9123. 'Constructor cannot called be as a function.');
  9124. }
  9125. if (!_isBuffer(buffer))
  9126. throw new Error('First argument needs to be ArrayBuffer.');
  9127. var array = new Uint8Array(buffer);
  9128. return this.checksum = _updateUint8Array(1, array);
  9129. });
  9130. }
  9131. proto.update = function update(binaryString) {
  9132. if (binaryString == null)
  9133. throw new Error('First argument needs to be a string.');
  9134. binaryString = binaryString.toString();
  9135. return this.checksum = _update(this.checksum, binaryString);
  9136. };
  9137. proto.updateUtf8 = function updateUtf8(utf8String) {
  9138. if (utf8String == null)
  9139. throw new Error('First argument needs to be a string.');
  9140. var binaryString = _utf8ToBinary(utf8String.toString());
  9141. return this.checksum = _update(this.checksum, binaryString);
  9142. };
  9143. if (_hasArrayBuffer) {
  9144. proto.updateBuffer = function updateBuffer(buffer) {
  9145. if (!_isBuffer(buffer))
  9146. throw new Error('First argument needs to be ArrayBuffer.');
  9147. var array = new Uint8Array(buffer);
  9148. return this.checksum = _updateUint8Array(this.checksum, array);
  9149. };
  9150. }
  9151. proto.clone = function clone() {
  9152. return new Adler32(this.checksum);
  9153. };
  9154. return ctor;
  9155. }());
  9156. exports.from = function from(binaryString) {
  9157. if (binaryString == null)
  9158. throw new Error('First argument needs to be a string.');
  9159. return _update(1, binaryString.toString());
  9160. };
  9161. exports.fromUtf8 = function fromUtf8(utf8String) {
  9162. if (utf8String == null)
  9163. throw new Error('First argument needs to be a string.');
  9164. var binaryString = _utf8ToBinary(utf8String.toString());
  9165. return _update(1, binaryString);
  9166. };
  9167. if (_hasArrayBuffer) {
  9168. exports.fromBuffer = function fromBuffer(buffer) {
  9169. if (!_isBuffer(buffer))
  9170. throw new Error('First argument need to be ArrayBuffer.');
  9171. var array = new Uint8Array(buffer);
  9172. return _updateUint8Array(1, array);
  9173. };
  9174. }
  9175. return exports;
  9176. });
  9177. /**
  9178. * CssColors
  9179. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  9180. *
  9181. * Licensed under the MIT License.
  9182. * http://opensource.org/licenses/mit-license
  9183. */
  9184. /**
  9185. * Usage CssColors('red');
  9186. * Returns RGB hex color with '#' prefix
  9187. */
  9188. var CssColors = {};
  9189. CssColors._colorsTable = {
  9190. "aliceblue": "#f0f8ff",
  9191. "antiquewhite": "#faebd7",
  9192. "aqua": "#00ffff",
  9193. "aquamarine": "#7fffd4",
  9194. "azure": "#f0ffff",
  9195. "beige": "#f5f5dc",
  9196. "bisque": "#ffe4c4",
  9197. "black": "#000000",
  9198. "blanchedalmond": "#ffebcd",
  9199. "blue": "#0000ff",
  9200. "blueviolet": "#8a2be2",
  9201. "brown": "#a52a2a",
  9202. "burlywood": "#deb887",
  9203. "cadetblue": "#5f9ea0",
  9204. "chartreuse": "#7fff00",
  9205. "chocolate": "#d2691e",
  9206. "coral": "#ff7f50",
  9207. "cornflowerblue": "#6495ed",
  9208. "cornsilk": "#fff8dc",
  9209. "crimson": "#dc143c",
  9210. "cyan": "#00ffff",
  9211. "darkblue": "#00008b",
  9212. "darkcyan": "#008b8b",
  9213. "darkgoldenrod": "#b8860b",
  9214. "darkgray": "#a9a9a9",
  9215. "darkgreen": "#006400",
  9216. "darkkhaki": "#bdb76b",
  9217. "darkmagenta": "#8b008b",
  9218. "darkolivegreen": "#556b2f",
  9219. "darkorange": "#ff8c00",
  9220. "darkorchid": "#9932cc",
  9221. "darkred": "#8b0000",
  9222. "darksalmon": "#e9967a",
  9223. "darkseagreen": "#8fbc8f",
  9224. "darkslateblue": "#483d8b",
  9225. "darkslategray": "#2f4f4f",
  9226. "darkturquoise": "#00ced1",
  9227. "darkviolet": "#9400d3",
  9228. "deeppink": "#ff1493",
  9229. "deepskyblue": "#00bfff",
  9230. "dimgray": "#696969",
  9231. "dodgerblue": "#1e90ff",
  9232. "firebrick": "#b22222",
  9233. "floralwhite": "#fffaf0",
  9234. "forestgreen": "#228b22",
  9235. "fuchsia": "#ff00ff",
  9236. "gainsboro": "#dcdcdc",
  9237. "ghostwhite": "#f8f8ff",
  9238. "gold": "#ffd700",
  9239. "goldenrod": "#daa520",
  9240. "gray": "#808080",
  9241. "green": "#008000",
  9242. "greenyellow": "#adff2f",
  9243. "honeydew": "#f0fff0",
  9244. "hotpink": "#ff69b4",
  9245. "indianred ": "#cd5c5c",
  9246. "indigo": "#4b0082",
  9247. "ivory": "#fffff0",
  9248. "khaki": "#f0e68c",
  9249. "lavender": "#e6e6fa",
  9250. "lavenderblush": "#fff0f5",
  9251. "lawngreen": "#7cfc00",
  9252. "lemonchiffon": "#fffacd",
  9253. "lightblue": "#add8e6",
  9254. "lightcoral": "#f08080",
  9255. "lightcyan": "#e0ffff",
  9256. "lightgoldenrodyellow": "#fafad2",
  9257. "lightgrey": "#d3d3d3",
  9258. "lightgreen": "#90ee90",
  9259. "lightpink": "#ffb6c1",
  9260. "lightsalmon": "#ffa07a",
  9261. "lightseagreen": "#20b2aa",
  9262. "lightskyblue": "#87cefa",
  9263. "lightslategray": "#778899",
  9264. "lightsteelblue": "#b0c4de",
  9265. "lightyellow": "#ffffe0",
  9266. "lime": "#00ff00",
  9267. "limegreen": "#32cd32",
  9268. "linen": "#faf0e6",
  9269. "magenta": "#ff00ff",
  9270. "maroon": "#800000",
  9271. "mediumaquamarine": "#66cdaa",
  9272. "mediumblue": "#0000cd",
  9273. "mediumorchid": "#ba55d3",
  9274. "mediumpurple": "#9370d8",
  9275. "mediumseagreen": "#3cb371",
  9276. "mediumslateblue": "#7b68ee",
  9277. "mediumspringgreen": "#00fa9a",
  9278. "mediumturquoise": "#48d1cc",
  9279. "mediumvioletred": "#c71585",
  9280. "midnightblue": "#191970",
  9281. "mintcream": "#f5fffa",
  9282. "mistyrose": "#ffe4e1",
  9283. "moccasin": "#ffe4b5",
  9284. "navajowhite": "#ffdead",
  9285. "navy": "#000080",
  9286. "oldlace": "#fdf5e6",
  9287. "olive": "#808000",
  9288. "olivedrab": "#6b8e23",
  9289. "orange": "#ffa500",
  9290. "orangered": "#ff4500",
  9291. "orchid": "#da70d6",
  9292. "palegoldenrod": "#eee8aa",
  9293. "palegreen": "#98fb98",
  9294. "paleturquoise": "#afeeee",
  9295. "palevioletred": "#d87093",
  9296. "papayawhip": "#ffefd5",
  9297. "peachpuff": "#ffdab9",
  9298. "peru": "#cd853f",
  9299. "pink": "#ffc0cb",
  9300. "plum": "#dda0dd",
  9301. "powderblue": "#b0e0e6",
  9302. "purple": "#800080",
  9303. "red": "#ff0000",
  9304. "rosybrown": "#bc8f8f",
  9305. "royalblue": "#4169e1",
  9306. "saddlebrown": "#8b4513",
  9307. "salmon": "#fa8072",
  9308. "sandybrown": "#f4a460",
  9309. "seagreen": "#2e8b57",
  9310. "seashell": "#fff5ee",
  9311. "sienna": "#a0522d",
  9312. "silver": "#c0c0c0",
  9313. "skyblue": "#87ceeb",
  9314. "slateblue": "#6a5acd",
  9315. "slategray": "#708090",
  9316. "snow": "#fffafa",
  9317. "springgreen": "#00ff7f",
  9318. "steelblue": "#4682b4",
  9319. "tan": "#d2b48c",
  9320. "teal": "#008080",
  9321. "thistle": "#d8bfd8",
  9322. "tomato": "#ff6347",
  9323. "turquoise": "#40e0d0",
  9324. "violet": "#ee82ee",
  9325. "wheat": "#f5deb3",
  9326. "white": "#ffffff",
  9327. "whitesmoke": "#f5f5f5",
  9328. "yellow": "#ffff00",
  9329. "yellowgreen": "#9acd32"
  9330. };
  9331. CssColors.colorNameToHex = function(color) {
  9332. color = color.toLowerCase();
  9333. if (typeof this._colorsTable[color] != 'undefined')
  9334. return this._colorsTable[color];
  9335. return false;
  9336. };
  9337. /*
  9338. Deflate.js - https://github.com/gildas-lormeau/zip.js
  9339. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  9340. Redistribution and use in source and binary forms, with or without
  9341. modification, are permitted provided that the following conditions are met:
  9342. 1. Redistributions of source code must retain the above copyright notice,
  9343. this list of conditions and the following disclaimer.
  9344. 2. Redistributions in binary form must reproduce the above copyright
  9345. notice, this list of conditions and the following disclaimer in
  9346. the documentation and/or other materials provided with the distribution.
  9347. 3. The names of the authors may not be used to endorse or promote products
  9348. derived from this software without specific prior written permission.
  9349. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  9350. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9351. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  9352. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  9353. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9354. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  9355. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  9356. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  9357. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  9358. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9359. */
  9360. /*
  9361. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  9362. * JZlib is based on zlib-1.1.3, so all credit should go authors
  9363. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  9364. * and contributors of zlib.
  9365. */
  9366. var Deflater = (function(obj) {
  9367. // Global
  9368. var MAX_BITS = 15;
  9369. var D_CODES = 30;
  9370. var BL_CODES = 19;
  9371. var LENGTH_CODES = 29;
  9372. var LITERALS = 256;
  9373. var L_CODES = (LITERALS + 1 + LENGTH_CODES);
  9374. var HEAP_SIZE = (2 * L_CODES + 1);
  9375. var END_BLOCK = 256;
  9376. // Bit length codes must not exceed MAX_BL_BITS bits
  9377. var MAX_BL_BITS = 7;
  9378. // repeat previous bit length 3-6 times (2 bits of repeat count)
  9379. var REP_3_6 = 16;
  9380. // repeat a zero length 3-10 times (3 bits of repeat count)
  9381. var REPZ_3_10 = 17;
  9382. // repeat a zero length 11-138 times (7 bits of repeat count)
  9383. var REPZ_11_138 = 18;
  9384. // The lengths of the bit length codes are sent in order of decreasing
  9385. // probability, to avoid transmitting the lengths for unused bit
  9386. // length codes.
  9387. var Buf_size = 8 * 2;
  9388. // JZlib version : "1.0.2"
  9389. var Z_DEFAULT_COMPRESSION = -1;
  9390. // compression strategy
  9391. var Z_FILTERED = 1;
  9392. var Z_HUFFMAN_ONLY = 2;
  9393. var Z_DEFAULT_STRATEGY = 0;
  9394. var Z_NO_FLUSH = 0;
  9395. var Z_PARTIAL_FLUSH = 1;
  9396. var Z_FULL_FLUSH = 3;
  9397. var Z_FINISH = 4;
  9398. var Z_OK = 0;
  9399. var Z_STREAM_END = 1;
  9400. var Z_NEED_DICT = 2;
  9401. var Z_STREAM_ERROR = -2;
  9402. var Z_DATA_ERROR = -3;
  9403. var Z_BUF_ERROR = -5;
  9404. // Tree
  9405. // see definition of array dist_code below
  9406. 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,
  9407. 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,
  9408. 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,
  9409. 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,
  9410. 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,
  9411. 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,
  9412. 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,
  9413. 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,
  9414. 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,
  9415. 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,
  9416. 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,
  9417. 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,
  9418. 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,
  9419. 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
  9420. ];
  9421. function Tree() {
  9422. var that = this;
  9423. // dyn_tree; // the dynamic tree
  9424. // max_code; // largest code with non zero frequency
  9425. // stat_desc; // the corresponding static tree
  9426. // Compute the optimal bit lengths for a tree and update the total bit
  9427. // length
  9428. // for the current block.
  9429. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  9430. // above are the tree nodes sorted by increasing frequency.
  9431. // OUT assertions: the field len is set to the optimal bit length, the
  9432. // array bl_count contains the frequencies for each bit length.
  9433. // The length opt_len is updated; static_len is also updated if stree is
  9434. // not null.
  9435. function gen_bitlen(s) {
  9436. var tree = that.dyn_tree;
  9437. var stree = that.stat_desc.static_tree;
  9438. var extra = that.stat_desc.extra_bits;
  9439. var base = that.stat_desc.extra_base;
  9440. var max_length = that.stat_desc.max_length;
  9441. var h; // heap index
  9442. var n, m; // iterate over the tree elements
  9443. var bits; // bit length
  9444. var xbits; // extra bits
  9445. var f; // frequency
  9446. var overflow = 0; // number of elements with bit length too large
  9447. for (bits = 0; bits <= MAX_BITS; bits++)
  9448. s.bl_count[bits] = 0;
  9449. // In a first pass, compute the optimal bit lengths (which may
  9450. // overflow in the case of the bit length tree).
  9451. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  9452. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9453. n = s.heap[h];
  9454. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  9455. if (bits > max_length) {
  9456. bits = max_length;
  9457. overflow++;
  9458. }
  9459. tree[n * 2 + 1] = bits;
  9460. // We overwrite tree[n*2+1] which is no longer needed
  9461. if (n > that.max_code)
  9462. continue; // not a leaf node
  9463. s.bl_count[bits]++;
  9464. xbits = 0;
  9465. if (n >= base)
  9466. xbits = extra[n - base];
  9467. f = tree[n * 2];
  9468. s.opt_len += f * (bits + xbits);
  9469. if (stree)
  9470. s.static_len += f * (stree[n * 2 + 1] + xbits);
  9471. }
  9472. if (overflow === 0)
  9473. return;
  9474. // This happens for example on obj2 and pic of the Calgary corpus
  9475. // Find the first bit length which could increase:
  9476. do {
  9477. bits = max_length - 1;
  9478. while (s.bl_count[bits] === 0)
  9479. bits--;
  9480. s.bl_count[bits]--; // move one leaf down the tree
  9481. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  9482. s.bl_count[max_length]--;
  9483. // The brother of the overflow item also moves one step up,
  9484. // but this does not affect bl_count[max_length]
  9485. overflow -= 2;
  9486. } while (overflow > 0);
  9487. for (bits = max_length; bits !== 0; bits--) {
  9488. n = s.bl_count[bits];
  9489. while (n !== 0) {
  9490. m = s.heap[--h];
  9491. if (m > that.max_code)
  9492. continue;
  9493. if (tree[m * 2 + 1] != bits) {
  9494. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  9495. tree[m * 2 + 1] = bits;
  9496. }
  9497. n--;
  9498. }
  9499. }
  9500. }
  9501. // Reverse the first len bits of a code, using straightforward code (a
  9502. // faster
  9503. // method would use a table)
  9504. // IN assertion: 1 <= len <= 15
  9505. function bi_reverse(code, // the value to invert
  9506. len // its bit length
  9507. ) {
  9508. var res = 0;
  9509. do {
  9510. res |= code & 1;
  9511. code >>>= 1;
  9512. res <<= 1;
  9513. } while (--len > 0);
  9514. return res >>> 1;
  9515. }
  9516. // Generate the codes for a given tree and bit counts (which need not be
  9517. // optimal).
  9518. // IN assertion: the array bl_count contains the bit length statistics for
  9519. // the given tree and the field len is set for all tree elements.
  9520. // OUT assertion: the field code is set for all tree elements of non
  9521. // zero code length.
  9522. function gen_codes(tree, // the tree to decorate
  9523. max_code, // largest code with non zero frequency
  9524. bl_count // number of codes at each bit length
  9525. ) {
  9526. var next_code = []; // next code value for each
  9527. // bit length
  9528. var code = 0; // running code value
  9529. var bits; // bit index
  9530. var n; // code index
  9531. var len;
  9532. // The distribution counts are first used to generate the code values
  9533. // without bit reversal.
  9534. for (bits = 1; bits <= MAX_BITS; bits++) {
  9535. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  9536. }
  9537. // Check that the bit counts in bl_count are consistent. The last code
  9538. // must be all ones.
  9539. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9540. // "inconsistent bit counts");
  9541. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9542. for (n = 0; n <= max_code; n++) {
  9543. len = tree[n * 2 + 1];
  9544. if (len === 0)
  9545. continue;
  9546. // Now reverse the bits
  9547. tree[n * 2] = bi_reverse(next_code[len]++, len);
  9548. }
  9549. }
  9550. // Construct one Huffman tree and assigns the code bit strings and lengths.
  9551. // Update the total bit length for the current block.
  9552. // IN assertion: the field freq is set for all tree elements.
  9553. // OUT assertions: the fields len and code are set to the optimal bit length
  9554. // and corresponding code. The length opt_len is updated; static_len is
  9555. // also updated if stree is not null. The field max_code is set.
  9556. that.build_tree = function(s) {
  9557. var tree = that.dyn_tree;
  9558. var stree = that.stat_desc.static_tree;
  9559. var elems = that.stat_desc.elems;
  9560. var n, m; // iterate over heap elements
  9561. var max_code = -1; // largest code with non zero frequency
  9562. var node; // new node being created
  9563. // Construct the initial heap, with least frequent element in
  9564. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9565. // heap[0] is not used.
  9566. s.heap_len = 0;
  9567. s.heap_max = HEAP_SIZE;
  9568. for (n = 0; n < elems; n++) {
  9569. if (tree[n * 2] !== 0) {
  9570. s.heap[++s.heap_len] = max_code = n;
  9571. s.depth[n] = 0;
  9572. } else {
  9573. tree[n * 2 + 1] = 0;
  9574. }
  9575. }
  9576. // The pkzip format requires that at least one distance code exists,
  9577. // and that at least one bit should be sent even if there is only one
  9578. // possible code. So to avoid special checks later on we force at least
  9579. // two codes of non zero frequency.
  9580. while (s.heap_len < 2) {
  9581. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  9582. tree[node * 2] = 1;
  9583. s.depth[node] = 0;
  9584. s.opt_len--;
  9585. if (stree)
  9586. s.static_len -= stree[node * 2 + 1];
  9587. // node is 0 or 1 so it does not have extra bits
  9588. }
  9589. that.max_code = max_code;
  9590. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9591. // establish sub-heaps of increasing lengths:
  9592. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  9593. s.pqdownheap(tree, n);
  9594. // Construct the Huffman tree by repeatedly combining the least two
  9595. // frequent nodes.
  9596. node = elems; // next internal node of the tree
  9597. do {
  9598. // n = node of least frequency
  9599. n = s.heap[1];
  9600. s.heap[1] = s.heap[s.heap_len--];
  9601. s.pqdownheap(tree, 1);
  9602. m = s.heap[1]; // m = node of next least frequency
  9603. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  9604. s.heap[--s.heap_max] = m;
  9605. // Create a new node father of n and m
  9606. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  9607. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  9608. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  9609. // and insert the new node in the heap
  9610. s.heap[1] = node++;
  9611. s.pqdownheap(tree, 1);
  9612. } while (s.heap_len >= 2);
  9613. s.heap[--s.heap_max] = s.heap[1];
  9614. // At this point, the fields freq and dad are set. We can now
  9615. // generate the bit lengths.
  9616. gen_bitlen(s);
  9617. // The field len is now set, we can generate the bit codes
  9618. gen_codes(tree, that.max_code, s.bl_count);
  9619. };
  9620. }
  9621. 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,
  9622. 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,
  9623. 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,
  9624. 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,
  9625. 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,
  9626. 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,
  9627. 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
  9628. ];
  9629. 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];
  9630. 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,
  9631. 24576
  9632. ];
  9633. // Mapping from a distance to a distance code. dist is the distance - 1 and
  9634. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  9635. // used.
  9636. Tree.d_code = function(dist) {
  9637. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  9638. };
  9639. // extra bits for each length code
  9640. 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];
  9641. // extra bits for each distance code
  9642. 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];
  9643. // extra bits for each bit length code
  9644. Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  9645. Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  9646. // StaticTree
  9647. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  9648. var that = this;
  9649. that.static_tree = static_tree;
  9650. that.extra_bits = extra_bits;
  9651. that.extra_base = extra_base;
  9652. that.elems = elems;
  9653. that.max_length = max_length;
  9654. }
  9655. 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,
  9656. 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,
  9657. 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,
  9658. 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,
  9659. 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,
  9660. 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,
  9661. 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,
  9662. 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,
  9663. 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,
  9664. 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,
  9665. 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,
  9666. 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,
  9667. 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,
  9668. 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,
  9669. 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,
  9670. 99, 8, 227, 8
  9671. ];
  9672. 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,
  9673. 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5
  9674. ];
  9675. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9676. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  9677. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9678. // Deflate
  9679. var MAX_MEM_LEVEL = 9;
  9680. var DEF_MEM_LEVEL = 8;
  9681. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  9682. var that = this;
  9683. that.good_length = good_length;
  9684. that.max_lazy = max_lazy;
  9685. that.nice_length = nice_length;
  9686. that.max_chain = max_chain;
  9687. that.func = func;
  9688. }
  9689. var STORED = 0;
  9690. var FAST = 1;
  9691. var SLOW = 2;
  9692. 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),
  9693. 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),
  9694. new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW)
  9695. ];
  9696. var z_errmsg = ["need dictionary", // Z_NEED_DICT
  9697. // 2
  9698. "stream end", // Z_STREAM_END 1
  9699. "", // Z_OK 0
  9700. "", // Z_ERRNO (-1)
  9701. "stream error", // Z_STREAM_ERROR (-2)
  9702. "data error", // Z_DATA_ERROR (-3)
  9703. "", // Z_MEM_ERROR (-4)
  9704. "buffer error", // Z_BUF_ERROR (-5)
  9705. "", // Z_VERSION_ERROR (-6)
  9706. ""
  9707. ];
  9708. // block not completed, need more input or more output
  9709. var NeedMore = 0;
  9710. // block flush performed
  9711. var BlockDone = 1;
  9712. // finish started, need only more output at next deflate
  9713. var FinishStarted = 2;
  9714. // finish done, accept no more input or output
  9715. var FinishDone = 3;
  9716. // preset dictionary flag in zlib header
  9717. var PRESET_DICT = 0x20;
  9718. var INIT_STATE = 42;
  9719. var BUSY_STATE = 113;
  9720. var FINISH_STATE = 666;
  9721. // The deflate compression method
  9722. var Z_DEFLATED = 8;
  9723. var STORED_BLOCK = 0;
  9724. var STATIC_TREES = 1;
  9725. var DYN_TREES = 2;
  9726. var MIN_MATCH = 3;
  9727. var MAX_MATCH = 258;
  9728. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  9729. function smaller(tree, n, m, depth) {
  9730. var tn2 = tree[n * 2];
  9731. var tm2 = tree[m * 2];
  9732. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  9733. }
  9734. function Deflate() {
  9735. var that = this;
  9736. var strm; // pointer back to this zlib stream
  9737. var status; // as the name implies
  9738. // pending_buf; // output still pending
  9739. var pending_buf_size; // size of pending_buf
  9740. // pending_out; // next pending byte to output to the stream
  9741. // pending; // nb of bytes in the pending buffer
  9742. var last_flush; // value of flush param for previous deflate call
  9743. var w_size; // LZ77 window size (32K by default)
  9744. var w_bits; // log2(w_size) (8..16)
  9745. var w_mask; // w_size - 1
  9746. var window;
  9747. // Sliding window. Input bytes are read into the second half of the window,
  9748. // and move to the first half later to keep a dictionary of at least wSize
  9749. // bytes. With this organization, matches are limited to a distance of
  9750. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  9751. // performed with a length multiple of the block size. Also, it limits
  9752. // the window size to 64K, which is quite useful on MSDOS.
  9753. // To do: use the user input buffer as sliding window.
  9754. var window_size;
  9755. // Actual size of window: 2*wSize, except when the user input buffer
  9756. // is directly used as sliding window.
  9757. var prev;
  9758. // Link to older string with same hash index. To limit the size of this
  9759. // array to 64K, this link is maintained only for the last 32K strings.
  9760. // An index in this array is thus a window index modulo 32K.
  9761. var head; // Heads of the hash chains or NIL.
  9762. var ins_h; // hash index of string to be inserted
  9763. var hash_size; // number of elements in hash table
  9764. var hash_bits; // log2(hash_size)
  9765. var hash_mask; // hash_size-1
  9766. // Number of bits by which ins_h must be shifted at each input
  9767. // step. It must be such that after MIN_MATCH steps, the oldest
  9768. // byte no longer takes part in the hash key, that is:
  9769. // hash_shift * MIN_MATCH >= hash_bits
  9770. var hash_shift;
  9771. // Window position at the beginning of the current output block. Gets
  9772. // negative when the window is moved backwards.
  9773. var block_start;
  9774. var match_length; // length of best match
  9775. var prev_match; // previous match
  9776. var match_available; // set if previous match exists
  9777. var strstart; // start of string to insert
  9778. var match_start; // start of matching string
  9779. var lookahead; // number of valid bytes ahead in window
  9780. // Length of the best match at previous step. Matches not greater than this
  9781. // are discarded. This is used in the lazy match evaluation.
  9782. var prev_length;
  9783. // To speed up deflation, hash chains are never searched beyond this
  9784. // length. A higher limit improves compression ratio but degrades the speed.
  9785. var max_chain_length;
  9786. // Attempt to find a better match only when the current match is strictly
  9787. // smaller than this value. This mechanism is used only for compression
  9788. // levels >= 4.
  9789. var max_lazy_match;
  9790. // Insert new strings in the hash table only if the match length is not
  9791. // greater than this length. This saves time but degrades compression.
  9792. // max_insert_length is used only for compression levels <= 3.
  9793. var level; // compression level (1..9)
  9794. var strategy; // favor or force Huffman coding
  9795. // Use a faster search when the previous match is longer than this
  9796. var good_match;
  9797. // Stop searching when current match exceeds this
  9798. var nice_match;
  9799. var dyn_ltree; // literal and length tree
  9800. var dyn_dtree; // distance tree
  9801. var bl_tree; // Huffman tree for bit lengths
  9802. var l_desc = new Tree(); // desc for literal tree
  9803. var d_desc = new Tree(); // desc for distance tree
  9804. var bl_desc = new Tree(); // desc for bit length tree
  9805. // that.heap_len; // number of elements in the heap
  9806. // that.heap_max; // element of largest frequency
  9807. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  9808. // The same heap array is used to build all trees.
  9809. // Depth of each subtree used as tie breaker for trees of equal frequency
  9810. that.depth = [];
  9811. var l_buf; // index for literals or lengths */
  9812. // Size of match buffer for literals/lengths. There are 4 reasons for
  9813. // limiting lit_bufsize to 64K:
  9814. // - frequencies can be kept in 16 bit counters
  9815. // - if compression is not successful for the first block, all input
  9816. // data is still in the window so we can still emit a stored block even
  9817. // when input comes from standard input. (This can also be done for
  9818. // all blocks if lit_bufsize is not greater than 32K.)
  9819. // - if compression is not successful for a file smaller than 64K, we can
  9820. // even emit a stored file instead of a stored block (saving 5 bytes).
  9821. // This is applicable only for zip (not gzip or zlib).
  9822. // - creating new Huffman trees less frequently may not provide fast
  9823. // adaptation to changes in the input data statistics. (Take for
  9824. // example a binary file with poorly compressible code followed by
  9825. // a highly compressible string table.) Smaller buffer sizes give
  9826. // fast adaptation but have of course the overhead of transmitting
  9827. // trees more frequently.
  9828. // - I can't count above 4
  9829. var lit_bufsize;
  9830. var last_lit; // running index in l_buf
  9831. // Buffer for distances. To simplify the code, d_buf and l_buf have
  9832. // the same number of elements. To use different lengths, an extra flag
  9833. // array would be necessary.
  9834. var d_buf; // index of pendig_buf
  9835. // that.opt_len; // bit length of current block with optimal trees
  9836. // that.static_len; // bit length of current block with static trees
  9837. var matches; // number of string matches in current block
  9838. var last_eob_len; // bit length of EOB code for last block
  9839. // Output buffer. bits are inserted starting at the bottom (least
  9840. // significant bits).
  9841. var bi_buf;
  9842. // Number of valid bits in bi_buf. All bits above the last valid bit
  9843. // are always zero.
  9844. var bi_valid;
  9845. // number of codes at each bit length for an optimal tree
  9846. that.bl_count = [];
  9847. // heap used to build the Huffman trees
  9848. that.heap = [];
  9849. dyn_ltree = [];
  9850. dyn_dtree = [];
  9851. bl_tree = [];
  9852. function lm_init() {
  9853. var i;
  9854. window_size = 2 * w_size;
  9855. head[hash_size - 1] = 0;
  9856. for (i = 0; i < hash_size - 1; i++) {
  9857. head[i] = 0;
  9858. }
  9859. // Set the default configuration parameters:
  9860. max_lazy_match = config_table[level].max_lazy;
  9861. good_match = config_table[level].good_length;
  9862. nice_match = config_table[level].nice_length;
  9863. max_chain_length = config_table[level].max_chain;
  9864. strstart = 0;
  9865. block_start = 0;
  9866. lookahead = 0;
  9867. match_length = prev_length = MIN_MATCH - 1;
  9868. match_available = 0;
  9869. ins_h = 0;
  9870. }
  9871. function init_block() {
  9872. var i;
  9873. // Initialize the trees.
  9874. for (i = 0; i < L_CODES; i++)
  9875. dyn_ltree[i * 2] = 0;
  9876. for (i = 0; i < D_CODES; i++)
  9877. dyn_dtree[i * 2] = 0;
  9878. for (i = 0; i < BL_CODES; i++)
  9879. bl_tree[i * 2] = 0;
  9880. dyn_ltree[END_BLOCK * 2] = 1;
  9881. that.opt_len = that.static_len = 0;
  9882. last_lit = matches = 0;
  9883. }
  9884. // Initialize the tree data structures for a new zlib stream.
  9885. function tr_init() {
  9886. l_desc.dyn_tree = dyn_ltree;
  9887. l_desc.stat_desc = StaticTree.static_l_desc;
  9888. d_desc.dyn_tree = dyn_dtree;
  9889. d_desc.stat_desc = StaticTree.static_d_desc;
  9890. bl_desc.dyn_tree = bl_tree;
  9891. bl_desc.stat_desc = StaticTree.static_bl_desc;
  9892. bi_buf = 0;
  9893. bi_valid = 0;
  9894. last_eob_len = 8; // enough lookahead for inflate
  9895. // Initialize the first block of the first file:
  9896. init_block();
  9897. }
  9898. // Restore the heap property by moving down the tree starting at node k,
  9899. // exchanging a node with the smallest of its two sons if necessary,
  9900. // stopping
  9901. // when the heap property is re-established (each father smaller than its
  9902. // two sons).
  9903. that.pqdownheap = function(tree, // the tree to restore
  9904. k // node to move down
  9905. ) {
  9906. var heap = that.heap;
  9907. var v = heap[k];
  9908. var j = k << 1; // left son of k
  9909. while (j <= that.heap_len) {
  9910. // Set j to the smallest of the two sons:
  9911. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  9912. j++;
  9913. }
  9914. // Exit if v is smaller than both sons
  9915. if (smaller(tree, v, heap[j], that.depth))
  9916. break;
  9917. // Exchange v with the smallest son
  9918. heap[k] = heap[j];
  9919. k = j;
  9920. // And continue down the tree, setting j to the left son of k
  9921. j <<= 1;
  9922. }
  9923. heap[k] = v;
  9924. };
  9925. // Scan a literal or distance tree to determine the frequencies of the codes
  9926. // in the bit length tree.
  9927. function scan_tree(tree, // the tree to be scanned
  9928. max_code // and its largest code of non zero frequency
  9929. ) {
  9930. var n; // iterates over all tree elements
  9931. var prevlen = -1; // last emitted length
  9932. var curlen; // length of current code
  9933. var nextlen = tree[0 * 2 + 1]; // length of next code
  9934. var count = 0; // repeat count of the current code
  9935. var max_count = 7; // max repeat count
  9936. var min_count = 4; // min repeat count
  9937. if (nextlen === 0) {
  9938. max_count = 138;
  9939. min_count = 3;
  9940. }
  9941. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  9942. for (n = 0; n <= max_code; n++) {
  9943. curlen = nextlen;
  9944. nextlen = tree[(n + 1) * 2 + 1];
  9945. if (++count < max_count && curlen == nextlen) {
  9946. continue;
  9947. } else if (count < min_count) {
  9948. bl_tree[curlen * 2] += count;
  9949. } else if (curlen !== 0) {
  9950. if (curlen != prevlen)
  9951. bl_tree[curlen * 2]++;
  9952. bl_tree[REP_3_6 * 2]++;
  9953. } else if (count <= 10) {
  9954. bl_tree[REPZ_3_10 * 2]++;
  9955. } else {
  9956. bl_tree[REPZ_11_138 * 2]++;
  9957. }
  9958. count = 0;
  9959. prevlen = curlen;
  9960. if (nextlen === 0) {
  9961. max_count = 138;
  9962. min_count = 3;
  9963. } else if (curlen == nextlen) {
  9964. max_count = 6;
  9965. min_count = 3;
  9966. } else {
  9967. max_count = 7;
  9968. min_count = 4;
  9969. }
  9970. }
  9971. }
  9972. // Construct the Huffman tree for the bit lengths and return the index in
  9973. // bl_order of the last bit length code to send.
  9974. function build_bl_tree() {
  9975. var max_blindex; // index of last bit length code of non zero freq
  9976. // Determine the bit length frequencies for literal and distance trees
  9977. scan_tree(dyn_ltree, l_desc.max_code);
  9978. scan_tree(dyn_dtree, d_desc.max_code);
  9979. // Build the bit length tree:
  9980. bl_desc.build_tree(that);
  9981. // opt_len now includes the length of the tree representations, except
  9982. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  9983. // counts.
  9984. // Determine the number of bit length codes to send. The pkzip format
  9985. // requires that at least 4 bit length codes be sent. (appnote.txt says
  9986. // 3 but the actual value used is 4.)
  9987. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  9988. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  9989. break;
  9990. }
  9991. // Update opt_len to include the bit length tree and counts
  9992. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  9993. return max_blindex;
  9994. }
  9995. // Output a byte on the stream.
  9996. // IN assertion: there is enough room in pending_buf.
  9997. function put_byte(p) {
  9998. that.pending_buf[that.pending++] = p;
  9999. }
  10000. function put_short(w) {
  10001. put_byte(w & 0xff);
  10002. put_byte((w >>> 8) & 0xff);
  10003. }
  10004. function putShortMSB(b) {
  10005. put_byte((b >> 8) & 0xff);
  10006. put_byte((b & 0xff) & 0xff);
  10007. }
  10008. function send_bits(value, length) {
  10009. var val, len = length;
  10010. if (bi_valid > Buf_size - len) {
  10011. val = value;
  10012. // bi_buf |= (val << bi_valid);
  10013. bi_buf |= ((val << bi_valid) & 0xffff);
  10014. put_short(bi_buf);
  10015. bi_buf = val >>> (Buf_size - bi_valid);
  10016. bi_valid += len - Buf_size;
  10017. } else {
  10018. // bi_buf |= (value) << bi_valid;
  10019. bi_buf |= (((value) << bi_valid) & 0xffff);
  10020. bi_valid += len;
  10021. }
  10022. }
  10023. function send_code(c, tree) {
  10024. var c2 = c * 2;
  10025. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  10026. }
  10027. // Send a literal or distance tree in compressed form, using the codes in
  10028. // bl_tree.
  10029. function send_tree(tree, // the tree to be sent
  10030. max_code // and its largest code of non zero frequency
  10031. ) {
  10032. var n; // iterates over all tree elements
  10033. var prevlen = -1; // last emitted length
  10034. var curlen; // length of current code
  10035. var nextlen = tree[0 * 2 + 1]; // length of next code
  10036. var count = 0; // repeat count of the current code
  10037. var max_count = 7; // max repeat count
  10038. var min_count = 4; // min repeat count
  10039. if (nextlen === 0) {
  10040. max_count = 138;
  10041. min_count = 3;
  10042. }
  10043. for (n = 0; n <= max_code; n++) {
  10044. curlen = nextlen;
  10045. nextlen = tree[(n + 1) * 2 + 1];
  10046. if (++count < max_count && curlen == nextlen) {
  10047. continue;
  10048. } else if (count < min_count) {
  10049. do {
  10050. send_code(curlen, bl_tree);
  10051. } while (--count !== 0);
  10052. } else if (curlen !== 0) {
  10053. if (curlen != prevlen) {
  10054. send_code(curlen, bl_tree);
  10055. count--;
  10056. }
  10057. send_code(REP_3_6, bl_tree);
  10058. send_bits(count - 3, 2);
  10059. } else if (count <= 10) {
  10060. send_code(REPZ_3_10, bl_tree);
  10061. send_bits(count - 3, 3);
  10062. } else {
  10063. send_code(REPZ_11_138, bl_tree);
  10064. send_bits(count - 11, 7);
  10065. }
  10066. count = 0;
  10067. prevlen = curlen;
  10068. if (nextlen === 0) {
  10069. max_count = 138;
  10070. min_count = 3;
  10071. } else if (curlen == nextlen) {
  10072. max_count = 6;
  10073. min_count = 3;
  10074. } else {
  10075. max_count = 7;
  10076. min_count = 4;
  10077. }
  10078. }
  10079. }
  10080. // Send the header for a block using dynamic Huffman trees: the counts, the
  10081. // lengths of the bit length codes, the literal tree and the distance tree.
  10082. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10083. function send_all_trees(lcodes, dcodes, blcodes) {
  10084. var rank; // index in bl_order
  10085. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  10086. send_bits(dcodes - 1, 5);
  10087. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  10088. for (rank = 0; rank < blcodes; rank++) {
  10089. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  10090. }
  10091. send_tree(dyn_ltree, lcodes - 1); // literal tree
  10092. send_tree(dyn_dtree, dcodes - 1); // distance tree
  10093. }
  10094. // Flush the bit buffer, keeping at most 7 bits in it.
  10095. function bi_flush() {
  10096. if (bi_valid == 16) {
  10097. put_short(bi_buf);
  10098. bi_buf = 0;
  10099. bi_valid = 0;
  10100. } else if (bi_valid >= 8) {
  10101. put_byte(bi_buf & 0xff);
  10102. bi_buf >>>= 8;
  10103. bi_valid -= 8;
  10104. }
  10105. }
  10106. // Send one empty static block to give enough lookahead for inflate.
  10107. // This takes 10 bits, of which 7 may remain in the bit buffer.
  10108. // The current inflate code requires 9 bits of lookahead. If the
  10109. // last two codes for the previous block (real code plus EOB) were coded
  10110. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  10111. // the last real code. In this case we send two empty static blocks instead
  10112. // of one. (There are no problems if the previous block is stored or fixed.)
  10113. // To simplify the code, we assume the worst case of last real code encoded
  10114. // on one bit only.
  10115. function _tr_align() {
  10116. send_bits(STATIC_TREES << 1, 3);
  10117. send_code(END_BLOCK, StaticTree.static_ltree);
  10118. bi_flush();
  10119. // Of the 10 bits for the empty block, we have already sent
  10120. // (10 - bi_valid) bits. The lookahead for the last real code (before
  10121. // the EOB of the previous block) was thus at least one plus the length
  10122. // of the EOB plus what we have just sent of the empty static block.
  10123. if (1 + last_eob_len + 10 - bi_valid < 9) {
  10124. send_bits(STATIC_TREES << 1, 3);
  10125. send_code(END_BLOCK, StaticTree.static_ltree);
  10126. bi_flush();
  10127. }
  10128. last_eob_len = 7;
  10129. }
  10130. // Save the match info and tally the frequency counts. Return true if
  10131. // the current block must be flushed.
  10132. function _tr_tally(dist, // distance of matched string
  10133. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  10134. ) {
  10135. var out_length, in_length, dcode;
  10136. that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
  10137. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  10138. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  10139. last_lit++;
  10140. if (dist === 0) {
  10141. // lc is the unmatched char
  10142. dyn_ltree[lc * 2]++;
  10143. } else {
  10144. matches++;
  10145. // Here, lc is the match length - MIN_MATCH
  10146. dist--; // dist = match distance - 1
  10147. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  10148. dyn_dtree[Tree.d_code(dist) * 2]++;
  10149. }
  10150. if ((last_lit & 0x1fff) === 0 && level > 2) {
  10151. // Compute an upper bound for the compressed length
  10152. out_length = last_lit * 8;
  10153. in_length = strstart - block_start;
  10154. for (dcode = 0; dcode < D_CODES; dcode++) {
  10155. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  10156. }
  10157. out_length >>>= 3;
  10158. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  10159. return true;
  10160. }
  10161. return (last_lit == lit_bufsize - 1);
  10162. // We avoid equality with lit_bufsize because of wraparound at 64K
  10163. // on 16 bit machines and because stored blocks are restricted to
  10164. // 64K-1 bytes.
  10165. }
  10166. // Send the block data compressed using the given Huffman trees
  10167. function compress_block(ltree, dtree) {
  10168. var dist; // distance of matched string
  10169. var lc; // match length or unmatched char (if dist === 0)
  10170. var lx = 0; // running index in l_buf
  10171. var code; // the code to send
  10172. var extra; // number of extra bits to send
  10173. if (last_lit !== 0) {
  10174. do {
  10175. dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
  10176. lc = (that.pending_buf[l_buf + lx]) & 0xff;
  10177. lx++;
  10178. if (dist === 0) {
  10179. send_code(lc, ltree); // send a literal byte
  10180. } else {
  10181. // Here, lc is the match length - MIN_MATCH
  10182. code = Tree._length_code[lc];
  10183. send_code(code + LITERALS + 1, ltree); // send the length
  10184. // code
  10185. extra = Tree.extra_lbits[code];
  10186. if (extra !== 0) {
  10187. lc -= Tree.base_length[code];
  10188. send_bits(lc, extra); // send the extra length bits
  10189. }
  10190. dist--; // dist is now the match distance - 1
  10191. code = Tree.d_code(dist);
  10192. send_code(code, dtree); // send the distance code
  10193. extra = Tree.extra_dbits[code];
  10194. if (extra !== 0) {
  10195. dist -= Tree.base_dist[code];
  10196. send_bits(dist, extra); // send the extra distance bits
  10197. }
  10198. } // literal or match pair ?
  10199. // Check that the overlay between pending_buf and d_buf+l_buf is
  10200. // ok:
  10201. } while (lx < last_lit);
  10202. }
  10203. send_code(END_BLOCK, ltree);
  10204. last_eob_len = ltree[END_BLOCK * 2 + 1];
  10205. }
  10206. // Flush the bit buffer and align the output on a byte boundary
  10207. function bi_windup() {
  10208. if (bi_valid > 8) {
  10209. put_short(bi_buf);
  10210. } else if (bi_valid > 0) {
  10211. put_byte(bi_buf & 0xff);
  10212. }
  10213. bi_buf = 0;
  10214. bi_valid = 0;
  10215. }
  10216. // Copy a stored block, storing first the length and its
  10217. // one's complement if requested.
  10218. function copy_block(buf, // the input data
  10219. len, // its length
  10220. header // true if block header must be written
  10221. ) {
  10222. bi_windup(); // align on byte boundary
  10223. last_eob_len = 8; // enough lookahead for inflate
  10224. if (header) {
  10225. put_short(len);
  10226. put_short(~len);
  10227. }
  10228. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  10229. that.pending += len;
  10230. }
  10231. // Send a stored block
  10232. function _tr_stored_block(buf, // input block
  10233. stored_len, // length of input block
  10234. eof // true if this is the last block for a file
  10235. ) {
  10236. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  10237. copy_block(buf, stored_len, true); // with header
  10238. }
  10239. // Determine the best encoding for the current block: dynamic trees, static
  10240. // trees or store, and output the encoded block to the zip file.
  10241. function _tr_flush_block(buf, // input block, or NULL if too old
  10242. stored_len, // length of input block
  10243. eof // true if this is the last block for a file
  10244. ) {
  10245. var opt_lenb, static_lenb; // opt_len and static_len in bytes
  10246. var max_blindex = 0; // index of last bit length code of non zero freq
  10247. // Build the Huffman trees unless a stored block is forced
  10248. if (level > 0) {
  10249. // Construct the literal and distance trees
  10250. l_desc.build_tree(that);
  10251. d_desc.build_tree(that);
  10252. // At this point, opt_len and static_len are the total bit lengths
  10253. // of
  10254. // the compressed block data, excluding the tree representations.
  10255. // Build the bit length tree for the above two trees, and get the
  10256. // index
  10257. // in bl_order of the last bit length code to send.
  10258. max_blindex = build_bl_tree();
  10259. // Determine the best encoding. Compute first the block length in
  10260. // bytes
  10261. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  10262. static_lenb = (that.static_len + 3 + 7) >>> 3;
  10263. if (static_lenb <= opt_lenb)
  10264. opt_lenb = static_lenb;
  10265. } else {
  10266. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  10267. }
  10268. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  10269. // 4: two words for the lengths
  10270. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10271. // Otherwise we can't have processed more than WSIZE input bytes
  10272. // since
  10273. // the last block flush, because compression would have been
  10274. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10275. // transform a block into a stored block.
  10276. _tr_stored_block(buf, stored_len, eof);
  10277. } else if (static_lenb == opt_lenb) {
  10278. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  10279. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  10280. } else {
  10281. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  10282. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  10283. compress_block(dyn_ltree, dyn_dtree);
  10284. }
  10285. // The above check is made mod 2^32, for files larger than 512 MB
  10286. // and uLong implemented on 32 bits.
  10287. init_block();
  10288. if (eof) {
  10289. bi_windup();
  10290. }
  10291. }
  10292. function flush_block_only(eof) {
  10293. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  10294. block_start = strstart;
  10295. strm.flush_pending();
  10296. }
  10297. // Fill the window when the lookahead becomes insufficient.
  10298. // Updates strstart and lookahead.
  10299. //
  10300. // IN assertion: lookahead < MIN_LOOKAHEAD
  10301. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  10302. // At least one byte has been read, or avail_in === 0; reads are
  10303. // performed for at least two bytes (required for the zip translate_eol
  10304. // option -- not supported here).
  10305. function fill_window() {
  10306. var n, m;
  10307. var p;
  10308. var more; // Amount of free space at the end of the window.
  10309. do {
  10310. more = (window_size - lookahead - strstart);
  10311. // Deal with !@#$% 64K limit:
  10312. if (more === 0 && strstart === 0 && lookahead === 0) {
  10313. more = w_size;
  10314. } else if (more == -1) {
  10315. // Very unlikely, but possible on 16 bit machine if strstart ==
  10316. // 0
  10317. // and lookahead == 1 (input done one byte at time)
  10318. more--;
  10319. // If the window is almost full and there is insufficient
  10320. // lookahead,
  10321. // move the upper half to the lower one to make room in the
  10322. // upper half.
  10323. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  10324. window.set(window.subarray(w_size, w_size + w_size), 0);
  10325. match_start -= w_size;
  10326. strstart -= w_size; // we now have strstart >= MAX_DIST
  10327. block_start -= w_size;
  10328. // Slide the hash table (could be avoided with 32 bit values
  10329. // at the expense of memory usage). We slide even when level ==
  10330. // 0
  10331. // to keep the hash table consistent if we switch back to level
  10332. // > 0
  10333. // later. (Using level 0 permanently is not an optimal usage of
  10334. // zlib, so we don't care about this pathological case.)
  10335. n = hash_size;
  10336. p = n;
  10337. do {
  10338. m = (head[--p] & 0xffff);
  10339. head[p] = (m >= w_size ? m - w_size : 0);
  10340. } while (--n !== 0);
  10341. n = w_size;
  10342. p = n;
  10343. do {
  10344. m = (prev[--p] & 0xffff);
  10345. prev[p] = (m >= w_size ? m - w_size : 0);
  10346. // If n is not on any hash chain, prev[n] is garbage but
  10347. // its value will never be used.
  10348. } while (--n !== 0);
  10349. more += w_size;
  10350. }
  10351. if (strm.avail_in === 0)
  10352. return;
  10353. // If there was no sliding:
  10354. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  10355. // more == window_size - lookahead - strstart
  10356. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  10357. // => more >= window_size - 2*WSIZE + 2
  10358. // In the BIG_MEM or MMAP case (not yet supported),
  10359. // window_size == input_size + MIN_LOOKAHEAD &&
  10360. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  10361. // Otherwise, window_size == 2*WSIZE so more >= 2.
  10362. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  10363. n = strm.read_buf(window, strstart + lookahead, more);
  10364. lookahead += n;
  10365. // Initialize the hash value now that we have some input:
  10366. if (lookahead >= MIN_MATCH) {
  10367. ins_h = window[strstart] & 0xff;
  10368. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10369. }
  10370. // If the whole input has less than MIN_MATCH bytes, ins_h is
  10371. // garbage,
  10372. // but this is not important since only literal bytes will be
  10373. // emitted.
  10374. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  10375. }
  10376. // Copy without compression as much as possible from the input stream,
  10377. // return
  10378. // the current block state.
  10379. // This function does not insert new strings in the dictionary since
  10380. // uncompressible data is probably not useful. This function is used
  10381. // only for the level=0 compression option.
  10382. // NOTE: this function should be optimized to avoid extra copying from
  10383. // window to pending_buf.
  10384. function deflate_stored(flush) {
  10385. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  10386. // to pending_buf_size, and each stored block has a 5 byte header:
  10387. var max_block_size = 0xffff;
  10388. var max_start;
  10389. if (max_block_size > pending_buf_size - 5) {
  10390. max_block_size = pending_buf_size - 5;
  10391. }
  10392. // Copy as much as possible from input to output:
  10393. while (true) {
  10394. // Fill the window as much as possible:
  10395. if (lookahead <= 1) {
  10396. fill_window();
  10397. if (lookahead === 0 && flush == Z_NO_FLUSH)
  10398. return NeedMore;
  10399. if (lookahead === 0)
  10400. break; // flush the current block
  10401. }
  10402. strstart += lookahead;
  10403. lookahead = 0;
  10404. // Emit a stored block if pending_buf will be full:
  10405. max_start = block_start + max_block_size;
  10406. if (strstart === 0 || strstart >= max_start) {
  10407. // strstart === 0 is possible when wraparound on 16-bit machine
  10408. lookahead = (strstart - max_start);
  10409. strstart = max_start;
  10410. flush_block_only(false);
  10411. if (strm.avail_out === 0)
  10412. return NeedMore;
  10413. }
  10414. // Flush if we may have to slide, otherwise block_start may become
  10415. // negative and the data will be gone:
  10416. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  10417. flush_block_only(false);
  10418. if (strm.avail_out === 0)
  10419. return NeedMore;
  10420. }
  10421. }
  10422. flush_block_only(flush == Z_FINISH);
  10423. if (strm.avail_out === 0)
  10424. return (flush == Z_FINISH) ? FinishStarted : NeedMore;
  10425. return flush == Z_FINISH ? FinishDone : BlockDone;
  10426. }
  10427. function longest_match(cur_match) {
  10428. var chain_length = max_chain_length; // max hash chain length
  10429. var scan = strstart; // current string
  10430. var match; // matched string
  10431. var len; // length of current match
  10432. var best_len = prev_length; // best match length so far
  10433. var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  10434. var _nice_match = nice_match;
  10435. // Stop when cur_match becomes <= limit. To simplify the code,
  10436. // we prevent matches with the string of window index 0.
  10437. var wmask = w_mask;
  10438. var strend = strstart + MAX_MATCH;
  10439. var scan_end1 = window[scan + best_len - 1];
  10440. var scan_end = window[scan + best_len];
  10441. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  10442. // 16.
  10443. // It is easy to get rid of this optimization if necessary.
  10444. // Do not waste too much time if we already have a good match:
  10445. if (prev_length >= good_match) {
  10446. chain_length >>= 2;
  10447. }
  10448. // Do not look for matches beyond the end of the input. This is
  10449. // necessary
  10450. // to make deflate deterministic.
  10451. if (_nice_match > lookahead)
  10452. _nice_match = lookahead;
  10453. do {
  10454. match = cur_match;
  10455. // Skip to next match if the match length cannot increase
  10456. // or if the match length is less than 2:
  10457. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] ||
  10458. window[++match] != window[scan + 1])
  10459. continue;
  10460. // The check at best_len-1 can be removed because it will be made
  10461. // again later. (This heuristic is not always a win.)
  10462. // It is not necessary to compare scan[2] and match[2] since they
  10463. // are always equal when the other bytes match, given that
  10464. // the hash keys are equal and that HASH_BITS >= 8.
  10465. scan += 2;
  10466. match++;
  10467. // We check for insufficient lookahead only every 8th comparison;
  10468. // the 256th check will be made at strstart+258.
  10469. do {} while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] &&
  10470. window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] &&
  10471. window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  10472. len = MAX_MATCH - (strend - scan);
  10473. scan = strend - MAX_MATCH;
  10474. if (len > best_len) {
  10475. match_start = cur_match;
  10476. best_len = len;
  10477. if (len >= _nice_match)
  10478. break;
  10479. scan_end1 = window[scan + best_len - 1];
  10480. scan_end = window[scan + best_len];
  10481. }
  10482. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  10483. if (best_len <= lookahead)
  10484. return best_len;
  10485. return lookahead;
  10486. }
  10487. // Compress as much as possible from the input stream, return the current
  10488. // block state.
  10489. // This function does not perform lazy evaluation of matches and inserts
  10490. // new strings in the dictionary only for unmatched strings or for short
  10491. // matches. It is used only for the fast compression options.
  10492. function deflate_fast(flush) {
  10493. // short hash_head = 0; // head of the hash chain
  10494. var hash_head = 0; // head of the hash chain
  10495. var bflush; // set if current block must be flushed
  10496. while (true) {
  10497. // Make sure that we always have enough lookahead, except
  10498. // at the end of the input file. We need MAX_MATCH bytes
  10499. // for the next match, plus MIN_MATCH bytes to insert the
  10500. // string following the next match.
  10501. if (lookahead < MIN_LOOKAHEAD) {
  10502. fill_window();
  10503. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10504. return NeedMore;
  10505. }
  10506. if (lookahead === 0)
  10507. break; // flush the current block
  10508. }
  10509. // Insert the string window[strstart .. strstart+2] in the
  10510. // dictionary, and set hash_head to the head of the hash chain:
  10511. if (lookahead >= MIN_MATCH) {
  10512. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10513. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10514. hash_head = (head[ins_h] & 0xffff);
  10515. prev[strstart & w_mask] = head[ins_h];
  10516. head[ins_h] = strstart;
  10517. }
  10518. // Find the longest match, discarding those <= prev_length.
  10519. // At this point we have always match_length < MIN_MATCH
  10520. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10521. // To simplify the code, we prevent matches with the string
  10522. // of window index 0 (in particular we have to avoid a match
  10523. // of the string with itself at the start of the input file).
  10524. if (strategy != Z_HUFFMAN_ONLY) {
  10525. match_length = longest_match(hash_head);
  10526. }
  10527. // longest_match() sets match_start
  10528. }
  10529. if (match_length >= MIN_MATCH) {
  10530. // check_match(strstart, match_start, match_length);
  10531. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  10532. lookahead -= match_length;
  10533. // Insert new strings in the hash table only if the match length
  10534. // is not too large. This saves time but degrades compression.
  10535. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  10536. match_length--; // string at strstart already in hash table
  10537. do {
  10538. strstart++;
  10539. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10540. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10541. hash_head = (head[ins_h] & 0xffff);
  10542. prev[strstart & w_mask] = head[ins_h];
  10543. head[ins_h] = strstart;
  10544. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  10545. // always MIN_MATCH bytes ahead.
  10546. } while (--match_length !== 0);
  10547. strstart++;
  10548. } else {
  10549. strstart += match_length;
  10550. match_length = 0;
  10551. ins_h = window[strstart] & 0xff;
  10552. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10553. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  10554. // not
  10555. // matter since it will be recomputed at next deflate call.
  10556. }
  10557. } else {
  10558. // No match, output a literal byte
  10559. bflush = _tr_tally(0, window[strstart] & 0xff);
  10560. lookahead--;
  10561. strstart++;
  10562. }
  10563. if (bflush) {
  10564. flush_block_only(false);
  10565. if (strm.avail_out === 0)
  10566. return NeedMore;
  10567. }
  10568. }
  10569. flush_block_only(flush == Z_FINISH);
  10570. if (strm.avail_out === 0) {
  10571. if (flush == Z_FINISH)
  10572. return FinishStarted;
  10573. else
  10574. return NeedMore;
  10575. }
  10576. return flush == Z_FINISH ? FinishDone : BlockDone;
  10577. }
  10578. // Same as above, but achieves better compression. We use a lazy
  10579. // evaluation for matches: a match is finally adopted only if there is
  10580. // no better match at the next window position.
  10581. function deflate_slow(flush) {
  10582. // short hash_head = 0; // head of hash chain
  10583. var hash_head = 0; // head of hash chain
  10584. var bflush; // set if current block must be flushed
  10585. var max_insert;
  10586. // Process the input block.
  10587. while (true) {
  10588. // Make sure that we always have enough lookahead, except
  10589. // at the end of the input file. We need MAX_MATCH bytes
  10590. // for the next match, plus MIN_MATCH bytes to insert the
  10591. // string following the next match.
  10592. if (lookahead < MIN_LOOKAHEAD) {
  10593. fill_window();
  10594. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10595. return NeedMore;
  10596. }
  10597. if (lookahead === 0)
  10598. break; // flush the current block
  10599. }
  10600. // Insert the string window[strstart .. strstart+2] in the
  10601. // dictionary, and set hash_head to the head of the hash chain:
  10602. if (lookahead >= MIN_MATCH) {
  10603. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10604. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10605. hash_head = (head[ins_h] & 0xffff);
  10606. prev[strstart & w_mask] = head[ins_h];
  10607. head[ins_h] = strstart;
  10608. }
  10609. // Find the longest match, discarding those <= prev_length.
  10610. prev_length = match_length;
  10611. prev_match = match_start;
  10612. match_length = MIN_MATCH - 1;
  10613. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10614. // To simplify the code, we prevent matches with the string
  10615. // of window index 0 (in particular we have to avoid a match
  10616. // of the string with itself at the start of the input file).
  10617. if (strategy != Z_HUFFMAN_ONLY) {
  10618. match_length = longest_match(hash_head);
  10619. }
  10620. // longest_match() sets match_start
  10621. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  10622. // If prev_match is also MIN_MATCH, match_start is garbage
  10623. // but we will ignore the current match anyway.
  10624. match_length = MIN_MATCH - 1;
  10625. }
  10626. }
  10627. // If there was a match at the previous step and the current
  10628. // match is not better, output the previous match:
  10629. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  10630. max_insert = strstart + lookahead - MIN_MATCH;
  10631. // Do not insert strings in hash table beyond this.
  10632. // check_match(strstart-1, prev_match, prev_length);
  10633. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  10634. // Insert in hash table all strings up to the end of the match.
  10635. // strstart-1 and strstart are already inserted. If there is not
  10636. // enough lookahead, the last two strings are not inserted in
  10637. // the hash table.
  10638. lookahead -= prev_length - 1;
  10639. prev_length -= 2;
  10640. do {
  10641. if (++strstart <= max_insert) {
  10642. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10643. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10644. hash_head = (head[ins_h] & 0xffff);
  10645. prev[strstart & w_mask] = head[ins_h];
  10646. head[ins_h] = strstart;
  10647. }
  10648. } while (--prev_length !== 0);
  10649. match_available = 0;
  10650. match_length = MIN_MATCH - 1;
  10651. strstart++;
  10652. if (bflush) {
  10653. flush_block_only(false);
  10654. if (strm.avail_out === 0)
  10655. return NeedMore;
  10656. }
  10657. } else if (match_available !== 0) {
  10658. // If there was no match at the previous position, output a
  10659. // single literal. If there was a match but the current match
  10660. // is longer, truncate the previous match to a single literal.
  10661. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10662. if (bflush) {
  10663. flush_block_only(false);
  10664. }
  10665. strstart++;
  10666. lookahead--;
  10667. if (strm.avail_out === 0)
  10668. return NeedMore;
  10669. } else {
  10670. // There is no previous match to compare with, wait for
  10671. // the next step to decide.
  10672. match_available = 1;
  10673. strstart++;
  10674. lookahead--;
  10675. }
  10676. }
  10677. if (match_available !== 0) {
  10678. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10679. match_available = 0;
  10680. }
  10681. flush_block_only(flush == Z_FINISH);
  10682. if (strm.avail_out === 0) {
  10683. if (flush == Z_FINISH)
  10684. return FinishStarted;
  10685. else
  10686. return NeedMore;
  10687. }
  10688. return flush == Z_FINISH ? FinishDone : BlockDone;
  10689. }
  10690. function deflateReset(strm) {
  10691. strm.total_in = strm.total_out = 0;
  10692. strm.msg = null; //
  10693. that.pending = 0;
  10694. that.pending_out = 0;
  10695. status = BUSY_STATE;
  10696. last_flush = Z_NO_FLUSH;
  10697. tr_init();
  10698. lm_init();
  10699. return Z_OK;
  10700. }
  10701. that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
  10702. if (!_method)
  10703. _method = Z_DEFLATED;
  10704. if (!memLevel)
  10705. memLevel = DEF_MEM_LEVEL;
  10706. if (!_strategy)
  10707. _strategy = Z_DEFAULT_STRATEGY;
  10708. // byte[] my_version=ZLIB_VERSION;
  10709. //
  10710. // if (!version || version[0] != my_version[0]
  10711. // || stream_size != sizeof(z_stream)) {
  10712. // return Z_VERSION_ERROR;
  10713. // }
  10714. strm.msg = null;
  10715. if (_level == Z_DEFAULT_COMPRESSION)
  10716. _level = 6;
  10717. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 ||
  10718. _strategy > Z_HUFFMAN_ONLY) {
  10719. return Z_STREAM_ERROR;
  10720. }
  10721. strm.dstate = that;
  10722. w_bits = bits;
  10723. w_size = 1 << w_bits;
  10724. w_mask = w_size - 1;
  10725. hash_bits = memLevel + 7;
  10726. hash_size = 1 << hash_bits;
  10727. hash_mask = hash_size - 1;
  10728. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  10729. window = new Uint8Array(w_size * 2);
  10730. prev = [];
  10731. head = [];
  10732. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  10733. // We overlay pending_buf and d_buf+l_buf. This works since the average
  10734. // output size for (length,distance) codes is <= 24 bits.
  10735. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  10736. pending_buf_size = lit_bufsize * 4;
  10737. d_buf = Math.floor(lit_bufsize / 2);
  10738. l_buf = (1 + 2) * lit_bufsize;
  10739. level = _level;
  10740. strategy = _strategy;
  10741. return deflateReset(strm);
  10742. };
  10743. that.deflateEnd = function() {
  10744. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  10745. return Z_STREAM_ERROR;
  10746. }
  10747. // Deallocate in reverse order of allocations:
  10748. that.pending_buf = null;
  10749. head = null;
  10750. prev = null;
  10751. window = null;
  10752. // free
  10753. that.dstate = null;
  10754. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  10755. };
  10756. that.deflateParams = function(strm, _level, _strategy) {
  10757. var err = Z_OK;
  10758. if (_level == Z_DEFAULT_COMPRESSION) {
  10759. _level = 6;
  10760. }
  10761. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  10762. return Z_STREAM_ERROR;
  10763. }
  10764. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  10765. // Flush the last buffer:
  10766. err = strm.deflate(Z_PARTIAL_FLUSH);
  10767. }
  10768. if (level != _level) {
  10769. level = _level;
  10770. max_lazy_match = config_table[level].max_lazy;
  10771. good_match = config_table[level].good_length;
  10772. nice_match = config_table[level].nice_length;
  10773. max_chain_length = config_table[level].max_chain;
  10774. }
  10775. strategy = _strategy;
  10776. return err;
  10777. };
  10778. that.deflateSetDictionary = function(strm, dictionary, dictLength) {
  10779. var length = dictLength;
  10780. var n, index = 0;
  10781. if (!dictionary || status != INIT_STATE)
  10782. return Z_STREAM_ERROR;
  10783. if (length < MIN_MATCH)
  10784. return Z_OK;
  10785. if (length > w_size - MIN_LOOKAHEAD) {
  10786. length = w_size - MIN_LOOKAHEAD;
  10787. index = dictLength - length; // use the tail of the dictionary
  10788. }
  10789. window.set(dictionary.subarray(index, index + length), 0);
  10790. strstart = length;
  10791. block_start = length;
  10792. // Insert all strings in the hash table (except for the last two bytes).
  10793. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  10794. // call of fill_window.
  10795. ins_h = window[0] & 0xff;
  10796. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  10797. for (n = 0; n <= length - MIN_MATCH; n++) {
  10798. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10799. prev[n & w_mask] = head[ins_h];
  10800. head[ins_h] = n;
  10801. }
  10802. return Z_OK;
  10803. };
  10804. that.deflate = function(_strm, flush) {
  10805. var i, header, level_flags, old_flush, bstate;
  10806. if (flush > Z_FINISH || flush < 0) {
  10807. return Z_STREAM_ERROR;
  10808. }
  10809. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
  10810. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  10811. return Z_STREAM_ERROR;
  10812. }
  10813. if (_strm.avail_out === 0) {
  10814. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10815. return Z_BUF_ERROR;
  10816. }
  10817. strm = _strm; // just in case
  10818. old_flush = last_flush;
  10819. last_flush = flush;
  10820. // Write the zlib header
  10821. if (status == INIT_STATE) {
  10822. header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  10823. level_flags = ((level - 1) & 0xff) >> 1;
  10824. if (level_flags > 3)
  10825. level_flags = 3;
  10826. header |= (level_flags << 6);
  10827. if (strstart !== 0)
  10828. header |= PRESET_DICT;
  10829. header += 31 - (header % 31);
  10830. status = BUSY_STATE;
  10831. putShortMSB(header);
  10832. }
  10833. // Flush as much pending output as possible
  10834. if (that.pending !== 0) {
  10835. strm.flush_pending();
  10836. if (strm.avail_out === 0) {
  10837. // console.log(" avail_out==0");
  10838. // Since avail_out is 0, deflate will be called again with
  10839. // more output space, but possibly with both pending and
  10840. // avail_in equal to zero. There won't be anything to do,
  10841. // but this is not an error situation so make sure we
  10842. // return OK instead of BUF_ERROR at next call of deflate:
  10843. last_flush = -1;
  10844. return Z_OK;
  10845. }
  10846. // Make sure there is something to do and avoid duplicate
  10847. // consecutive
  10848. // flushes. For repeated and useless calls with Z_FINISH, we keep
  10849. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  10850. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  10851. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10852. return Z_BUF_ERROR;
  10853. }
  10854. // User must not provide more input after the first FINISH:
  10855. if (status == FINISH_STATE && strm.avail_in !== 0) {
  10856. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10857. return Z_BUF_ERROR;
  10858. }
  10859. // Start a new block or continue the current one.
  10860. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
  10861. bstate = -1;
  10862. switch (config_table[level].func) {
  10863. case STORED:
  10864. bstate = deflate_stored(flush);
  10865. break;
  10866. case FAST:
  10867. bstate = deflate_fast(flush);
  10868. break;
  10869. case SLOW:
  10870. bstate = deflate_slow(flush);
  10871. break;
  10872. default:
  10873. }
  10874. if (bstate == FinishStarted || bstate == FinishDone) {
  10875. status = FINISH_STATE;
  10876. }
  10877. if (bstate == NeedMore || bstate == FinishStarted) {
  10878. if (strm.avail_out === 0) {
  10879. last_flush = -1; // avoid BUF_ERROR next call, see above
  10880. }
  10881. return Z_OK;
  10882. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  10883. // of deflate should use the same flush parameter to make sure
  10884. // that the flush is complete. So we don't have to output an
  10885. // empty block here, this will be done at next call. This also
  10886. // ensures that for a very small output buffer, we emit at most
  10887. // one empty block.
  10888. }
  10889. if (bstate == BlockDone) {
  10890. if (flush == Z_PARTIAL_FLUSH) {
  10891. _tr_align();
  10892. } else { // FULL_FLUSH or SYNC_FLUSH
  10893. _tr_stored_block(0, 0, false);
  10894. // For a full flush, this empty block will be recognized
  10895. // as a special marker by inflate_sync().
  10896. if (flush == Z_FULL_FLUSH) {
  10897. // state.head[s.hash_size-1]=0;
  10898. for (i = 0; i < hash_size /*-1*/ ; i++)
  10899. // forget history
  10900. head[i] = 0;
  10901. }
  10902. }
  10903. strm.flush_pending();
  10904. if (strm.avail_out === 0) {
  10905. last_flush = -1; // avoid BUF_ERROR at next call, see above
  10906. return Z_OK;
  10907. }
  10908. }
  10909. }
  10910. if (flush != Z_FINISH)
  10911. return Z_OK;
  10912. return Z_STREAM_END;
  10913. };
  10914. }
  10915. // ZStream
  10916. function ZStream() {
  10917. var that = this;
  10918. that.next_in_index = 0;
  10919. that.next_out_index = 0;
  10920. // that.next_in; // next input byte
  10921. that.avail_in = 0; // number of bytes available at next_in
  10922. that.total_in = 0; // total nb of input bytes read so far
  10923. // that.next_out; // next output byte should be put there
  10924. that.avail_out = 0; // remaining free space at next_out
  10925. that.total_out = 0; // total nb of bytes output so far
  10926. // that.msg;
  10927. // that.dstate;
  10928. }
  10929. ZStream.prototype = {
  10930. deflateInit: function(level, bits) {
  10931. var that = this;
  10932. that.dstate = new Deflate();
  10933. if (!bits)
  10934. bits = MAX_BITS;
  10935. return that.dstate.deflateInit(that, level, bits);
  10936. },
  10937. deflate: function(flush) {
  10938. var that = this;
  10939. if (!that.dstate) {
  10940. return Z_STREAM_ERROR;
  10941. }
  10942. return that.dstate.deflate(that, flush);
  10943. },
  10944. deflateEnd: function() {
  10945. var that = this;
  10946. if (!that.dstate)
  10947. return Z_STREAM_ERROR;
  10948. var ret = that.dstate.deflateEnd();
  10949. that.dstate = null;
  10950. return ret;
  10951. },
  10952. deflateParams: function(level, strategy) {
  10953. var that = this;
  10954. if (!that.dstate)
  10955. return Z_STREAM_ERROR;
  10956. return that.dstate.deflateParams(that, level, strategy);
  10957. },
  10958. deflateSetDictionary: function(dictionary, dictLength) {
  10959. var that = this;
  10960. if (!that.dstate)
  10961. return Z_STREAM_ERROR;
  10962. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  10963. },
  10964. // Read a new buffer from the current input stream, update the
  10965. // total number of bytes read. All deflate() input goes through
  10966. // this function so some applications may wish to modify it to avoid
  10967. // allocating a large strm->next_in buffer and copying from it.
  10968. // (See also flush_pending()).
  10969. read_buf: function(buf, start, size) {
  10970. var that = this;
  10971. var len = that.avail_in;
  10972. if (len > size)
  10973. len = size;
  10974. if (len === 0)
  10975. return 0;
  10976. that.avail_in -= len;
  10977. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  10978. that.next_in_index += len;
  10979. that.total_in += len;
  10980. return len;
  10981. },
  10982. // Flush as much pending output as possible. All deflate() output goes
  10983. // through this function so some applications may wish to modify it
  10984. // to avoid allocating a large strm->next_out buffer and copying into it.
  10985. // (See also read_buf()).
  10986. flush_pending: function() {
  10987. var that = this;
  10988. var len = that.dstate.pending;
  10989. if (len > that.avail_out)
  10990. len = that.avail_out;
  10991. if (len === 0)
  10992. return;
  10993. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  10994. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  10995. // len)) {
  10996. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  10997. // that.next_out_index + ", " + len);
  10998. // console.log("avail_out=" + that.avail_out);
  10999. // }
  11000. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  11001. that.next_out_index += len;
  11002. that.dstate.pending_out += len;
  11003. that.total_out += len;
  11004. that.avail_out -= len;
  11005. that.dstate.pending -= len;
  11006. if (that.dstate.pending === 0) {
  11007. that.dstate.pending_out = 0;
  11008. }
  11009. }
  11010. };
  11011. // Deflater
  11012. return function Deflater(level) {
  11013. var that = this;
  11014. var z = new ZStream();
  11015. var bufsize = 512;
  11016. var flush = Z_NO_FLUSH;
  11017. var buf = new Uint8Array(bufsize);
  11018. if (typeof level == "undefined")
  11019. level = Z_DEFAULT_COMPRESSION;
  11020. z.deflateInit(level);
  11021. z.next_out = buf;
  11022. that.append = function(data, onprogress) {
  11023. var err, buffers = [],
  11024. lastIndex = 0,
  11025. bufferIndex = 0,
  11026. bufferSize = 0,
  11027. array;
  11028. if (!data.length)
  11029. return;
  11030. z.next_in_index = 0;
  11031. z.next_in = data;
  11032. z.avail_in = data.length;
  11033. do {
  11034. z.next_out_index = 0;
  11035. z.avail_out = bufsize;
  11036. err = z.deflate(flush);
  11037. if (err != Z_OK)
  11038. throw "deflating: " + z.msg;
  11039. if (z.next_out_index)
  11040. if (z.next_out_index == bufsize)
  11041. buffers.push(new Uint8Array(buf));
  11042. else
  11043. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11044. bufferSize += z.next_out_index;
  11045. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  11046. onprogress(z.next_in_index);
  11047. lastIndex = z.next_in_index;
  11048. }
  11049. } while (z.avail_in > 0 || z.avail_out === 0);
  11050. array = new Uint8Array(bufferSize);
  11051. buffers.forEach(function(chunk) {
  11052. array.set(chunk, bufferIndex);
  11053. bufferIndex += chunk.length;
  11054. });
  11055. return array;
  11056. };
  11057. that.flush = function() {
  11058. var err, buffers = [],
  11059. bufferIndex = 0,
  11060. bufferSize = 0,
  11061. array;
  11062. do {
  11063. z.next_out_index = 0;
  11064. z.avail_out = bufsize;
  11065. err = z.deflate(Z_FINISH);
  11066. if (err != Z_STREAM_END && err != Z_OK)
  11067. throw "deflating: " + z.msg;
  11068. if (bufsize - z.avail_out > 0)
  11069. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11070. bufferSize += z.next_out_index;
  11071. } while (z.avail_in > 0 || z.avail_out === 0);
  11072. z.deflateEnd();
  11073. array = new Uint8Array(bufferSize);
  11074. buffers.forEach(function(chunk) {
  11075. array.set(chunk, bufferIndex);
  11076. bufferIndex += chunk.length;
  11077. });
  11078. return array;
  11079. };
  11080. };
  11081. })(undefined);
  11082. /*
  11083. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  11084. Copyright (c) 2016 Niklas von Hertzen
  11085. Released under License
  11086. */
  11087. ! function(e) { if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();
  11088. else if ("function" == typeof define && define.amd) define([], e);
  11089. else { var f; "undefined" != typeof window ? f = window : "undefined" != typeof global ? f = global : "undefined" != typeof self && (f = self), f.html2canvas = e(); } }(function() {
  11090. var define;
  11091. return (function e(t, n, r) {
  11092. 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: {} };
  11093. 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 })({
  11094. 1: [function(_dereq_, module, exports) {
  11095. (function(global) {
  11096. /*! http://mths.be/punycode v1.2.4 by @mathias */
  11097. (function(root) {
  11098. /** Detect free variables */
  11099. var freeExports = typeof exports == 'object' && exports;
  11100. var freeModule = typeof module == 'object' && module &&
  11101. module.exports == freeExports && module;
  11102. var freeGlobal = typeof global == 'object' && global;
  11103. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  11104. root = freeGlobal;
  11105. }
  11106. /**
  11107. * The `punycode` object.
  11108. * @name punycode
  11109. * @type Object
  11110. */
  11111. var punycode,
  11112. /** Highest positive signed 32-bit float value */
  11113. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  11114. /** Bootstring parameters */
  11115. base = 36,
  11116. tMin = 1,
  11117. tMax = 26,
  11118. skew = 38,
  11119. damp = 700,
  11120. initialBias = 72,
  11121. initialN = 128, // 0x80
  11122. delimiter = '-', // '\x2D'
  11123. /** Regular expressions */
  11124. regexPunycode = /^xn--/,
  11125. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  11126. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  11127. /** Error messages */
  11128. errors = {
  11129. 'overflow': 'Overflow: input needs wider integers to process',
  11130. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  11131. 'invalid-input': 'Invalid input'
  11132. },
  11133. /** Convenience shortcuts */
  11134. baseMinusTMin = base - tMin,
  11135. floor = Math.floor,
  11136. stringFromCharCode = String.fromCharCode,
  11137. /** Temporary variable */
  11138. key;
  11139. /*--------------------------------------------------------------------------*/
  11140. /**
  11141. * A generic error utility function.
  11142. * @private
  11143. * @param {String} type The error type.
  11144. * @returns {Error} Throws a `RangeError` with the applicable error message.
  11145. */
  11146. function error(type) {
  11147. throw RangeError(errors[type]);
  11148. }
  11149. /**
  11150. * A generic `Array#map` utility function.
  11151. * @private
  11152. * @param {Array} array The array to iterate over.
  11153. * @param {Function} callback The function that gets called for every array
  11154. * item.
  11155. * @returns {Array} A new array of values returned by the callback function.
  11156. */
  11157. function map(array, fn) {
  11158. var length = array.length;
  11159. while (length--) {
  11160. array[length] = fn(array[length]);
  11161. }
  11162. return array;
  11163. }
  11164. /**
  11165. * A simple `Array#map`-like wrapper to work with domain name strings.
  11166. * @private
  11167. * @param {String} domain The domain name.
  11168. * @param {Function} callback The function that gets called for every
  11169. * character.
  11170. * @returns {Array} A new string of characters returned by the callback
  11171. * function.
  11172. */
  11173. function mapDomain(string, fn) {
  11174. return map(string.split(regexSeparators), fn).join('.');
  11175. }
  11176. /**
  11177. * Creates an array containing the numeric code points of each Unicode
  11178. * character in the string. While JavaScript uses UCS-2 internally,
  11179. * this function will convert a pair of surrogate halves (each of which
  11180. * UCS-2 exposes as separate characters) into a single code point,
  11181. * matching UTF-16.
  11182. * @see `punycode.ucs2.encode`
  11183. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11184. * @memberOf punycode.ucs2
  11185. * @name decode
  11186. * @param {String} string The Unicode input string (UCS-2).
  11187. * @returns {Array} The new array of code points.
  11188. */
  11189. function ucs2decode(string) {
  11190. var output = [],
  11191. counter = 0,
  11192. length = string.length,
  11193. value,
  11194. extra;
  11195. while (counter < length) {
  11196. value = string.charCodeAt(counter++);
  11197. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11198. // high surrogate, and there is a next character
  11199. extra = string.charCodeAt(counter++);
  11200. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11201. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11202. } else {
  11203. // unmatched surrogate; only append this code unit, in case the next
  11204. // code unit is the high surrogate of a surrogate pair
  11205. output.push(value);
  11206. counter--;
  11207. }
  11208. } else {
  11209. output.push(value);
  11210. }
  11211. }
  11212. return output;
  11213. }
  11214. /**
  11215. * Creates a string based on an array of numeric code points.
  11216. * @see `punycode.ucs2.decode`
  11217. * @memberOf punycode.ucs2
  11218. * @name encode
  11219. * @param {Array} codePoints The array of numeric code points.
  11220. * @returns {String} The new Unicode string (UCS-2).
  11221. */
  11222. function ucs2encode(array) {
  11223. return map(array, function(value) {
  11224. var output = '';
  11225. if (value > 0xFFFF) {
  11226. value -= 0x10000;
  11227. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11228. value = 0xDC00 | value & 0x3FF;
  11229. }
  11230. output += stringFromCharCode(value);
  11231. return output;
  11232. }).join('');
  11233. }
  11234. /**
  11235. * Converts a basic code point into a digit/integer.
  11236. * @see `digitToBasic()`
  11237. * @private
  11238. * @param {Number} codePoint The basic numeric code point value.
  11239. * @returns {Number} The numeric value of a basic code point (for use in
  11240. * representing integers) in the range `0` to `base - 1`, or `base` if
  11241. * the code point does not represent a value.
  11242. */
  11243. function basicToDigit(codePoint) {
  11244. if (codePoint - 48 < 10) {
  11245. return codePoint - 22;
  11246. }
  11247. if (codePoint - 65 < 26) {
  11248. return codePoint - 65;
  11249. }
  11250. if (codePoint - 97 < 26) {
  11251. return codePoint - 97;
  11252. }
  11253. return base;
  11254. }
  11255. /**
  11256. * Converts a digit/integer into a basic code point.
  11257. * @see `basicToDigit()`
  11258. * @private
  11259. * @param {Number} digit The numeric value of a basic code point.
  11260. * @returns {Number} The basic code point whose value (when used for
  11261. * representing integers) is `digit`, which needs to be in the range
  11262. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11263. * used; else, the lowercase form is used. The behavior is undefined
  11264. * if `flag` is non-zero and `digit` has no uppercase form.
  11265. */
  11266. function digitToBasic(digit, flag) {
  11267. // 0..25 map to ASCII a..z or A..Z
  11268. // 26..35 map to ASCII 0..9
  11269. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11270. }
  11271. /**
  11272. * Bias adaptation function as per section 3.4 of RFC 3492.
  11273. * http://tools.ietf.org/html/rfc3492#section-3.4
  11274. * @private
  11275. */
  11276. function adapt(delta, numPoints, firstTime) {
  11277. var k = 0;
  11278. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11279. delta += floor(delta / numPoints);
  11280. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  11281. delta = floor(delta / baseMinusTMin);
  11282. }
  11283. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11284. }
  11285. /**
  11286. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11287. * symbols.
  11288. * @memberOf punycode
  11289. * @param {String} input The Punycode string of ASCII-only symbols.
  11290. * @returns {String} The resulting string of Unicode symbols.
  11291. */
  11292. function decode(input) {
  11293. // Don't use UCS-2
  11294. var output = [],
  11295. inputLength = input.length,
  11296. out,
  11297. i = 0,
  11298. n = initialN,
  11299. bias = initialBias,
  11300. basic,
  11301. j,
  11302. index,
  11303. oldi,
  11304. w,
  11305. k,
  11306. digit,
  11307. t,
  11308. /** Cached calculation results */
  11309. baseMinusT;
  11310. // Handle the basic code points: let `basic` be the number of input code
  11311. // points before the last delimiter, or `0` if there is none, then copy
  11312. // the first basic code points to the output.
  11313. basic = input.lastIndexOf(delimiter);
  11314. if (basic < 0) {
  11315. basic = 0;
  11316. }
  11317. for (j = 0; j < basic; ++j) {
  11318. // if it's not a basic code point
  11319. if (input.charCodeAt(j) >= 0x80) {
  11320. error('not-basic');
  11321. }
  11322. output.push(input.charCodeAt(j));
  11323. }
  11324. // Main decoding loop: start just after the last delimiter if any basic code
  11325. // points were copied; start at the beginning otherwise.
  11326. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) {
  11327. // `index` is the index of the next character to be consumed.
  11328. // Decode a generalized variable-length integer into `delta`,
  11329. // which gets added to `i`. The overflow checking is easier
  11330. // if we increase `i` as we go, then subtract off its starting
  11331. // value at the end to obtain `delta`.
  11332. for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) {
  11333. if (index >= inputLength) {
  11334. error('invalid-input');
  11335. }
  11336. digit = basicToDigit(input.charCodeAt(index++));
  11337. if (digit >= base || digit > floor((maxInt - i) / w)) {
  11338. error('overflow');
  11339. }
  11340. i += digit * w;
  11341. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11342. if (digit < t) {
  11343. break;
  11344. }
  11345. baseMinusT = base - t;
  11346. if (w > floor(maxInt / baseMinusT)) {
  11347. error('overflow');
  11348. }
  11349. w *= baseMinusT;
  11350. }
  11351. out = output.length + 1;
  11352. bias = adapt(i - oldi, out, oldi == 0);
  11353. // `i` was supposed to wrap around from `out` to `0`,
  11354. // incrementing `n` each time, so we'll fix that now:
  11355. if (floor(i / out) > maxInt - n) {
  11356. error('overflow');
  11357. }
  11358. n += floor(i / out);
  11359. i %= out;
  11360. // Insert `n` at position `i` of the output
  11361. output.splice(i++, 0, n);
  11362. }
  11363. return ucs2encode(output);
  11364. }
  11365. /**
  11366. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  11367. * symbols.
  11368. * @memberOf punycode
  11369. * @param {String} input The string of Unicode symbols.
  11370. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  11371. */
  11372. function encode(input) {
  11373. var n,
  11374. delta,
  11375. handledCPCount,
  11376. basicLength,
  11377. bias,
  11378. j,
  11379. m,
  11380. q,
  11381. k,
  11382. t,
  11383. currentValue,
  11384. output = [],
  11385. /** `inputLength` will hold the number of code points in `input`. */
  11386. inputLength,
  11387. /** Cached calculation results */
  11388. handledCPCountPlusOne,
  11389. baseMinusT,
  11390. qMinusT;
  11391. // Convert the input in UCS-2 to Unicode
  11392. input = ucs2decode(input);
  11393. // Cache the length
  11394. inputLength = input.length;
  11395. // Initialize the state
  11396. n = initialN;
  11397. delta = 0;
  11398. bias = initialBias;
  11399. // Handle the basic code points
  11400. for (j = 0; j < inputLength; ++j) {
  11401. currentValue = input[j];
  11402. if (currentValue < 0x80) {
  11403. output.push(stringFromCharCode(currentValue));
  11404. }
  11405. }
  11406. handledCPCount = basicLength = output.length;
  11407. // `handledCPCount` is the number of code points that have been handled;
  11408. // `basicLength` is the number of basic code points.
  11409. // Finish the basic string - if it is not empty - with a delimiter
  11410. if (basicLength) {
  11411. output.push(delimiter);
  11412. }
  11413. // Main encoding loop:
  11414. while (handledCPCount < inputLength) {
  11415. // All non-basic code points < n have been handled already. Find the next
  11416. // larger one:
  11417. for (m = maxInt, j = 0; j < inputLength; ++j) {
  11418. currentValue = input[j];
  11419. if (currentValue >= n && currentValue < m) {
  11420. m = currentValue;
  11421. }
  11422. }
  11423. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  11424. // but guard against overflow
  11425. handledCPCountPlusOne = handledCPCount + 1;
  11426. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  11427. error('overflow');
  11428. }
  11429. delta += (m - n) * handledCPCountPlusOne;
  11430. n = m;
  11431. for (j = 0; j < inputLength; ++j) {
  11432. currentValue = input[j];
  11433. if (currentValue < n && ++delta > maxInt) {
  11434. error('overflow');
  11435. }
  11436. if (currentValue == n) {
  11437. // Represent delta as a generalized variable-length integer
  11438. for (q = delta, k = base; /* no condition */ ; k += base) {
  11439. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11440. if (q < t) {
  11441. break;
  11442. }
  11443. qMinusT = q - t;
  11444. baseMinusT = base - t;
  11445. output.push(
  11446. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  11447. );
  11448. q = floor(qMinusT / baseMinusT);
  11449. }
  11450. output.push(stringFromCharCode(digitToBasic(q, 0)));
  11451. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  11452. delta = 0;
  11453. ++handledCPCount;
  11454. }
  11455. }
  11456. ++delta;
  11457. ++n;
  11458. }
  11459. return output.join('');
  11460. }
  11461. /**
  11462. * Converts a Punycode string representing a domain name to Unicode. Only the
  11463. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  11464. * matter if you call it on a string that has already been converted to
  11465. * Unicode.
  11466. * @memberOf punycode
  11467. * @param {String} domain The Punycode domain name to convert to Unicode.
  11468. * @returns {String} The Unicode representation of the given Punycode
  11469. * string.
  11470. */
  11471. function toUnicode(domain) {
  11472. return mapDomain(domain, function(string) {
  11473. return regexPunycode.test(string) ?
  11474. decode(string.slice(4).toLowerCase()) :
  11475. string;
  11476. });
  11477. }
  11478. /**
  11479. * Converts a Unicode string representing a domain name to Punycode. Only the
  11480. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  11481. * matter if you call it with a domain that's already in ASCII.
  11482. * @memberOf punycode
  11483. * @param {String} domain The domain name to convert, as a Unicode string.
  11484. * @returns {String} The Punycode representation of the given domain name.
  11485. */
  11486. function toASCII(domain) {
  11487. return mapDomain(domain, function(string) {
  11488. return regexNonASCII.test(string) ?
  11489. 'xn--' + encode(string) :
  11490. string;
  11491. });
  11492. }
  11493. /*--------------------------------------------------------------------------*/
  11494. /** Define the public API */
  11495. punycode = {
  11496. /**
  11497. * A string representing the current Punycode.js version number.
  11498. * @memberOf punycode
  11499. * @type String
  11500. */
  11501. 'version': '1.2.4',
  11502. /**
  11503. * An object of methods to convert from JavaScript's internal character
  11504. * representation (UCS-2) to Unicode code points, and back.
  11505. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11506. * @memberOf punycode
  11507. * @type Object
  11508. */
  11509. 'ucs2': {
  11510. 'decode': ucs2decode,
  11511. 'encode': ucs2encode
  11512. },
  11513. 'decode': decode,
  11514. 'encode': encode,
  11515. 'toASCII': toASCII,
  11516. 'toUnicode': toUnicode
  11517. };
  11518. /** Expose `punycode` */
  11519. // Some AMD build optimizers, like r.js, check for specific condition patterns
  11520. // like the following:
  11521. if (
  11522. typeof define == 'function' &&
  11523. typeof define.amd == 'object' &&
  11524. define.amd
  11525. ) {
  11526. } else if (freeExports && !freeExports.nodeType) {
  11527. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  11528. freeModule.exports = punycode;
  11529. } else { // in Narwhal or RingoJS v0.7.0-
  11530. for (key in punycode) {
  11531. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  11532. }
  11533. }
  11534. } else { // in Rhino or a web browser
  11535. root.punycode = punycode;
  11536. }
  11537. }(this));
  11538. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
  11539. }, {}],
  11540. 2: [function(_dereq_, module, exports) {
  11541. var log = _dereq_('./log');
  11542. function restoreOwnerScroll(ownerDocument, x, y) {
  11543. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  11544. ownerDocument.defaultView.scrollTo(x, y);
  11545. }
  11546. }
  11547. function cloneCanvasContents(canvas, clonedCanvas) {
  11548. try {
  11549. if (clonedCanvas) {
  11550. clonedCanvas.width = canvas.width;
  11551. clonedCanvas.height = canvas.height;
  11552. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  11553. }
  11554. } catch (e) {
  11555. log("Unable to copy canvas content from", canvas, e);
  11556. }
  11557. }
  11558. function cloneNode(node, javascriptEnabled) {
  11559. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  11560. var child = node.firstChild;
  11561. while (child) {
  11562. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  11563. clone.appendChild(cloneNode(child, javascriptEnabled));
  11564. }
  11565. child = child.nextSibling;
  11566. }
  11567. if (node.nodeType === 1) {
  11568. clone._scrollTop = node.scrollTop;
  11569. clone._scrollLeft = node.scrollLeft;
  11570. if (node.nodeName === "CANVAS") {
  11571. cloneCanvasContents(node, clone);
  11572. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  11573. clone.value = node.value;
  11574. }
  11575. }
  11576. return clone;
  11577. }
  11578. function initNode(node) {
  11579. if (node.nodeType === 1) {
  11580. node.scrollTop = node._scrollTop;
  11581. node.scrollLeft = node._scrollLeft;
  11582. var child = node.firstChild;
  11583. while (child) {
  11584. initNode(child);
  11585. child = child.nextSibling;
  11586. }
  11587. }
  11588. }
  11589. module.exports = function(ownerDocument, containerDocument, width, height, options, x, y) {
  11590. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  11591. var container = containerDocument.createElement("iframe");
  11592. container.className = "html2canvas-container";
  11593. container.style.visibility = "hidden";
  11594. container.style.position = "fixed";
  11595. container.style.left = "-10000px";
  11596. container.style.top = "0px";
  11597. container.style.border = "0";
  11598. container.width = width;
  11599. container.height = height;
  11600. container.scrolling = "no"; // ios won't scroll without it
  11601. containerDocument.body.appendChild(container);
  11602. return new Promise(function(resolve) {
  11603. var documentClone = container.contentWindow.document;
  11604. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  11605. if window url is about:blank, we can assign the url to current by writing onto the document
  11606. */
  11607. container.contentWindow.onload = container.onload = function() {
  11608. var interval = setInterval(function() {
  11609. if (documentClone.body.childNodes.length > 0) {
  11610. initNode(documentClone.documentElement);
  11611. clearInterval(interval);
  11612. if (options.type === "view") {
  11613. container.contentWindow.scrollTo(x, y);
  11614. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  11615. documentClone.documentElement.style.top = (-y) + "px";
  11616. documentClone.documentElement.style.left = (-x) + "px";
  11617. documentClone.documentElement.style.position = 'absolute';
  11618. }
  11619. }
  11620. resolve(container);
  11621. }
  11622. }, 50);
  11623. };
  11624. documentClone.open();
  11625. documentClone.write("<!DOCTYPE html><html></html>");
  11626. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  11627. restoreOwnerScroll(ownerDocument, x, y);
  11628. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  11629. documentClone.close();
  11630. });
  11631. };
  11632. }, { "./log": 13 }],
  11633. 3: [function(_dereq_, module, exports) {
  11634. // http://dev.w3.org/csswg/css-color/
  11635. function Color(value) {
  11636. this.r = 0;
  11637. this.g = 0;
  11638. this.b = 0;
  11639. this.a = null;
  11640. var result = this.fromArray(value) ||
  11641. this.namedColor(value) ||
  11642. this.rgb(value) ||
  11643. this.rgba(value) ||
  11644. this.hex6(value) ||
  11645. this.hex3(value);
  11646. }
  11647. Color.prototype.darken = function(amount) {
  11648. var a = 1 - amount;
  11649. return new Color([
  11650. Math.round(this.r * a),
  11651. Math.round(this.g * a),
  11652. Math.round(this.b * a),
  11653. this.a
  11654. ]);
  11655. };
  11656. Color.prototype.isTransparent = function() {
  11657. return this.a === 0;
  11658. };
  11659. Color.prototype.isBlack = function() {
  11660. return this.r === 0 && this.g === 0 && this.b === 0;
  11661. };
  11662. Color.prototype.fromArray = function(array) {
  11663. if (Array.isArray(array)) {
  11664. this.r = Math.min(array[0], 255);
  11665. this.g = Math.min(array[1], 255);
  11666. this.b = Math.min(array[2], 255);
  11667. if (array.length > 3) {
  11668. this.a = array[3];
  11669. }
  11670. }
  11671. return (Array.isArray(array));
  11672. };
  11673. var _hex3 = /^#([a-f0-9]{3})$/i;
  11674. Color.prototype.hex3 = function(value) {
  11675. var match = null;
  11676. if ((match = value.match(_hex3)) !== null) {
  11677. this.r = parseInt(match[1][0] + match[1][0], 16);
  11678. this.g = parseInt(match[1][1] + match[1][1], 16);
  11679. this.b = parseInt(match[1][2] + match[1][2], 16);
  11680. }
  11681. return match !== null;
  11682. };
  11683. var _hex6 = /^#([a-f0-9]{6})$/i;
  11684. Color.prototype.hex6 = function(value) {
  11685. var match = null;
  11686. if ((match = value.match(_hex6)) !== null) {
  11687. this.r = parseInt(match[1].substring(0, 2), 16);
  11688. this.g = parseInt(match[1].substring(2, 4), 16);
  11689. this.b = parseInt(match[1].substring(4, 6), 16);
  11690. }
  11691. return match !== null;
  11692. };
  11693. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  11694. Color.prototype.rgb = function(value) {
  11695. var match = null;
  11696. if ((match = value.match(_rgb)) !== null) {
  11697. this.r = Number(match[1]);
  11698. this.g = Number(match[2]);
  11699. this.b = Number(match[3]);
  11700. }
  11701. return match !== null;
  11702. };
  11703. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  11704. Color.prototype.rgba = function(value) {
  11705. var match = null;
  11706. if ((match = value.match(_rgba)) !== null) {
  11707. this.r = Number(match[1]);
  11708. this.g = Number(match[2]);
  11709. this.b = Number(match[3]);
  11710. this.a = Number(match[4]);
  11711. }
  11712. return match !== null;
  11713. };
  11714. Color.prototype.toString = function() {
  11715. return this.a !== null && this.a !== 1 ?
  11716. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  11717. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  11718. };
  11719. Color.prototype.namedColor = function(value) {
  11720. value = value.toLowerCase();
  11721. var color = colors[value];
  11722. if (color) {
  11723. this.r = color[0];
  11724. this.g = color[1];
  11725. this.b = color[2];
  11726. } else if (value === "transparent") {
  11727. this.r = this.g = this.b = this.a = 0;
  11728. return true;
  11729. }
  11730. return !!color;
  11731. };
  11732. Color.prototype.isColor = true;
  11733. // 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}, {}))
  11734. var colors = {
  11735. "aliceblue": [240, 248, 255],
  11736. "antiquewhite": [250, 235, 215],
  11737. "aqua": [0, 255, 255],
  11738. "aquamarine": [127, 255, 212],
  11739. "azure": [240, 255, 255],
  11740. "beige": [245, 245, 220],
  11741. "bisque": [255, 228, 196],
  11742. "black": [0, 0, 0],
  11743. "blanchedalmond": [255, 235, 205],
  11744. "blue": [0, 0, 255],
  11745. "blueviolet": [138, 43, 226],
  11746. "brown": [165, 42, 42],
  11747. "burlywood": [222, 184, 135],
  11748. "cadetblue": [95, 158, 160],
  11749. "chartreuse": [127, 255, 0],
  11750. "chocolate": [210, 105, 30],
  11751. "coral": [255, 127, 80],
  11752. "cornflowerblue": [100, 149, 237],
  11753. "cornsilk": [255, 248, 220],
  11754. "crimson": [220, 20, 60],
  11755. "cyan": [0, 255, 255],
  11756. "darkblue": [0, 0, 139],
  11757. "darkcyan": [0, 139, 139],
  11758. "darkgoldenrod": [184, 134, 11],
  11759. "darkgray": [169, 169, 169],
  11760. "darkgreen": [0, 100, 0],
  11761. "darkgrey": [169, 169, 169],
  11762. "darkkhaki": [189, 183, 107],
  11763. "darkmagenta": [139, 0, 139],
  11764. "darkolivegreen": [85, 107, 47],
  11765. "darkorange": [255, 140, 0],
  11766. "darkorchid": [153, 50, 204],
  11767. "darkred": [139, 0, 0],
  11768. "darksalmon": [233, 150, 122],
  11769. "darkseagreen": [143, 188, 143],
  11770. "darkslateblue": [72, 61, 139],
  11771. "darkslategray": [47, 79, 79],
  11772. "darkslategrey": [47, 79, 79],
  11773. "darkturquoise": [0, 206, 209],
  11774. "darkviolet": [148, 0, 211],
  11775. "deeppink": [255, 20, 147],
  11776. "deepskyblue": [0, 191, 255],
  11777. "dimgray": [105, 105, 105],
  11778. "dimgrey": [105, 105, 105],
  11779. "dodgerblue": [30, 144, 255],
  11780. "firebrick": [178, 34, 34],
  11781. "floralwhite": [255, 250, 240],
  11782. "forestgreen": [34, 139, 34],
  11783. "fuchsia": [255, 0, 255],
  11784. "gainsboro": [220, 220, 220],
  11785. "ghostwhite": [248, 248, 255],
  11786. "gold": [255, 215, 0],
  11787. "goldenrod": [218, 165, 32],
  11788. "gray": [128, 128, 128],
  11789. "green": [0, 128, 0],
  11790. "greenyellow": [173, 255, 47],
  11791. "grey": [128, 128, 128],
  11792. "honeydew": [240, 255, 240],
  11793. "hotpink": [255, 105, 180],
  11794. "indianred": [205, 92, 92],
  11795. "indigo": [75, 0, 130],
  11796. "ivory": [255, 255, 240],
  11797. "khaki": [240, 230, 140],
  11798. "lavender": [230, 230, 250],
  11799. "lavenderblush": [255, 240, 245],
  11800. "lawngreen": [124, 252, 0],
  11801. "lemonchiffon": [255, 250, 205],
  11802. "lightblue": [173, 216, 230],
  11803. "lightcoral": [240, 128, 128],
  11804. "lightcyan": [224, 255, 255],
  11805. "lightgoldenrodyellow": [250, 250, 210],
  11806. "lightgray": [211, 211, 211],
  11807. "lightgreen": [144, 238, 144],
  11808. "lightgrey": [211, 211, 211],
  11809. "lightpink": [255, 182, 193],
  11810. "lightsalmon": [255, 160, 122],
  11811. "lightseagreen": [32, 178, 170],
  11812. "lightskyblue": [135, 206, 250],
  11813. "lightslategray": [119, 136, 153],
  11814. "lightslategrey": [119, 136, 153],
  11815. "lightsteelblue": [176, 196, 222],
  11816. "lightyellow": [255, 255, 224],
  11817. "lime": [0, 255, 0],
  11818. "limegreen": [50, 205, 50],
  11819. "linen": [250, 240, 230],
  11820. "magenta": [255, 0, 255],
  11821. "maroon": [128, 0, 0],
  11822. "mediumaquamarine": [102, 205, 170],
  11823. "mediumblue": [0, 0, 205],
  11824. "mediumorchid": [186, 85, 211],
  11825. "mediumpurple": [147, 112, 219],
  11826. "mediumseagreen": [60, 179, 113],
  11827. "mediumslateblue": [123, 104, 238],
  11828. "mediumspringgreen": [0, 250, 154],
  11829. "mediumturquoise": [72, 209, 204],
  11830. "mediumvioletred": [199, 21, 133],
  11831. "midnightblue": [25, 25, 112],
  11832. "mintcream": [245, 255, 250],
  11833. "mistyrose": [255, 228, 225],
  11834. "moccasin": [255, 228, 181],
  11835. "navajowhite": [255, 222, 173],
  11836. "navy": [0, 0, 128],
  11837. "oldlace": [253, 245, 230],
  11838. "olive": [128, 128, 0],
  11839. "olivedrab": [107, 142, 35],
  11840. "orange": [255, 165, 0],
  11841. "orangered": [255, 69, 0],
  11842. "orchid": [218, 112, 214],
  11843. "palegoldenrod": [238, 232, 170],
  11844. "palegreen": [152, 251, 152],
  11845. "paleturquoise": [175, 238, 238],
  11846. "palevioletred": [219, 112, 147],
  11847. "papayawhip": [255, 239, 213],
  11848. "peachpuff": [255, 218, 185],
  11849. "peru": [205, 133, 63],
  11850. "pink": [255, 192, 203],
  11851. "plum": [221, 160, 221],
  11852. "powderblue": [176, 224, 230],
  11853. "purple": [128, 0, 128],
  11854. "rebeccapurple": [102, 51, 153],
  11855. "red": [255, 0, 0],
  11856. "rosybrown": [188, 143, 143],
  11857. "royalblue": [65, 105, 225],
  11858. "saddlebrown": [139, 69, 19],
  11859. "salmon": [250, 128, 114],
  11860. "sandybrown": [244, 164, 96],
  11861. "seagreen": [46, 139, 87],
  11862. "seashell": [255, 245, 238],
  11863. "sienna": [160, 82, 45],
  11864. "silver": [192, 192, 192],
  11865. "skyblue": [135, 206, 235],
  11866. "slateblue": [106, 90, 205],
  11867. "slategray": [112, 128, 144],
  11868. "slategrey": [112, 128, 144],
  11869. "snow": [255, 250, 250],
  11870. "springgreen": [0, 255, 127],
  11871. "steelblue": [70, 130, 180],
  11872. "tan": [210, 180, 140],
  11873. "teal": [0, 128, 128],
  11874. "thistle": [216, 191, 216],
  11875. "tomato": [255, 99, 71],
  11876. "turquoise": [64, 224, 208],
  11877. "violet": [238, 130, 238],
  11878. "wheat": [245, 222, 179],
  11879. "white": [255, 255, 255],
  11880. "whitesmoke": [245, 245, 245],
  11881. "yellow": [255, 255, 0],
  11882. "yellowgreen": [154, 205, 50]
  11883. };
  11884. module.exports = Color;
  11885. }, {}],
  11886. 4: [function(_dereq_, module, exports) {
  11887. var Support = _dereq_('./support');
  11888. var CanvasRenderer = _dereq_('./renderers/canvas');
  11889. var ImageLoader = _dereq_('./imageloader');
  11890. var NodeParser = _dereq_('./nodeparser');
  11891. var NodeContainer = _dereq_('./nodecontainer');
  11892. var log = _dereq_('./log');
  11893. var utils = _dereq_('./utils');
  11894. var createWindowClone = _dereq_('./clone');
  11895. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  11896. var getBounds = utils.getBounds;
  11897. var html2canvasNodeAttribute = "data-html2canvas-node";
  11898. var html2canvasCloneIndex = 0;
  11899. function html2canvas(nodeList, options) {
  11900. var index = html2canvasCloneIndex++;
  11901. options = options || {};
  11902. if (options.logging) {
  11903. log.options.logging = true;
  11904. log.options.start = Date.now();
  11905. }
  11906. options.async = typeof(options.async) === "undefined" ? true : options.async;
  11907. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  11908. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  11909. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  11910. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  11911. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  11912. options.strict = !!options.strict;
  11913. if (typeof(nodeList) === "string") {
  11914. if (typeof(options.proxy) !== "string") {
  11915. return Promise.reject("Proxy must be used when rendering url");
  11916. }
  11917. var width = options.width != null ? options.width : window.innerWidth;
  11918. var height = options.height != null ? options.height : window.innerHeight;
  11919. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  11920. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  11921. });
  11922. }
  11923. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  11924. node.setAttribute(html2canvasNodeAttribute + index, index);
  11925. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  11926. if (typeof(options.onrendered) === "function") {
  11927. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  11928. options.onrendered(canvas);
  11929. }
  11930. return canvas;
  11931. });
  11932. }
  11933. html2canvas.CanvasRenderer = CanvasRenderer;
  11934. html2canvas.NodeContainer = NodeContainer;
  11935. html2canvas.log = log;
  11936. html2canvas.utils = utils;
  11937. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  11938. return Promise.reject("No canvas support");
  11939. } : html2canvas;
  11940. module.exports = html2canvasExport;
  11941. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  11942. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  11943. log("Document cloned");
  11944. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  11945. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  11946. document.querySelector(selector).removeAttribute(attributeName);
  11947. var clonedWindow = container.contentWindow;
  11948. var node = clonedWindow.document.querySelector(selector);
  11949. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  11950. return oncloneHandler.then(function() {
  11951. return renderWindow(node, container, options, windowWidth, windowHeight);
  11952. });
  11953. });
  11954. }
  11955. function renderWindow(node, container, options, windowWidth, windowHeight) {
  11956. var clonedWindow = container.contentWindow;
  11957. var support = new Support(clonedWindow.document);
  11958. var imageLoader = new ImageLoader(options, support);
  11959. var bounds = getBounds(node);
  11960. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  11961. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  11962. var renderer = new options.renderer(width, height, imageLoader, options, document);
  11963. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  11964. return parser.ready.then(function() {
  11965. log("Finished rendering");
  11966. var canvas;
  11967. if (options.type === "view") {
  11968. canvas = crop(renderer.canvas, { width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0 });
  11969. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  11970. canvas = renderer.canvas;
  11971. } else {
  11972. 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 });
  11973. }
  11974. cleanupContainer(container, options);
  11975. return canvas;
  11976. });
  11977. }
  11978. function cleanupContainer(container, options) {
  11979. if (options.removeContainer) {
  11980. container.parentNode.removeChild(container);
  11981. log("Cleaned up container");
  11982. }
  11983. }
  11984. function crop(canvas, bounds) {
  11985. var croppedCanvas = document.createElement("canvas");
  11986. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  11987. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  11988. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  11989. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  11990. croppedCanvas.width = bounds.width;
  11991. croppedCanvas.height = bounds.height;
  11992. var width = x2 - x1;
  11993. var height = y2 - y1;
  11994. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  11995. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  11996. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  11997. return croppedCanvas;
  11998. }
  11999. function documentWidth(doc) {
  12000. return Math.max(
  12001. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  12002. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  12003. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  12004. );
  12005. }
  12006. function documentHeight(doc) {
  12007. return Math.max(
  12008. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  12009. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  12010. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  12011. );
  12012. }
  12013. function absoluteUrl(url) {
  12014. var link = document.createElement("a");
  12015. link.href = url;
  12016. link.href = link.href;
  12017. return link;
  12018. }
  12019. }, { "./clone": 2, "./imageloader": 11, "./log": 13, "./nodecontainer": 14, "./nodeparser": 15, "./proxy": 16, "./renderers/canvas": 20, "./support": 22, "./utils": 26 }],
  12020. 5: [function(_dereq_, module, exports) {
  12021. var log = _dereq_('./log');
  12022. var smallImage = _dereq_('./utils').smallImage;
  12023. function DummyImageContainer(src) {
  12024. this.src = src;
  12025. log("DummyImageContainer for", src);
  12026. if (!this.promise || !this.image) {
  12027. log("Initiating DummyImageContainer");
  12028. DummyImageContainer.prototype.image = new Image();
  12029. var image = this.image;
  12030. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  12031. image.onload = resolve;
  12032. image.onerror = reject;
  12033. image.src = smallImage();
  12034. if (image.complete === true) {
  12035. resolve(image);
  12036. }
  12037. });
  12038. }
  12039. }
  12040. module.exports = DummyImageContainer;
  12041. }, { "./log": 13, "./utils": 26 }],
  12042. 6: [function(_dereq_, module, exports) {
  12043. var smallImage = _dereq_('./utils').smallImage;
  12044. function Font(family, size) {
  12045. var container = document.createElement('div'),
  12046. img = document.createElement('img'),
  12047. span = document.createElement('span'),
  12048. sampleText = 'Hidden Text',
  12049. baseline,
  12050. middle;
  12051. container.style.visibility = "hidden";
  12052. container.style.fontFamily = family;
  12053. container.style.fontSize = size;
  12054. container.style.margin = 0;
  12055. container.style.padding = 0;
  12056. document.body.appendChild(container);
  12057. img.src = smallImage();
  12058. img.width = 1;
  12059. img.height = 1;
  12060. img.style.margin = 0;
  12061. img.style.padding = 0;
  12062. img.style.verticalAlign = "baseline";
  12063. span.style.fontFamily = family;
  12064. span.style.fontSize = size;
  12065. span.style.margin = 0;
  12066. span.style.padding = 0;
  12067. span.appendChild(document.createTextNode(sampleText));
  12068. container.appendChild(span);
  12069. container.appendChild(img);
  12070. baseline = (img.offsetTop - span.offsetTop) + 1;
  12071. container.removeChild(span);
  12072. container.appendChild(document.createTextNode(sampleText));
  12073. container.style.lineHeight = "normal";
  12074. img.style.verticalAlign = "super";
  12075. middle = (img.offsetTop - container.offsetTop) + 1;
  12076. document.body.removeChild(container);
  12077. this.baseline = baseline;
  12078. this.lineWidth = 1;
  12079. this.middle = middle;
  12080. }
  12081. module.exports = Font;
  12082. }, { "./utils": 26 }],
  12083. 7: [function(_dereq_, module, exports) {
  12084. var Font = _dereq_('./font');
  12085. function FontMetrics() {
  12086. this.data = {};
  12087. }
  12088. FontMetrics.prototype.getMetrics = function(family, size) {
  12089. if (this.data[family + "-" + size] === undefined) {
  12090. this.data[family + "-" + size] = new Font(family, size);
  12091. }
  12092. return this.data[family + "-" + size];
  12093. };
  12094. module.exports = FontMetrics;
  12095. }, { "./font": 6 }],
  12096. 8: [function(_dereq_, module, exports) {
  12097. var utils = _dereq_('./utils');
  12098. var getBounds = utils.getBounds;
  12099. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  12100. function FrameContainer(container, sameOrigin, options) {
  12101. this.image = null;
  12102. this.src = container;
  12103. var self = this;
  12104. var bounds = getBounds(container);
  12105. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  12106. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  12107. container.contentWindow.onload = container.onload = function() {
  12108. resolve(container);
  12109. };
  12110. } else {
  12111. resolve(container);
  12112. }
  12113. })).then(function(container) {
  12114. var html2canvas = _dereq_('./core');
  12115. 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 });
  12116. }).then(function(canvas) {
  12117. return self.image = canvas;
  12118. });
  12119. }
  12120. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  12121. var container = this.src;
  12122. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  12123. };
  12124. module.exports = FrameContainer;
  12125. }, { "./core": 4, "./proxy": 16, "./utils": 26 }],
  12126. 9: [function(_dereq_, module, exports) {
  12127. function GradientContainer(imageData) {
  12128. this.src = imageData.value;
  12129. this.colorStops = [];
  12130. this.type = null;
  12131. this.x0 = 0.5;
  12132. this.y0 = 0.5;
  12133. this.x1 = 0.5;
  12134. this.y1 = 0.5;
  12135. this.promise = Promise.resolve(true);
  12136. }
  12137. GradientContainer.TYPES = {
  12138. LINEAR: 1,
  12139. RADIAL: 2
  12140. };
  12141. // TODO: support hsl[a], negative %/length values
  12142. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12143. 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;
  12144. module.exports = GradientContainer;
  12145. }, {}],
  12146. 10: [function(_dereq_, module, exports) {
  12147. function ImageContainer(src, cors) {
  12148. this.src = src;
  12149. this.image = new Image();
  12150. var self = this;
  12151. this.tainted = null;
  12152. this.promise = new Promise(function(resolve, reject) {
  12153. self.image.onload = resolve;
  12154. self.image.onerror = reject;
  12155. if (cors) {
  12156. self.image.crossOrigin = "anonymous";
  12157. }
  12158. self.image.src = src;
  12159. if (self.image.complete === true) {
  12160. resolve(self.image);
  12161. }
  12162. });
  12163. }
  12164. module.exports = ImageContainer;
  12165. }, {}],
  12166. 11: [function(_dereq_, module, exports) {
  12167. var log = _dereq_('./log');
  12168. var ImageContainer = _dereq_('./imagecontainer');
  12169. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  12170. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  12171. var FrameContainer = _dereq_('./framecontainer');
  12172. var SVGContainer = _dereq_('./svgcontainer');
  12173. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  12174. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  12175. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  12176. var bind = _dereq_('./utils').bind;
  12177. function ImageLoader(options, support) {
  12178. this.link = null;
  12179. this.options = options;
  12180. this.support = support;
  12181. this.origin = this.getOrigin(window.location.href);
  12182. }
  12183. ImageLoader.prototype.findImages = function(nodes) {
  12184. var images = [];
  12185. nodes.reduce(function(imageNodes, container) {
  12186. switch (container.node.nodeName) {
  12187. case "IMG":
  12188. return imageNodes.concat([{
  12189. args: [container.node.src],
  12190. method: "url"
  12191. }]);
  12192. case "svg":
  12193. case "IFRAME":
  12194. return imageNodes.concat([{
  12195. args: [container.node],
  12196. method: container.node.nodeName
  12197. }]);
  12198. }
  12199. return imageNodes;
  12200. }, []).forEach(this.addImage(images, this.loadImage), this);
  12201. return images;
  12202. };
  12203. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  12204. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  12205. return images;
  12206. };
  12207. ImageLoader.prototype.addImage = function(images, callback) {
  12208. return function(newImage) {
  12209. newImage.args.forEach(function(image) {
  12210. if (!this.imageExists(images, image)) {
  12211. images.splice(0, 0, callback.call(this, newImage));
  12212. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  12213. }
  12214. }, this);
  12215. };
  12216. };
  12217. ImageLoader.prototype.hasImageBackground = function(imageData) {
  12218. return imageData.method !== "none";
  12219. };
  12220. ImageLoader.prototype.loadImage = function(imageData) {
  12221. if (imageData.method === "url") {
  12222. var src = imageData.args[0];
  12223. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  12224. return new SVGContainer(src);
  12225. } else if (src.match(/data:image\/.*;base64,/i)) {
  12226. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  12227. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  12228. return new ImageContainer(src, false);
  12229. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  12230. return new ImageContainer(src, true);
  12231. } else if (this.options.proxy) {
  12232. return new ProxyImageContainer(src, this.options.proxy);
  12233. } else {
  12234. return new DummyImageContainer(src);
  12235. }
  12236. } else if (imageData.method === "linear-gradient") {
  12237. return new LinearGradientContainer(imageData);
  12238. } else if (imageData.method === "gradient") {
  12239. return new WebkitGradientContainer(imageData);
  12240. } else if (imageData.method === "svg") {
  12241. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  12242. } else if (imageData.method === "IFRAME") {
  12243. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  12244. } else {
  12245. return new DummyImageContainer(imageData);
  12246. }
  12247. };
  12248. ImageLoader.prototype.isSVG = function(src) {
  12249. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  12250. };
  12251. ImageLoader.prototype.imageExists = function(images, src) {
  12252. return images.some(function(image) {
  12253. return image.src === src;
  12254. });
  12255. };
  12256. ImageLoader.prototype.isSameOrigin = function(url) {
  12257. return (this.getOrigin(url) === this.origin);
  12258. };
  12259. ImageLoader.prototype.getOrigin = function(url) {
  12260. var link = this.link || (this.link = document.createElement("a"));
  12261. link.href = url;
  12262. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  12263. return link.protocol + link.hostname + link.port;
  12264. };
  12265. ImageLoader.prototype.getPromise = function(container) {
  12266. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  12267. var dummy = new DummyImageContainer(container.src);
  12268. return dummy.promise.then(function(image) {
  12269. container.image = image;
  12270. });
  12271. });
  12272. };
  12273. ImageLoader.prototype.get = function(src) {
  12274. var found = null;
  12275. return this.images.some(function(img) {
  12276. return (found = img).src === src;
  12277. }) ? found : null;
  12278. };
  12279. ImageLoader.prototype.fetch = function(nodes) {
  12280. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  12281. this.images.forEach(function(image, index) {
  12282. image.promise.then(function() {
  12283. log("Succesfully loaded image #" + (index + 1), image);
  12284. }, function(e) {
  12285. log("Failed loading image #" + (index + 1), image, e);
  12286. });
  12287. });
  12288. this.ready = Promise.all(this.images.map(this.getPromise, this));
  12289. log("Finished searching images");
  12290. return this;
  12291. };
  12292. ImageLoader.prototype.timeout = function(container, timeout) {
  12293. var timer;
  12294. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  12295. timer = setTimeout(function() {
  12296. log("Timed out loading image", container);
  12297. reject(container);
  12298. }, timeout);
  12299. })]).then(function(container) {
  12300. clearTimeout(timer);
  12301. return container;
  12302. });
  12303. promise['catch'](function() {
  12304. clearTimeout(timer);
  12305. });
  12306. return promise;
  12307. };
  12308. module.exports = ImageLoader;
  12309. }, { "./dummyimagecontainer": 5, "./framecontainer": 8, "./imagecontainer": 10, "./lineargradientcontainer": 12, "./log": 13, "./proxyimagecontainer": 17, "./svgcontainer": 23, "./svgnodecontainer": 24, "./utils": 26, "./webkitgradientcontainer": 27 }],
  12310. 12: [function(_dereq_, module, exports) {
  12311. var GradientContainer = _dereq_('./gradientcontainer');
  12312. var Color = _dereq_('./color');
  12313. function LinearGradientContainer(imageData) {
  12314. GradientContainer.apply(this, arguments);
  12315. this.type = GradientContainer.TYPES.LINEAR;
  12316. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test(imageData.args[0]) ||
  12317. !GradientContainer.REGEXP_COLORSTOP.test(imageData.args[0]);
  12318. if (hasDirection) {
  12319. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  12320. switch (position) {
  12321. case "left":
  12322. this.x0 = 0;
  12323. this.x1 = 1;
  12324. break;
  12325. case "top":
  12326. this.y0 = 0;
  12327. this.y1 = 1;
  12328. break;
  12329. case "right":
  12330. this.x0 = 1;
  12331. this.x1 = 0;
  12332. break;
  12333. case "bottom":
  12334. this.y0 = 1;
  12335. this.y1 = 0;
  12336. break;
  12337. case "to":
  12338. var y0 = this.y0;
  12339. var x0 = this.x0;
  12340. this.y0 = this.y1;
  12341. this.x0 = this.x1;
  12342. this.x1 = x0;
  12343. this.y1 = y0;
  12344. break;
  12345. case "center":
  12346. break; // centered by default
  12347. // Firefox internally converts position keywords to percentages:
  12348. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  12349. default: // percentage or absolute length
  12350. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  12351. var ratio = parseFloat(position, 10) * 1e-2;
  12352. if (isNaN(ratio)) { // invalid or unhandled value
  12353. break;
  12354. }
  12355. if (index === 0) {
  12356. this.y0 = ratio;
  12357. this.y1 = 1 - this.y0;
  12358. } else {
  12359. this.x0 = ratio;
  12360. this.x1 = 1 - this.x0;
  12361. }
  12362. break;
  12363. }
  12364. }, this);
  12365. } else {
  12366. this.y0 = 0;
  12367. this.y1 = 1;
  12368. }
  12369. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  12370. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  12371. var value = +colorStopMatch[2];
  12372. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  12373. return {
  12374. color: new Color(colorStopMatch[1]),
  12375. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  12376. stop: unit === "%" ? value / 100 : null
  12377. };
  12378. });
  12379. if (this.colorStops[0].stop === null) {
  12380. this.colorStops[0].stop = 0;
  12381. }
  12382. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  12383. this.colorStops[this.colorStops.length - 1].stop = 1;
  12384. }
  12385. // calculates and fills-in explicit stop positions when omitted from rule
  12386. this.colorStops.forEach(function(colorStop, index) {
  12387. if (colorStop.stop === null) {
  12388. this.colorStops.slice(index).some(function(find, count) {
  12389. if (find.stop !== null) {
  12390. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  12391. return true;
  12392. } else {
  12393. return false;
  12394. }
  12395. }, this);
  12396. }
  12397. }, this);
  12398. }
  12399. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  12400. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12401. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  12402. module.exports = LinearGradientContainer;
  12403. }, { "./color": 3, "./gradientcontainer": 9 }],
  12404. 13: [function(_dereq_, module, exports) {
  12405. var logger = function() {
  12406. if (logger.options.logging && window.console && window.console.log) {
  12407. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  12408. }
  12409. };
  12410. logger.options = { logging: false };
  12411. module.exports = logger;
  12412. }, {}],
  12413. 14: [function(_dereq_, module, exports) {
  12414. var Color = _dereq_('./color');
  12415. var utils = _dereq_('./utils');
  12416. var getBounds = utils.getBounds;
  12417. var parseBackgrounds = utils.parseBackgrounds;
  12418. var offsetBounds = utils.offsetBounds;
  12419. function NodeContainer(node, parent) {
  12420. this.node = node;
  12421. this.parent = parent;
  12422. this.stack = null;
  12423. this.bounds = null;
  12424. this.borders = null;
  12425. this.clip = [];
  12426. this.backgroundClip = [];
  12427. this.offsetBounds = null;
  12428. this.visible = null;
  12429. this.computedStyles = null;
  12430. this.colors = {};
  12431. this.styles = {};
  12432. this.backgroundImages = null;
  12433. this.transformData = null;
  12434. this.transformMatrix = null;
  12435. this.isPseudoElement = false;
  12436. this.opacity = null;
  12437. }
  12438. NodeContainer.prototype.cloneTo = function(stack) {
  12439. stack.visible = this.visible;
  12440. stack.borders = this.borders;
  12441. stack.bounds = this.bounds;
  12442. stack.clip = this.clip;
  12443. stack.backgroundClip = this.backgroundClip;
  12444. stack.computedStyles = this.computedStyles;
  12445. stack.styles = this.styles;
  12446. stack.backgroundImages = this.backgroundImages;
  12447. stack.opacity = this.opacity;
  12448. };
  12449. NodeContainer.prototype.getOpacity = function() {
  12450. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  12451. };
  12452. NodeContainer.prototype.assignStack = function(stack) {
  12453. this.stack = stack;
  12454. stack.children.push(this);
  12455. };
  12456. NodeContainer.prototype.isElementVisible = function() {
  12457. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  12458. this.css('display') !== "none" &&
  12459. this.css('visibility') !== "hidden" &&
  12460. !this.node.hasAttribute("data-html2canvas-ignore") &&
  12461. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  12462. );
  12463. };
  12464. NodeContainer.prototype.css = function(attribute) {
  12465. if (!this.computedStyles) {
  12466. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  12467. }
  12468. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  12469. };
  12470. NodeContainer.prototype.prefixedCss = function(attribute) {
  12471. var prefixes = ["webkit", "moz", "ms", "o"];
  12472. var value = this.css(attribute);
  12473. if (value === undefined) {
  12474. prefixes.some(function(prefix) {
  12475. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  12476. return value !== undefined;
  12477. }, this);
  12478. }
  12479. return value === undefined ? null : value;
  12480. };
  12481. NodeContainer.prototype.computedStyle = function(type) {
  12482. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  12483. };
  12484. NodeContainer.prototype.cssInt = function(attribute) {
  12485. var value = parseInt(this.css(attribute), 10);
  12486. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  12487. };
  12488. NodeContainer.prototype.color = function(attribute) {
  12489. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  12490. };
  12491. NodeContainer.prototype.cssFloat = function(attribute) {
  12492. var value = parseFloat(this.css(attribute));
  12493. return (isNaN(value)) ? 0 : value;
  12494. };
  12495. NodeContainer.prototype.fontWeight = function() {
  12496. var weight = this.css("fontWeight");
  12497. switch (parseInt(weight, 10)) {
  12498. case 401:
  12499. weight = "bold";
  12500. break;
  12501. case 400:
  12502. weight = "normal";
  12503. break;
  12504. }
  12505. return weight;
  12506. };
  12507. NodeContainer.prototype.parseClip = function() {
  12508. var matches = this.css('clip').match(this.CLIP);
  12509. if (matches) {
  12510. return {
  12511. top: parseInt(matches[1], 10),
  12512. right: parseInt(matches[2], 10),
  12513. bottom: parseInt(matches[3], 10),
  12514. left: parseInt(matches[4], 10)
  12515. };
  12516. }
  12517. return null;
  12518. };
  12519. NodeContainer.prototype.parseBackgroundImages = function() {
  12520. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  12521. };
  12522. NodeContainer.prototype.cssList = function(property, index) {
  12523. var value = (this.css(property) || '').split(',');
  12524. value = value[index || 0] || value[0] || 'auto';
  12525. value = value.trim().split(' ');
  12526. if (value.length === 1) {
  12527. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  12528. }
  12529. return value;
  12530. };
  12531. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  12532. var size = this.cssList("backgroundSize", index);
  12533. var width, height;
  12534. if (isPercentage(size[0])) {
  12535. width = bounds.width * parseFloat(size[0]) / 100;
  12536. } else if (/contain|cover/.test(size[0])) {
  12537. var targetRatio = bounds.width / bounds.height,
  12538. currentRatio = image.width / image.height;
  12539. return (targetRatio < currentRatio ^ size[0] === 'contain') ? { width: bounds.height * currentRatio, height: bounds.height } : { width: bounds.width, height: bounds.width / currentRatio };
  12540. } else {
  12541. width = parseInt(size[0], 10);
  12542. }
  12543. if (size[0] === 'auto' && size[1] === 'auto') {
  12544. height = image.height;
  12545. } else if (size[1] === 'auto') {
  12546. height = width / image.width * image.height;
  12547. } else if (isPercentage(size[1])) {
  12548. height = bounds.height * parseFloat(size[1]) / 100;
  12549. } else {
  12550. height = parseInt(size[1], 10);
  12551. }
  12552. if (size[0] === 'auto') {
  12553. width = height / image.height * image.width;
  12554. }
  12555. return { width: width, height: height };
  12556. };
  12557. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  12558. var position = this.cssList('backgroundPosition', index);
  12559. var left, top;
  12560. if (isPercentage(position[0])) {
  12561. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  12562. } else {
  12563. left = parseInt(position[0], 10);
  12564. }
  12565. if (position[1] === 'auto') {
  12566. top = left / image.width * image.height;
  12567. } else if (isPercentage(position[1])) {
  12568. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  12569. } else {
  12570. top = parseInt(position[1], 10);
  12571. }
  12572. if (position[0] === 'auto') {
  12573. left = top / image.height * image.width;
  12574. }
  12575. return { left: left, top: top };
  12576. };
  12577. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  12578. return this.cssList("backgroundRepeat", index)[0];
  12579. };
  12580. NodeContainer.prototype.parseTextShadows = function() {
  12581. var textShadow = this.css("textShadow");
  12582. var results = [];
  12583. if (textShadow && textShadow !== 'none') {
  12584. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  12585. for (var i = 0; shadows && (i < shadows.length); i++) {
  12586. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  12587. results.push({
  12588. color: new Color(s[0]),
  12589. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  12590. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  12591. blur: s[3] ? s[3].replace('px', '') : 0
  12592. });
  12593. }
  12594. }
  12595. return results;
  12596. };
  12597. NodeContainer.prototype.parseTransform = function() {
  12598. if (!this.transformData) {
  12599. if (this.hasTransform()) {
  12600. var offset = this.parseBounds();
  12601. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  12602. origin[0] += offset.left;
  12603. origin[1] += offset.top;
  12604. this.transformData = {
  12605. origin: origin,
  12606. matrix: this.parseTransformMatrix()
  12607. };
  12608. } else {
  12609. this.transformData = {
  12610. origin: [0, 0],
  12611. matrix: [1, 0, 0, 1, 0, 0]
  12612. };
  12613. }
  12614. }
  12615. return this.transformData;
  12616. };
  12617. NodeContainer.prototype.parseTransformMatrix = function() {
  12618. if (!this.transformMatrix) {
  12619. var transform = this.prefixedCss("transform");
  12620. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  12621. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  12622. }
  12623. return this.transformMatrix;
  12624. };
  12625. NodeContainer.prototype.parseBounds = function() {
  12626. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  12627. };
  12628. NodeContainer.prototype.hasTransform = function() {
  12629. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  12630. };
  12631. NodeContainer.prototype.getValue = function() {
  12632. var value = this.node.value || "";
  12633. if (this.node.tagName === "SELECT") {
  12634. value = selectionValue(this.node);
  12635. } else if (this.node.type === "password") {
  12636. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  12637. }
  12638. return value.length === 0 ? (this.node.placeholder || "") : value;
  12639. };
  12640. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  12641. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  12642. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  12643. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  12644. function selectionValue(node) {
  12645. var option = node.options[node.selectedIndex || 0];
  12646. return option ? (option.text || "") : "";
  12647. }
  12648. function parseMatrix(match) {
  12649. if (match && match[1] === "matrix") {
  12650. return match[2].split(",").map(function(s) {
  12651. return parseFloat(s.trim());
  12652. });
  12653. } else if (match && match[1] === "matrix3d") {
  12654. var matrix3d = match[2].split(",").map(function(s) {
  12655. return parseFloat(s.trim());
  12656. });
  12657. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  12658. }
  12659. }
  12660. function isPercentage(value) {
  12661. return value.toString().indexOf("%") !== -1;
  12662. }
  12663. function removePx(str) {
  12664. return str.replace("px", "");
  12665. }
  12666. function asFloat(str) {
  12667. return parseFloat(str);
  12668. }
  12669. module.exports = NodeContainer;
  12670. }, { "./color": 3, "./utils": 26 }],
  12671. 15: [function(_dereq_, module, exports) {
  12672. var log = _dereq_('./log');
  12673. var punycode = _dereq_('punycode');
  12674. var NodeContainer = _dereq_('./nodecontainer');
  12675. var TextContainer = _dereq_('./textcontainer');
  12676. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  12677. var FontMetrics = _dereq_('./fontmetrics');
  12678. var Color = _dereq_('./color');
  12679. var StackingContext = _dereq_('./stackingcontext');
  12680. var utils = _dereq_('./utils');
  12681. var bind = utils.bind;
  12682. var getBounds = utils.getBounds;
  12683. var parseBackgrounds = utils.parseBackgrounds;
  12684. var offsetBounds = utils.offsetBounds;
  12685. function NodeParser(element, renderer, support, imageLoader, options) {
  12686. log("Starting NodeParser");
  12687. this.renderer = renderer;
  12688. this.options = options;
  12689. this.range = null;
  12690. this.support = support;
  12691. this.renderQueue = [];
  12692. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  12693. var parent = new NodeContainer(element, null);
  12694. if (options.background) {
  12695. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  12696. }
  12697. if (element === element.ownerDocument.documentElement) {
  12698. // http://www.w3.org/TR/css3-background/#special-backgrounds
  12699. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  12700. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  12701. }
  12702. parent.visibile = parent.isElementVisible();
  12703. this.createPseudoHideStyles(element.ownerDocument);
  12704. this.disableAnimations(element.ownerDocument);
  12705. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  12706. return container.visible = container.isElementVisible();
  12707. }).map(this.getPseudoElements, this));
  12708. this.fontMetrics = new FontMetrics();
  12709. log("Fetched nodes, total:", this.nodes.length);
  12710. log("Calculate overflow clips");
  12711. this.calculateOverflowClips();
  12712. log("Start fetching images");
  12713. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  12714. this.ready = this.images.ready.then(bind(function() {
  12715. log("Images loaded, starting parsing");
  12716. log("Creating stacking contexts");
  12717. this.createStackingContexts();
  12718. log("Sorting stacking contexts");
  12719. this.sortStackingContexts(this.stack);
  12720. this.parse(this.stack);
  12721. log("Render queue created with " + this.renderQueue.length + " items");
  12722. return new Promise(bind(function(resolve) {
  12723. if (!options.async) {
  12724. this.renderQueue.forEach(this.paint, this);
  12725. resolve();
  12726. } else if (typeof(options.async) === "function") {
  12727. options.async.call(this, this.renderQueue, resolve);
  12728. } else if (this.renderQueue.length > 0) {
  12729. this.renderIndex = 0;
  12730. this.asyncRenderer(this.renderQueue, resolve);
  12731. } else {
  12732. resolve();
  12733. }
  12734. }, this));
  12735. }, this));
  12736. }
  12737. NodeParser.prototype.calculateOverflowClips = function() {
  12738. this.nodes.forEach(function(container) {
  12739. if (isElement(container)) {
  12740. if (isPseudoElement(container)) {
  12741. container.appendToDOM();
  12742. }
  12743. container.borders = this.parseBorders(container);
  12744. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  12745. var cssClip = container.parseClip();
  12746. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  12747. clip.push([
  12748. ["rect",
  12749. container.bounds.left + cssClip.left,
  12750. container.bounds.top + cssClip.top,
  12751. cssClip.right - cssClip.left,
  12752. cssClip.bottom - cssClip.top
  12753. ]
  12754. ]);
  12755. }
  12756. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  12757. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  12758. if (isPseudoElement(container)) {
  12759. container.cleanDOM();
  12760. }
  12761. } else if (isTextNode(container)) {
  12762. container.clip = hasParentClip(container) ? container.parent.clip : [];
  12763. }
  12764. if (!isPseudoElement(container)) {
  12765. container.bounds = null;
  12766. }
  12767. }, this);
  12768. };
  12769. function hasParentClip(container) {
  12770. return container.parent && container.parent.clip.length;
  12771. }
  12772. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  12773. asyncTimer = asyncTimer || Date.now();
  12774. this.paint(queue[this.renderIndex++]);
  12775. if (queue.length === this.renderIndex) {
  12776. resolve();
  12777. } else if (asyncTimer + 20 > Date.now()) {
  12778. this.asyncRenderer(queue, resolve, asyncTimer);
  12779. } else {
  12780. setTimeout(bind(function() {
  12781. this.asyncRenderer(queue, resolve);
  12782. }, this), 0);
  12783. }
  12784. };
  12785. NodeParser.prototype.createPseudoHideStyles = function(document) {
  12786. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  12787. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  12788. };
  12789. NodeParser.prototype.disableAnimations = function(document) {
  12790. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  12791. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  12792. };
  12793. NodeParser.prototype.createStyles = function(document, styles) {
  12794. var hidePseudoElements = document.createElement('style');
  12795. hidePseudoElements.innerHTML = styles;
  12796. document.body.appendChild(hidePseudoElements);
  12797. };
  12798. NodeParser.prototype.getPseudoElements = function(container) {
  12799. var nodes = [
  12800. [container]
  12801. ];
  12802. if (container.node.nodeType === Node.ELEMENT_NODE) {
  12803. var before = this.getPseudoElement(container, ":before");
  12804. var after = this.getPseudoElement(container, ":after");
  12805. if (before) {
  12806. nodes.push(before);
  12807. }
  12808. if (after) {
  12809. nodes.push(after);
  12810. }
  12811. }
  12812. return flatten(nodes);
  12813. };
  12814. function toCamelCase(str) {
  12815. return str.replace(/(\-[a-z])/g, function(match) {
  12816. return match.toUpperCase().replace('-', '');
  12817. });
  12818. }
  12819. NodeParser.prototype.getPseudoElement = function(container, type) {
  12820. var style = container.computedStyle(type);
  12821. if (!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  12822. return null;
  12823. }
  12824. var content = stripQuotes(style.content);
  12825. var isImage = content.substr(0, 3) === 'url';
  12826. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  12827. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  12828. for (var i = style.length - 1; i >= 0; i--) {
  12829. var property = toCamelCase(style.item(i));
  12830. pseudoNode.style[property] = style[property];
  12831. }
  12832. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  12833. if (isImage) {
  12834. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  12835. return [pseudoContainer];
  12836. } else {
  12837. var text = document.createTextNode(content);
  12838. pseudoNode.appendChild(text);
  12839. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  12840. }
  12841. };
  12842. NodeParser.prototype.getChildren = function(parentContainer) {
  12843. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  12844. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  12845. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  12846. }, this));
  12847. };
  12848. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  12849. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  12850. container.cloneTo(stack);
  12851. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  12852. parentStack.contexts.push(stack);
  12853. container.stack = stack;
  12854. };
  12855. NodeParser.prototype.createStackingContexts = function() {
  12856. this.nodes.forEach(function(container) {
  12857. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  12858. this.newStackingContext(container, true);
  12859. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  12860. this.newStackingContext(container, false);
  12861. } else {
  12862. container.assignStack(container.parent.stack);
  12863. }
  12864. }, this);
  12865. };
  12866. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  12867. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  12868. };
  12869. NodeParser.prototype.isRootElement = function(container) {
  12870. return container.parent === null;
  12871. };
  12872. NodeParser.prototype.sortStackingContexts = function(stack) {
  12873. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  12874. stack.contexts.forEach(this.sortStackingContexts, this);
  12875. };
  12876. NodeParser.prototype.parseTextBounds = function(container) {
  12877. return function(text, index, textList) {
  12878. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  12879. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  12880. var offset = textList.slice(0, index).join("").length;
  12881. return this.getRangeBounds(container.node, offset, text.length);
  12882. } else if (container.node && typeof(container.node.data) === "string") {
  12883. var replacementNode = container.node.splitText(text.length);
  12884. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  12885. container.node = replacementNode;
  12886. return bounds;
  12887. }
  12888. } else if (!this.support.rangeBounds || container.parent.hasTransform()) {
  12889. container.node = container.node.splitText(text.length);
  12890. }
  12891. return {};
  12892. };
  12893. };
  12894. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  12895. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  12896. var parent = node.parentNode,
  12897. backupText = node.cloneNode(true);
  12898. wrapper.appendChild(node.cloneNode(true));
  12899. parent.replaceChild(wrapper, node);
  12900. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  12901. parent.replaceChild(backupText, wrapper);
  12902. return bounds;
  12903. };
  12904. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  12905. var range = this.range || (this.range = node.ownerDocument.createRange());
  12906. range.setStart(node, offset);
  12907. range.setEnd(node, offset + length);
  12908. return range.getBoundingClientRect();
  12909. };
  12910. function ClearTransform() {}
  12911. NodeParser.prototype.parse = function(stack) {
  12912. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  12913. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  12914. var descendantElements = stack.children.filter(isElement);
  12915. var descendantNonFloats = descendantElements.filter(not(isFloating));
  12916. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  12917. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  12918. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  12919. 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.
  12920. var text = stack.children.filter(isTextNode).filter(hasText);
  12921. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  12922. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  12923. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  12924. this.renderQueue.push(container);
  12925. if (isStackingContext(container)) {
  12926. this.parse(container);
  12927. this.renderQueue.push(new ClearTransform());
  12928. }
  12929. }, this);
  12930. };
  12931. NodeParser.prototype.paint = function(container) {
  12932. try {
  12933. if (container instanceof ClearTransform) {
  12934. this.renderer.ctx.restore();
  12935. } else if (isTextNode(container)) {
  12936. if (isPseudoElement(container.parent)) {
  12937. container.parent.appendToDOM();
  12938. }
  12939. this.paintText(container);
  12940. if (isPseudoElement(container.parent)) {
  12941. container.parent.cleanDOM();
  12942. }
  12943. } else {
  12944. this.paintNode(container);
  12945. }
  12946. } catch (e) {
  12947. log(e);
  12948. if (this.options.strict) {
  12949. throw e;
  12950. }
  12951. }
  12952. };
  12953. NodeParser.prototype.paintNode = function(container) {
  12954. if (isStackingContext(container)) {
  12955. this.renderer.setOpacity(container.opacity);
  12956. this.renderer.ctx.save();
  12957. if (container.hasTransform()) {
  12958. this.renderer.setTransform(container.parseTransform());
  12959. }
  12960. }
  12961. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  12962. this.paintCheckbox(container);
  12963. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  12964. this.paintRadio(container);
  12965. } else {
  12966. this.paintElement(container);
  12967. }
  12968. };
  12969. NodeParser.prototype.paintElement = function(container) {
  12970. var bounds = container.parseBounds();
  12971. this.renderer.clip(container.backgroundClip, function() {
  12972. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  12973. }, this);
  12974. this.renderer.clip(container.clip, function() {
  12975. this.renderer.renderBorders(container.borders.borders);
  12976. }, this);
  12977. this.renderer.clip(container.backgroundClip, function() {
  12978. switch (container.node.nodeName) {
  12979. case "svg":
  12980. case "IFRAME":
  12981. var imgContainer = this.images.get(container.node);
  12982. if (imgContainer) {
  12983. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  12984. } else {
  12985. log("Error loading <" + container.node.nodeName + ">", container.node);
  12986. }
  12987. break;
  12988. case "IMG":
  12989. var imageContainer = this.images.get(container.node.src);
  12990. if (imageContainer) {
  12991. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  12992. } else {
  12993. log("Error loading <img>", container.node.src);
  12994. }
  12995. break;
  12996. case "CANVAS":
  12997. this.renderer.renderImage(container, bounds, container.borders, { image: container.node });
  12998. break;
  12999. case "SELECT":
  13000. case "INPUT":
  13001. case "TEXTAREA":
  13002. this.paintFormValue(container);
  13003. break;
  13004. }
  13005. }, this);
  13006. };
  13007. NodeParser.prototype.paintCheckbox = function(container) {
  13008. var b = container.parseBounds();
  13009. var size = Math.min(b.width, b.height);
  13010. var bounds = { width: size - 1, height: size - 1, top: b.top, left: b.left };
  13011. var r = [3, 3];
  13012. var radius = [r, r, r, r];
  13013. var borders = [1, 1, 1, 1].map(function(w) {
  13014. return { color: new Color('#A5A5A5'), width: w };
  13015. });
  13016. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  13017. this.renderer.clip(container.backgroundClip, function() {
  13018. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  13019. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  13020. if (container.node.checked) {
  13021. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  13022. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  13023. }
  13024. }, this);
  13025. };
  13026. NodeParser.prototype.paintRadio = function(container) {
  13027. var bounds = container.parseBounds();
  13028. var size = Math.min(bounds.width, bounds.height) - 2;
  13029. this.renderer.clip(container.backgroundClip, function() {
  13030. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  13031. if (container.node.checked) {
  13032. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  13033. }
  13034. }, this);
  13035. };
  13036. NodeParser.prototype.paintFormValue = function(container) {
  13037. var value = container.getValue();
  13038. if (value.length > 0) {
  13039. var document = container.node.ownerDocument;
  13040. var wrapper = document.createElement('html2canvaswrapper');
  13041. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  13042. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  13043. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  13044. 'boxSizing', 'whiteSpace', 'wordWrap'
  13045. ];
  13046. properties.forEach(function(property) {
  13047. try {
  13048. wrapper.style[property] = container.css(property);
  13049. } catch (e) {
  13050. // Older IE has issues with "border"
  13051. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  13052. }
  13053. });
  13054. var bounds = container.parseBounds();
  13055. wrapper.style.position = "fixed";
  13056. wrapper.style.left = bounds.left + "px";
  13057. wrapper.style.top = bounds.top + "px";
  13058. wrapper.textContent = value;
  13059. document.body.appendChild(wrapper);
  13060. this.paintText(new TextContainer(wrapper.firstChild, container));
  13061. document.body.removeChild(wrapper);
  13062. }
  13063. };
  13064. NodeParser.prototype.paintText = function(container) {
  13065. container.applyTextTransform();
  13066. var characters = punycode.ucs2.decode(container.node.data);
  13067. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  13068. return punycode.ucs2.encode([character]);
  13069. });
  13070. var weight = container.parent.fontWeight();
  13071. var size = container.parent.css('fontSize');
  13072. var family = container.parent.css('fontFamily');
  13073. var shadows = container.parent.parseTextShadows();
  13074. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  13075. if (shadows.length) {
  13076. // TODO: support multiple text shadows
  13077. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  13078. } else {
  13079. this.renderer.clearShadow();
  13080. }
  13081. this.renderer.clip(container.parent.clip, function() {
  13082. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  13083. if (bounds) {
  13084. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  13085. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  13086. }
  13087. }, this);
  13088. }, this);
  13089. };
  13090. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  13091. switch (container.css("textDecoration").split(" ")[0]) {
  13092. case "underline":
  13093. // Draws a line at the baseline of the font
  13094. // 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
  13095. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13096. break;
  13097. case "overline":
  13098. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  13099. break;
  13100. case "line-through":
  13101. // TODO try and find exact position for line-through
  13102. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13103. break;
  13104. }
  13105. };
  13106. var borderColorTransforms = {
  13107. inset: [
  13108. ["darken", 0.60],
  13109. ["darken", 0.10],
  13110. ["darken", 0.10],
  13111. ["darken", 0.60]
  13112. ]
  13113. };
  13114. NodeParser.prototype.parseBorders = function(container) {
  13115. var nodeBounds = container.parseBounds();
  13116. var radius = getBorderRadiusData(container);
  13117. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  13118. var style = container.css('border' + side + 'Style');
  13119. var color = container.color('border' + side + 'Color');
  13120. if (style === "inset" && color.isBlack()) {
  13121. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  13122. }
  13123. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  13124. return {
  13125. width: container.cssInt('border' + side + 'Width'),
  13126. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  13127. args: null
  13128. };
  13129. });
  13130. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  13131. return {
  13132. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  13133. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  13134. };
  13135. };
  13136. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  13137. return borders.map(function(border, borderSide) {
  13138. if (border.width > 0) {
  13139. var bx = nodeBounds.left;
  13140. var by = nodeBounds.top;
  13141. var bw = nodeBounds.width;
  13142. var bh = nodeBounds.height - (borders[2].width);
  13143. switch (borderSide) {
  13144. case 0:
  13145. // top border
  13146. bh = borders[0].width;
  13147. border.args = drawSide({
  13148. c1: [bx, by],
  13149. c2: [bx + bw, by],
  13150. c3: [bx + bw - borders[1].width, by + bh],
  13151. c4: [bx + borders[3].width, by + bh]
  13152. }, radius[0], radius[1],
  13153. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  13154. break;
  13155. case 1:
  13156. // right border
  13157. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  13158. bw = borders[1].width;
  13159. border.args = drawSide({
  13160. c1: [bx + bw, by],
  13161. c2: [bx + bw, by + bh + borders[2].width],
  13162. c3: [bx, by + bh],
  13163. c4: [bx, by + borders[0].width]
  13164. }, radius[1], radius[2],
  13165. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  13166. break;
  13167. case 2:
  13168. // bottom border
  13169. by = (by + nodeBounds.height) - (borders[2].width);
  13170. bh = borders[2].width;
  13171. border.args = drawSide({
  13172. c1: [bx + bw, by + bh],
  13173. c2: [bx, by + bh],
  13174. c3: [bx + borders[3].width, by],
  13175. c4: [bx + bw - borders[3].width, by]
  13176. }, radius[2], radius[3],
  13177. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  13178. break;
  13179. case 3:
  13180. // left border
  13181. bw = borders[3].width;
  13182. border.args = drawSide({
  13183. c1: [bx, by + bh + borders[2].width],
  13184. c2: [bx, by],
  13185. c3: [bx + bw, by + borders[0].width],
  13186. c4: [bx + bw, by + bh]
  13187. }, radius[3], radius[0],
  13188. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  13189. break;
  13190. }
  13191. }
  13192. return border;
  13193. });
  13194. }
  13195. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  13196. var backgroundClip = container.css('backgroundClip'),
  13197. borderArgs = [];
  13198. switch (backgroundClip) {
  13199. case "content-box":
  13200. case "padding-box":
  13201. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  13202. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  13203. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  13204. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  13205. break;
  13206. default:
  13207. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  13208. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  13209. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  13210. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  13211. break;
  13212. }
  13213. return borderArgs;
  13214. };
  13215. function getCurvePoints(x, y, r1, r2) {
  13216. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  13217. var ox = (r1) * kappa, // control point offset horizontal
  13218. oy = (r2) * kappa, // control point offset vertical
  13219. xm = x + r1, // x-middle
  13220. ym = y + r2; // y-middle
  13221. return {
  13222. topLeft: bezierCurve({ x: x, y: ym }, { x: x, y: ym - oy }, { x: xm - ox, y: y }, { x: xm, y: y }),
  13223. topRight: bezierCurve({ x: x, y: y }, { x: x + ox, y: y }, { x: xm, y: ym - oy }, { x: xm, y: ym }),
  13224. bottomRight: bezierCurve({ x: xm, y: y }, { x: xm, y: y + oy }, { x: x + ox, y: ym }, { x: x, y: ym }),
  13225. bottomLeft: bezierCurve({ x: xm, y: ym }, { x: xm - ox, y: ym }, { x: x, y: y + oy }, { x: x, y: y })
  13226. };
  13227. }
  13228. function calculateCurvePoints(bounds, borderRadius, borders) {
  13229. var x = bounds.left,
  13230. y = bounds.top,
  13231. width = bounds.width,
  13232. height = bounds.height,
  13233. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  13234. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  13235. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  13236. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  13237. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  13238. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  13239. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  13240. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  13241. var topWidth = width - trh,
  13242. rightHeight = height - brv,
  13243. bottomWidth = width - brh,
  13244. leftHeight = height - blv;
  13245. return {
  13246. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  13247. 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),
  13248. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  13249. 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),
  13250. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  13251. 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),
  13252. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  13253. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  13254. };
  13255. }
  13256. function bezierCurve(start, startControl, endControl, end) {
  13257. var lerp = function(a, b, t) {
  13258. return {
  13259. x: a.x + (b.x - a.x) * t,
  13260. y: a.y + (b.y - a.y) * t
  13261. };
  13262. };
  13263. return {
  13264. start: start,
  13265. startControl: startControl,
  13266. endControl: endControl,
  13267. end: end,
  13268. subdivide: function(t) {
  13269. var ab = lerp(start, startControl, t),
  13270. bc = lerp(startControl, endControl, t),
  13271. cd = lerp(endControl, end, t),
  13272. abbc = lerp(ab, bc, t),
  13273. bccd = lerp(bc, cd, t),
  13274. dest = lerp(abbc, bccd, t);
  13275. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  13276. },
  13277. curveTo: function(borderArgs) {
  13278. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  13279. },
  13280. curveToReversed: function(borderArgs) {
  13281. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  13282. }
  13283. };
  13284. }
  13285. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  13286. var borderArgs = [];
  13287. if (radius1[0] > 0 || radius1[1] > 0) {
  13288. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  13289. outer1[1].curveTo(borderArgs);
  13290. } else {
  13291. borderArgs.push(["line", borderData.c1[0], borderData.c1[1]]);
  13292. }
  13293. if (radius2[0] > 0 || radius2[1] > 0) {
  13294. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  13295. outer2[0].curveTo(borderArgs);
  13296. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  13297. inner2[0].curveToReversed(borderArgs);
  13298. } else {
  13299. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  13300. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  13301. }
  13302. if (radius1[0] > 0 || radius1[1] > 0) {
  13303. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  13304. inner1[1].curveToReversed(borderArgs);
  13305. } else {
  13306. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  13307. }
  13308. return borderArgs;
  13309. }
  13310. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  13311. if (radius1[0] > 0 || radius1[1] > 0) {
  13312. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  13313. corner1[0].curveTo(borderArgs);
  13314. corner1[1].curveTo(borderArgs);
  13315. } else {
  13316. borderArgs.push(["line", x, y]);
  13317. }
  13318. if (radius2[0] > 0 || radius2[1] > 0) {
  13319. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  13320. }
  13321. }
  13322. function negativeZIndex(container) {
  13323. return container.cssInt("zIndex") < 0;
  13324. }
  13325. function positiveZIndex(container) {
  13326. return container.cssInt("zIndex") > 0;
  13327. }
  13328. function zIndex0(container) {
  13329. return container.cssInt("zIndex") === 0;
  13330. }
  13331. function inlineLevel(container) {
  13332. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13333. }
  13334. function isStackingContext(container) {
  13335. return (container instanceof StackingContext);
  13336. }
  13337. function hasText(container) {
  13338. return container.node.data.trim().length > 0;
  13339. }
  13340. function noLetterSpacing(container) {
  13341. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  13342. }
  13343. function getBorderRadiusData(container) {
  13344. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  13345. var value = container.css('border' + side + 'Radius');
  13346. var arr = value.split(" ");
  13347. if (arr.length <= 1) {
  13348. arr[1] = arr[0];
  13349. }
  13350. return arr.map(asInt);
  13351. });
  13352. }
  13353. function renderableNode(node) {
  13354. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  13355. }
  13356. function isPositionedForStacking(container) {
  13357. var position = container.css("position");
  13358. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  13359. return zIndex !== "auto";
  13360. }
  13361. function isPositioned(container) {
  13362. return container.css("position") !== "static";
  13363. }
  13364. function isFloating(container) {
  13365. return container.css("float") !== "none";
  13366. }
  13367. function isInlineBlock(container) {
  13368. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13369. }
  13370. function not(callback) {
  13371. var context = this;
  13372. return function() {
  13373. return !callback.apply(context, arguments);
  13374. };
  13375. }
  13376. function isElement(container) {
  13377. return container.node.nodeType === Node.ELEMENT_NODE;
  13378. }
  13379. function isPseudoElement(container) {
  13380. return container.isPseudoElement === true;
  13381. }
  13382. function isTextNode(container) {
  13383. return container.node.nodeType === Node.TEXT_NODE;
  13384. }
  13385. function zIndexSort(contexts) {
  13386. return function(a, b) {
  13387. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  13388. };
  13389. }
  13390. function hasOpacity(container) {
  13391. return container.getOpacity() < 1;
  13392. }
  13393. function asInt(value) {
  13394. return parseInt(value, 10);
  13395. }
  13396. function getWidth(border) {
  13397. return border.width;
  13398. }
  13399. function nonIgnoredElement(nodeContainer) {
  13400. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  13401. }
  13402. function flatten(arrays) {
  13403. return [].concat.apply([], arrays);
  13404. }
  13405. function stripQuotes(content) {
  13406. var first = content.substr(0, 1);
  13407. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  13408. }
  13409. function getWords(characters) {
  13410. var words = [],
  13411. i = 0,
  13412. onWordBoundary = false,
  13413. word;
  13414. while (characters.length) {
  13415. if (isWordBoundary(characters[i]) === onWordBoundary) {
  13416. word = characters.splice(0, i);
  13417. if (word.length) {
  13418. words.push(punycode.ucs2.encode(word));
  13419. }
  13420. onWordBoundary = !onWordBoundary;
  13421. i = 0;
  13422. } else {
  13423. i++;
  13424. }
  13425. if (i >= characters.length) {
  13426. word = characters.splice(0, i);
  13427. if (word.length) {
  13428. words.push(punycode.ucs2.encode(word));
  13429. }
  13430. }
  13431. }
  13432. return words;
  13433. }
  13434. function isWordBoundary(characterCode) {
  13435. return [
  13436. 32, // <space>
  13437. 13, // \r
  13438. 10, // \n
  13439. 9, // \t
  13440. 45 // -
  13441. ].indexOf(characterCode) !== -1;
  13442. }
  13443. function hasUnicode(string) {
  13444. return (/[^\u0000-\u00ff]/).test(string);
  13445. }
  13446. module.exports = NodeParser;
  13447. }, { "./color": 3, "./fontmetrics": 7, "./log": 13, "./nodecontainer": 14, "./pseudoelementcontainer": 18, "./stackingcontext": 21, "./textcontainer": 25, "./utils": 26, "punycode": 1 }],
  13448. 16: [function(_dereq_, module, exports) {
  13449. var XHR = _dereq_('./xhr');
  13450. var utils = _dereq_('./utils');
  13451. var log = _dereq_('./log');
  13452. var createWindowClone = _dereq_('./clone');
  13453. var decode64 = utils.decode64;
  13454. function Proxy(src, proxyUrl, document) {
  13455. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  13456. if (!proxyUrl) {
  13457. return Promise.reject("No proxy configured");
  13458. }
  13459. var callback = createCallback(supportsCORS);
  13460. var url = createProxyUrl(proxyUrl, src, callback);
  13461. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  13462. return decode64(response.content);
  13463. }));
  13464. }
  13465. var proxyCount = 0;
  13466. function ProxyURL(src, proxyUrl, document) {
  13467. var supportsCORSImage = ('crossOrigin' in new Image());
  13468. var callback = createCallback(supportsCORSImage);
  13469. var url = createProxyUrl(proxyUrl, src, callback);
  13470. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  13471. return "data:" + response.type + ";base64," + response.content;
  13472. }));
  13473. }
  13474. function jsonp(document, url, callback) {
  13475. return new Promise(function(resolve, reject) {
  13476. var s = document.createElement("script");
  13477. var cleanup = function() {
  13478. delete window.html2canvas.proxy[callback];
  13479. document.body.removeChild(s);
  13480. };
  13481. window.html2canvas.proxy[callback] = function(response) {
  13482. cleanup();
  13483. resolve(response);
  13484. };
  13485. s.src = url;
  13486. s.onerror = function(e) {
  13487. cleanup();
  13488. reject(e);
  13489. };
  13490. document.body.appendChild(s);
  13491. });
  13492. }
  13493. function createCallback(useCORS) {
  13494. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  13495. }
  13496. function createProxyUrl(proxyUrl, src, callback) {
  13497. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  13498. }
  13499. function documentFromHTML(src) {
  13500. return function(html) {
  13501. var parser = new DOMParser(),
  13502. doc;
  13503. try {
  13504. doc = parser.parseFromString(html, "text/html");
  13505. } catch (e) {
  13506. log("DOMParser not supported, falling back to createHTMLDocument");
  13507. doc = document.implementation.createHTMLDocument("");
  13508. try {
  13509. doc.open();
  13510. doc.write(html);
  13511. doc.close();
  13512. } catch (ee) {
  13513. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  13514. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  13515. }
  13516. }
  13517. var b = doc.querySelector("base");
  13518. if (!b || !b.href.host) {
  13519. var base = doc.createElement("base");
  13520. base.href = src;
  13521. doc.head.insertBefore(base, doc.head.firstChild);
  13522. }
  13523. return doc;
  13524. };
  13525. }
  13526. function loadUrlDocument(src, proxy, document, width, height, options) {
  13527. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  13528. return createWindowClone(doc, document, width, height, options, 0, 0);
  13529. });
  13530. }
  13531. exports.Proxy = Proxy;
  13532. exports.ProxyURL = ProxyURL;
  13533. exports.loadUrlDocument = loadUrlDocument;
  13534. }, { "./clone": 2, "./log": 13, "./utils": 26, "./xhr": 28 }],
  13535. 17: [function(_dereq_, module, exports) {
  13536. var ProxyURL = _dereq_('./proxy').ProxyURL;
  13537. function ProxyImageContainer(src, proxy) {
  13538. var link = document.createElement("a");
  13539. link.href = src;
  13540. src = link.href;
  13541. this.src = src;
  13542. this.image = new Image();
  13543. var self = this;
  13544. this.promise = new Promise(function(resolve, reject) {
  13545. self.image.crossOrigin = "Anonymous";
  13546. self.image.onload = resolve;
  13547. self.image.onerror = reject;
  13548. new ProxyURL(src, proxy, document).then(function(url) {
  13549. self.image.src = url;
  13550. })['catch'](reject);
  13551. });
  13552. }
  13553. module.exports = ProxyImageContainer;
  13554. }, { "./proxy": 16 }],
  13555. 18: [function(_dereq_, module, exports) {
  13556. var NodeContainer = _dereq_('./nodecontainer');
  13557. function PseudoElementContainer(node, parent, type) {
  13558. NodeContainer.call(this, node, parent);
  13559. this.isPseudoElement = true;
  13560. this.before = type === ":before";
  13561. }
  13562. PseudoElementContainer.prototype.cloneTo = function(stack) {
  13563. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  13564. stack.isPseudoElement = true;
  13565. stack.before = this.before;
  13566. };
  13567. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  13568. PseudoElementContainer.prototype.appendToDOM = function() {
  13569. if (this.before) {
  13570. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  13571. } else {
  13572. this.parent.node.appendChild(this.node);
  13573. }
  13574. this.parent.node.className += " " + this.getHideClass();
  13575. };
  13576. PseudoElementContainer.prototype.cleanDOM = function() {
  13577. this.node.parentNode.removeChild(this.node);
  13578. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  13579. };
  13580. PseudoElementContainer.prototype.getHideClass = function() {
  13581. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  13582. };
  13583. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  13584. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  13585. module.exports = PseudoElementContainer;
  13586. }, { "./nodecontainer": 14 }],
  13587. 19: [function(_dereq_, module, exports) {
  13588. var log = _dereq_('./log');
  13589. function Renderer(width, height, images, options, document) {
  13590. this.width = width;
  13591. this.height = height;
  13592. this.images = images;
  13593. this.options = options;
  13594. this.document = document;
  13595. }
  13596. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  13597. var paddingLeft = container.cssInt('paddingLeft'),
  13598. paddingTop = container.cssInt('paddingTop'),
  13599. paddingRight = container.cssInt('paddingRight'),
  13600. paddingBottom = container.cssInt('paddingBottom'),
  13601. borders = borderData.borders;
  13602. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  13603. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  13604. this.drawImage(
  13605. imageContainer,
  13606. 0,
  13607. 0,
  13608. imageContainer.image.width || width,
  13609. imageContainer.image.height || height,
  13610. bounds.left + paddingLeft + borders[3].width,
  13611. bounds.top + paddingTop + borders[0].width,
  13612. width,
  13613. height
  13614. );
  13615. };
  13616. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  13617. if (bounds.height > 0 && bounds.width > 0) {
  13618. this.renderBackgroundColor(container, bounds);
  13619. this.renderBackgroundImage(container, bounds, borderData);
  13620. }
  13621. };
  13622. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  13623. var color = container.color("backgroundColor");
  13624. if (!color.isTransparent()) {
  13625. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  13626. }
  13627. };
  13628. Renderer.prototype.renderBorders = function(borders) {
  13629. borders.forEach(this.renderBorder, this);
  13630. };
  13631. Renderer.prototype.renderBorder = function(data) {
  13632. if (!data.color.isTransparent() && data.args !== null) {
  13633. this.drawShape(data.args, data.color);
  13634. }
  13635. };
  13636. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  13637. var backgroundImages = container.parseBackgroundImages();
  13638. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  13639. switch (backgroundImage.method) {
  13640. case "url":
  13641. var image = this.images.get(backgroundImage.args[0]);
  13642. if (image) {
  13643. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index + 1), borderData);
  13644. } else {
  13645. log("Error loading background-image", backgroundImage.args[0]);
  13646. }
  13647. break;
  13648. case "linear-gradient":
  13649. case "gradient":
  13650. var gradientImage = this.images.get(backgroundImage.value);
  13651. if (gradientImage) {
  13652. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  13653. } else {
  13654. log("Error loading background-image", backgroundImage.args[0]);
  13655. }
  13656. break;
  13657. case "none":
  13658. break;
  13659. default:
  13660. log("Unknown background-image type", backgroundImage.args[0]);
  13661. }
  13662. }, this);
  13663. };
  13664. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  13665. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  13666. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  13667. var repeat = container.parseBackgroundRepeat(index);
  13668. switch (repeat) {
  13669. case "repeat-x":
  13670. case "repeat no-repeat":
  13671. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  13672. break;
  13673. case "repeat-y":
  13674. case "no-repeat repeat":
  13675. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  13676. break;
  13677. case "no-repeat":
  13678. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  13679. break;
  13680. default:
  13681. this.renderBackgroundRepeat(imageContainer, position, size, { top: bounds.top, left: bounds.left }, borderData[3], borderData[0]);
  13682. break;
  13683. }
  13684. };
  13685. module.exports = Renderer;
  13686. }, { "./log": 13 }],
  13687. 20: [function(_dereq_, module, exports) {
  13688. var Renderer = _dereq_('../renderer');
  13689. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  13690. var log = _dereq_('../log');
  13691. function CanvasRenderer(width, height) {
  13692. Renderer.apply(this, arguments);
  13693. this.canvas = this.options.canvas || this.document.createElement("canvas");
  13694. if (!this.options.canvas) {
  13695. this.canvas.width = width;
  13696. this.canvas.height = height;
  13697. }
  13698. this.ctx = this.canvas.getContext("2d");
  13699. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  13700. this.ctx.textBaseline = "bottom";
  13701. this.variables = {};
  13702. log("Initialized CanvasRenderer with size", width, "x", height);
  13703. }
  13704. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  13705. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  13706. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  13707. return this.ctx;
  13708. };
  13709. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  13710. this.setFillStyle(color).fillRect(left, top, width, height);
  13711. };
  13712. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  13713. this.setFillStyle(color);
  13714. this.ctx.beginPath();
  13715. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI * 2, true);
  13716. this.ctx.closePath();
  13717. this.ctx.fill();
  13718. };
  13719. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  13720. this.circle(left, top, size, color);
  13721. this.ctx.strokeStyle = strokeColor.toString();
  13722. this.ctx.stroke();
  13723. };
  13724. CanvasRenderer.prototype.drawShape = function(shape, color) {
  13725. this.shape(shape);
  13726. this.setFillStyle(color).fill();
  13727. };
  13728. CanvasRenderer.prototype.taints = function(imageContainer) {
  13729. if (imageContainer.tainted === null) {
  13730. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  13731. try {
  13732. this.taintCtx.getImageData(0, 0, 1, 1);
  13733. imageContainer.tainted = false;
  13734. } catch (e) {
  13735. this.taintCtx = document.createElement("canvas").getContext("2d");
  13736. imageContainer.tainted = true;
  13737. }
  13738. }
  13739. return imageContainer.tainted;
  13740. };
  13741. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  13742. if (!this.taints(imageContainer) || this.options.allowTaint) {
  13743. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  13744. }
  13745. };
  13746. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  13747. this.ctx.save();
  13748. shapes.filter(hasEntries).forEach(function(shape) {
  13749. this.shape(shape).clip();
  13750. }, this);
  13751. callback.call(context);
  13752. this.ctx.restore();
  13753. };
  13754. CanvasRenderer.prototype.shape = function(shape) {
  13755. this.ctx.beginPath();
  13756. shape.forEach(function(point, index) {
  13757. if (point[0] === "rect") {
  13758. this.ctx.rect.apply(this.ctx, point.slice(1));
  13759. } else {
  13760. this.ctx[(index === 0) ? "moveTo" : point[0] + "To"].apply(this.ctx, point.slice(1));
  13761. }
  13762. }, this);
  13763. this.ctx.closePath();
  13764. return this.ctx;
  13765. };
  13766. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  13767. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  13768. };
  13769. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  13770. this.setVariable("shadowColor", color.toString())
  13771. .setVariable("shadowOffsetY", offsetX)
  13772. .setVariable("shadowOffsetX", offsetY)
  13773. .setVariable("shadowBlur", blur);
  13774. };
  13775. CanvasRenderer.prototype.clearShadow = function() {
  13776. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  13777. };
  13778. CanvasRenderer.prototype.setOpacity = function(opacity) {
  13779. this.ctx.globalAlpha = opacity;
  13780. };
  13781. CanvasRenderer.prototype.setTransform = function(transform) {
  13782. this.ctx.translate(transform.origin[0], transform.origin[1]);
  13783. this.ctx.transform.apply(this.ctx, transform.matrix);
  13784. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  13785. };
  13786. CanvasRenderer.prototype.setVariable = function(property, value) {
  13787. if (this.variables[property] !== value) {
  13788. this.variables[property] = this.ctx[property] = value;
  13789. }
  13790. return this;
  13791. };
  13792. CanvasRenderer.prototype.text = function(text, left, bottom) {
  13793. this.ctx.fillText(text, left, bottom);
  13794. };
  13795. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  13796. var shape = [
  13797. ["line", Math.round(left), Math.round(top)],
  13798. ["line", Math.round(left + width), Math.round(top)],
  13799. ["line", Math.round(left + width), Math.round(height + top)],
  13800. ["line", Math.round(left), Math.round(height + top)]
  13801. ];
  13802. this.clip([shape], function() {
  13803. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  13804. }, this);
  13805. };
  13806. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  13807. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft),
  13808. offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  13809. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  13810. this.ctx.translate(offsetX, offsetY);
  13811. this.ctx.fill();
  13812. this.ctx.translate(-offsetX, -offsetY);
  13813. };
  13814. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  13815. if (gradientImage instanceof LinearGradientContainer) {
  13816. var gradient = this.ctx.createLinearGradient(
  13817. bounds.left + bounds.width * gradientImage.x0,
  13818. bounds.top + bounds.height * gradientImage.y0,
  13819. bounds.left + bounds.width * gradientImage.x1,
  13820. bounds.top + bounds.height * gradientImage.y1);
  13821. gradientImage.colorStops.forEach(function(colorStop) {
  13822. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  13823. });
  13824. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  13825. }
  13826. };
  13827. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  13828. var image = imageContainer.image;
  13829. if (image.width === size.width && image.height === size.height) {
  13830. return image;
  13831. }
  13832. var ctx, canvas = document.createElement('canvas');
  13833. canvas.width = size.width;
  13834. canvas.height = size.height;
  13835. ctx = canvas.getContext("2d");
  13836. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height);
  13837. return canvas;
  13838. };
  13839. function hasEntries(array) {
  13840. return array.length > 0;
  13841. }
  13842. module.exports = CanvasRenderer;
  13843. }, { "../lineargradientcontainer": 12, "../log": 13, "../renderer": 19 }],
  13844. 21: [function(_dereq_, module, exports) {
  13845. var NodeContainer = _dereq_('./nodecontainer');
  13846. function StackingContext(hasOwnStacking, opacity, element, parent) {
  13847. NodeContainer.call(this, element, parent);
  13848. this.ownStacking = hasOwnStacking;
  13849. this.contexts = [];
  13850. this.children = [];
  13851. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  13852. }
  13853. StackingContext.prototype = Object.create(NodeContainer.prototype);
  13854. StackingContext.prototype.getParentStack = function(context) {
  13855. var parentStack = (this.parent) ? this.parent.stack : null;
  13856. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  13857. };
  13858. module.exports = StackingContext;
  13859. }, { "./nodecontainer": 14 }],
  13860. 22: [function(_dereq_, module, exports) {
  13861. function Support(document) {
  13862. this.rangeBounds = this.testRangeBounds(document);
  13863. this.cors = this.testCORS();
  13864. this.svg = this.testSVG();
  13865. }
  13866. Support.prototype.testRangeBounds = function(document) {
  13867. var range, testElement, rangeBounds, rangeHeight, support = false;
  13868. if (document.createRange) {
  13869. range = document.createRange();
  13870. if (range.getBoundingClientRect) {
  13871. testElement = document.createElement('boundtest');
  13872. testElement.style.height = "123px";
  13873. testElement.style.display = "block";
  13874. document.body.appendChild(testElement);
  13875. range.selectNode(testElement);
  13876. rangeBounds = range.getBoundingClientRect();
  13877. rangeHeight = rangeBounds.height;
  13878. if (rangeHeight === 123) {
  13879. support = true;
  13880. }
  13881. document.body.removeChild(testElement);
  13882. }
  13883. }
  13884. return support;
  13885. };
  13886. Support.prototype.testCORS = function() {
  13887. return typeof((new Image()).crossOrigin) !== "undefined";
  13888. };
  13889. Support.prototype.testSVG = function() {
  13890. var img = new Image();
  13891. var canvas = document.createElement("canvas");
  13892. var ctx = canvas.getContext("2d");
  13893. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  13894. try {
  13895. ctx.drawImage(img, 0, 0);
  13896. canvas.toDataURL();
  13897. } catch (e) {
  13898. return false;
  13899. }
  13900. return true;
  13901. };
  13902. module.exports = Support;
  13903. }, {}],
  13904. 23: [function(_dereq_, module, exports) {
  13905. var XHR = _dereq_('./xhr');
  13906. var decode64 = _dereq_('./utils').decode64;
  13907. function SVGContainer(src) {
  13908. this.src = src;
  13909. this.image = null;
  13910. var self = this;
  13911. this.promise = this.hasFabric().then(function() {
  13912. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  13913. }).then(function(svg) {
  13914. return new Promise(function(resolve) {
  13915. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  13916. });
  13917. });
  13918. }
  13919. SVGContainer.prototype.hasFabric = function() {
  13920. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  13921. };
  13922. SVGContainer.prototype.inlineFormatting = function(src) {
  13923. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  13924. };
  13925. SVGContainer.prototype.removeContentType = function(src) {
  13926. return src.replace(/^data:image\/svg\+xml(;base64)?,/, '');
  13927. };
  13928. SVGContainer.prototype.isInline = function(src) {
  13929. return (/^data:image\/svg\+xml/i.test(src));
  13930. };
  13931. SVGContainer.prototype.createCanvas = function(resolve) {
  13932. var self = this;
  13933. return function(objects, options) {
  13934. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  13935. self.image = canvas.lowerCanvasEl;
  13936. canvas
  13937. .setWidth(options.width)
  13938. .setHeight(options.height)
  13939. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  13940. .renderAll();
  13941. resolve(canvas.lowerCanvasEl);
  13942. };
  13943. };
  13944. SVGContainer.prototype.decode64 = function(str) {
  13945. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  13946. };
  13947. module.exports = SVGContainer;
  13948. }, { "./utils": 26, "./xhr": 28 }],
  13949. 24: [function(_dereq_, module, exports) {
  13950. var SVGContainer = _dereq_('./svgcontainer');
  13951. function SVGNodeContainer(node, _native) {
  13952. this.src = node;
  13953. this.image = null;
  13954. var self = this;
  13955. this.promise = _native ? new Promise(function(resolve, reject) {
  13956. self.image = new Image();
  13957. self.image.onload = resolve;
  13958. self.image.onerror = reject;
  13959. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  13960. if (self.image.complete === true) {
  13961. resolve(self.image);
  13962. }
  13963. }) : this.hasFabric().then(function() {
  13964. return new Promise(function(resolve) {
  13965. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  13966. });
  13967. });
  13968. }
  13969. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  13970. module.exports = SVGNodeContainer;
  13971. }, { "./svgcontainer": 23 }],
  13972. 25: [function(_dereq_, module, exports) {
  13973. var NodeContainer = _dereq_('./nodecontainer');
  13974. function TextContainer(node, parent) {
  13975. NodeContainer.call(this, node, parent);
  13976. }
  13977. TextContainer.prototype = Object.create(NodeContainer.prototype);
  13978. TextContainer.prototype.applyTextTransform = function() {
  13979. this.node.data = this.transform(this.parent.css("textTransform"));
  13980. };
  13981. TextContainer.prototype.transform = function(transform) {
  13982. var text = this.node.data;
  13983. switch (transform) {
  13984. case "lowercase":
  13985. return text.toLowerCase();
  13986. case "capitalize":
  13987. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  13988. case "uppercase":
  13989. return text.toUpperCase();
  13990. default:
  13991. return text;
  13992. }
  13993. };
  13994. function capitalize(m, p1, p2) {
  13995. if (m.length > 0) {
  13996. return p1 + p2.toUpperCase();
  13997. }
  13998. }
  13999. module.exports = TextContainer;
  14000. }, { "./nodecontainer": 14 }],
  14001. 26: [function(_dereq_, module, exports) {
  14002. exports.smallImage = function smallImage() {
  14003. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  14004. };
  14005. exports.bind = function(callback, context) {
  14006. return function() {
  14007. return callback.apply(context, arguments);
  14008. };
  14009. };
  14010. /*
  14011. * base64-arraybuffer
  14012. * https://github.com/niklasvh/base64-arraybuffer
  14013. *
  14014. * Copyright (c) 2012 Niklas von Hertzen
  14015. * Licensed under the MIT license.
  14016. */
  14017. exports.decode64 = function(base64) {
  14018. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  14019. var len = base64.length,
  14020. i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  14021. var output = "";
  14022. for (i = 0; i < len; i += 4) {
  14023. encoded1 = chars.indexOf(base64[i]);
  14024. encoded2 = chars.indexOf(base64[i + 1]);
  14025. encoded3 = chars.indexOf(base64[i + 2]);
  14026. encoded4 = chars.indexOf(base64[i + 3]);
  14027. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  14028. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  14029. byte3 = ((encoded3 & 3) << 6) | encoded4;
  14030. if (encoded3 === 64) {
  14031. output += String.fromCharCode(byte1);
  14032. } else if (encoded4 === 64 || encoded4 === -1) {
  14033. output += String.fromCharCode(byte1, byte2);
  14034. } else {
  14035. output += String.fromCharCode(byte1, byte2, byte3);
  14036. }
  14037. }
  14038. return output;
  14039. };
  14040. exports.getBounds = function(node) {
  14041. if (node.getBoundingClientRect) {
  14042. var clientRect = node.getBoundingClientRect();
  14043. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  14044. return {
  14045. top: clientRect.top,
  14046. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  14047. right: clientRect.left + width,
  14048. left: clientRect.left,
  14049. width: width,
  14050. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  14051. };
  14052. }
  14053. return {};
  14054. };
  14055. exports.offsetBounds = function(node) {
  14056. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : { top: 0, left: 0 };
  14057. return {
  14058. top: node.offsetTop + parent.top,
  14059. bottom: node.offsetTop + node.offsetHeight + parent.top,
  14060. right: node.offsetLeft + parent.left + node.offsetWidth,
  14061. left: node.offsetLeft + parent.left,
  14062. width: node.offsetWidth,
  14063. height: node.offsetHeight
  14064. };
  14065. };
  14066. exports.parseBackgrounds = function(backgroundImage) {
  14067. var whitespace = ' \r\n\t',
  14068. method, definition, prefix, prefix_i, block, results = [],
  14069. mode = 0,
  14070. numParen = 0,
  14071. quote, args;
  14072. var appendResult = function() {
  14073. if (method) {
  14074. if (definition.substr(0, 1) === '"') {
  14075. definition = definition.substr(1, definition.length - 2);
  14076. }
  14077. if (definition) {
  14078. args.push(definition);
  14079. }
  14080. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1) + 1) > 0) {
  14081. prefix = method.substr(0, prefix_i);
  14082. method = method.substr(prefix_i);
  14083. }
  14084. results.push({
  14085. prefix: prefix,
  14086. method: method.toLowerCase(),
  14087. value: block,
  14088. args: args,
  14089. image: null
  14090. });
  14091. }
  14092. args = [];
  14093. method = prefix = definition = block = '';
  14094. };
  14095. args = [];
  14096. method = prefix = definition = block = '';
  14097. backgroundImage.split("").forEach(function(c) {
  14098. if (mode === 0 && whitespace.indexOf(c) > -1) {
  14099. return;
  14100. }
  14101. switch (c) {
  14102. case '"':
  14103. if (!quote) {
  14104. quote = c;
  14105. } else if (quote === c) {
  14106. quote = null;
  14107. }
  14108. break;
  14109. case '(':
  14110. if (quote) {
  14111. break;
  14112. } else if (mode === 0) {
  14113. mode = 1;
  14114. block += c;
  14115. return;
  14116. } else {
  14117. numParen++;
  14118. }
  14119. break;
  14120. case ')':
  14121. if (quote) {
  14122. break;
  14123. } else if (mode === 1) {
  14124. if (numParen === 0) {
  14125. mode = 0;
  14126. block += c;
  14127. appendResult();
  14128. return;
  14129. } else {
  14130. numParen--;
  14131. }
  14132. }
  14133. break;
  14134. case ',':
  14135. if (quote) {
  14136. break;
  14137. } else if (mode === 0) {
  14138. appendResult();
  14139. return;
  14140. } else if (mode === 1) {
  14141. if (numParen === 0 && !method.match(/^url$/i)) {
  14142. args.push(definition);
  14143. definition = '';
  14144. block += c;
  14145. return;
  14146. }
  14147. }
  14148. break;
  14149. }
  14150. block += c;
  14151. if (mode === 0) {
  14152. method += c;
  14153. } else {
  14154. definition += c;
  14155. }
  14156. });
  14157. appendResult();
  14158. return results;
  14159. };
  14160. }, {}],
  14161. 27: [function(_dereq_, module, exports) {
  14162. var GradientContainer = _dereq_('./gradientcontainer');
  14163. function WebkitGradientContainer(imageData) {
  14164. GradientContainer.apply(this, arguments);
  14165. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  14166. }
  14167. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  14168. module.exports = WebkitGradientContainer;
  14169. }, { "./gradientcontainer": 9 }],
  14170. 28: [function(_dereq_, module, exports) {
  14171. function XHR(url) {
  14172. return new Promise(function(resolve, reject) {
  14173. var xhr = new XMLHttpRequest();
  14174. xhr.open('GET', url);
  14175. xhr.onload = function() {
  14176. if (xhr.status === 200) {
  14177. resolve(xhr.responseText);
  14178. } else {
  14179. reject(new Error(xhr.statusText));
  14180. }
  14181. };
  14182. xhr.onerror = function() {
  14183. reject(new Error("Network Error"));
  14184. };
  14185. xhr.send();
  14186. });
  14187. }
  14188. module.exports = XHR;
  14189. }, {}]
  14190. }, {}, [4])(4)
  14191. });
  14192. // Generated by CoffeeScript 1.4.0
  14193. /*
  14194. # PNG.js
  14195. # Copyright (c) 2011 Devon Govett
  14196. # MIT LICENSE
  14197. #
  14198. #
  14199. */
  14200. (function(global) {
  14201. var PNG;
  14202. PNG = (function() {
  14203. var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  14204. PNG.load = function(url, canvas, callback) {
  14205. var xhr;
  14206. if (typeof canvas === 'function') {
  14207. callback = canvas;
  14208. }
  14209. xhr = new XMLHttpRequest;
  14210. xhr.open("GET", url, true);
  14211. xhr.responseType = "arraybuffer";
  14212. xhr.onload = function() {
  14213. var data, png;
  14214. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  14215. png = new PNG(data);
  14216. if (typeof(canvas != null ? canvas.getContext : void 0) === 'function') {
  14217. png.render(canvas);
  14218. }
  14219. return typeof callback === "function" ? callback(png) : void 0;
  14220. };
  14221. return xhr.send(null);
  14222. };
  14223. APNG_DISPOSE_OP_BACKGROUND = 1;
  14224. APNG_DISPOSE_OP_PREVIOUS = 2;
  14225. APNG_BLEND_OP_SOURCE = 0;
  14226. function PNG(data) {
  14227. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  14228. this.data = data;
  14229. this.pos = 8;
  14230. this.palette = [];
  14231. this.imgData = [];
  14232. this.transparency = {};
  14233. this.animation = null;
  14234. this.text = {};
  14235. frame = null;
  14236. while (true) {
  14237. chunkSize = this.readUInt32();
  14238. section = ((function() {
  14239. var _i, _results;
  14240. _results = [];
  14241. for (i = _i = 0; _i < 4; i = ++_i) {
  14242. _results.push(String.fromCharCode(this.data[this.pos++]));
  14243. }
  14244. return _results;
  14245. }).call(this)).join('');
  14246. switch (section) {
  14247. case 'IHDR':
  14248. this.width = this.readUInt32();
  14249. this.height = this.readUInt32();
  14250. this.bits = this.data[this.pos++];
  14251. this.colorType = this.data[this.pos++];
  14252. this.compressionMethod = this.data[this.pos++];
  14253. this.filterMethod = this.data[this.pos++];
  14254. this.interlaceMethod = this.data[this.pos++];
  14255. break;
  14256. case 'acTL':
  14257. this.animation = {
  14258. numFrames: this.readUInt32(),
  14259. numPlays: this.readUInt32() || Infinity,
  14260. frames: []
  14261. };
  14262. break;
  14263. case 'PLTE':
  14264. this.palette = this.read(chunkSize);
  14265. break;
  14266. case 'fcTL':
  14267. if (frame) {
  14268. this.animation.frames.push(frame);
  14269. }
  14270. this.pos += 4;
  14271. frame = {
  14272. width: this.readUInt32(),
  14273. height: this.readUInt32(),
  14274. xOffset: this.readUInt32(),
  14275. yOffset: this.readUInt32()
  14276. };
  14277. delayNum = this.readUInt16();
  14278. delayDen = this.readUInt16() || 100;
  14279. frame.delay = 1000 * delayNum / delayDen;
  14280. frame.disposeOp = this.data[this.pos++];
  14281. frame.blendOp = this.data[this.pos++];
  14282. frame.data = [];
  14283. break;
  14284. case 'IDAT':
  14285. case 'fdAT':
  14286. if (section === 'fdAT') {
  14287. this.pos += 4;
  14288. chunkSize -= 4;
  14289. }
  14290. data = (frame != null ? frame.data : void 0) || this.imgData;
  14291. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  14292. data.push(this.data[this.pos++]);
  14293. }
  14294. break;
  14295. case 'tRNS':
  14296. this.transparency = {};
  14297. switch (this.colorType) {
  14298. case 3:
  14299. palLen = this.palette.length / 3;
  14300. this.transparency.indexed = this.read(chunkSize);
  14301. if (this.transparency.indexed.length > palLen)
  14302. throw new Error('More transparent colors than palette size');
  14303. /*
  14304. * According to the PNG spec trns should be increased to the same size as palette if shorter
  14305. */
  14306. //palShort = 255 - this.transparency.indexed.length;
  14307. palShort = palLen - this.transparency.indexed.length;
  14308. if (palShort > 0) {
  14309. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  14310. this.transparency.indexed.push(255);
  14311. }
  14312. }
  14313. break;
  14314. case 0:
  14315. this.transparency.grayscale = this.read(chunkSize)[0];
  14316. break;
  14317. case 2:
  14318. this.transparency.rgb = this.read(chunkSize);
  14319. }
  14320. break;
  14321. case 'tEXt':
  14322. text = this.read(chunkSize);
  14323. index = text.indexOf(0);
  14324. key = String.fromCharCode.apply(String, text.slice(0, index));
  14325. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  14326. break;
  14327. case 'IEND':
  14328. if (frame) {
  14329. this.animation.frames.push(frame);
  14330. }
  14331. this.colors = (function() {
  14332. switch (this.colorType) {
  14333. case 0:
  14334. case 3:
  14335. case 4:
  14336. return 1;
  14337. case 2:
  14338. case 6:
  14339. return 3;
  14340. }
  14341. }).call(this);
  14342. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  14343. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  14344. this.pixelBitlength = this.bits * colors;
  14345. this.colorSpace = (function() {
  14346. switch (this.colors) {
  14347. case 1:
  14348. return 'DeviceGray';
  14349. case 3:
  14350. return 'DeviceRGB';
  14351. }
  14352. }).call(this);
  14353. this.imgData = new Uint8Array(this.imgData);
  14354. return;
  14355. default:
  14356. this.pos += chunkSize;
  14357. }
  14358. this.pos += 4;
  14359. if (this.pos > this.data.length) {
  14360. throw new Error("Incomplete or corrupt PNG file");
  14361. }
  14362. }
  14363. return;
  14364. }
  14365. PNG.prototype.read = function(bytes) {
  14366. var i, _i, _results;
  14367. _results = [];
  14368. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  14369. _results.push(this.data[this.pos++]);
  14370. }
  14371. return _results;
  14372. };
  14373. PNG.prototype.readUInt32 = function() {
  14374. var b1, b2, b3, b4;
  14375. b1 = this.data[this.pos++] << 24;
  14376. b2 = this.data[this.pos++] << 16;
  14377. b3 = this.data[this.pos++] << 8;
  14378. b4 = this.data[this.pos++];
  14379. return b1 | b2 | b3 | b4;
  14380. };
  14381. PNG.prototype.readUInt16 = function() {
  14382. var b1, b2;
  14383. b1 = this.data[this.pos++] << 8;
  14384. b2 = this.data[this.pos++];
  14385. return b1 | b2;
  14386. };
  14387. PNG.prototype.decodePixels = function(data) {
  14388. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  14389. if (data == null) {
  14390. data = this.imgData;
  14391. }
  14392. if (data.length === 0) {
  14393. return new Uint8Array(0);
  14394. }
  14395. data = new FlateStream(data);
  14396. data = data.getBytes();
  14397. pixelBytes = this.pixelBitlength / 8;
  14398. scanlineLength = pixelBytes * this.width;
  14399. pixels = new Uint8Array(scanlineLength * this.height);
  14400. length = data.length;
  14401. row = 0;
  14402. pos = 0;
  14403. c = 0;
  14404. while (pos < length) {
  14405. switch (data[pos++]) {
  14406. case 0:
  14407. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  14408. pixels[c++] = data[pos++];
  14409. }
  14410. break;
  14411. case 1:
  14412. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  14413. abyte = data[pos++];
  14414. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14415. pixels[c++] = (abyte + left) % 256;
  14416. }
  14417. break;
  14418. case 2:
  14419. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  14420. abyte = data[pos++];
  14421. col = (i - (i % pixelBytes)) / pixelBytes;
  14422. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14423. pixels[c++] = (upper + abyte) % 256;
  14424. }
  14425. break;
  14426. case 3:
  14427. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  14428. abyte = data[pos++];
  14429. col = (i - (i % pixelBytes)) / pixelBytes;
  14430. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14431. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14432. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  14433. }
  14434. break;
  14435. case 4:
  14436. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  14437. abyte = data[pos++];
  14438. col = (i - (i % pixelBytes)) / pixelBytes;
  14439. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14440. if (row === 0) {
  14441. upper = upperLeft = 0;
  14442. } else {
  14443. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14444. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
  14445. }
  14446. p = left + upper - upperLeft;
  14447. pa = Math.abs(p - left);
  14448. pb = Math.abs(p - upper);
  14449. pc = Math.abs(p - upperLeft);
  14450. if (pa <= pb && pa <= pc) {
  14451. paeth = left;
  14452. } else if (pb <= pc) {
  14453. paeth = upper;
  14454. } else {
  14455. paeth = upperLeft;
  14456. }
  14457. pixels[c++] = (abyte + paeth) % 256;
  14458. }
  14459. break;
  14460. default:
  14461. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  14462. }
  14463. row++;
  14464. }
  14465. return pixels;
  14466. };
  14467. PNG.prototype.decodePalette = function() {
  14468. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  14469. palette = this.palette;
  14470. transparency = this.transparency.indexed || [];
  14471. ret = new Uint8Array((transparency.length || 0) + palette.length);
  14472. pos = 0;
  14473. c = 0;
  14474. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  14475. ret[pos++] = palette[i];
  14476. ret[pos++] = palette[i + 1];
  14477. ret[pos++] = palette[i + 2];
  14478. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  14479. }
  14480. return ret;
  14481. };
  14482. PNG.prototype.copyToImageData = function(imageData, pixels) {
  14483. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  14484. colors = this.colors;
  14485. palette = null;
  14486. alpha = this.hasAlphaChannel;
  14487. if (this.palette.length) {
  14488. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  14489. colors = 4;
  14490. alpha = true;
  14491. }
  14492. data = imageData.data || imageData;
  14493. length = data.length;
  14494. input = palette || pixels;
  14495. i = j = 0;
  14496. if (colors === 1) {
  14497. while (i < length) {
  14498. k = palette ? pixels[i / 4] * 4 : j;
  14499. v = input[k++];
  14500. data[i++] = v;
  14501. data[i++] = v;
  14502. data[i++] = v;
  14503. data[i++] = alpha ? input[k++] : 255;
  14504. j = k;
  14505. }
  14506. } else {
  14507. while (i < length) {
  14508. k = palette ? pixels[i / 4] * 4 : j;
  14509. data[i++] = input[k++];
  14510. data[i++] = input[k++];
  14511. data[i++] = input[k++];
  14512. data[i++] = alpha ? input[k++] : 255;
  14513. j = k;
  14514. }
  14515. }
  14516. };
  14517. PNG.prototype.decode = function() {
  14518. var ret;
  14519. ret = new Uint8Array(this.width * this.height * 4);
  14520. this.copyToImageData(ret, this.decodePixels());
  14521. return ret;
  14522. };
  14523. try {
  14524. scratchCanvas = global.document.createElement('canvas');
  14525. scratchCtx = scratchCanvas.getContext('2d');
  14526. } catch (e) {
  14527. return -1;
  14528. }
  14529. makeImage = function(imageData) {
  14530. var img;
  14531. scratchCtx.width = imageData.width;
  14532. scratchCtx.height = imageData.height;
  14533. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  14534. scratchCtx.putImageData(imageData, 0, 0);
  14535. img = new Image;
  14536. img.src = scratchCanvas.toDataURL();
  14537. return img;
  14538. };
  14539. PNG.prototype.decodeFrames = function(ctx) {
  14540. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  14541. if (!this.animation) {
  14542. return;
  14543. }
  14544. _ref = this.animation.frames;
  14545. _results = [];
  14546. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  14547. frame = _ref[i];
  14548. imageData = ctx.createImageData(frame.width, frame.height);
  14549. pixels = this.decodePixels(new Uint8Array(frame.data));
  14550. this.copyToImageData(imageData, pixels);
  14551. frame.imageData = imageData;
  14552. _results.push(frame.image = makeImage(imageData));
  14553. }
  14554. return _results;
  14555. };
  14556. PNG.prototype.renderFrame = function(ctx, number) {
  14557. var frame, frames, prev;
  14558. frames = this.animation.frames;
  14559. frame = frames[number];
  14560. prev = frames[number - 1];
  14561. if (number === 0) {
  14562. ctx.clearRect(0, 0, this.width, this.height);
  14563. }
  14564. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  14565. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  14566. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  14567. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  14568. }
  14569. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  14570. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  14571. }
  14572. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  14573. };
  14574. PNG.prototype.animate = function(ctx) {
  14575. var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
  14576. _this = this;
  14577. frameNumber = 0;
  14578. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  14579. return (doFrame = function() {
  14580. var f, frame;
  14581. f = frameNumber++ % numFrames;
  14582. frame = frames[f];
  14583. _this.renderFrame(ctx, f);
  14584. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  14585. return _this.animation._timeout = setTimeout(doFrame, frame.delay);
  14586. }
  14587. })();
  14588. };
  14589. PNG.prototype.stopAnimation = function() {
  14590. var _ref;
  14591. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  14592. };
  14593. PNG.prototype.render = function(canvas) {
  14594. var ctx, data;
  14595. if (canvas._png) {
  14596. canvas._png.stopAnimation();
  14597. }
  14598. canvas._png = this;
  14599. canvas.width = this.width;
  14600. canvas.height = this.height;
  14601. ctx = canvas.getContext("2d");
  14602. if (this.animation) {
  14603. this.decodeFrames(ctx);
  14604. return this.animate(ctx);
  14605. } else {
  14606. data = ctx.createImageData(this.width, this.height);
  14607. this.copyToImageData(data, this.decodePixels());
  14608. return ctx.putImageData(data, 0, 0);
  14609. }
  14610. };
  14611. return PNG;
  14612. })();
  14613. global.PNG = PNG;
  14614. })(typeof window !== "undefined" && window || undefined);
  14615. /*
  14616. * Extracted from pdf.js
  14617. * https://github.com/andreasgal/pdf.js
  14618. *
  14619. * Copyright (c) 2011 Mozilla Foundation
  14620. *
  14621. * Contributors: Andreas Gal <gal@mozilla.com>
  14622. * Chris G Jones <cjones@mozilla.com>
  14623. * Shaon Barman <shaon.barman@gmail.com>
  14624. * Vivien Nicolas <21@vingtetun.org>
  14625. * Justin D'Arcangelo <justindarc@gmail.com>
  14626. * Yury Delendik
  14627. *
  14628. *
  14629. */
  14630. var DecodeStream = (function() {
  14631. function constructor() {
  14632. this.pos = 0;
  14633. this.bufferLength = 0;
  14634. this.eof = false;
  14635. this.buffer = null;
  14636. }
  14637. constructor.prototype = {
  14638. ensureBuffer: function decodestream_ensureBuffer(requested) {
  14639. var buffer = this.buffer;
  14640. var current = buffer ? buffer.byteLength : 0;
  14641. if (requested < current)
  14642. return buffer;
  14643. var size = 512;
  14644. while (size < requested)
  14645. size <<= 1;
  14646. var buffer2 = new Uint8Array(size);
  14647. for (var i = 0; i < current; ++i)
  14648. buffer2[i] = buffer[i];
  14649. return this.buffer = buffer2;
  14650. },
  14651. getByte: function decodestream_getByte() {
  14652. var pos = this.pos;
  14653. while (this.bufferLength <= pos) {
  14654. if (this.eof)
  14655. return null;
  14656. this.readBlock();
  14657. }
  14658. return this.buffer[this.pos++];
  14659. },
  14660. getBytes: function decodestream_getBytes(length) {
  14661. var pos = this.pos;
  14662. if (length) {
  14663. this.ensureBuffer(pos + length);
  14664. var end = pos + length;
  14665. while (!this.eof && this.bufferLength < end)
  14666. this.readBlock();
  14667. var bufEnd = this.bufferLength;
  14668. if (end > bufEnd)
  14669. end = bufEnd;
  14670. } else {
  14671. while (!this.eof)
  14672. this.readBlock();
  14673. var end = this.bufferLength;
  14674. }
  14675. this.pos = end;
  14676. return this.buffer.subarray(pos, end);
  14677. },
  14678. lookChar: function decodestream_lookChar() {
  14679. var pos = this.pos;
  14680. while (this.bufferLength <= pos) {
  14681. if (this.eof)
  14682. return null;
  14683. this.readBlock();
  14684. }
  14685. return String.fromCharCode(this.buffer[this.pos]);
  14686. },
  14687. getChar: function decodestream_getChar() {
  14688. var pos = this.pos;
  14689. while (this.bufferLength <= pos) {
  14690. if (this.eof)
  14691. return null;
  14692. this.readBlock();
  14693. }
  14694. return String.fromCharCode(this.buffer[this.pos++]);
  14695. },
  14696. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  14697. var end = start + length;
  14698. while (this.bufferLength <= end && !this.eof)
  14699. this.readBlock();
  14700. return new Stream(this.buffer, start, length, dict);
  14701. },
  14702. skip: function decodestream_skip(n) {
  14703. if (!n)
  14704. n = 1;
  14705. this.pos += n;
  14706. },
  14707. reset: function decodestream_reset() {
  14708. this.pos = 0;
  14709. }
  14710. };
  14711. return constructor;
  14712. })();
  14713. var FlateStream = (function() {
  14714. if (typeof Uint32Array === 'undefined') {
  14715. return undefined;
  14716. }
  14717. var codeLenCodeMap = new Uint32Array([
  14718. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  14719. ]);
  14720. var lengthDecode = new Uint32Array([
  14721. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  14722. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  14723. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  14724. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  14725. ]);
  14726. var distDecode = new Uint32Array([
  14727. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  14728. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  14729. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  14730. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  14731. ]);
  14732. var fixedLitCodeTab = [new Uint32Array([
  14733. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  14734. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  14735. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  14736. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  14737. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  14738. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  14739. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  14740. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  14741. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  14742. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  14743. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  14744. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  14745. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  14746. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  14747. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  14748. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  14749. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  14750. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  14751. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  14752. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  14753. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  14754. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  14755. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  14756. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  14757. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  14758. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  14759. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  14760. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  14761. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  14762. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  14763. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  14764. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  14765. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  14766. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  14767. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  14768. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  14769. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  14770. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  14771. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  14772. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  14773. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  14774. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  14775. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  14776. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  14777. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  14778. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  14779. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  14780. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  14781. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  14782. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  14783. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  14784. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  14785. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  14786. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  14787. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  14788. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  14789. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  14790. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  14791. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  14792. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  14793. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  14794. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  14795. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  14796. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  14797. ]), 9];
  14798. var fixedDistCodeTab = [new Uint32Array([
  14799. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  14800. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  14801. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  14802. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  14803. ]), 5];
  14804. function error(e) {
  14805. throw new Error(e)
  14806. }
  14807. function constructor(bytes) {
  14808. //var bytes = stream.getBytes();
  14809. var bytesPos = 0;
  14810. var cmf = bytes[bytesPos++];
  14811. var flg = bytes[bytesPos++];
  14812. if (cmf == -1 || flg == -1)
  14813. error('Invalid header in flate stream');
  14814. if ((cmf & 0x0f) != 0x08)
  14815. error('Unknown compression method in flate stream');
  14816. if ((((cmf << 8) + flg) % 31) != 0)
  14817. error('Bad FCHECK in flate stream');
  14818. if (flg & 0x20)
  14819. error('FDICT bit set in flate stream');
  14820. this.bytes = bytes;
  14821. this.bytesPos = bytesPos;
  14822. this.codeSize = 0;
  14823. this.codeBuf = 0;
  14824. DecodeStream.call(this);
  14825. }
  14826. constructor.prototype = Object.create(DecodeStream.prototype);
  14827. constructor.prototype.getBits = function(bits) {
  14828. var codeSize = this.codeSize;
  14829. var codeBuf = this.codeBuf;
  14830. var bytes = this.bytes;
  14831. var bytesPos = this.bytesPos;
  14832. var b;
  14833. while (codeSize < bits) {
  14834. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14835. error('Bad encoding in flate stream');
  14836. codeBuf |= b << codeSize;
  14837. codeSize += 8;
  14838. }
  14839. b = codeBuf & ((1 << bits) - 1);
  14840. this.codeBuf = codeBuf >> bits;
  14841. this.codeSize = codeSize -= bits;
  14842. this.bytesPos = bytesPos;
  14843. return b;
  14844. };
  14845. constructor.prototype.getCode = function(table) {
  14846. var codes = table[0];
  14847. var maxLen = table[1];
  14848. var codeSize = this.codeSize;
  14849. var codeBuf = this.codeBuf;
  14850. var bytes = this.bytes;
  14851. var bytesPos = this.bytesPos;
  14852. while (codeSize < maxLen) {
  14853. var b;
  14854. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14855. error('Bad encoding in flate stream');
  14856. codeBuf |= (b << codeSize);
  14857. codeSize += 8;
  14858. }
  14859. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  14860. var codeLen = code >> 16;
  14861. var codeVal = code & 0xffff;
  14862. if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
  14863. error('Bad encoding in flate stream');
  14864. this.codeBuf = (codeBuf >> codeLen);
  14865. this.codeSize = (codeSize - codeLen);
  14866. this.bytesPos = bytesPos;
  14867. return codeVal;
  14868. };
  14869. constructor.prototype.generateHuffmanTable = function(lengths) {
  14870. var n = lengths.length;
  14871. // find max code length
  14872. var maxLen = 0;
  14873. for (var i = 0; i < n; ++i) {
  14874. if (lengths[i] > maxLen)
  14875. maxLen = lengths[i];
  14876. }
  14877. // build the table
  14878. var size = 1 << maxLen;
  14879. var codes = new Uint32Array(size);
  14880. for (var len = 1, code = 0, skip = 2; len <= maxLen;
  14881. ++len, code <<= 1, skip <<= 1) {
  14882. for (var val = 0; val < n; ++val) {
  14883. if (lengths[val] == len) {
  14884. // bit-reverse the code
  14885. var code2 = 0;
  14886. var t = code;
  14887. for (var i = 0; i < len; ++i) {
  14888. code2 = (code2 << 1) | (t & 1);
  14889. t >>= 1;
  14890. }
  14891. // fill the table entries
  14892. for (var i = code2; i < size; i += skip)
  14893. codes[i] = (len << 16) | val;
  14894. ++code;
  14895. }
  14896. }
  14897. }
  14898. return [codes, maxLen];
  14899. };
  14900. constructor.prototype.readBlock = function() {
  14901. function repeat(stream, array, len, offset, what) {
  14902. var repeat = stream.getBits(len) + offset;
  14903. while (repeat-- > 0)
  14904. array[i++] = what;
  14905. }
  14906. // read block header
  14907. var hdr = this.getBits(3);
  14908. if (hdr & 1)
  14909. this.eof = true;
  14910. hdr >>= 1;
  14911. if (hdr == 0) { // uncompressed block
  14912. var bytes = this.bytes;
  14913. var bytesPos = this.bytesPos;
  14914. var b;
  14915. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14916. error('Bad block header in flate stream');
  14917. var blockLen = b;
  14918. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14919. error('Bad block header in flate stream');
  14920. blockLen |= (b << 8);
  14921. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14922. error('Bad block header in flate stream');
  14923. var check = b;
  14924. if (typeof(b = bytes[bytesPos++]) == 'undefined')
  14925. error('Bad block header in flate stream');
  14926. check |= (b << 8);
  14927. if (check != (~blockLen & 0xffff))
  14928. error('Bad uncompressed block length in flate stream');
  14929. this.codeBuf = 0;
  14930. this.codeSize = 0;
  14931. var bufferLength = this.bufferLength;
  14932. var buffer = this.ensureBuffer(bufferLength + blockLen);
  14933. var end = bufferLength + blockLen;
  14934. this.bufferLength = end;
  14935. for (var n = bufferLength; n < end; ++n) {
  14936. if (typeof(b = bytes[bytesPos++]) == 'undefined') {
  14937. this.eof = true;
  14938. break;
  14939. }
  14940. buffer[n] = b;
  14941. }
  14942. this.bytesPos = bytesPos;
  14943. return;
  14944. }
  14945. var litCodeTable;
  14946. var distCodeTable;
  14947. if (hdr == 1) { // compressed block, fixed codes
  14948. litCodeTable = fixedLitCodeTab;
  14949. distCodeTable = fixedDistCodeTab;
  14950. } else if (hdr == 2) { // compressed block, dynamic codes
  14951. var numLitCodes = this.getBits(5) + 257;
  14952. var numDistCodes = this.getBits(5) + 1;
  14953. var numCodeLenCodes = this.getBits(4) + 4;
  14954. // build the code lengths code table
  14955. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  14956. var i = 0;
  14957. while (i < numCodeLenCodes)
  14958. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  14959. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  14960. // build the literal and distance code tables
  14961. var len = 0;
  14962. var i = 0;
  14963. var codes = numLitCodes + numDistCodes;
  14964. var codeLengths = new Array(codes);
  14965. while (i < codes) {
  14966. var code = this.getCode(codeLenCodeTab);
  14967. if (code == 16) {
  14968. repeat(this, codeLengths, 2, 3, len);
  14969. } else if (code == 17) {
  14970. repeat(this, codeLengths, 3, 3, len = 0);
  14971. } else if (code == 18) {
  14972. repeat(this, codeLengths, 7, 11, len = 0);
  14973. } else {
  14974. codeLengths[i++] = len = code;
  14975. }
  14976. }
  14977. litCodeTable =
  14978. this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  14979. distCodeTable =
  14980. this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  14981. } else {
  14982. error('Unknown block type in flate stream');
  14983. }
  14984. var buffer = this.buffer;
  14985. var limit = buffer ? buffer.length : 0;
  14986. var pos = this.bufferLength;
  14987. while (true) {
  14988. var code1 = this.getCode(litCodeTable);
  14989. if (code1 < 256) {
  14990. if (pos + 1 >= limit) {
  14991. buffer = this.ensureBuffer(pos + 1);
  14992. limit = buffer.length;
  14993. }
  14994. buffer[pos++] = code1;
  14995. continue;
  14996. }
  14997. if (code1 == 256) {
  14998. this.bufferLength = pos;
  14999. return;
  15000. }
  15001. code1 -= 257;
  15002. code1 = lengthDecode[code1];
  15003. var code2 = code1 >> 16;
  15004. if (code2 > 0)
  15005. code2 = this.getBits(code2);
  15006. var len = (code1 & 0xffff) + code2;
  15007. code1 = this.getCode(distCodeTable);
  15008. code1 = distDecode[code1];
  15009. code2 = code1 >> 16;
  15010. if (code2 > 0)
  15011. code2 = this.getBits(code2);
  15012. var dist = (code1 & 0xffff) + code2;
  15013. if (pos + len >= limit) {
  15014. buffer = this.ensureBuffer(pos + len);
  15015. limit = buffer.length;
  15016. }
  15017. for (var k = 0; k < len; ++k, ++pos)
  15018. buffer[pos] = buffer[pos - dist];
  15019. }
  15020. };
  15021. return constructor;
  15022. })();
  15023. /**
  15024. * JavaScript Polyfill functions for jsPDF
  15025. * Collected from public resources by
  15026. * https://github.com/diegocr
  15027. */
  15028. (function(global) {
  15029. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15030. if (typeof global.btoa === 'undefined') {
  15031. global.btoa = function(data) {
  15032. // discuss at: http://phpjs.org/functions/base64_encode/
  15033. // original by: Tyler Akins (http://rumkin.com)
  15034. // improved by: Bayron Guevara
  15035. // improved by: Thunder.m
  15036. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15037. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15038. // improved by: Rafal Kukawski (http://kukawski.pl)
  15039. // bugfixed by: Pellentesque Malesuada
  15040. // example 1: base64_encode('Kevin van Zonneveld');
  15041. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  15042. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  15043. ac = 0,
  15044. enc = '',
  15045. tmp_arr = [];
  15046. if (!data) {
  15047. return data;
  15048. }
  15049. do { // pack three octets into four hexets
  15050. o1 = data.charCodeAt(i++);
  15051. o2 = data.charCodeAt(i++);
  15052. o3 = data.charCodeAt(i++);
  15053. bits = o1 << 16 | o2 << 8 | o3;
  15054. h1 = bits >> 18 & 0x3f;
  15055. h2 = bits >> 12 & 0x3f;
  15056. h3 = bits >> 6 & 0x3f;
  15057. h4 = bits & 0x3f;
  15058. // use hexets to index into b64, and append result to encoded string
  15059. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  15060. } while (i < data.length);
  15061. enc = tmp_arr.join('');
  15062. var r = data.length % 3;
  15063. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  15064. };
  15065. }
  15066. if (typeof global.atob === 'undefined') {
  15067. global.atob = function(data) {
  15068. // discuss at: http://phpjs.org/functions/base64_decode/
  15069. // original by: Tyler Akins (http://rumkin.com)
  15070. // improved by: Thunder.m
  15071. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15072. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15073. // input by: Aman Gupta
  15074. // input by: Brett Zamir (http://brett-zamir.me)
  15075. // bugfixed by: Onno Marsman
  15076. // bugfixed by: Pellentesque Malesuada
  15077. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15078. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  15079. // returns 1: 'Kevin van Zonneveld'
  15080. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  15081. ac = 0,
  15082. dec = '',
  15083. tmp_arr = [];
  15084. if (!data) {
  15085. return data;
  15086. }
  15087. data += '';
  15088. do { // unpack four hexets into three octets using index points in b64
  15089. h1 = b64.indexOf(data.charAt(i++));
  15090. h2 = b64.indexOf(data.charAt(i++));
  15091. h3 = b64.indexOf(data.charAt(i++));
  15092. h4 = b64.indexOf(data.charAt(i++));
  15093. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  15094. o1 = bits >> 16 & 0xff;
  15095. o2 = bits >> 8 & 0xff;
  15096. o3 = bits & 0xff;
  15097. if (h3 == 64) {
  15098. tmp_arr[ac++] = String.fromCharCode(o1);
  15099. } else if (h4 == 64) {
  15100. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  15101. } else {
  15102. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  15103. }
  15104. } while (i < data.length);
  15105. dec = tmp_arr.join('');
  15106. return dec;
  15107. };
  15108. }
  15109. if (!Array.prototype.map) {
  15110. Array.prototype.map = function(fun /*, thisArg */ ) {
  15111. if (this === void 0 || this === null || typeof fun !== "function")
  15112. throw new TypeError();
  15113. var t = Object(this),
  15114. len = t.length >>> 0,
  15115. res = new Array(len);
  15116. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  15117. for (var i = 0; i < len; i++) {
  15118. // NOTE: Absolute correctness would demand Object.defineProperty
  15119. // be used. But this method is fairly new, and failure is
  15120. // possible only if Object.prototype or Array.prototype
  15121. // has a property |i| (very unlikely), so use a less-correct
  15122. // but more portable alternative.
  15123. if (i in t)
  15124. res[i] = fun.call(thisArg, t[i], i, t);
  15125. }
  15126. return res;
  15127. };
  15128. }
  15129. if (!Array.isArray) {
  15130. Array.isArray = function(arg) {
  15131. return Object.prototype.toString.call(arg) === '[object Array]';
  15132. };
  15133. }
  15134. if (!Array.prototype.forEach) {
  15135. Array.prototype.forEach = function(fun, thisArg) {
  15136. "use strict";
  15137. if (this === void 0 || this === null || typeof fun !== "function")
  15138. throw new TypeError();
  15139. var t = Object(this),
  15140. len = t.length >>> 0;
  15141. for (var i = 0; i < len; i++) {
  15142. if (i in t)
  15143. fun.call(thisArg, t[i], i, t);
  15144. }
  15145. };
  15146. }
  15147. if (!Object.keys) {
  15148. Object.keys = (function() {
  15149. 'use strict';
  15150. var hasOwnProperty = Object.prototype.hasOwnProperty,
  15151. hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
  15152. dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
  15153. 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
  15154. ],
  15155. dontEnumsLength = dontEnums.length;
  15156. return function(obj) {
  15157. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  15158. throw new TypeError();
  15159. }
  15160. var result = [],
  15161. prop, i;
  15162. for (prop in obj) {
  15163. if (hasOwnProperty.call(obj, prop)) {
  15164. result.push(prop);
  15165. }
  15166. }
  15167. if (hasDontEnumBug) {
  15168. for (i = 0; i < dontEnumsLength; i++) {
  15169. if (hasOwnProperty.call(obj, dontEnums[i])) {
  15170. result.push(dontEnums[i]);
  15171. }
  15172. }
  15173. }
  15174. return result;
  15175. };
  15176. }());
  15177. }
  15178. if (!String.prototype.trim) {
  15179. String.prototype.trim = function() {
  15180. return this.replace(/^\s+|\s+$/g, '');
  15181. };
  15182. }
  15183. if (!String.prototype.trimLeft) {
  15184. String.prototype.trimLeft = function() {
  15185. return this.replace(/^\s+/g, "");
  15186. };
  15187. }
  15188. if (!String.prototype.trimRight) {
  15189. String.prototype.trimRight = function() {
  15190. return this.replace(/\s+$/g, "");
  15191. };
  15192. }
  15193. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  15194. return jsPDF;
  15195. })));