jsPdf.debug.js 741 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363
  1. /**
  2. * Created by linyuhua on 2017/4/25.
  3. */
  4. (function (global, factory) {
  5. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  6. typeof define === 'function' && define.amd ? define(factory) :
  7. (global.jspdf = factory());
  8. }(this, (function () { 'use strict';
  9. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  10. return typeof obj;
  11. } : function (obj) {
  12. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  13. };
  14. var asyncGenerator = function () {
  15. function AwaitValue(value) {
  16. this.value = value;
  17. }
  18. function AsyncGenerator(gen) {
  19. var front, back;
  20. function send(key, arg) {
  21. return new Promise(function (resolve, reject) {
  22. var request = {
  23. key: key,
  24. arg: arg,
  25. resolve: resolve,
  26. reject: reject,
  27. next: null
  28. };
  29. if (back) {
  30. back = back.next = request;
  31. } else {
  32. front = back = request;
  33. resume(key, arg);
  34. }
  35. });
  36. }
  37. function resume(key, arg) {
  38. try {
  39. var result = gen[key](arg);
  40. var value = result.value;
  41. if (value instanceof AwaitValue) {
  42. Promise.resolve(value.value).then(function (arg) {
  43. resume("next", arg);
  44. }, function (arg) {
  45. resume("throw", arg);
  46. });
  47. } else {
  48. settle(result.done ? "return" : "normal", result.value);
  49. }
  50. } catch (err) {
  51. settle("throw", err);
  52. }
  53. }
  54. function settle(type, value) {
  55. switch (type) {
  56. case "return":
  57. front.resolve({
  58. value: value,
  59. done: true
  60. });
  61. break;
  62. case "throw":
  63. front.reject(value);
  64. break;
  65. default:
  66. front.resolve({
  67. value: value,
  68. done: false
  69. });
  70. break;
  71. }
  72. front = front.next;
  73. if (front) {
  74. resume(front.key, front.arg);
  75. } else {
  76. back = null;
  77. }
  78. }
  79. this._invoke = send;
  80. if (typeof gen.return !== "function") {
  81. this.return = undefined;
  82. }
  83. }
  84. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  85. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  86. return this;
  87. };
  88. }
  89. AsyncGenerator.prototype.next = function (arg) {
  90. return this._invoke("next", arg);
  91. };
  92. AsyncGenerator.prototype.throw = function (arg) {
  93. return this._invoke("throw", arg);
  94. };
  95. AsyncGenerator.prototype.return = function (arg) {
  96. return this._invoke("return", arg);
  97. };
  98. return {
  99. wrap: function (fn) {
  100. return function () {
  101. return new AsyncGenerator(fn.apply(this, arguments));
  102. };
  103. },
  104. await: function (value) {
  105. return new AwaitValue(value);
  106. }
  107. };
  108. }();
  109. var get$1 = function get$1(object, property, receiver) {
  110. if (object === null) object = Function.prototype;
  111. var desc = Object.getOwnPropertyDescriptor(object, property);
  112. if (desc === undefined) {
  113. var parent = Object.getPrototypeOf(object);
  114. if (parent === null) {
  115. return undefined;
  116. } else {
  117. return get$1(parent, property, receiver);
  118. }
  119. } else if ("value" in desc) {
  120. return desc.value;
  121. } else {
  122. var getter = desc.get;
  123. if (getter === undefined) {
  124. return undefined;
  125. }
  126. return getter.call(receiver);
  127. }
  128. };
  129. var set$1 = function set$1(object, property, value, receiver) {
  130. var desc = Object.getOwnPropertyDescriptor(object, property);
  131. if (desc === undefined) {
  132. var parent = Object.getPrototypeOf(object);
  133. if (parent !== null) {
  134. set$1(parent, property, value, receiver);
  135. }
  136. } else if ("value" in desc && desc.writable) {
  137. desc.value = value;
  138. } else {
  139. var setter = desc.set;
  140. if (setter !== undefined) {
  141. setter.call(receiver, value);
  142. }
  143. }
  144. return value;
  145. };
  146. /** @preserve
  147. * jsPDF - PDF Document creation from JavaScript
  148. * Version 1.3.4 Built on 2017-04-10T14:14:44.483Z
  149. * CommitID cf4827d221
  150. *
  151. * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  152. * 2010 Aaron Spike, https://github.com/acspike
  153. * 2012 Willow Systems Corporation, willow-systems.com
  154. * 2012 Pablo Hess, https://github.com/pablohess
  155. * 2012 Florian Jenett, https://github.com/fjenett
  156. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  157. * 2013 Youssef Beddad, https://github.com/lifof
  158. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  159. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  160. * 2013 Jeremy Morel, https://github.com/jmorel
  161. * 2013 Christoph Hartmann, https://github.com/chris-rock
  162. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  163. * 2014 James Makes, https://github.com/dollaruw
  164. * 2014 Diego Casorran, https://github.com/diegocr
  165. * 2014 Steven Spungin, https://github.com/Flamenco
  166. * 2014 Kenneth Glassey, https://github.com/Gavvers
  167. *
  168. * Licensed under the MIT License
  169. *
  170. * Contributor(s):
  171. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  172. * kim3er, mfo, alnorth, Flamenco
  173. */
  174. /**
  175. * Creates new jsPDF document object instance.
  176. *
  177. * @class
  178. * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
  179. * @param unit Measurement unit to be used when coordinates are specified.
  180. * One of "pt" (points), "mm" (Default), "cm", "in"
  181. * @param format One of 'pageFormats' as shown below, default: a4
  182. * @returns {jsPDF}
  183. * @name jsPDF
  184. */
  185. var jsPDF = function (global) {
  186. 'use strict';
  187. var pdfVersion = '1.3',
  188. pageFormats = { // Size in pt of various paper formats
  189. 'a0': [2383.94, 3370.39],
  190. 'a1': [1683.78, 2383.94],
  191. 'a2': [1190.55, 1683.78],
  192. 'a3': [841.89, 1190.55],
  193. 'a4': [595.28, 841.89],
  194. 'a5': [419.53, 595.28],
  195. 'a6': [297.64, 419.53],
  196. 'a7': [209.76, 297.64],
  197. 'a8': [147.40, 209.76],
  198. 'a9': [104.88, 147.40],
  199. 'a10': [73.70, 104.88],
  200. 'b0': [2834.65, 4008.19],
  201. 'b1': [2004.09, 2834.65],
  202. 'b2': [1417.32, 2004.09],
  203. 'b3': [1000.63, 1417.32],
  204. 'b4': [708.66, 1000.63],
  205. 'b5': [498.90, 708.66],
  206. 'b6': [354.33, 498.90],
  207. 'b7': [249.45, 354.33],
  208. 'b8': [175.75, 249.45],
  209. 'b9': [124.72, 175.75],
  210. 'b10': [87.87, 124.72],
  211. 'c0': [2599.37, 3676.54],
  212. 'c1': [1836.85, 2599.37],
  213. 'c2': [1298.27, 1836.85],
  214. 'c3': [918.43, 1298.27],
  215. 'c4': [649.13, 918.43],
  216. 'c5': [459.21, 649.13],
  217. 'c6': [323.15, 459.21],
  218. 'c7': [229.61, 323.15],
  219. 'c8': [161.57, 229.61],
  220. 'c9': [113.39, 161.57],
  221. 'c10': [79.37, 113.39],
  222. 'dl': [311.81, 623.62],
  223. 'letter': [612, 792],
  224. 'government-letter': [576, 756],
  225. 'legal': [612, 1008],
  226. 'junior-legal': [576, 360],
  227. 'ledger': [1224, 792],
  228. 'tabloid': [792, 1224],
  229. 'credit-card': [153, 243]
  230. };
  231. /**
  232. * jsPDF's Internal PubSub Implementation.
  233. * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
  234. * Backward compatible rewritten on 2014 by
  235. * Diego Casorran, https://github.com/diegocr
  236. *
  237. * @class
  238. * @name PubSub
  239. * @ignore This should not be in the public docs.
  240. */
  241. function PubSub(context) {
  242. var topics = {};
  243. this.subscribe = function (topic, callback, once) {
  244. if (typeof callback !== 'function') {
  245. return false;
  246. }
  247. if (!topics.hasOwnProperty(topic)) {
  248. topics[topic] = {};
  249. }
  250. var id = Math.random().toString(35);
  251. topics[topic][id] = [callback, !!once];
  252. return id;
  253. };
  254. this.unsubscribe = function (token) {
  255. for (var topic in topics) {
  256. if (topics[topic][token]) {
  257. delete topics[topic][token];
  258. return true;
  259. }
  260. }
  261. return false;
  262. };
  263. this.publish = function (topic) {
  264. if (topics.hasOwnProperty(topic)) {
  265. var args = Array.prototype.slice.call(arguments, 1),
  266. idr = [];
  267. for (var id in topics[topic]) {
  268. var sub = topics[topic][id];
  269. try {
  270. sub[0].apply(context, args);
  271. } catch (ex) {
  272. if (global.console) {
  273. console.error('jsPDF PubSub Error', ex.message, ex);
  274. }
  275. }
  276. if (sub[1]) idr.push(id);
  277. }
  278. if (idr.length) idr.forEach(this.unsubscribe);
  279. }
  280. };
  281. }
  282. /**
  283. * @constructor
  284. * @private
  285. */
  286. function jsPDF(orientation, unit, format, compressPdf) {
  287. var options = {};
  288. if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
  289. options = orientation;
  290. orientation = options.orientation;
  291. unit = options.unit || unit;
  292. format = options.format || format;
  293. compressPdf = options.compress || options.compressPdf || compressPdf;
  294. }
  295. // Default options
  296. unit = unit || 'mm';
  297. format = format || 'a4';
  298. orientation = ('' + (orientation || 'P')).toLowerCase();
  299. var format_as_string = ('' + format).toLowerCase(),
  300. compress = !!compressPdf && typeof Uint8Array === 'function',
  301. textColor = options.textColor || '0 g',
  302. drawColor = options.drawColor || '0 G',
  303. activeFontSize = options.fontSize || 16,
  304. lineHeightProportion = options.lineHeight || 1.15,
  305. lineWidth = options.lineWidth || 0.200025,
  306. // 2mm
  307. objectNumber = 2,
  308. // 'n' Current object number
  309. outToPages = !1,
  310. // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  311. offsets = [],
  312. // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  313. fonts = {},
  314. // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  315. fontmap = {},
  316. // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  317. activeFontKey,
  318. // will be string representing the KEY of the font as combination of fontName + fontStyle
  319. k,
  320. // Scale factor
  321. tmp,
  322. page = 0,
  323. currentPage,
  324. pages = [],
  325. pagesContext = [],
  326. // same index as pages and pagedim
  327. pagedim = [],
  328. content = [],
  329. additionalObjects = [],
  330. lineCapID = 0,
  331. lineJoinID = 0,
  332. content_length = 0,
  333. pageWidth,
  334. pageHeight,
  335. pageMode,
  336. zoomMode,
  337. layoutMode,
  338. documentProperties = {
  339. 'title': '',
  340. 'subject': '',
  341. 'author': '',
  342. 'keywords': '',
  343. 'creator': ''
  344. },
  345. API = {},
  346. events = new PubSub(API),
  347. /////////////////////
  348. // Private functions
  349. /////////////////////
  350. f2 = function f2(number) {
  351. return number.toFixed(2); // Ie, %.2f
  352. },
  353. f3 = function f3(number) {
  354. return number.toFixed(3); // Ie, %.3f
  355. },
  356. padd2 = function padd2(number) {
  357. return ('0' + parseInt(number)).slice(-2);
  358. },
  359. out = function out(string) {
  360. if (outToPages) {
  361. /* set by beginPage */
  362. pages[currentPage].push(string);
  363. } else {
  364. // +1 for '\n' that will be used to join 'content'
  365. content_length += string.length + 1;
  366. content.push(string);
  367. }
  368. },
  369. newObject = function newObject() {
  370. // Begin a new object
  371. objectNumber++;
  372. offsets[objectNumber] = content_length;
  373. out(objectNumber + ' 0 obj');
  374. return objectNumber;
  375. },
  376. // Does not output the object until after the pages have been output.
  377. // Returns an object containing the objectId and content.
  378. // All pages have been added so the object ID can be estimated to start right after.
  379. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  380. newAdditionalObject = function newAdditionalObject() {
  381. var objId = pages.length * 2 + 1;
  382. objId += additionalObjects.length;
  383. var obj = {
  384. objId: objId,
  385. content: ''
  386. };
  387. additionalObjects.push(obj);
  388. return obj;
  389. },
  390. // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  391. newObjectDeferred = function newObjectDeferred() {
  392. objectNumber++;
  393. offsets[objectNumber] = function () {
  394. return content_length;
  395. };
  396. return objectNumber;
  397. },
  398. newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
  399. offsets[oid] = content_length;
  400. },
  401. putStream = function putStream(str) {
  402. out('stream');
  403. out(str);
  404. out('endstream');
  405. },
  406. putPages = function putPages() {
  407. var n,
  408. p,
  409. arr,
  410. i,
  411. deflater,
  412. adler32,
  413. adler32cs,
  414. wPt,
  415. hPt,
  416. pageObjectNumbers = [];
  417. adler32cs = global.adler32cs || jsPDF.adler32cs;
  418. if (compress && typeof adler32cs === 'undefined') {
  419. compress = false;
  420. }
  421. // outToPages = false as set in endDocument(). out() writes to content.
  422. for (n = 1; n <= page; n++) {
  423. pageObjectNumbers.push(newObject());
  424. wPt = (pageWidth = pagedim[n].width) * k;
  425. hPt = (pageHeight = pagedim[n].height) * k;
  426. out('<</Type /Page');
  427. out('/Parent 1 0 R');
  428. out('/Resources 2 0 R');
  429. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  430. // Added for annotation plugin
  431. events.publish('putPage', {
  432. pageNumber: n,
  433. page: pages[n]
  434. });
  435. out('/Contents ' + (objectNumber + 1) + ' 0 R');
  436. out('>>');
  437. out('endobj');
  438. // Page content
  439. p = pages[n].join('\n');
  440. newObject();
  441. if (compress) {
  442. arr = [];
  443. i = p.length;
  444. while (i--) {
  445. arr[i] = p.charCodeAt(i);
  446. }
  447. adler32 = adler32cs.from(p);
  448. deflater = new Deflater(6);
  449. deflater.append(new Uint8Array(arr));
  450. p = deflater.flush();
  451. arr = new Uint8Array(p.length + 6);
  452. arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
  453. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
  454. p = String.fromCharCode.apply(null, arr);
  455. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  456. } else {
  457. out('<</Length ' + p.length + '>>');
  458. }
  459. putStream(p);
  460. out('endobj');
  461. }
  462. offsets[1] = content_length;
  463. out('1 0 obj');
  464. out('<</Type /Pages');
  465. var kids = '/Kids [';
  466. for (i = 0; i < page; i++) {
  467. kids += pageObjectNumbers[i] + ' 0 R ';
  468. }
  469. out(kids + ']');
  470. out('/Count ' + page);
  471. out('>>');
  472. out('endobj');
  473. events.publish('postPutPages');
  474. },
  475. putFont = function putFont(font) {
  476. font.objectNumber = newObject();
  477. out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
  478. if (typeof font.encoding === 'string') {
  479. out('/Encoding/' + font.encoding);
  480. }
  481. out('/Subtype/Type1>>');
  482. out('endobj');
  483. },
  484. putFonts = function putFonts() {
  485. for (var fontKey in fonts) {
  486. if (fonts.hasOwnProperty(fontKey)) {
  487. putFont(fonts[fontKey]);
  488. }
  489. }
  490. },
  491. putXobjectDict = function putXobjectDict() {
  492. // Loop through images, or other data objects
  493. events.publish('putXobjectDict');
  494. },
  495. putResourceDictionary = function putResourceDictionary() {
  496. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  497. out('/Font <<');
  498. // Do this for each font, the '1' bit is the index of the font
  499. for (var fontKey in fonts) {
  500. if (fonts.hasOwnProperty(fontKey)) {
  501. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  502. }
  503. }
  504. out('>>');
  505. out('/XObject <<');
  506. putXobjectDict();
  507. out('>>');
  508. },
  509. putResources = function putResources() {
  510. putFonts();
  511. events.publish('putResources');
  512. // Resource dictionary
  513. offsets[2] = content_length;
  514. out('2 0 obj');
  515. out('<<');
  516. putResourceDictionary();
  517. out('>>');
  518. out('endobj');
  519. events.publish('postPutResources');
  520. },
  521. putAdditionalObjects = function putAdditionalObjects() {
  522. events.publish('putAdditionalObjects');
  523. for (var i = 0; i < additionalObjects.length; i++) {
  524. var obj = additionalObjects[i];
  525. offsets[obj.objId] = content_length;
  526. out(obj.objId + ' 0 obj');
  527. out(obj.content);
  528. out('endobj');
  529. }
  530. objectNumber += additionalObjects.length;
  531. events.publish('postPutAdditionalObjects');
  532. },
  533. addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  534. // this is mapping structure for quick font key lookup.
  535. // returns the KEY of the font (ex: "F1") for a given
  536. // pair of font name and type (ex: "Arial". "Italic")
  537. if (!fontmap.hasOwnProperty(fontName)) {
  538. fontmap[fontName] = {};
  539. }
  540. fontmap[fontName][fontStyle] = fontKey;
  541. },
  542. /**
  543. * FontObject describes a particular font as member of an instnace of jsPDF
  544. *
  545. * It's a collection of properties like 'id' (to be used in PDF stream),
  546. * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  547. *
  548. * @class
  549. * @public
  550. * @property id {String} PDF-document-instance-specific label assinged to the font.
  551. * @property PostScriptName {String} PDF specification full name for the font
  552. * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  553. * @name FontObject
  554. * @ignore This should not be in the public docs.
  555. */
  556. addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
  557. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  558. // This is FontObject
  559. font = fonts[fontKey] = {
  560. 'id': fontKey,
  561. 'PostScriptName': PostScriptName,
  562. 'fontName': fontName,
  563. 'fontStyle': fontStyle,
  564. 'encoding': encoding,
  565. 'metadata': {}
  566. };
  567. addToFontDictionary(fontKey, fontName, fontStyle);
  568. events.publish('addFont', font);
  569. return fontKey;
  570. },
  571. addFonts = function addFonts() {
  572. var HELVETICA = "helvetica",
  573. TIMES = "times",
  574. COURIER = "courier",
  575. NORMAL = "normal",
  576. BOLD = "bold",
  577. ITALIC = "italic",
  578. BOLD_ITALIC = "bolditalic",
  579. encoding = 'StandardEncoding',
  580. ZAPF = "zapfdingbats",
  581. standardFonts = [['Helvetica', HELVETICA, NORMAL], ['Helvetica-Bold', HELVETICA, BOLD], ['Helvetica-Oblique', HELVETICA, ITALIC], ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC], ['Courier', COURIER, NORMAL], ['Courier-Bold', COURIER, BOLD], ['Courier-Oblique', COURIER, ITALIC], ['Courier-BoldOblique', COURIER, BOLD_ITALIC], ['Times-Roman', TIMES, NORMAL], ['Times-Bold', TIMES, BOLD], ['Times-Italic', TIMES, ITALIC], ['Times-BoldItalic', TIMES, BOLD_ITALIC], ['ZapfDingbats', ZAPF]];
  582. for (var i = 0, l = standardFonts.length; i < l; i++) {
  583. var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
  584. // adding aliases for standard fonts, this time matching the capitalization
  585. var parts = standardFonts[i][0].split('-');
  586. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  587. }
  588. events.publish('addFonts', {
  589. fonts: fonts,
  590. dictionary: fontmap
  591. });
  592. },
  593. SAFE = function __safeCall(fn) {
  594. fn.foo = function __safeCallWrapper() {
  595. try {
  596. return fn.apply(this, arguments);
  597. } catch (e) {
  598. var stack = e.stack || '';
  599. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  600. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  601. if (global.console) {
  602. global.console.error(m, e);
  603. if (global.alert) alert(m);
  604. } else {
  605. throw new Error(m);
  606. }
  607. }
  608. };
  609. fn.foo.bar = fn;
  610. return fn.foo;
  611. },
  612. to8bitStream = function to8bitStream(text, flags) {
  613. /**
  614. * PDF 1.3 spec:
  615. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  616. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  617. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  618. * to be a meaningful beginning of a word or phrase.) The remainder of the
  619. * string consists of Unicode character codes, according to the UTF-16 encoding
  620. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  621. * are represented as 2 bytes per character, with the high-order byte appearing first
  622. * in the string."
  623. *
  624. * In other words, if there are chars in a string with char code above 255, we
  625. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  626. *
  627. * HOWEVER!
  628. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  629. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  630. *
  631. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  632. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  633. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  634. * code page. There, however, all characters in the stream are treated as GIDs,
  635. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  636. * that is tied to a font).
  637. *
  638. * To signal this "special" PDFEscape / to8bitStream handling mode,
  639. * API.text() function sets (unless you overwrite it with manual values
  640. * given to API.text(.., flags) )
  641. * flags.autoencode = true
  642. * flags.noBOM = true
  643. *
  644. * ===================================================================================
  645. * `flags` properties relied upon:
  646. * .sourceEncoding = string with encoding label.
  647. * "Unicode" by default. = encoding of the incoming text.
  648. * pass some non-existing encoding name
  649. * (ex: 'Do not touch my strings! I know what I am doing.')
  650. * to make encoding code skip the encoding step.
  651. * .outputEncoding = Either valid PDF encoding name
  652. * (must be supported by jsPDF font metrics, otherwise no encoding)
  653. * or a JS object, where key = sourceCharCode, value = outputCharCode
  654. * missing keys will be treated as: sourceCharCode === outputCharCode
  655. * .noBOM
  656. * See comment higher above for explanation for why this is important
  657. * .autoencode
  658. * See comment higher above for explanation for why this is important
  659. */
  660. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  661. flags = flags || {};
  662. sourceEncoding = flags.sourceEncoding || 'Unicode';
  663. outputEncoding = flags.outputEncoding;
  664. // This 'encoding' section relies on font metrics format
  665. // attached to font objects by, among others,
  666. // "Willow Systems' standard_font_metrics plugin"
  667. // see jspdf.plugin.standard_font_metrics.js for format
  668. // of the font.metadata.encoding Object.
  669. // It should be something like
  670. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  671. // .widths = {0:width, code:width, ..., 'fof':divisor}
  672. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  673. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  674. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  675. // each font has default encoding. Some have it clearly defined.
  676. if (!outputEncoding && fonts[activeFontKey].encoding) {
  677. outputEncoding = fonts[activeFontKey].encoding;
  678. }
  679. // Hmmm, the above did not work? Let's try again, in different place.
  680. if (!outputEncoding && encodingBlock.codePages) {
  681. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  682. }
  683. if (typeof outputEncoding === 'string') {
  684. outputEncoding = encodingBlock[outputEncoding];
  685. }
  686. // we want output encoding to be a JS Object, where
  687. // key = sourceEncoding's character code and
  688. // value = outputEncoding's character code.
  689. if (outputEncoding) {
  690. isUnicode = false;
  691. newtext = [];
  692. for (i = 0, l = text.length; i < l; i++) {
  693. ch = outputEncoding[text.charCodeAt(i)];
  694. if (ch) {
  695. newtext.push(String.fromCharCode(ch));
  696. } else {
  697. newtext.push(text[i]);
  698. }
  699. // since we are looping over chars anyway, might as well
  700. // check for residual unicodeness
  701. if (newtext[i].charCodeAt(0) >> 8) {
  702. /* more than 255 */
  703. isUnicode = true;
  704. }
  705. }
  706. text = newtext.join('');
  707. }
  708. }
  709. i = text.length;
  710. // isUnicode may be set to false above. Hence the triple-equal to undefined
  711. while (isUnicode === undefined && i !== 0) {
  712. if (text.charCodeAt(i - 1) >> 8) {
  713. /* more than 255 */
  714. isUnicode = true;
  715. }
  716. i--;
  717. }
  718. if (!isUnicode) {
  719. return text;
  720. }
  721. newtext = flags.noBOM ? [] : [254, 255];
  722. for (i = 0, l = text.length; i < l; i++) {
  723. ch = text.charCodeAt(i);
  724. bch = ch >> 8; // divide by 256
  725. if (bch >> 8) {
  726. /* something left after dividing by 256 second time */
  727. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  728. }
  729. newtext.push(bch);
  730. newtext.push(ch - (bch << 8));
  731. }
  732. return String.fromCharCode.apply(undefined, newtext);
  733. },
  734. pdfEscape = function pdfEscape(text, flags) {
  735. /**
  736. * Replace '/', '(', and ')' with pdf-safe versions
  737. *
  738. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  739. * we also need to reference a unicode font and embed it - royal pain in the rear.
  740. *
  741. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  742. * which JavaScript Strings are happy to provide. So, while we still cannot display
  743. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  744. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  745. * is still parseable.
  746. * This will allow immediate support for unicode in document properties strings.
  747. */
  748. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  749. },
  750. putInfo = function putInfo() {
  751. out('/Producer (jsPDF ' + jsPDF.version + ')');
  752. for (var key in documentProperties) {
  753. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  754. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  755. }
  756. }
  757. var created = new Date(),
  758. tzoffset = created.getTimezoneOffset(),
  759. tzsign = tzoffset < 0 ? '+' : '-',
  760. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  761. tzmin = Math.abs(tzoffset % 60),
  762. tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  763. out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
  764. },
  765. putCatalog = function putCatalog() {
  766. out('/Type /Catalog');
  767. out('/Pages 1 0 R');
  768. // PDF13ref Section 7.2.1
  769. if (!zoomMode) zoomMode = 'fullwidth';
  770. switch (zoomMode) {
  771. case 'fullwidth':
  772. out('/OpenAction [3 0 R /FitH null]');
  773. break;
  774. case 'fullheight':
  775. out('/OpenAction [3 0 R /FitV null]');
  776. break;
  777. case 'fullpage':
  778. out('/OpenAction [3 0 R /Fit]');
  779. break;
  780. case 'original':
  781. out('/OpenAction [3 0 R /XYZ null null 1]');
  782. break;
  783. default:
  784. var pcn = '' + zoomMode;
  785. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  786. if (typeof zoomMode === 'number') {
  787. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  788. }
  789. }
  790. if (!layoutMode) layoutMode = 'continuous';
  791. switch (layoutMode) {
  792. case 'continuous':
  793. out('/PageLayout /OneColumn');
  794. break;
  795. case 'single':
  796. out('/PageLayout /SinglePage');
  797. break;
  798. case 'two':
  799. case 'twoleft':
  800. out('/PageLayout /TwoColumnLeft');
  801. break;
  802. case 'tworight':
  803. out('/PageLayout /TwoColumnRight');
  804. break;
  805. }
  806. if (pageMode) {
  807. /**
  808. * A name object specifying how the document should be displayed when opened:
  809. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  810. * UseOutlines : Document outline visible
  811. * UseThumbs : Thumbnail images visible
  812. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  813. */
  814. out('/PageMode /' + pageMode);
  815. }
  816. events.publish('putCatalog');
  817. },
  818. putTrailer = function putTrailer() {
  819. out('/Size ' + (objectNumber + 1));
  820. out('/Root ' + objectNumber + ' 0 R');
  821. out('/Info ' + (objectNumber - 1) + ' 0 R');
  822. },
  823. beginPage = function beginPage(width, height) {
  824. // Dimensions are stored as user units and converted to points on output
  825. var orientation = typeof height === 'string' && height.toLowerCase();
  826. if (typeof width === 'string') {
  827. var format = width.toLowerCase();
  828. if (pageFormats.hasOwnProperty(format)) {
  829. width = pageFormats[format][0] / k;
  830. height = pageFormats[format][1] / k;
  831. }
  832. }
  833. if (Array.isArray(width)) {
  834. height = width[1];
  835. width = width[0];
  836. }
  837. if (orientation) {
  838. switch (orientation.substr(0, 1)) {
  839. case 'l':
  840. if (height > width) orientation = 's';
  841. break;
  842. case 'p':
  843. if (width > height) orientation = 's';
  844. break;
  845. }
  846. if (orientation === 's') {
  847. tmp = width;
  848. width = height;
  849. height = tmp;
  850. }
  851. }
  852. outToPages = true;
  853. pages[++page] = [];
  854. pagedim[page] = {
  855. width: Number(width) || pageWidth,
  856. height: Number(height) || pageHeight
  857. };
  858. pagesContext[page] = {};
  859. _setPage(page);
  860. },
  861. _addPage = function _addPage() {
  862. beginPage.apply(this, arguments);
  863. // Set line width
  864. out(f2(lineWidth * k) + ' w');
  865. // Set draw color
  866. out(drawColor);
  867. // resurrecting non-default line caps, joins
  868. if (lineCapID !== 0) {
  869. out(lineCapID + ' J');
  870. }
  871. if (lineJoinID !== 0) {
  872. out(lineJoinID + ' j');
  873. }
  874. events.publish('addPage', {
  875. pageNumber: page
  876. });
  877. },
  878. _deletePage = function _deletePage(n) {
  879. if (n > 0 && n <= page) {
  880. pages.splice(n, 1);
  881. pagedim.splice(n, 1);
  882. page--;
  883. if (currentPage > page) {
  884. currentPage = page;
  885. }
  886. this.setPage(currentPage);
  887. }
  888. },
  889. _setPage = function _setPage(n) {
  890. if (n > 0 && n <= page) {
  891. currentPage = n;
  892. pageWidth = pagedim[n].width;
  893. pageHeight = pagedim[n].height;
  894. }
  895. },
  896. /**
  897. * Returns a document-specific font key - a label assigned to a
  898. * font name + font type combination at the time the font was added
  899. * to the font inventory.
  900. *
  901. * Font key is used as label for the desired font for a block of text
  902. * to be added to the PDF document stream.
  903. * @private
  904. * @function
  905. * @param fontName {String} can be undefined on "falthy" to indicate "use current"
  906. * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  907. * @returns {String} Font key.
  908. */
  909. _getFont = function _getFont(fontName, fontStyle) {
  910. var key;
  911. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  912. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  913. if (fontName !== undefined) {
  914. fontName = fontName.toLowerCase();
  915. }
  916. switch (fontName) {
  917. case 'sans-serif':
  918. case 'verdana':
  919. case 'arial':
  920. case 'helvetica':
  921. fontName = 'helvetica';
  922. break;
  923. case 'fixed':
  924. case 'monospace':
  925. case 'terminal':
  926. case 'courier':
  927. fontName = 'courier';
  928. break;
  929. case 'serif':
  930. case 'cursive':
  931. case 'fantasy':
  932. default:
  933. fontName = 'times';
  934. break;
  935. }
  936. try {
  937. // get a string like 'F3' - the KEY corresponding tot he font + type combination.
  938. key = fontmap[fontName][fontStyle];
  939. } catch (e) {}
  940. if (!key) {
  941. //throw new Error("Unable to look up font label for font '" + fontName + "', '"
  942. //+ fontStyle + "'. Refer to getFontList() for available fonts.");
  943. key = fontmap['times'][fontStyle];
  944. if (key == null) {
  945. key = fontmap['times']['normal'];
  946. }
  947. }
  948. return key;
  949. },
  950. buildDocument = function buildDocument() {
  951. outToPages = false; // switches out() to content
  952. objectNumber = 2;
  953. content_length = 0;
  954. content = [];
  955. offsets = [];
  956. additionalObjects = [];
  957. // Added for AcroForm
  958. events.publish('buildDocument');
  959. // putHeader()
  960. out('%PDF-' + pdfVersion);
  961. putPages();
  962. // Must happen after putPages
  963. // Modifies current object Id
  964. putAdditionalObjects();
  965. putResources();
  966. // Info
  967. newObject();
  968. out('<<');
  969. putInfo();
  970. out('>>');
  971. out('endobj');
  972. // Catalog
  973. newObject();
  974. out('<<');
  975. putCatalog();
  976. out('>>');
  977. out('endobj');
  978. // Cross-ref
  979. var o = content_length,
  980. i,
  981. p = "0000000000";
  982. out('xref');
  983. out('0 ' + (objectNumber + 1));
  984. out(p + ' 65535 f ');
  985. for (i = 1; i <= objectNumber; i++) {
  986. var offset = offsets[i];
  987. if (typeof offset === 'function') {
  988. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  989. } else {
  990. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  991. }
  992. }
  993. // Trailer
  994. out('trailer');
  995. out('<<');
  996. putTrailer();
  997. out('>>');
  998. out('startxref');
  999. out('' + o);
  1000. out('%%EOF');
  1001. outToPages = true;
  1002. return content.join('\n');
  1003. },
  1004. getStyle = function getStyle(style) {
  1005. // see path-painting operators in PDF spec
  1006. var op = 'S'; // stroke
  1007. if (style === 'F') {
  1008. op = 'f'; // fill
  1009. } else if (style === 'FD' || style === 'DF') {
  1010. op = 'B'; // both
  1011. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  1012. /*
  1013. Allow direct use of these PDF path-painting operators:
  1014. - f fill using nonzero winding number rule
  1015. - f* fill using even-odd rule
  1016. - B fill then stroke with fill using non-zero winding number rule
  1017. - B* fill then stroke with fill using even-odd rule
  1018. */
  1019. op = style;
  1020. }
  1021. return op;
  1022. },
  1023. getArrayBuffer = function getArrayBuffer() {
  1024. var data = buildDocument(),
  1025. len = data.length,
  1026. ab = new ArrayBuffer(len),
  1027. u8 = new Uint8Array(ab);
  1028. while (len--) {
  1029. u8[len] = data.charCodeAt(len);
  1030. }return ab;
  1031. },
  1032. getBlob = function getBlob() {
  1033. return new Blob([getArrayBuffer()], {
  1034. type: "application/pdf"
  1035. });
  1036. },
  1037. /**
  1038. * Generates the PDF document.
  1039. *
  1040. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1041. *
  1042. * @param {String} type A string identifying one of the possible output types.
  1043. * @param {Object} options An object providing some additional signalling to PDF generator.
  1044. * @function
  1045. * @returns {jsPDF}
  1046. * @methodOf jsPDF#
  1047. * @name output
  1048. */
  1049. _output = SAFE(function (type, options) {
  1050. var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
  1051. switch (type) {
  1052. case undefined:
  1053. return buildDocument();
  1054. case 'save':
  1055. if (navigator.getUserMedia) {
  1056. if (global.URL === undefined || global.URL.createObjectURL === undefined) {
  1057. return API.output('dataurlnewwindow');
  1058. }
  1059. }
  1060. saveAs(getBlob(), options);
  1061. if (typeof saveAs.unload === 'function') {
  1062. if (global.setTimeout) {
  1063. setTimeout(saveAs.unload, 911);
  1064. }
  1065. }
  1066. break;
  1067. case 'arraybuffer':
  1068. return getArrayBuffer();
  1069. case 'blob':
  1070. return getBlob();
  1071. case 'bloburi':
  1072. case 'bloburl':
  1073. // User is responsible of calling revokeObjectURL
  1074. return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
  1075. case 'datauristring':
  1076. case 'dataurlstring':
  1077. return datauri;
  1078. case 'dataurlnewwindow':
  1079. var nW = global.open(datauri);
  1080. if (nW || typeof safari === "undefined") return nW;
  1081. /* pass through */
  1082. case 'datauri':
  1083. case 'dataurl':
  1084. return global.document.location.href = datauri;
  1085. default:
  1086. throw new Error('Output type "' + type + '" is not supported.');
  1087. }
  1088. // @TODO: Add different output options
  1089. });
  1090. switch (unit) {
  1091. case 'pt':
  1092. k = 1;
  1093. break;
  1094. case 'mm':
  1095. k = 72 / 25.4000508;
  1096. break;
  1097. case 'cm':
  1098. k = 72 / 2.54000508;
  1099. break;
  1100. case 'in':
  1101. k = 72;
  1102. break;
  1103. case 'px':
  1104. k = 96 / 72;
  1105. break;
  1106. case 'pc':
  1107. k = 12;
  1108. break;
  1109. case 'em':
  1110. k = 12;
  1111. break;
  1112. case 'ex':
  1113. k = 6;
  1114. break;
  1115. default:
  1116. throw 'Invalid unit: ' + unit;
  1117. }
  1118. //---------------------------------------
  1119. // Public API
  1120. /**
  1121. * Object exposing internal API to plugins
  1122. * @public
  1123. */
  1124. API.internal = {
  1125. 'pdfEscape': pdfEscape,
  1126. 'getStyle': getStyle,
  1127. /**
  1128. * Returns {FontObject} describing a particular font.
  1129. * @public
  1130. * @function
  1131. * @param fontName {String} (Optional) Font's family name
  1132. * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  1133. * @returns {FontObject}
  1134. */
  1135. 'getFont': function getFont() {
  1136. return fonts[_getFont.apply(API, arguments)];
  1137. },
  1138. 'getFontSize': function getFontSize() {
  1139. return activeFontSize;
  1140. },
  1141. 'getLineHeight': function getLineHeight() {
  1142. return activeFontSize * lineHeightProportion;
  1143. },
  1144. 'write': function write(string1 /*, string2, string3, etc */) {
  1145. out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
  1146. },
  1147. 'getCoordinateString': function getCoordinateString(value) {
  1148. return f2(value * k);
  1149. },
  1150. 'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
  1151. return f2((pageHeight - value) * k);
  1152. },
  1153. 'collections': {},
  1154. 'newObject': newObject,
  1155. 'newAdditionalObject': newAdditionalObject,
  1156. 'newObjectDeferred': newObjectDeferred,
  1157. 'newObjectDeferredBegin': newObjectDeferredBegin,
  1158. 'putStream': putStream,
  1159. 'events': events,
  1160. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  1161. // units of measurement.
  1162. // scaleFactor is set at initialization of the document and calculated against the stated
  1163. // default measurement units for the document.
  1164. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  1165. // through multiplication.
  1166. 'scaleFactor': k,
  1167. 'pageSize': {
  1168. get width() {
  1169. return pageWidth;
  1170. },
  1171. get height() {
  1172. return pageHeight;
  1173. }
  1174. },
  1175. 'output': function output(type, options) {
  1176. return _output(type, options);
  1177. },
  1178. 'getNumberOfPages': function getNumberOfPages() {
  1179. return pages.length - 1;
  1180. },
  1181. 'pages': pages,
  1182. 'out': out,
  1183. 'f2': f2,
  1184. 'getPageInfo': function getPageInfo(pageNumberOneBased) {
  1185. var objId = (pageNumberOneBased - 1) * 2 + 3;
  1186. return {
  1187. objId: objId,
  1188. pageNumber: pageNumberOneBased,
  1189. pageContext: pagesContext[pageNumberOneBased]
  1190. };
  1191. },
  1192. 'getCurrentPageInfo': function getCurrentPageInfo() {
  1193. var objId = (currentPage - 1) * 2 + 3;
  1194. return {
  1195. objId: objId,
  1196. pageNumber: currentPage,
  1197. pageContext: pagesContext[currentPage]
  1198. };
  1199. },
  1200. 'getPDFVersion': function getPDFVersion() {
  1201. return pdfVersion;
  1202. }
  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. var linesLeft = Math.ceil((pageHeight - y - this._runningPageHeight) * k / (activeFontSize * lineHeightProportion));
  1415. if (0 <= linesLeft && linesLeft < da.length + 1) {
  1416. //todo = da.splice(linesLeft-1);
  1417. }
  1418. if (align) {
  1419. var left,
  1420. prevX,
  1421. maxLineLength,
  1422. leading = activeFontSize * lineHeightProportion,
  1423. lineWidths = text.map(function (v) {
  1424. return this.getStringUnitWidth(v) * activeFontSize / k;
  1425. }, this);
  1426. maxLineLength = Math.max.apply(Math, lineWidths);
  1427. // The first line uses the "main" Td setting,
  1428. // and the subsequent lines are offset by the
  1429. // previous line's x coordinate.
  1430. if (align === "center") {
  1431. // The passed in x coordinate defines
  1432. // the center point.
  1433. left = x - maxLineLength / 2;
  1434. x -= lineWidths[0] / 2;
  1435. } else if (align === "right") {
  1436. // The passed in x coordinate defines the
  1437. // rightmost point of the text.
  1438. left = x - maxLineLength;
  1439. x -= lineWidths[0];
  1440. } else {
  1441. throw new Error('Unrecognized alignment option, use "center" or "right".');
  1442. }
  1443. prevX = x;
  1444. text = da[0];
  1445. for (var i = 1, len = da.length; i < len; i++) {
  1446. var delta = maxLineLength - lineWidths[i];
  1447. if (align === "center") delta /= 2;
  1448. // T* = x-offset leading Td ( text )
  1449. text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
  1450. prevX = left + delta;
  1451. }
  1452. } else {
  1453. text = da.join(") Tj\nT* (");
  1454. }
  1455. } else {
  1456. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1457. }
  1458. // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
  1459. // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
  1460. // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
  1461. // Thus, there is NO useful, *reliable* concept of "default" font for a page.
  1462. // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
  1463. // - readers dealing smartly with brokenness of jsPDF's markup.
  1464. var curY;
  1465. if (todo) {
  1466. //this.addPage();
  1467. //this._runningPageHeight += y - (activeFontSize * 1.7 / k);
  1468. //curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1469. } else {
  1470. curY = f2((pageHeight - y) * k);
  1471. }
  1472. //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
  1473. // if (curY < 0){
  1474. // console.log('auto page break');
  1475. // this.addPage();
  1476. // this._runningPageHeight = y - (activeFontSize * 1.7 / k);
  1477. // curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1478. // }
  1479. out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1480. activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
  1481. strokeOption + // stroke option
  1482. textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
  1483. if (todo) {
  1484. //this.text( todo, x, activeFontSize * 1.7 / k);
  1485. //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
  1486. this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
  1487. }
  1488. return this;
  1489. };
  1490. /**
  1491. * Letter spacing method to print text with gaps
  1492. *
  1493. * @function
  1494. * @param {String|Array} text String to be added to the page.
  1495. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1496. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1497. * @param {Number} spacing Spacing (in units declared at inception)
  1498. * @returns {jsPDF}
  1499. * @methodOf jsPDF#
  1500. * @name lstext
  1501. * @deprecated We'll be removing this function. It doesn't take character width into account.
  1502. */
  1503. API.lstext = function (text, x, y, spacing) {
  1504. console.warn('jsPDF.lstext is deprecated');
  1505. for (var i = 0, len = text.length; i < len; i++, x += spacing) {
  1506. this.text(text[i], x, y);
  1507. }return this;
  1508. };
  1509. API.line = function (x1, y1, x2, y2) {
  1510. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  1511. };
  1512. API.clip = function () {
  1513. // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
  1514. // Call .clip() after calling .rect() with a style argument of null
  1515. out('W'); // clip
  1516. out('S'); // stroke path; necessary for clip to work
  1517. };
  1518. /**
  1519. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  1520. * We introduce the fixed version so as to not break API.
  1521. * @param fillRule
  1522. */
  1523. API.clip_fixed = function (fillRule) {
  1524. // Call .clip() after calling drawing ops with a style argument of null
  1525. // W is the PDF clipping op
  1526. if ('evenodd' === fillRule) {
  1527. out('W*');
  1528. } else {
  1529. out('W');
  1530. }
  1531. // End the path object without filling or stroking it.
  1532. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  1533. // (see Section 4.4.3, “Clipping Path Operators”)
  1534. out('n');
  1535. };
  1536. /**
  1537. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1538. * All data points in `lines` are relative to last line origin.
  1539. * `x`, `y` become x1,y1 for first line / curve in the set.
  1540. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1541. * 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.
  1542. *
  1543. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1544. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1545. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1546. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1547. * @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.
  1548. * @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.
  1549. * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1550. * @function
  1551. * @returns {jsPDF}
  1552. * @methodOf jsPDF#
  1553. * @name lines
  1554. */
  1555. API.lines = function (lines, x, y, scale, style, closed) {
  1556. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1557. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1558. // in effort to make all calls have similar signature like
  1559. // function(content, coordinateX, coordinateY , miscellaneous)
  1560. // this method had its args flipped.
  1561. // code below allows backward compatibility with old arg order.
  1562. if (typeof lines === 'number') {
  1563. tmp = y;
  1564. y = x;
  1565. x = lines;
  1566. lines = tmp;
  1567. }
  1568. scale = scale || [1, 1];
  1569. // starting point
  1570. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1571. scalex = scale[0];
  1572. scaley = scale[1];
  1573. l = lines.length;
  1574. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1575. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1576. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1577. x4 = x; // last / ending point = starting point for first item.
  1578. y4 = y; // last / ending point = starting point for first item.
  1579. for (i = 0; i < l; i++) {
  1580. leg = lines[i];
  1581. if (leg.length === 2) {
  1582. // simple line
  1583. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1584. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1585. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1586. } else {
  1587. // bezier curve
  1588. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1589. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1590. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1591. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1592. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1593. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1594. out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
  1595. }
  1596. }
  1597. if (closed) {
  1598. out(' h');
  1599. }
  1600. // stroking / filling / both the path
  1601. if (style !== null) {
  1602. out(getStyle(style));
  1603. }
  1604. return this;
  1605. };
  1606. /**
  1607. * Adds a rectangle to PDF
  1608. *
  1609. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1610. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1611. * @param {Number} w Width (in units declared at inception of PDF document)
  1612. * @param {Number} h Height (in units declared at inception of PDF document)
  1613. * @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.
  1614. * @function
  1615. * @returns {jsPDF}
  1616. * @methodOf jsPDF#
  1617. * @name rect
  1618. */
  1619. API.rect = function (x, y, w, h, style) {
  1620. var op = getStyle(style);
  1621. out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
  1622. if (style !== null) {
  1623. out(getStyle(style));
  1624. }
  1625. return this;
  1626. };
  1627. /**
  1628. * Adds a triangle to PDF
  1629. *
  1630. * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1631. * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1632. * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1633. * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1634. * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1635. * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1636. * @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.
  1637. * @function
  1638. * @returns {jsPDF}
  1639. * @methodOf jsPDF#
  1640. * @name triangle
  1641. */
  1642. API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  1643. this.lines([[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([[w - 2 * rx, 0], [rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry], [0, h - 2 * ry], [0, ry * MyArc, -(rx * MyArc), ry, -rx, ry], [-w + 2 * rx, 0], [-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry], [0, -h + 2 * ry], [0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]], x + rx, y, // start of path
  1668. [1, 1], style);
  1669. return this;
  1670. };
  1671. /**
  1672. * Adds an ellipse to PDF
  1673. *
  1674. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1675. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1676. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1677. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1678. * @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.
  1679. * @function
  1680. * @returns {jsPDF}
  1681. * @methodOf jsPDF#
  1682. * @name ellipse
  1683. */
  1684. API.ellipse = function (x, y, rx, ry, style) {
  1685. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1686. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1687. 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(' '));
  1688. 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(' '));
  1689. 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(' '));
  1690. 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(' '));
  1691. if (style !== null) {
  1692. out(getStyle(style));
  1693. }
  1694. return this;
  1695. };
  1696. /**
  1697. * Adds an circle to PDF
  1698. *
  1699. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1700. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1701. * @param {Number} r Radius (in units declared at inception of PDF document)
  1702. * @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.
  1703. * @function
  1704. * @returns {jsPDF}
  1705. * @methodOf jsPDF#
  1706. * @name circle
  1707. */
  1708. API.circle = function (x, y, r, style) {
  1709. return this.ellipse(x, y, r, r, style);
  1710. };
  1711. /**
  1712. * Adds a properties to the PDF document
  1713. *
  1714. * @param {Object} A property_name-to-property_value object structure.
  1715. * @function
  1716. * @returns {jsPDF}
  1717. * @methodOf jsPDF#
  1718. * @name setProperties
  1719. */
  1720. API.setProperties = function (properties) {
  1721. // copying only those properties we can render.
  1722. for (var property in documentProperties) {
  1723. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1724. documentProperties[property] = properties[property];
  1725. }
  1726. }
  1727. return this;
  1728. };
  1729. /**
  1730. * Sets font size for upcoming text elements.
  1731. *
  1732. * @param {Number} size Font size in points.
  1733. * @function
  1734. * @returns {jsPDF}
  1735. * @methodOf jsPDF#
  1736. * @name setFontSize
  1737. */
  1738. API.setFontSize = function (size) {
  1739. activeFontSize = size;
  1740. return this;
  1741. };
  1742. /**
  1743. * Sets text font face, variant for upcoming text elements.
  1744. * See output of jsPDF.getFontList() for possible font names, styles.
  1745. *
  1746. * @param {String} fontName Font name or family. Example: "times"
  1747. * @param {String} fontStyle Font style or variant. Example: "italic"
  1748. * @function
  1749. * @returns {jsPDF}
  1750. * @methodOf jsPDF#
  1751. * @name setFont
  1752. */
  1753. API.setFont = function (fontName, fontStyle) {
  1754. activeFontKey = _getFont(fontName, fontStyle);
  1755. // if font is not found, the above line blows up and we never go further
  1756. return this;
  1757. };
  1758. /**
  1759. * Switches font style or variant for upcoming text elements,
  1760. * while keeping the font face or family same.
  1761. * See output of jsPDF.getFontList() for possible font names, styles.
  1762. *
  1763. * @param {String} style Font style or variant. Example: "italic"
  1764. * @function
  1765. * @returns {jsPDF}
  1766. * @methodOf jsPDF#
  1767. * @name setFontStyle
  1768. */
  1769. API.setFontStyle = API.setFontType = function (style) {
  1770. activeFontKey = _getFont(undefined, style);
  1771. // if font is not found, the above line blows up and we never go further
  1772. return this;
  1773. };
  1774. /**
  1775. * Returns an object - a tree of fontName to fontStyle relationships available to
  1776. * active PDF document.
  1777. *
  1778. * @public
  1779. * @function
  1780. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  1781. * @methodOf jsPDF#
  1782. * @name getFontList
  1783. */
  1784. API.getFontList = function () {
  1785. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  1786. var list = {},
  1787. fontName,
  1788. fontStyle,
  1789. tmp;
  1790. for (fontName in fontmap) {
  1791. if (fontmap.hasOwnProperty(fontName)) {
  1792. list[fontName] = tmp = [];
  1793. for (fontStyle in fontmap[fontName]) {
  1794. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  1795. tmp.push(fontStyle);
  1796. }
  1797. }
  1798. }
  1799. }
  1800. return list;
  1801. };
  1802. /**
  1803. * Add a custom font.
  1804. *
  1805. * @param {String} Postscript name of the Font. Example: "Menlo-Regular"
  1806. * @param {String} Name of font-family from @font-face definition. Example: "Menlo Regular"
  1807. * @param {String} Font style. Example: "normal"
  1808. * @function
  1809. * @returns the {fontKey} (same as the internal method)
  1810. * @methodOf jsPDF#
  1811. * @name addFont
  1812. */
  1813. API.addFont = function (postScriptName, fontName, fontStyle) {
  1814. addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
  1815. };
  1816. /**
  1817. * Sets line width for upcoming lines.
  1818. *
  1819. * @param {Number} width Line width (in units declared at inception of PDF document)
  1820. * @function
  1821. * @returns {jsPDF}
  1822. * @methodOf jsPDF#
  1823. * @name setLineWidth
  1824. */
  1825. API.setLineWidth = function (width) {
  1826. out((width * k).toFixed(2) + ' w');
  1827. return this;
  1828. };
  1829. /**
  1830. * Sets the stroke color for upcoming elements.
  1831. *
  1832. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1833. * color space is implied.
  1834. *
  1835. * When only ch1 is given, "Gray" color space is implied and it
  1836. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1837. * if values are communicated as String types, or in range from 0 (black)
  1838. * to 255 (white) if communicated as Number type.
  1839. * The RGB-like 0-255 range is provided for backward compatibility.
  1840. *
  1841. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1842. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1843. * (max intensity) if values are communicated as String types, or
  1844. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1845. * as Number types.
  1846. * The RGB-like 0-255 range is provided for backward compatibility.
  1847. *
  1848. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1849. * value must be a in the range from 0.00 (0% concentration) to to
  1850. * 1.00 (100% concentration)
  1851. *
  1852. * Because JavaScript treats fixed point numbers badly (rounds to
  1853. * floating point nearest to binary representation) it is highly advised to
  1854. * communicate the fractional numbers as String types, not JavaScript Number type.
  1855. *
  1856. * @param {Number|String} ch1 Color channel value
  1857. * @param {Number|String} ch2 Color channel value
  1858. * @param {Number|String} ch3 Color channel value
  1859. * @param {Number|String} ch4 Color channel value
  1860. *
  1861. * @function
  1862. * @returns {jsPDF}
  1863. * @methodOf jsPDF#
  1864. * @name setDrawColor
  1865. */
  1866. API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  1867. var color;
  1868. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1869. // Gray color space.
  1870. if (typeof ch1 === 'string') {
  1871. color = ch1 + ' G';
  1872. } else {
  1873. color = f2(ch1 / 255) + ' G';
  1874. }
  1875. } else if (ch4 === undefined) {
  1876. // RGB
  1877. if (typeof ch1 === 'string') {
  1878. color = [ch1, ch2, ch3, 'RG'].join(' ');
  1879. } else {
  1880. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
  1881. }
  1882. } else {
  1883. // CMYK
  1884. if (typeof ch1 === 'string') {
  1885. color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
  1886. } else {
  1887. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
  1888. }
  1889. }
  1890. out(color);
  1891. return this;
  1892. };
  1893. /**
  1894. * Sets the fill color for upcoming elements.
  1895. *
  1896. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1897. * color space is implied.
  1898. *
  1899. * When only ch1 is given, "Gray" color space is implied and it
  1900. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1901. * if values are communicated as String types, or in range from 0 (black)
  1902. * to 255 (white) if communicated as Number type.
  1903. * The RGB-like 0-255 range is provided for backward compatibility.
  1904. *
  1905. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1906. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1907. * (max intensity) if values are communicated as String types, or
  1908. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1909. * as Number types.
  1910. * The RGB-like 0-255 range is provided for backward compatibility.
  1911. *
  1912. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1913. * value must be a in the range from 0.00 (0% concentration) to to
  1914. * 1.00 (100% concentration)
  1915. *
  1916. * Because JavaScript treats fixed point numbers badly (rounds to
  1917. * floating point nearest to binary representation) it is highly advised to
  1918. * communicate the fractional numbers as String types, not JavaScript Number type.
  1919. *
  1920. * @param {Number|String} ch1 Color channel value
  1921. * @param {Number|String} ch2 Color channel value
  1922. * @param {Number|String} ch3 Color channel value
  1923. * @param {Number|String} ch4 Color channel value
  1924. *
  1925. * @function
  1926. * @returns {jsPDF}
  1927. * @methodOf jsPDF#
  1928. * @name setFillColor
  1929. */
  1930. API.setFillColor = function (ch1, ch2, ch3, ch4) {
  1931. var color;
  1932. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1933. // Gray color space.
  1934. if (typeof ch1 === 'string') {
  1935. color = ch1 + ' g';
  1936. } else {
  1937. color = f2(ch1 / 255) + ' g';
  1938. }
  1939. } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
  1940. // RGB
  1941. if (typeof ch1 === 'string') {
  1942. color = [ch1, ch2, ch3, 'rg'].join(' ');
  1943. } else {
  1944. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
  1945. }
  1946. if (ch4 && ch4.a === 0) {
  1947. //TODO Implement transparency.
  1948. //WORKAROUND use white for now
  1949. color = ['255', '255', '255', 'rg'].join(' ');
  1950. }
  1951. } else {
  1952. // CMYK
  1953. if (typeof ch1 === 'string') {
  1954. color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
  1955. } else {
  1956. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
  1957. }
  1958. }
  1959. out(color);
  1960. return this;
  1961. };
  1962. /**
  1963. * Sets the text color for upcoming elements.
  1964. * If only one, first argument is given,
  1965. * treats the value as gray-scale color value.
  1966. *
  1967. * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
  1968. * @param {Number} g Green channel color value in range 0-255
  1969. * @param {Number} b Blue channel color value in range 0-255
  1970. * @function
  1971. * @returns {jsPDF}
  1972. * @methodOf jsPDF#
  1973. * @name setTextColor
  1974. */
  1975. API.setTextColor = function (r, g, b) {
  1976. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  1977. var hex = parseInt(r.substr(1), 16);
  1978. r = hex >> 16 & 255;
  1979. g = hex >> 8 & 255;
  1980. b = hex & 255;
  1981. }
  1982. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  1983. textColor = f3(r / 255) + ' g';
  1984. } else {
  1985. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  1986. }
  1987. return this;
  1988. };
  1989. /**
  1990. * Is an Object providing a mapping from human-readable to
  1991. * integer flag values designating the varieties of line cap
  1992. * and join styles.
  1993. *
  1994. * @returns {Object}
  1995. * @fieldOf jsPDF#
  1996. * @name CapJoinStyles
  1997. */
  1998. API.CapJoinStyles = {
  1999. 0: 0,
  2000. 'butt': 0,
  2001. 'but': 0,
  2002. 'miter': 0,
  2003. 1: 1,
  2004. 'round': 1,
  2005. 'rounded': 1,
  2006. 'circle': 1,
  2007. 2: 2,
  2008. 'projecting': 2,
  2009. 'project': 2,
  2010. 'square': 2,
  2011. 'bevel': 2
  2012. };
  2013. /**
  2014. * Sets the line cap styles
  2015. * See {jsPDF.CapJoinStyles} for variants
  2016. *
  2017. * @param {String|Number} style A string or number identifying the type of line cap
  2018. * @function
  2019. * @returns {jsPDF}
  2020. * @methodOf jsPDF#
  2021. * @name setLineCap
  2022. */
  2023. API.setLineCap = function (style) {
  2024. var id = this.CapJoinStyles[style];
  2025. if (id === undefined) {
  2026. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2027. }
  2028. lineCapID = id;
  2029. out(id + ' J');
  2030. return this;
  2031. };
  2032. /**
  2033. * Sets the line join styles
  2034. * See {jsPDF.CapJoinStyles} for variants
  2035. *
  2036. * @param {String|Number} style A string or number identifying the type of line join
  2037. * @function
  2038. * @returns {jsPDF}
  2039. * @methodOf jsPDF#
  2040. * @name setLineJoin
  2041. */
  2042. API.setLineJoin = function (style) {
  2043. var id = this.CapJoinStyles[style];
  2044. if (id === undefined) {
  2045. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2046. }
  2047. lineJoinID = id;
  2048. out(id + ' j');
  2049. return this;
  2050. };
  2051. // Output is both an internal (for plugins) and external function
  2052. API.output = _output;
  2053. /**
  2054. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  2055. * @param {String} filename The filename including extension.
  2056. *
  2057. * @function
  2058. * @returns {jsPDF}
  2059. * @methodOf jsPDF#
  2060. * @name save
  2061. */
  2062. API.save = function (filename) {
  2063. API.output('save', filename);
  2064. };
  2065. // applying plugins (more methods) ON TOP of built-in API.
  2066. // this is intentional as we allow plugins to override
  2067. // built-ins
  2068. for (var plugin in jsPDF.API) {
  2069. if (jsPDF.API.hasOwnProperty(plugin)) {
  2070. if (plugin === 'events' && jsPDF.API.events.length) {
  2071. (function (events, newEvents) {
  2072. // jsPDF.API.events is a JS Array of Arrays
  2073. // where each Array is a pair of event name, handler
  2074. // Events were added by plugins to the jsPDF instantiator.
  2075. // These are always added to the new instance and some ran
  2076. // during instantiation.
  2077. var eventname, handler_and_args, i;
  2078. for (i = newEvents.length - 1; i !== -1; i--) {
  2079. // subscribe takes 3 args: 'topic', function, runonce_flag
  2080. // if undefined, runonce is false.
  2081. // users can attach callback directly,
  2082. // or they can attach an array with [callback, runonce_flag]
  2083. // that's what the "apply" magic is for below.
  2084. eventname = newEvents[i][0];
  2085. handler_and_args = newEvents[i][1];
  2086. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  2087. }
  2088. })(events, jsPDF.API.events);
  2089. } else {
  2090. API[plugin] = jsPDF.API[plugin];
  2091. }
  2092. }
  2093. }
  2094. //////////////////////////////////////////////////////
  2095. // continuing initialization of jsPDF Document object
  2096. //////////////////////////////////////////////////////
  2097. // Add the first page automatically
  2098. addFonts();
  2099. activeFontKey = 'F1';
  2100. _addPage(format, orientation);
  2101. events.publish('initialized');
  2102. return API;
  2103. }
  2104. /**
  2105. * jsPDF.API is a STATIC property of jsPDF class.
  2106. * jsPDF.API is an object you can add methods and properties to.
  2107. * The methods / properties you add will show up in new jsPDF objects.
  2108. *
  2109. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  2110. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  2111. * Examples:
  2112. * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  2113. * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  2114. *
  2115. * @static
  2116. * @public
  2117. * @memberOf jsPDF
  2118. * @name API
  2119. *
  2120. * @example
  2121. * jsPDF.API.mymethod = function(){
  2122. * // 'this' will be ref to internal API object. see jsPDF source
  2123. * // , so you can refer to built-in methods like so:
  2124. * // this.line(....)
  2125. * // this.text(....)
  2126. * }
  2127. * var pdfdoc = new jsPDF()
  2128. * pdfdoc.mymethod() // <- !!!!!!
  2129. */
  2130. jsPDF.API = {
  2131. events: []
  2132. };
  2133. jsPDF.version = "1.x-master";
  2134. if (typeof define === 'function' && define.amd) {
  2135. define('jsPDF', function () {
  2136. return jsPDF;
  2137. });
  2138. } else if (typeof module !== 'undefined' && module.exports) {
  2139. module.exports = jsPDF;
  2140. } else {
  2141. global.jsPDF = jsPDF;
  2142. }
  2143. return jsPDF;
  2144. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  2145. /**
  2146. * jsPDF AcroForm Plugin
  2147. * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
  2148. *
  2149. * Licensed under the MIT License.
  2150. * http://opensource.org/licenses/mit-license
  2151. */
  2152. (window.AcroForm = function (jsPDFAPI) {
  2153. 'use strict';
  2154. var AcroForm = window.AcroForm;
  2155. AcroForm.scale = function (x) {
  2156. return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
  2157. };
  2158. AcroForm.antiScale = function (x) {
  2159. return 1 / acroformPlugin.internal.scaleFactor * x;
  2160. };
  2161. var acroformPlugin = {
  2162. fields: [],
  2163. xForms: [],
  2164. /**
  2165. * acroFormDictionaryRoot contains information about the AcroForm Dictionary
  2166. * 0: The Event-Token, the AcroFormDictionaryCallback has
  2167. * 1: The Object ID of the Root
  2168. */
  2169. acroFormDictionaryRoot: null,
  2170. /**
  2171. * After the PDF gets evaluated, the reference to the root has to be reset,
  2172. * this indicates, whether the root has already been printed out
  2173. */
  2174. printedOut: false,
  2175. internal: null
  2176. };
  2177. jsPDF.API.acroformPlugin = acroformPlugin;
  2178. var annotReferenceCallback = function annotReferenceCallback() {
  2179. for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
  2180. var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
  2181. // add Annot Reference!
  2182. if (formObject.hasAnnotation) {
  2183. // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
  2184. createAnnotationReference.call(this, formObject);
  2185. }
  2186. }
  2187. };
  2188. var createAcroForm = function createAcroForm() {
  2189. if (this.acroformPlugin.acroFormDictionaryRoot) {
  2190. //return;
  2191. throw new Error("Exception while creating AcroformDictionary");
  2192. }
  2193. // The Object Number of the AcroForm Dictionary
  2194. this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
  2195. this.acroformPlugin.internal = this.internal;
  2196. // add Callback for creating the AcroForm Dictionary
  2197. this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  2198. this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
  2199. // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
  2200. this.internal.events.subscribe('putCatalog', putCatalogCallback);
  2201. // Register event, that creates all Fields
  2202. this.internal.events.subscribe('postPutPages', createFieldCallback);
  2203. };
  2204. /**
  2205. * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
  2206. * (Requires the Annotation Plugin)
  2207. */
  2208. var createAnnotationReference = function createAnnotationReference(object) {
  2209. var options = {
  2210. type: 'reference',
  2211. object: object
  2212. };
  2213. jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
  2214. };
  2215. var putForm = function putForm(formObject) {
  2216. if (this.acroformPlugin.printedOut) {
  2217. this.acroformPlugin.printedOut = false;
  2218. this.acroformPlugin.acroFormDictionaryRoot = null;
  2219. }
  2220. if (!this.acroformPlugin.acroFormDictionaryRoot) {
  2221. createAcroForm.call(this);
  2222. }
  2223. this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  2224. };
  2225. // Callbacks
  2226. var putCatalogCallback = function putCatalogCallback() {
  2227. //Put reference to AcroForm to DocumentCatalog
  2228. if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  2229. // for safety, shouldn't normally be the case
  2230. this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  2231. } else {
  2232. console.log('Root missing...');
  2233. }
  2234. };
  2235. /**
  2236. * Adds /Acroform X 0 R to Document Catalog,
  2237. * and creates the AcroForm Dictionary
  2238. */
  2239. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  2240. // Remove event
  2241. this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
  2242. delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
  2243. this.acroformPlugin.printedOut = true;
  2244. };
  2245. /**
  2246. * Creates the single Fields and writes them into the Document
  2247. *
  2248. * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
  2249. * (for the FormXObjects...)
  2250. */
  2251. var createFieldCallback = function createFieldCallback(fieldArray) {
  2252. var standardFields = !fieldArray;
  2253. if (!fieldArray) {
  2254. // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
  2255. // Print out Root
  2256. this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
  2257. this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
  2258. }
  2259. var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
  2260. for (var i in fieldArray) {
  2261. var key = i;
  2262. var form = fieldArray[i];
  2263. var oldRect = form.Rect;
  2264. if (form.Rect) {
  2265. form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
  2266. }
  2267. // Start Writing the Object
  2268. this.internal.newObjectDeferredBegin(form.objId);
  2269. var content = "";
  2270. content += form.objId + " 0 obj\n";
  2271. content += "<<\n" + form.getContent();
  2272. form.Rect = oldRect;
  2273. if (form.hasAppearanceStream && !form.appearanceStreamContent) {
  2274. // Calculate Appearance
  2275. var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
  2276. content += "/AP << /N " + appearance + " >>\n";
  2277. this.acroformPlugin.xForms.push(appearance);
  2278. }
  2279. // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
  2280. if (form.appearanceStreamContent) {
  2281. content += "/AP << ";
  2282. // Iterate over N,R and D
  2283. for (var k in form.appearanceStreamContent) {
  2284. var value = form.appearanceStreamContent[k];
  2285. content += "/" + k + " ";
  2286. content += "<< ";
  2287. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  2288. // appearanceStream is an Array or Object!
  2289. for (var i in value) {
  2290. var obj = value[i];
  2291. if (typeof obj === 'function') {
  2292. // if Function is referenced, call it in order to get the FormXObject
  2293. obj = obj.call(this, form);
  2294. }
  2295. content += "/" + i + " " + obj + " ";
  2296. // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
  2297. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2298. }
  2299. } else {
  2300. var obj = value;
  2301. if (typeof obj === 'function') {
  2302. // if Function is referenced, call it in order to get the FormXObject
  2303. obj = obj.call(this, form);
  2304. }
  2305. content += "/" + i + " " + obj + " \n";
  2306. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2307. }
  2308. content += " >>\n";
  2309. }
  2310. // appearance stream is a normal Object..
  2311. content += ">>\n";
  2312. }
  2313. content += ">>\nendobj\n";
  2314. this.internal.out(content);
  2315. }
  2316. if (standardFields) {
  2317. createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
  2318. }
  2319. };
  2320. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  2321. for (var i in fieldArray) {
  2322. var key = i;
  2323. var form = fieldArray[i];
  2324. // Start Writing the Object
  2325. this.internal.newObjectDeferredBegin(form && form.objId);
  2326. var content = "";
  2327. content += form ? form.getString() : '';
  2328. this.internal.out(content);
  2329. delete fieldArray[key];
  2330. }
  2331. };
  2332. // Public:
  2333. jsPDFAPI.addField = function (fieldObject) {
  2334. //var opt = parseOptions(fieldObject);
  2335. if (fieldObject instanceof AcroForm.TextField) {
  2336. addTextField.call(this, fieldObject);
  2337. } else if (fieldObject instanceof AcroForm.ChoiceField) {
  2338. addChoiceField.call(this, fieldObject);
  2339. } else if (fieldObject instanceof AcroForm.Button) {
  2340. addButton.call(this, fieldObject);
  2341. } else if (fieldObject instanceof AcroForm.ChildClass) {
  2342. putForm.call(this, fieldObject);
  2343. } else if (fieldObject) {
  2344. // try to put..
  2345. putForm.call(this, fieldObject);
  2346. }
  2347. fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
  2348. return this;
  2349. };
  2350. // ############### sort in:
  2351. /**
  2352. * Button
  2353. * FT = Btn
  2354. */
  2355. var addButton = function addButton(options) {
  2356. var options = options || new AcroForm.Field();
  2357. options.FT = '/Btn';
  2358. /**
  2359. * Calculating the Ff entry:
  2360. *
  2361. * The Ff entry contains flags, that have to be set bitwise
  2362. * In the Following the number in the Comment is the BitPosition
  2363. */
  2364. var flags = options.Ff || 0;
  2365. // 17, Pushbutton
  2366. if (options.pushbutton) {
  2367. // Options.pushbutton should be 1 or 0
  2368. flags = AcroForm.internal.setBitPosition(flags, 17);
  2369. delete options.pushbutton;
  2370. }
  2371. //16, Radio
  2372. if (options.radio) {
  2373. //flags = options.Ff | options.radio << 15;
  2374. flags = AcroForm.internal.setBitPosition(flags, 16);
  2375. delete options.radio;
  2376. }
  2377. // 15, NoToggleToOff (Radio buttons only
  2378. if (options.noToggleToOff) {
  2379. //flags = options.Ff | options.noToggleToOff << 14;
  2380. flags = AcroForm.internal.setBitPosition(flags, 15);
  2381. //delete options.noToggleToOff;
  2382. }
  2383. // In case, there is no Flag set, it is a check-box
  2384. options.Ff = flags;
  2385. putForm.call(this, options);
  2386. };
  2387. var addTextField = function addTextField(options) {
  2388. var options = options || new AcroForm.Field();
  2389. options.FT = '/Tx';
  2390. /**
  2391. * Calculating the Ff entry:
  2392. *
  2393. * The Ff entry contains flags, that have to be set bitwise
  2394. * In the Following the number in the Comment is the BitPosition
  2395. */
  2396. var flags = options.Ff || 0;
  2397. // 13, multiline
  2398. if (options.multiline) {
  2399. // Set Flag
  2400. flags = flags | 1 << 12;
  2401. // Remove multiline from FieldObject
  2402. //delete options.multiline;
  2403. }
  2404. // 14, Password
  2405. if (options.password) {
  2406. flags = flags | 1 << 13;
  2407. //delete options.password;
  2408. }
  2409. // 21, FileSelect, PDF 1.4...
  2410. if (options.fileSelect) {
  2411. flags = flags | 1 << 20;
  2412. //delete options.fileSelect;
  2413. }
  2414. // 23, DoNotSpellCheck, PDF 1.4...
  2415. if (options.doNotSpellCheck) {
  2416. flags = flags | 1 << 22;
  2417. //delete options.doNotSpellCheck;
  2418. }
  2419. // 24, DoNotScroll, PDF 1.4...
  2420. if (options.doNotScroll) {
  2421. flags = flags | 1 << 23;
  2422. //delete options.doNotScroll;
  2423. }
  2424. options.Ff = options.Ff || flags;
  2425. // Add field
  2426. putForm.call(this, options);
  2427. };
  2428. var addChoiceField = function addChoiceField(opt) {
  2429. var options = opt || new AcroForm.Field();
  2430. options.FT = '/Ch';
  2431. /**
  2432. * Calculating the Ff entry:
  2433. *
  2434. * The Ff entry contains flags, that have to be set bitwise
  2435. * In the Following the number in the Comment is the BitPosition
  2436. */
  2437. var flags = options.Ff || 0;
  2438. // 18, Combo (If not set, the choiceField is a listBox!!)
  2439. if (options.combo) {
  2440. // Set Flag
  2441. flags = AcroForm.internal.setBitPosition(flags, 18);
  2442. // Remove combo from FieldObject
  2443. delete options.combo;
  2444. }
  2445. // 19, Edit
  2446. if (options.edit) {
  2447. flags = AcroForm.internal.setBitPosition(flags, 19);
  2448. delete options.edit;
  2449. }
  2450. // 20, Sort
  2451. if (options.sort) {
  2452. flags = AcroForm.internal.setBitPosition(flags, 20);
  2453. delete options.sort;
  2454. }
  2455. // 22, MultiSelect (PDF 1.4)
  2456. if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
  2457. flags = AcroForm.internal.setBitPosition(flags, 22);
  2458. delete options.multiSelect;
  2459. }
  2460. // 23, DoNotSpellCheck (PDF 1.4)
  2461. if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
  2462. flags = AcroForm.internal.setBitPosition(flags, 23);
  2463. delete options.doNotSpellCheck;
  2464. }
  2465. options.Ff = flags;
  2466. //options.hasAnnotation = true;
  2467. // Add field
  2468. putForm.call(this, options);
  2469. };
  2470. })(jsPDF.API);
  2471. var AcroForm = window.AcroForm;
  2472. AcroForm.internal = {};
  2473. AcroForm.createFormXObject = function (formObject) {
  2474. var xobj = new AcroForm.FormXObject();
  2475. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  2476. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  2477. xobj.BBox = [0, 0, width, height];
  2478. return xobj;
  2479. };
  2480. // Contains Methods for creating standard appearances
  2481. AcroForm.Appearance = {
  2482. CheckBox: {
  2483. createAppearanceStream: function createAppearanceStream() {
  2484. var appearance = {
  2485. N: {
  2486. On: AcroForm.Appearance.CheckBox.YesNormal
  2487. },
  2488. D: {
  2489. On: AcroForm.Appearance.CheckBox.YesPushDown,
  2490. Off: AcroForm.Appearance.CheckBox.OffPushDown
  2491. }
  2492. };
  2493. return appearance;
  2494. },
  2495. /**
  2496. * If any other icons are needed, the number between the brackets can be changed
  2497. * @returns {string}
  2498. */
  2499. createMK: function createMK() {
  2500. // 3-> Hook
  2501. return "<< /CA (3)>>";
  2502. },
  2503. /**
  2504. * Returns the standard On Appearance for a CheckBox
  2505. * @returns {AcroForm.FormXObject}
  2506. */
  2507. YesPushDown: function YesPushDown(formObject) {
  2508. var xobj = AcroForm.createFormXObject(formObject);
  2509. var stream = "";
  2510. // F13 is ZapfDingbats (Symbolic)
  2511. formObject.Q = 1; // set text-alignment as centered
  2512. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
  2513. stream += "0.749023 g\n\
  2514. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2515. f\n\
  2516. BMC\n\
  2517. q\n\
  2518. 0 0 1 rg\n\
  2519. /F13 " + calcRes.fontSize + " Tf 0 g\n\
  2520. BT\n";
  2521. stream += calcRes.text;
  2522. stream += "ET\n\
  2523. Q\n\
  2524. EMC\n";
  2525. xobj.stream = stream;
  2526. return xobj;
  2527. },
  2528. YesNormal: function YesNormal(formObject) {
  2529. var xobj = AcroForm.createFormXObject(formObject);
  2530. var stream = "";
  2531. formObject.Q = 1; // set text-alignment as centered
  2532. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formObject) * 0.9);
  2533. stream += "1 g\n\
  2534. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2535. f\n\
  2536. q\n\
  2537. 0 0 1 rg\n\
  2538. 0 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
  2539. W\n\
  2540. n\n\
  2541. 0 g\n\
  2542. BT\n\
  2543. /F13 " + calcRes.fontSize + " Tf 0 g\n";
  2544. stream += calcRes.text;
  2545. stream += "ET\n\
  2546. Q\n";
  2547. xobj.stream = stream;
  2548. return xobj;
  2549. },
  2550. /**
  2551. * Returns the standard Off Appearance for a CheckBox
  2552. * @returns {AcroForm.FormXObject}
  2553. */
  2554. OffPushDown: function OffPushDown(formObject) {
  2555. var xobj = AcroForm.createFormXObject(formObject);
  2556. var stream = "";
  2557. stream += "0.749023 g\n\
  2558. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2559. f\n";
  2560. xobj.stream = stream;
  2561. return xobj;
  2562. }
  2563. },
  2564. RadioButton: {
  2565. Circle: {
  2566. createAppearanceStream: function createAppearanceStream(name) {
  2567. var appearanceStreamContent = {
  2568. D: {
  2569. 'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
  2570. },
  2571. N: {}
  2572. };
  2573. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
  2574. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
  2575. return appearanceStreamContent;
  2576. },
  2577. createMK: function createMK() {
  2578. return "<< /CA (l)>>";
  2579. },
  2580. YesNormal: function YesNormal(formObject) {
  2581. var xobj = AcroForm.createFormXObject(formObject);
  2582. var stream = "";
  2583. // Make the Radius of the Circle relative to min(height, width) of formObject
  2584. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2585. // The Borderpadding...
  2586. DotRadius *= 0.9;
  2587. var c = AcroForm.Appearance.internal.Bezier_C;
  2588. /*
  2589. The Following is a Circle created with Bezier-Curves.
  2590. */
  2591. stream += "q\n\
  2592. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2593. " + DotRadius + " 0 m\n\
  2594. " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2595. -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2596. -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2597. " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2598. f\n\
  2599. Q\n";
  2600. xobj.stream = stream;
  2601. return xobj;
  2602. },
  2603. YesPushDown: function YesPushDown(formObject) {
  2604. var xobj = AcroForm.createFormXObject(formObject);
  2605. var stream = "";
  2606. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2607. // The Borderpadding...
  2608. DotRadius *= 0.9;
  2609. // Save results for later use; no need to waste processor ticks on doing math
  2610. var k = DotRadius * 2;
  2611. // var c = AcroForm.Appearance.internal.Bezier_C;
  2612. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2613. var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
  2614. // stream += "0.749023 g\n\
  2615. // q\n\
  2616. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2617. // " + DotRadius * 2 + " 0 m\n\
  2618. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2619. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2620. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2621. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2622. // f\n\
  2623. // Q\n\
  2624. // 0 g\n\
  2625. // q\n\
  2626. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2627. // " + DotRadius + " 0 m\n\
  2628. // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2629. // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2630. // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2631. // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2632. // f\n\
  2633. // Q\n";
  2634. // FASTER VERSION with less processor ticks spent on math operations
  2635. stream += "0.749023 g\n\
  2636. q\n\
  2637. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2638. " + k + " 0 m\n\
  2639. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2640. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2641. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2642. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2643. f\n\
  2644. Q\n\
  2645. 0 g\n\
  2646. q\n\
  2647. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2648. " + DotRadius + " 0 m\n\
  2649. " + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2650. -" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
  2651. -" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2652. " + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
  2653. f\n\
  2654. Q\n";
  2655. xobj.stream = stream;
  2656. return xobj;
  2657. },
  2658. OffPushDown: function OffPushDown(formObject) {
  2659. var xobj = AcroForm.createFormXObject(formObject);
  2660. var stream = "";
  2661. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2662. // The Borderpadding...
  2663. DotRadius *= 0.9;
  2664. // Save results for later use; no need to waste processor ticks on doing math
  2665. var k = DotRadius * 2;
  2666. // var c = AcroForm.Appearance.internal.Bezier_C;
  2667. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2668. // stream += "0.749023 g\n\
  2669. // q\n\
  2670. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2671. // " + DotRadius * 2 + " 0 m\n\
  2672. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2673. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2674. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2675. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2676. // f\n\
  2677. // Q\n";
  2678. // FASTER VERSION with less processor ticks spent on math operations
  2679. stream += "0.749023 g\n\
  2680. q\n\
  2681. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2682. " + k + " 0 m\n\
  2683. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2684. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2685. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2686. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2687. f\n\
  2688. Q\n";
  2689. xobj.stream = stream;
  2690. return xobj;
  2691. }
  2692. },
  2693. Cross: {
  2694. /**
  2695. * Creates the Actual AppearanceDictionary-References
  2696. * @param name
  2697. * @returns
  2698. */
  2699. createAppearanceStream: function createAppearanceStream(name) {
  2700. var appearanceStreamContent = {
  2701. D: {
  2702. 'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
  2703. },
  2704. N: {}
  2705. };
  2706. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
  2707. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
  2708. return appearanceStreamContent;
  2709. },
  2710. createMK: function createMK() {
  2711. return "<< /CA (8)>>";
  2712. },
  2713. YesNormal: function YesNormal(formObject) {
  2714. var xobj = AcroForm.createFormXObject(formObject);
  2715. var stream = "";
  2716. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2717. stream += "q\n\
  2718. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2719. W\n\
  2720. n\n\
  2721. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2722. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2723. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2724. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2725. s\n\
  2726. Q\n";
  2727. xobj.stream = stream;
  2728. return xobj;
  2729. },
  2730. YesPushDown: function YesPushDown(formObject) {
  2731. var xobj = AcroForm.createFormXObject(formObject);
  2732. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2733. var stream = "";
  2734. stream += "0.749023 g\n\
  2735. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2736. f\n\
  2737. q\n\
  2738. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2739. W\n\
  2740. n\n\
  2741. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2742. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2743. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2744. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2745. s\n\
  2746. Q\n";
  2747. xobj.stream = stream;
  2748. return xobj;
  2749. },
  2750. OffPushDown: function OffPushDown(formObject) {
  2751. var xobj = AcroForm.createFormXObject(formObject);
  2752. var stream = "";
  2753. stream += "0.749023 g\n\
  2754. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2755. f\n";
  2756. xobj.stream = stream;
  2757. return xobj;
  2758. }
  2759. }
  2760. },
  2761. /**
  2762. * Returns the standard Appearance
  2763. * @returns {AcroForm.FormXObject}
  2764. */
  2765. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  2766. var stream = "";
  2767. // Set Helvetica to Standard Font (size: auto)
  2768. // Color: Black
  2769. stream += "/Helv 0 Tf 0 g";
  2770. return stream;
  2771. }
  2772. };
  2773. AcroForm.Appearance.internal = {
  2774. Bezier_C: 0.551915024494,
  2775. calculateCross: function calculateCross(formObject) {
  2776. var min = function min(x, y) {
  2777. return x > y ? y : x;
  2778. };
  2779. var width = AcroForm.Appearance.internal.getWidth(formObject);
  2780. var height = AcroForm.Appearance.internal.getHeight(formObject);
  2781. var a = min(width, height);
  2782. var crossSize = a;
  2783. var borderPadding = 2; // The Padding in px
  2784. var cross = {
  2785. x1: { // upperLeft
  2786. x: (width - a) / 2,
  2787. y: (height - a) / 2 + a },
  2788. x2: { // lowerRight
  2789. x: (width - a) / 2 + a,
  2790. y: (height - a) / 2 //borderPadding
  2791. },
  2792. x3: { // lowerLeft
  2793. x: (width - a) / 2,
  2794. y: (height - a) / 2 //borderPadding
  2795. },
  2796. x4: { // upperRight
  2797. x: (width - a) / 2 + a,
  2798. y: (height - a) / 2 + a }
  2799. };
  2800. return cross;
  2801. }
  2802. };
  2803. AcroForm.Appearance.internal.getWidth = function (formObject) {
  2804. return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
  2805. };
  2806. AcroForm.Appearance.internal.getHeight = function (formObject) {
  2807. return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
  2808. };
  2809. // ##########################
  2810. //### For inheritance:
  2811. AcroForm.internal.inherit = function (child, parent) {
  2812. var ObjectCreate = Object.create || function (o) {
  2813. var F = function F() {};
  2814. F.prototype = o;
  2815. return new F();
  2816. };
  2817. child.prototype = Object.create(parent.prototype);
  2818. child.prototype.constructor = child;
  2819. };
  2820. // ### Handy Functions:
  2821. AcroForm.internal.arrayToPdfArray = function (array) {
  2822. if (Array.isArray(array)) {
  2823. var content = ' [';
  2824. for (var i in array) {
  2825. var element = array[i].toString();
  2826. content += element;
  2827. content += i < array.length - 1 ? ' ' : '';
  2828. }
  2829. content += ']';
  2830. return content;
  2831. }
  2832. };
  2833. AcroForm.internal.toPdfString = function (string) {
  2834. string = string || "";
  2835. // put Bracket at the Beginning of the String
  2836. if (string.indexOf('(') !== 0) {
  2837. string = '(' + string;
  2838. }
  2839. if (string.substring(string.length - 1) != ')') {
  2840. string += '(';
  2841. }
  2842. return string;
  2843. };
  2844. // ##########################
  2845. // Classes
  2846. // ##########################
  2847. AcroForm.PDFObject = function () {
  2848. // The Object ID in the PDF Object Model
  2849. // todo
  2850. var _objId;
  2851. Object.defineProperty(this, 'objId', {
  2852. get: function get() {
  2853. if (!_objId) {
  2854. if (this.internal) {
  2855. _objId = this.internal.newObjectDeferred();
  2856. } else if (jsPDF.API.acroformPlugin.internal) {
  2857. // todo - find better option, that doesn't rely on a Global Static var
  2858. _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
  2859. }
  2860. }
  2861. if (!_objId) {
  2862. console.log("Couldn't create Object ID");
  2863. }
  2864. return _objId;
  2865. },
  2866. configurable: false
  2867. });
  2868. };
  2869. AcroForm.PDFObject.prototype.toString = function () {
  2870. return this.objId + " 0 R";
  2871. };
  2872. AcroForm.PDFObject.prototype.getString = function () {
  2873. var res = this.objId + " 0 obj\n<<";
  2874. var content = this.getContent();
  2875. res += content + ">>\n";
  2876. if (this.stream) {
  2877. res += "stream\n";
  2878. res += this.stream;
  2879. res += "endstream\n";
  2880. }
  2881. res += "endobj\n";
  2882. return res;
  2883. };
  2884. AcroForm.PDFObject.prototype.getContent = function () {
  2885. /**
  2886. * Prints out all enumerable Variables from the Object
  2887. * @param fieldObject
  2888. * @returns {string}
  2889. */
  2890. var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
  2891. var content = '';
  2892. var keys = Object.keys(fieldObject).filter(function (key) {
  2893. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  2894. });
  2895. for (var i in keys) {
  2896. var key = keys[i];
  2897. var value = fieldObject[key];
  2898. /*if (key == 'Rect' && value) {
  2899. value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
  2900. }*/
  2901. if (value) {
  2902. if (Array.isArray(value)) {
  2903. content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
  2904. } else if (value instanceof AcroForm.PDFObject) {
  2905. // In case it is a reference to another PDFObject, take the referennce number
  2906. content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
  2907. } else {
  2908. content += '/' + key + ' ' + value + '\n';
  2909. }
  2910. }
  2911. }
  2912. return content;
  2913. };
  2914. var object = "";
  2915. object += createContentFromFieldObject(this);
  2916. return object;
  2917. };
  2918. AcroForm.FormXObject = function () {
  2919. AcroForm.PDFObject.call(this);
  2920. this.Type = "/XObject";
  2921. this.Subtype = "/Form";
  2922. this.FormType = 1;
  2923. this.BBox;
  2924. this.Matrix;
  2925. this.Resources = "2 0 R";
  2926. this.PieceInfo;
  2927. var _stream;
  2928. Object.defineProperty(this, 'Length', {
  2929. enumerable: true,
  2930. get: function get() {
  2931. return _stream !== undefined ? _stream.length : 0;
  2932. }
  2933. });
  2934. Object.defineProperty(this, 'stream', {
  2935. enumerable: false,
  2936. set: function set(val) {
  2937. _stream = val;
  2938. },
  2939. get: function get() {
  2940. if (_stream) {
  2941. return _stream;
  2942. } else {
  2943. return null;
  2944. }
  2945. }
  2946. });
  2947. };
  2948. AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
  2949. AcroForm.AcroFormDictionary = function () {
  2950. AcroForm.PDFObject.call(this);
  2951. var _Kids = [];
  2952. Object.defineProperty(this, 'Kids', {
  2953. enumerable: false,
  2954. configurable: true,
  2955. get: function get() {
  2956. if (_Kids.length > 0) {
  2957. return _Kids;
  2958. } else {
  2959. return;
  2960. }
  2961. }
  2962. });
  2963. Object.defineProperty(this, 'Fields', {
  2964. enumerable: true,
  2965. configurable: true,
  2966. get: function get() {
  2967. return _Kids;
  2968. }
  2969. });
  2970. // Default Appearance
  2971. this.DA;
  2972. };
  2973. AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
  2974. // ##### The Objects, the User can Create:
  2975. // The Field Object contains the Variables, that every Field needs
  2976. // Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
  2977. AcroForm.Field = function () {
  2978. 'use strict';
  2979. AcroForm.PDFObject.call(this);
  2980. var _Rect;
  2981. Object.defineProperty(this, 'Rect', {
  2982. enumerable: true,
  2983. configurable: false,
  2984. get: function get() {
  2985. if (!_Rect) {
  2986. return;
  2987. }
  2988. var tmp = _Rect;
  2989. //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
  2990. return tmp;
  2991. },
  2992. set: function set(val) {
  2993. _Rect = val;
  2994. }
  2995. });
  2996. var _FT = "";
  2997. Object.defineProperty(this, 'FT', {
  2998. enumerable: true,
  2999. set: function set(val) {
  3000. _FT = val;
  3001. },
  3002. get: function get() {
  3003. return _FT;
  3004. }
  3005. });
  3006. /**
  3007. * The Partial name of the Field Object.
  3008. * It has to be unique.
  3009. */
  3010. var _T;
  3011. Object.defineProperty(this, 'T', {
  3012. enumerable: true,
  3013. configurable: false,
  3014. set: function set(val) {
  3015. _T = val;
  3016. },
  3017. get: function get() {
  3018. if (!_T || _T.length < 1) {
  3019. if (this instanceof AcroForm.ChildClass) {
  3020. // In case of a Child from a Radio´Group, you don't need a FieldName!!!
  3021. return;
  3022. }
  3023. return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
  3024. }
  3025. if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
  3026. return _T;
  3027. }
  3028. return "(" + _T + ")";
  3029. }
  3030. });
  3031. var _DA;
  3032. // Defines the default appearance (Needed for variable Text)
  3033. Object.defineProperty(this, 'DA', {
  3034. enumerable: true,
  3035. get: function get() {
  3036. if (!_DA) {
  3037. return;
  3038. }
  3039. return '(' + _DA + ')';
  3040. },
  3041. set: function set(val) {
  3042. _DA = val;
  3043. }
  3044. });
  3045. var _DV;
  3046. // Defines the default value
  3047. Object.defineProperty(this, 'DV', {
  3048. enumerable: true,
  3049. configurable: true,
  3050. get: function get() {
  3051. if (!_DV) {
  3052. return;
  3053. }
  3054. return _DV;
  3055. },
  3056. set: function set(val) {
  3057. _DV = val;
  3058. }
  3059. });
  3060. //this.Type = "/Annot";
  3061. //this.Subtype = "/Widget";
  3062. Object.defineProperty(this, 'Type', {
  3063. enumerable: true,
  3064. get: function get() {
  3065. return this.hasAnnotation ? "/Annot" : null;
  3066. }
  3067. });
  3068. Object.defineProperty(this, 'Subtype', {
  3069. enumerable: true,
  3070. get: function get() {
  3071. return this.hasAnnotation ? "/Widget" : null;
  3072. }
  3073. });
  3074. /**
  3075. *
  3076. * @type {Array}
  3077. */
  3078. this.BG;
  3079. Object.defineProperty(this, 'hasAnnotation', {
  3080. enumerable: false,
  3081. get: function get() {
  3082. if (this.Rect || this.BC || this.BG) {
  3083. return true;
  3084. }
  3085. return false;
  3086. }
  3087. });
  3088. Object.defineProperty(this, 'hasAppearanceStream', {
  3089. enumerable: false,
  3090. configurable: true,
  3091. writable: true
  3092. });
  3093. Object.defineProperty(this, 'page', {
  3094. enumerable: false,
  3095. configurable: true,
  3096. writable: true
  3097. });
  3098. };
  3099. AcroForm.Field.FieldNum = 0;
  3100. AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
  3101. AcroForm.ChoiceField = function () {
  3102. AcroForm.Field.call(this);
  3103. // Field Type = Choice Field
  3104. this.FT = "/Ch";
  3105. // options
  3106. this.Opt = [];
  3107. this.V = '()';
  3108. // Top Index
  3109. this.TI = 0;
  3110. /**
  3111. * Defines, whether the
  3112. * @type {boolean}
  3113. */
  3114. this.combo = false;
  3115. /**
  3116. * Defines, whether the Choice Field is an Edit Field.
  3117. * An Edit Field is automatically an Combo Field.
  3118. */
  3119. Object.defineProperty(this, 'edit', {
  3120. enumerable: true,
  3121. set: function set(val) {
  3122. if (val == true) {
  3123. this._edit = true;
  3124. // ComboBox has to be true
  3125. this.combo = true;
  3126. } else {
  3127. this._edit = false;
  3128. }
  3129. },
  3130. get: function get() {
  3131. if (!this._edit) {
  3132. return false;
  3133. }
  3134. return this._edit;
  3135. },
  3136. configurable: false
  3137. });
  3138. this.hasAppearanceStream = true;
  3139. Object.defineProperty(this, 'V', {
  3140. get: function get() {
  3141. AcroForm.internal.toPdfString();
  3142. }
  3143. });
  3144. };
  3145. AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
  3146. window["ChoiceField"] = AcroForm.ChoiceField;
  3147. AcroForm.ListBox = function () {
  3148. AcroForm.ChoiceField.call(this);
  3149. //var combo = true;
  3150. };
  3151. AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
  3152. window["ListBox"] = AcroForm.ListBox;
  3153. AcroForm.ComboBox = function () {
  3154. AcroForm.ListBox.call(this);
  3155. this.combo = true;
  3156. };
  3157. AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
  3158. window["ComboBox"] = AcroForm.ComboBox;
  3159. AcroForm.EditBox = function () {
  3160. AcroForm.ComboBox.call(this);
  3161. this.edit = true;
  3162. };
  3163. AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
  3164. window["EditBox"] = AcroForm.EditBox;
  3165. AcroForm.Button = function () {
  3166. AcroForm.Field.call(this);
  3167. this.FT = "/Btn";
  3168. //this.hasAnnotation = true;
  3169. };
  3170. AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
  3171. window["Button"] = AcroForm.Button;
  3172. AcroForm.PushButton = function () {
  3173. AcroForm.Button.call(this);
  3174. this.pushbutton = true;
  3175. };
  3176. AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
  3177. window["PushButton"] = AcroForm.PushButton;
  3178. AcroForm.RadioButton = function () {
  3179. AcroForm.Button.call(this);
  3180. this.radio = true;
  3181. var _Kids = [];
  3182. Object.defineProperty(this, 'Kids', {
  3183. enumerable: true,
  3184. get: function get() {
  3185. if (_Kids.length > 0) {
  3186. return _Kids;
  3187. }
  3188. }
  3189. });
  3190. Object.defineProperty(this, '__Kids', {
  3191. get: function get() {
  3192. return _Kids;
  3193. }
  3194. });
  3195. var _noToggleToOff;
  3196. Object.defineProperty(this, 'noToggleToOff', {
  3197. enumerable: false,
  3198. get: function get() {
  3199. return _noToggleToOff;
  3200. },
  3201. set: function set(val) {
  3202. _noToggleToOff = val;
  3203. }
  3204. });
  3205. //this.hasAnnotation = false;
  3206. };
  3207. AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
  3208. window["RadioButton"] = AcroForm.RadioButton;
  3209. /*
  3210. * The Child classs of a RadioButton (the radioGroup)
  3211. * -> The single Buttons
  3212. */
  3213. AcroForm.ChildClass = function (parent, name) {
  3214. AcroForm.Field.call(this);
  3215. this.Parent = parent;
  3216. // todo: set AppearanceType as variable that can be set from the outside...
  3217. this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
  3218. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  3219. // Set Print in the Annot Flag
  3220. this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
  3221. // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
  3222. this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
  3223. // Default Appearance is Off
  3224. this.AS = "/Off"; // + name;
  3225. this._Name = name;
  3226. };
  3227. AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
  3228. AcroForm.RadioButton.prototype.setAppearance = function (appearance) {
  3229. if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
  3230. console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  3231. return;
  3232. }
  3233. for (var i in this.__Kids) {
  3234. var child = this.__Kids[i];
  3235. child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
  3236. child.MK = appearance.createMK();
  3237. }
  3238. };
  3239. AcroForm.RadioButton.prototype.createOption = function (name) {
  3240. var parent = this;
  3241. var kidCount = this.__Kids.length;
  3242. // Create new Child for RadioGroup
  3243. var child = new AcroForm.ChildClass(parent, name);
  3244. // Add to Parent
  3245. this.__Kids.push(child);
  3246. jsPDF.API.addField(child);
  3247. return child;
  3248. };
  3249. AcroForm.CheckBox = function () {
  3250. Button.call(this);
  3251. this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
  3252. this.MK = AcroForm.Appearance.CheckBox.createMK();
  3253. this.AS = "/On";
  3254. this.V = "/On";
  3255. };
  3256. AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
  3257. window["CheckBox"] = AcroForm.CheckBox;
  3258. AcroForm.TextField = function () {
  3259. AcroForm.Field.call(this);
  3260. this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
  3261. this.F = 4;
  3262. var _V;
  3263. Object.defineProperty(this, 'V', {
  3264. get: function get() {
  3265. if (_V) {
  3266. return "(" + _V + ")";
  3267. } else {
  3268. return _V;
  3269. }
  3270. },
  3271. enumerable: true,
  3272. set: function set(val) {
  3273. _V = val;
  3274. }
  3275. });
  3276. var _DV;
  3277. Object.defineProperty(this, 'DV', {
  3278. get: function get() {
  3279. if (_DV) {
  3280. return "(" + _DV + ")";
  3281. } else {
  3282. return _DV;
  3283. }
  3284. },
  3285. enumerable: true,
  3286. set: function set(val) {
  3287. _DV = val;
  3288. }
  3289. });
  3290. var _multiline = false;
  3291. Object.defineProperty(this, 'multiline', {
  3292. enumerable: false,
  3293. get: function get() {
  3294. return _multiline;
  3295. },
  3296. set: function set(val) {
  3297. _multiline = val;
  3298. }
  3299. });
  3300. //this.multiline = false;
  3301. //this.password = false;
  3302. /**
  3303. * For PDF 1.4
  3304. * @type {boolean}
  3305. */
  3306. //this.fileSelect = false;
  3307. /**
  3308. * For PDF 1.4
  3309. * @type {boolean}
  3310. */
  3311. //this.doNotSpellCheck = false;
  3312. /**
  3313. * For PDF 1.4
  3314. * @type {boolean}
  3315. */
  3316. //this.doNotScroll = false;
  3317. var _MaxLen = false;
  3318. Object.defineProperty(this, 'MaxLen', {
  3319. enumerable: true,
  3320. get: function get() {
  3321. return _MaxLen;
  3322. },
  3323. set: function set(val) {
  3324. _MaxLen = val;
  3325. }
  3326. });
  3327. Object.defineProperty(this, 'hasAppearanceStream', {
  3328. enumerable: false,
  3329. get: function get() {
  3330. return this.V || this.DV;
  3331. }
  3332. });
  3333. };
  3334. AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
  3335. window["TextField"] = AcroForm.TextField;
  3336. AcroForm.PasswordField = function () {
  3337. TextField.call(this);
  3338. Object.defineProperty(this, 'password', {
  3339. value: true,
  3340. enumerable: false,
  3341. configurable: false,
  3342. writable: false
  3343. });
  3344. };
  3345. AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
  3346. window["PasswordField"] = AcroForm.PasswordField;
  3347. // ############ internal functions
  3348. /*
  3349. * small workaround for calculating the TextMetric approximately
  3350. * @param text
  3351. * @param fontsize
  3352. * @returns {TextMetrics} (Has Height and Width)
  3353. */
  3354. AcroForm.internal.calculateFontSpace = function (text, fontsize, fonttype) {
  3355. var fonttype = fonttype || "helvetica";
  3356. //re-use canvas object for speed improvements
  3357. var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
  3358. var context = canvas.getContext('2d');
  3359. context.save();
  3360. var newFont = fontsize + " " + fonttype;
  3361. context.font = newFont;
  3362. var res = context.measureText(text);
  3363. context.fontcolor = 'black';
  3364. // Calculate height:
  3365. var context = canvas.getContext('2d');
  3366. res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
  3367. context.restore();
  3368. var width = res.width;
  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 color = "0 g\n";
  3388. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3389. var lineSpacing = 2;
  3390. var borderPadding = 2;
  3391. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  3392. height = height < 0 ? -height : height;
  3393. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  3394. width = width < 0 ? -width : width;
  3395. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3396. if (i + 1 < textSplit.length) {
  3397. var tmp = lastLine + " " + textSplit[i + 1];
  3398. var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
  3399. var FieldWidth = width - 2 * borderPadding;
  3400. return TextWidth <= FieldWidth;
  3401. } else {
  3402. return false;
  3403. }
  3404. };
  3405. fontSize++;
  3406. FontSize: while (true) {
  3407. var text = "";
  3408. fontSize--;
  3409. var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
  3410. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3411. startY += lineSpacing;
  3412. var startX = -borderPadding;
  3413. var lastX = startX,
  3414. lastY = startY;
  3415. var firstWordInLine = 0,
  3416. lastWordInLine = 0;
  3417. var lastLength = 0;
  3418. var y = 0;
  3419. if (fontSize == 0) {
  3420. // In case, the Text doesn't fit at all
  3421. fontSize = 12;
  3422. text = "(...) Tj\n";
  3423. text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
  3424. break;
  3425. }
  3426. lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
  3427. var lastLine = "";
  3428. var lineCount = 0;
  3429. Line: for (var i in textSplit) {
  3430. lastLine += textSplit[i] + " ";
  3431. // Remove last blank
  3432. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3433. var key = parseInt(i);
  3434. lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
  3435. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3436. var isLastWord = i >= textSplit.length - 1;
  3437. if (nextLineIsSmaller && !isLastWord) {
  3438. lastLine += " ";
  3439. continue; // Line
  3440. } else if (!nextLineIsSmaller && !isLastWord) {
  3441. if (!formObject.multiline) {
  3442. continue FontSize;
  3443. } else {
  3444. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3445. // If the Text is higher than the FieldObject
  3446. continue FontSize;
  3447. }
  3448. lastWordInLine = key;
  3449. // go on
  3450. }
  3451. } else if (isLastWord) {
  3452. lastWordInLine = key;
  3453. } else {
  3454. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3455. // If the Text is higher than the FieldObject
  3456. continue FontSize;
  3457. }
  3458. }
  3459. var line = '';
  3460. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3461. line += textSplit[x] + ' ';
  3462. }
  3463. // Remove last blank
  3464. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
  3465. //lastLength -= blankSpace.width;
  3466. lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
  3467. // Calculate startX
  3468. switch (formObject.Q) {
  3469. case 2:
  3470. // Right justified
  3471. startX = width - lastLength - borderPadding;
  3472. break;
  3473. case 1:
  3474. // Q = 1 := Text-Alignment: Center
  3475. startX = (width - lastLength) / 2;
  3476. break;
  3477. case 0:
  3478. default:
  3479. startX = borderPadding;
  3480. break;
  3481. }
  3482. text += startX + ' ' + lastY + ' Td\n';
  3483. text += '(' + line + ') Tj\n';
  3484. // reset X in PDF
  3485. text += -startX + ' 0 Td\n';
  3486. // After a Line, adjust y position
  3487. lastY = -(fontSize + lineSpacing);
  3488. lastX = startX;
  3489. // Reset for next iteration step
  3490. lastLength = 0;
  3491. firstWordInLine = lastWordInLine + 1;
  3492. lineCount++;
  3493. lastLine = "";
  3494. continue Line;
  3495. }
  3496. break;
  3497. }
  3498. returnValue.text = text;
  3499. returnValue.fontSize = fontSize;
  3500. return returnValue;
  3501. };
  3502. AcroForm.internal.calculateAppearanceStream = function (formObject) {
  3503. if (formObject.appearanceStreamContent) {
  3504. // If appearanceStream is already set, use it
  3505. return formObject.appearanceStreamContent;
  3506. }
  3507. if (!formObject.V && !formObject.DV) {
  3508. return;
  3509. }
  3510. // else calculate it
  3511. var stream = '';
  3512. var text = formObject.V || formObject.DV;
  3513. var calcRes = AcroForm.internal.calculateX(formObject, text);
  3514. stream += '/Tx BMC\n' + 'q\n' +
  3515. //color + '\n' +
  3516. '/F1 ' + calcRes.fontSize + ' Tf\n' +
  3517. // Text Matrix
  3518. '1 0 0 1 0 0 Tm\n';
  3519. // Begin Text
  3520. stream += 'BT\n';
  3521. stream += calcRes.text;
  3522. // End Text
  3523. stream += 'ET\n';
  3524. stream += 'Q\n' + 'EMC\n';
  3525. var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
  3526. appearanceStreamContent.stream = stream;
  3527. var appearance = {
  3528. N: {
  3529. 'Normal': appearanceStreamContent
  3530. }
  3531. };
  3532. return appearanceStreamContent;
  3533. };
  3534. /*
  3535. * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
  3536. * @param x
  3537. * @param y
  3538. * @param w
  3539. * @param h
  3540. * @returns {*[]}
  3541. */
  3542. AcroForm.internal.calculateCoordinates = function (x, y, w, h) {
  3543. var coordinates = {};
  3544. if (this.internal) {
  3545. var mmtopx = function mmtopx(x) {
  3546. return x * this.internal.scaleFactor;
  3547. };
  3548. if (Array.isArray(x)) {
  3549. x[0] = AcroForm.scale(x[0]);
  3550. x[1] = AcroForm.scale(x[1]);
  3551. x[2] = AcroForm.scale(x[2]);
  3552. x[3] = AcroForm.scale(x[3]);
  3553. coordinates.lowerLeft_X = x[0] || 0;
  3554. coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
  3555. coordinates.upperRight_X = x[0] + x[2] || 0;
  3556. coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
  3557. } else {
  3558. x = AcroForm.scale(x);
  3559. y = AcroForm.scale(y);
  3560. w = AcroForm.scale(w);
  3561. h = AcroForm.scale(h);
  3562. coordinates.lowerLeft_X = x || 0;
  3563. coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
  3564. coordinates.upperRight_X = x + w || 0;
  3565. coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
  3566. }
  3567. } else {
  3568. // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
  3569. if (Array.isArray(x)) {
  3570. coordinates.lowerLeft_X = x[0] || 0;
  3571. coordinates.lowerLeft_Y = x[1] || 0;
  3572. coordinates.upperRight_X = x[0] + x[2] || 0;
  3573. coordinates.upperRight_Y = x[1] + x[3] || 0;
  3574. } else {
  3575. coordinates.lowerLeft_X = x || 0;
  3576. coordinates.lowerLeft_Y = y || 0;
  3577. coordinates.upperRight_X = x + w || 0;
  3578. coordinates.upperRight_Y = y + h || 0;
  3579. }
  3580. }
  3581. return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
  3582. };
  3583. AcroForm.internal.calculateColor = function (r, g, b) {
  3584. var color = new Array(3);
  3585. color.r = r | 0;
  3586. color.g = g | 0;
  3587. color.b = b | 0;
  3588. return color;
  3589. };
  3590. AcroForm.internal.getBitPosition = function (variable, position) {
  3591. variable = variable || 0;
  3592. var bitMask = 1;
  3593. bitMask = bitMask << position - 1;
  3594. return variable | bitMask;
  3595. };
  3596. AcroForm.internal.setBitPosition = function (variable, position, value) {
  3597. variable = variable || 0;
  3598. value = value || 1;
  3599. var bitMask = 1;
  3600. bitMask = bitMask << position - 1;
  3601. if (value == 1) {
  3602. // Set the Bit to 1
  3603. var variable = variable | bitMask;
  3604. } else {
  3605. // Set the Bit to 0
  3606. var variable = variable & ~bitMask;
  3607. }
  3608. return variable;
  3609. };
  3610. /**
  3611. * jsPDF addHTML PlugIn
  3612. * Copyright (c) 2014 Diego Casorran
  3613. *
  3614. * Licensed under the MIT License.
  3615. * http://opensource.org/licenses/mit-license
  3616. */
  3617. (function (jsPDFAPI) {
  3618. 'use strict';
  3619. /**
  3620. * Renders an HTML element to canvas object which added to the PDF
  3621. *
  3622. * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
  3623. * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
  3624. *
  3625. * @returns {jsPDF}
  3626. * @name addHTML
  3627. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  3628. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  3629. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  3630. * @param options {Object} Additional options, check the code below.
  3631. * @param callback {Function} to call when the rendering has finished.
  3632. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  3633. * case the image is positioned at 0x0 covering the whole PDF document
  3634. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  3635. * @deprecated This is being replace with a vector-supporting API. See
  3636. * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
  3637. */
  3638. jsPDFAPI.addHTML = function (element, x, y, options, callback) {
  3639. 'use strict';
  3640. 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');
  3641. if (typeof x !== 'number') {
  3642. options = x;
  3643. callback = y;
  3644. }
  3645. if (typeof options === 'function') {
  3646. callback = options;
  3647. options = null;
  3648. }
  3649. var I = this.internal,
  3650. K = I.scaleFactor,
  3651. W = I.pageSize.width,
  3652. H = I.pageSize.height;
  3653. options = options || {};
  3654. options.onrendered = function (obj) {
  3655. x = parseInt(x) || 0;
  3656. y = parseInt(y) || 0;
  3657. var dim = options.dim || {};
  3658. var h = dim.h || 0;
  3659. var w = dim.w || Math.min(W, obj.width / K) - x;
  3660. var format = 'JPEG';
  3661. if (options.format) format = options.format;
  3662. if (obj.height > H && options.pagesplit) {
  3663. var crop = function () {
  3664. var cy = 0;
  3665. while (1) {
  3666. var canvas = document.createElement('canvas');
  3667. canvas.width = Math.min(W * K, obj.width);
  3668. canvas.height = Math.min(H * K, obj.height - cy);
  3669. var ctx = canvas.getContext('2d');
  3670. ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
  3671. var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
  3672. this.addImage.apply(this, args);
  3673. cy += canvas.height;
  3674. if (cy >= obj.height) break;
  3675. this.addPage();
  3676. }
  3677. callback(w, cy, null, args);
  3678. }.bind(this);
  3679. if (obj.nodeName === 'CANVAS') {
  3680. var img = new Image();
  3681. img.onload = crop;
  3682. img.src = obj.toDataURL("image/png");
  3683. obj = img;
  3684. } else {
  3685. crop();
  3686. }
  3687. } else {
  3688. var alias = Math.random().toString(35);
  3689. var args = [obj, x, y, w, h, format, alias, 'SLOW'];
  3690. this.addImage.apply(this, args);
  3691. callback(w, h, alias, args);
  3692. }
  3693. }.bind(this);
  3694. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  3695. return html2canvas(element, options);
  3696. }
  3697. if (typeof rasterizeHTML !== 'undefined') {
  3698. var meth = 'drawDocument';
  3699. if (typeof element === 'string') {
  3700. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  3701. }
  3702. options.width = options.width || W * K;
  3703. return rasterizeHTML[meth](element, void 0, options).then(function (r) {
  3704. options.onrendered(r.image);
  3705. }, function (e) {
  3706. callback(null, e);
  3707. });
  3708. }
  3709. return null;
  3710. };
  3711. })(jsPDF.API);
  3712. /** @preserve
  3713. * jsPDF addImage plugin
  3714. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  3715. * 2013 Chris Dowling, https://github.com/gingerchris
  3716. * 2013 Trinh Ho, https://github.com/ineedfat
  3717. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  3718. * 2013 Norah Smith, https://github.com/burnburnrocket
  3719. * 2014 Diego Casorran, https://github.com/diegocr
  3720. * 2014 James Robb, https://github.com/jamesbrobb
  3721. *
  3722. *
  3723. */
  3724. (function (jsPDFAPI) {
  3725. 'use strict';
  3726. var namespace = 'addImage_',
  3727. supported_image_types = ['jpeg', 'jpg', 'png'];
  3728. // Image functionality ported from pdf.js
  3729. var putImage = function putImage(img) {
  3730. var objectNumber = this.internal.newObject(),
  3731. out = this.internal.write,
  3732. putStream = this.internal.putStream;
  3733. img['n'] = objectNumber;
  3734. out('<</Type /XObject');
  3735. out('/Subtype /Image');
  3736. out('/Width ' + img['w']);
  3737. out('/Height ' + img['h']);
  3738. if (img['cs'] === this.color_spaces.INDEXED) {
  3739. out('/ColorSpace [/Indexed /DeviceRGB '
  3740. // if an indexed png defines more than one colour with transparency, we've created a smask
  3741. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
  3742. } else {
  3743. out('/ColorSpace /' + img['cs']);
  3744. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  3745. out('/Decode [1 0 1 0 1 0 1 0]');
  3746. }
  3747. }
  3748. out('/BitsPerComponent ' + img['bpc']);
  3749. if ('f' in img) {
  3750. out('/Filter /' + img['f']);
  3751. }
  3752. if ('dp' in img) {
  3753. out('/DecodeParms <<' + img['dp'] + '>>');
  3754. }
  3755. if ('trns' in img && img['trns'].constructor == Array) {
  3756. var trns = '',
  3757. i = 0,
  3758. len = img['trns'].length;
  3759. for (; i < len; i++) {
  3760. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  3761. }out('/Mask [' + trns + ']');
  3762. }
  3763. if ('smask' in img) {
  3764. out('/SMask ' + (objectNumber + 1) + ' 0 R');
  3765. }
  3766. out('/Length ' + img['data'].length + '>>');
  3767. putStream(img['data']);
  3768. out('endobj');
  3769. // Soft mask
  3770. if ('smask' in img) {
  3771. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  3772. var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
  3773. if ('f' in img) smask.f = img['f'];
  3774. putImage.call(this, smask);
  3775. }
  3776. //Palette
  3777. if (img['cs'] === this.color_spaces.INDEXED) {
  3778. this.internal.newObject();
  3779. //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  3780. //putStream(zlib.compress(img['pal']));
  3781. out('<< /Length ' + img['pal'].length + '>>');
  3782. putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
  3783. out('endobj');
  3784. }
  3785. },
  3786. putResourcesCallback = function putResourcesCallback() {
  3787. var images = this.internal.collections[namespace + 'images'];
  3788. for (var i in images) {
  3789. putImage.call(this, images[i]);
  3790. }
  3791. },
  3792. putXObjectsDictCallback = function putXObjectsDictCallback() {
  3793. var images = this.internal.collections[namespace + 'images'],
  3794. out = this.internal.write,
  3795. image;
  3796. for (var i in images) {
  3797. image = images[i];
  3798. out('/I' + image['i'], image['n'], '0', 'R');
  3799. }
  3800. },
  3801. checkCompressValue = function checkCompressValue(value) {
  3802. if (value && typeof value === 'string') value = value.toUpperCase();
  3803. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  3804. },
  3805. getImages = function getImages() {
  3806. var images = this.internal.collections[namespace + 'images'];
  3807. //first run, so initialise stuff
  3808. if (!images) {
  3809. this.internal.collections[namespace + 'images'] = images = {};
  3810. this.internal.events.subscribe('putResources', putResourcesCallback);
  3811. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  3812. }
  3813. return images;
  3814. },
  3815. getImageIndex = function getImageIndex(images) {
  3816. var imageIndex = 0;
  3817. if (images) {
  3818. // this is NOT the first time this method is ran on this instance of jsPDF object.
  3819. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  3820. var i = 0;
  3821. for (var e in o) {
  3822. if (o.hasOwnProperty(e)) {
  3823. i++;
  3824. }
  3825. }
  3826. return i;
  3827. }(images);
  3828. }
  3829. return imageIndex;
  3830. },
  3831. notDefined = function notDefined(value) {
  3832. return typeof value === 'undefined' || value === null;
  3833. },
  3834. generateAliasFromData = function generateAliasFromData(data) {
  3835. return typeof data === 'string' && jsPDFAPI.sHashCode(data);
  3836. },
  3837. doesNotSupportImageType = function doesNotSupportImageType(type) {
  3838. return supported_image_types.indexOf(type) === -1;
  3839. },
  3840. processMethodNotEnabled = function processMethodNotEnabled(type) {
  3841. return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
  3842. },
  3843. isDOMElement = function isDOMElement(object) {
  3844. return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
  3845. },
  3846. createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
  3847. //if element is an image which uses data url definition, just return the dataurl
  3848. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  3849. var src = '' + element.getAttribute('src');
  3850. if (!angle && src.indexOf('data:image/') === 0) return src;
  3851. // only if the user doesn't care about a format
  3852. if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
  3853. }
  3854. if (element.nodeName === 'CANVAS') {
  3855. var canvas = element;
  3856. } else {
  3857. var canvas = document.createElement('canvas');
  3858. canvas.width = element.clientWidth || element.width;
  3859. canvas.height = element.clientHeight || element.height;
  3860. var ctx = canvas.getContext('2d');
  3861. if (!ctx) {
  3862. throw 'addImage requires canvas to be supported by browser.';
  3863. }
  3864. if (angle) {
  3865. var x,
  3866. y,
  3867. b,
  3868. c,
  3869. s,
  3870. w,
  3871. h,
  3872. to_radians = Math.PI / 180,
  3873. angleInRadians;
  3874. if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
  3875. x = angle.x;
  3876. y = angle.y;
  3877. b = angle.bg;
  3878. angle = angle.angle;
  3879. }
  3880. angleInRadians = angle * to_radians;
  3881. c = Math.abs(Math.cos(angleInRadians));
  3882. s = Math.abs(Math.sin(angleInRadians));
  3883. w = canvas.width;
  3884. h = canvas.height;
  3885. canvas.width = h * s + w * c;
  3886. canvas.height = h * c + w * s;
  3887. if (isNaN(x)) x = canvas.width / 2;
  3888. if (isNaN(y)) y = canvas.height / 2;
  3889. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3890. ctx.fillStyle = b || 'white';
  3891. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3892. ctx.save();
  3893. ctx.translate(x, y);
  3894. ctx.rotate(angleInRadians);
  3895. ctx.drawImage(element, -(w / 2), -(h / 2));
  3896. ctx.rotate(-angleInRadians);
  3897. ctx.translate(-x, -y);
  3898. ctx.restore();
  3899. } else {
  3900. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  3901. }
  3902. }
  3903. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  3904. },
  3905. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  3906. var cached_info;
  3907. if (images) {
  3908. for (var e in images) {
  3909. if (alias === images[e].alias) {
  3910. cached_info = images[e];
  3911. break;
  3912. }
  3913. }
  3914. }
  3915. return cached_info;
  3916. },
  3917. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  3918. if (!w && !h) {
  3919. w = -96;
  3920. h = -96;
  3921. }
  3922. if (w < 0) {
  3923. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  3924. }
  3925. if (h < 0) {
  3926. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  3927. }
  3928. if (w === 0) {
  3929. w = h * info['w'] / info['h'];
  3930. }
  3931. if (h === 0) {
  3932. h = w * info['h'] / info['w'];
  3933. }
  3934. return [w, h];
  3935. },
  3936. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
  3937. var dims = determineWidthAndHeight.call(this, w, h, info),
  3938. coord = this.internal.getCoordinateString,
  3939. vcoord = this.internal.getVerticalCoordinateString;
  3940. w = dims[0];
  3941. h = dims[1];
  3942. images[index] = info;
  3943. this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
  3944. , coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
  3945. };
  3946. /**
  3947. * COLOR SPACES
  3948. */
  3949. jsPDFAPI.color_spaces = {
  3950. DEVICE_RGB: 'DeviceRGB',
  3951. DEVICE_GRAY: 'DeviceGray',
  3952. DEVICE_CMYK: 'DeviceCMYK',
  3953. CAL_GREY: 'CalGray',
  3954. CAL_RGB: 'CalRGB',
  3955. LAB: 'Lab',
  3956. ICC_BASED: 'ICCBased',
  3957. INDEXED: 'Indexed',
  3958. PATTERN: 'Pattern',
  3959. SEPARATION: 'Separation',
  3960. DEVICE_N: 'DeviceN'
  3961. };
  3962. /**
  3963. * DECODE METHODS
  3964. */
  3965. jsPDFAPI.decode = {
  3966. DCT_DECODE: 'DCTDecode',
  3967. FLATE_DECODE: 'FlateDecode',
  3968. LZW_DECODE: 'LZWDecode',
  3969. JPX_DECODE: 'JPXDecode',
  3970. JBIG2_DECODE: 'JBIG2Decode',
  3971. ASCII85_DECODE: 'ASCII85Decode',
  3972. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  3973. RUN_LENGTH_DECODE: 'RunLengthDecode',
  3974. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  3975. };
  3976. /**
  3977. * IMAGE COMPRESSION TYPES
  3978. */
  3979. jsPDFAPI.image_compression = {
  3980. NONE: 'NONE',
  3981. FAST: 'FAST',
  3982. MEDIUM: 'MEDIUM',
  3983. SLOW: 'SLOW'
  3984. };
  3985. jsPDFAPI.sHashCode = function (str) {
  3986. return Array.prototype.reduce && str.split("").reduce(function (a, b) {
  3987. a = (a << 5) - a + b.charCodeAt(0);return a & a;
  3988. }, 0);
  3989. };
  3990. jsPDFAPI.isString = function (object) {
  3991. return typeof object === 'string';
  3992. };
  3993. /**
  3994. * Strips out and returns info from a valid base64 data URI
  3995. * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  3996. * @returns an Array containing the following
  3997. * [0] the complete data URI
  3998. * [1] <MIME-type>
  3999. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  4000. * [4] <data>
  4001. */
  4002. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  4003. return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI)
  4004. );
  4005. };
  4006. /**
  4007. * Check to see if ArrayBuffer is supported
  4008. */
  4009. jsPDFAPI.supportsArrayBuffer = function () {
  4010. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  4011. };
  4012. /**
  4013. * Tests supplied object to determine if ArrayBuffer
  4014. * @param {Object[object]}
  4015. */
  4016. jsPDFAPI.isArrayBuffer = function (object) {
  4017. if (!this.supportsArrayBuffer()) return false;
  4018. return object instanceof ArrayBuffer;
  4019. };
  4020. /**
  4021. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  4022. * @param {Object[object]}
  4023. */
  4024. jsPDFAPI.isArrayBufferView = function (object) {
  4025. if (!this.supportsArrayBuffer()) return false;
  4026. if (typeof Uint32Array === 'undefined') return false;
  4027. 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;
  4028. };
  4029. /**
  4030. * Exactly what it says on the tin
  4031. */
  4032. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  4033. /*
  4034. * not sure how efficient this will be will bigger files. Is there a native method?
  4035. */
  4036. var len = binary_string.length;
  4037. var bytes = new Uint8Array(len);
  4038. for (var i = 0; i < len; i++) {
  4039. bytes[i] = binary_string.charCodeAt(i);
  4040. }
  4041. return bytes;
  4042. };
  4043. /**
  4044. * @see this discussion
  4045. * http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers
  4046. *
  4047. * As stated, i imagine the method below is highly inefficent for large files.
  4048. *
  4049. * Also of note from Mozilla,
  4050. *
  4051. * "However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats)."
  4052. *
  4053. * https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView
  4054. *
  4055. * Although i'm strugglig to see how StringView solves this issue? Doesn't appear to be a direct method for conversion?
  4056. *
  4057. * Async method using Blob and FileReader could be best, but i'm not sure how to fit it into the flow?
  4058. */
  4059. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  4060. /*if('TextDecoder' in window){
  4061. var decoder = new TextDecoder('ascii');
  4062. return decoder.decode(buffer);
  4063. }*/
  4064. if (this.isArrayBuffer(buffer)) buffer = new Uint8Array(buffer);
  4065. var binary_string = '';
  4066. var len = buffer.byteLength;
  4067. for (var i = 0; i < len; i++) {
  4068. binary_string += String.fromCharCode(buffer[i]);
  4069. }
  4070. return binary_string;
  4071. /*
  4072. * Another solution is the method below - convert array buffer straight to base64 and then use atob
  4073. */
  4074. //return atob(this.arrayBufferToBase64(buffer));
  4075. };
  4076. /**
  4077. * Converts an ArrayBuffer directly to base64
  4078. *
  4079. * Taken from here
  4080. *
  4081. * http://jsperf.com/encoding-xhr-image-data/31
  4082. *
  4083. * Need to test if this is a better solution for larger files
  4084. *
  4085. */
  4086. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  4087. var base64 = '';
  4088. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  4089. var bytes = new Uint8Array(arrayBuffer);
  4090. var byteLength = bytes.byteLength;
  4091. var byteRemainder = byteLength % 3;
  4092. var mainLength = byteLength - byteRemainder;
  4093. var a, b, c, d;
  4094. var chunk;
  4095. // Main loop deals with bytes in chunks of 3
  4096. for (var i = 0; i < mainLength; i = i + 3) {
  4097. // Combine the three bytes into a single integer
  4098. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
  4099. // Use bitmasks to extract 6-bit segments from the triplet
  4100. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  4101. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  4102. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  4103. d = chunk & 63; // 63 = 2^6 - 1
  4104. // Convert the raw binary segments to the appropriate ASCII encoding
  4105. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  4106. }
  4107. // Deal with the remaining bytes and padding
  4108. if (byteRemainder == 1) {
  4109. chunk = bytes[mainLength];
  4110. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  4111. // Set the 4 least significant bits to zero
  4112. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  4113. base64 += encodings[a] + encodings[b] + '==';
  4114. } else if (byteRemainder == 2) {
  4115. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  4116. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  4117. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  4118. // Set the 2 least significant bits to zero
  4119. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  4120. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  4121. }
  4122. return base64;
  4123. };
  4124. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  4125. var info = {
  4126. alias: alias,
  4127. w: wd,
  4128. h: ht,
  4129. cs: cs,
  4130. bpc: bpc,
  4131. i: imageIndex,
  4132. data: data
  4133. // n: objectNumber will be added by putImage code
  4134. };
  4135. if (f) info.f = f;
  4136. if (dp) info.dp = dp;
  4137. if (trns) info.trns = trns;
  4138. if (pal) info.pal = pal;
  4139. if (smask) info.smask = smask;
  4140. if (p) info.p = p; // predictor parameter for PNG compression
  4141. return info;
  4142. };
  4143. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  4144. 'use strict';
  4145. if (typeof format !== 'string') {
  4146. var tmp = h;
  4147. h = w;
  4148. w = y;
  4149. y = x;
  4150. x = format;
  4151. format = tmp;
  4152. }
  4153. if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  4154. var options = imageData;
  4155. imageData = options.imageData;
  4156. format = options.format || format;
  4157. x = options.x || x || 0;
  4158. y = options.y || y || 0;
  4159. w = options.w || w;
  4160. h = options.h || h;
  4161. alias = options.alias || alias;
  4162. compression = options.compression || compression;
  4163. rotation = options.rotation || options.angle || rotation;
  4164. }
  4165. if (isNaN(x) || isNaN(y)) {
  4166. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  4167. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  4168. }
  4169. var images = getImages.call(this),
  4170. info;
  4171. if (!(info = checkImagesForAlias(imageData, images))) {
  4172. var dataAsBinaryString;
  4173. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
  4174. if (notDefined(alias)) alias = generateAliasFromData(imageData);
  4175. if (!(info = checkImagesForAlias(alias, images))) {
  4176. if (this.isString(imageData)) {
  4177. var base64Info = this.extractInfoFromBase64DataURI(imageData);
  4178. if (base64Info) {
  4179. format = base64Info[2];
  4180. imageData = atob(base64Info[3]); //convert to binary string
  4181. } else {
  4182. if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
  4183. }
  4184. }
  4185. format = (format || 'JPEG').toLowerCase();
  4186. if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
  4187. if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
  4188. /**
  4189. * need to test if it's more efficient to convert all binary strings
  4190. * to TypedArray - or should we just leave and process as string?
  4191. */
  4192. if (this.supportsArrayBuffer()) {
  4193. // no need to convert if imageData is already uint8array
  4194. if (!(imageData instanceof Uint8Array)) {
  4195. dataAsBinaryString = imageData;
  4196. imageData = this.binaryStringToUint8Array(imageData);
  4197. }
  4198. }
  4199. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  4200. if (!info) throw new Error('An unkwown error occurred whilst processing the image');
  4201. }
  4202. }
  4203. writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
  4204. return this;
  4205. };
  4206. /**
  4207. * JPEG SUPPORT
  4208. **/
  4209. //takes a string imgData containing the raw bytes of
  4210. //a jpeg image and returns [width, height]
  4211. //Algorithm from: http://www.64lines.com/jpeg-width-height
  4212. var getJpegSize = function getJpegSize(imgData) {
  4213. 'use strict';
  4214. var width, height, numcomponents;
  4215. // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  4216. 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) {
  4217. throw new Error('getJpegSize requires a binary string jpeg file');
  4218. }
  4219. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  4220. var i = 4,
  4221. len = imgData.length;
  4222. while (i < len) {
  4223. i += blockLength;
  4224. if (imgData.charCodeAt(i) !== 0xff) {
  4225. throw new Error('getJpegSize could not find the size of the image');
  4226. }
  4227. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  4228. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  4229. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  4230. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  4231. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  4232. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  4233. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  4234. imgData.charCodeAt(i + 1) === 0xc7) {
  4235. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  4236. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  4237. numcomponents = imgData.charCodeAt(i + 9);
  4238. return [width, height, numcomponents];
  4239. } else {
  4240. i += 2;
  4241. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  4242. }
  4243. }
  4244. },
  4245. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  4246. var hdr = data[0] << 8 | data[1];
  4247. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  4248. var len = data.length,
  4249. block = (data[4] << 8) + data[5],
  4250. pos = 4,
  4251. bytes,
  4252. width,
  4253. height,
  4254. numcomponents;
  4255. while (pos < len) {
  4256. pos += block;
  4257. bytes = readBytes(data, pos);
  4258. block = (bytes[2] << 8) + bytes[3];
  4259. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  4260. bytes = readBytes(data, pos + 5);
  4261. width = (bytes[2] << 8) + bytes[3];
  4262. height = (bytes[0] << 8) + bytes[1];
  4263. numcomponents = bytes[4];
  4264. return { width: width, height: height, numcomponents: numcomponents };
  4265. }
  4266. pos += 2;
  4267. }
  4268. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  4269. },
  4270. readBytes = function readBytes(data, offset) {
  4271. return data.subarray(offset, offset + 5);
  4272. };
  4273. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString) {
  4274. 'use strict';
  4275. var colorSpace = this.color_spaces.DEVICE_RGB,
  4276. filter = this.decode.DCT_DECODE,
  4277. bpc = 8,
  4278. dims;
  4279. if (this.isString(data)) {
  4280. dims = getJpegSize(data);
  4281. return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4282. }
  4283. if (this.isArrayBuffer(data)) data = new Uint8Array(data);
  4284. if (this.isArrayBufferView(data)) {
  4285. dims = getJpegSizeFromBytes(data);
  4286. // if we already have a stored binary string rep use that
  4287. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  4288. return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4289. }
  4290. return null;
  4291. };
  4292. jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
  4293. return this.processJPEG.apply(this, arguments);
  4294. };
  4295. })(jsPDF.API);
  4296. /**
  4297. * jsPDF Annotations PlugIn
  4298. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4299. *
  4300. * Licensed under the MIT License.
  4301. * http://opensource.org/licenses/mit-license
  4302. */
  4303. /**
  4304. * There are many types of annotations in a PDF document. Annotations are placed
  4305. * on a page at a particular location. They are not 'attached' to an object.
  4306. * <br />
  4307. * This plugin current supports <br />
  4308. * <li> Goto Page (set pageNumber and top in options)
  4309. * <li> Goto Name (set name and top in options)
  4310. * <li> Goto URL (set url in options)
  4311. * <p>
  4312. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  4313. * (set magFactor in options). XYZ is the default.
  4314. * </p>
  4315. * <p>
  4316. * Links, Text, Popup, and FreeText are supported.
  4317. * </p>
  4318. * <p>
  4319. * Options In PDF spec Not Implemented Yet
  4320. * <li> link border
  4321. * <li> named target
  4322. * <li> page coordinates
  4323. * <li> destination page scaling and layout
  4324. * <li> actions other than URL and GotoPage
  4325. * <li> background / hover actions
  4326. * </p>
  4327. */
  4328. /*
  4329. Destination Magnification Factors
  4330. See PDF 1.3 Page 386 for meanings and options
  4331. [supported]
  4332. XYZ (options; left top zoom)
  4333. Fit (no options)
  4334. FitH (options: top)
  4335. FitV (options: left)
  4336. [not supported]
  4337. FitR
  4338. FitB
  4339. FitBH
  4340. FitBV
  4341. */
  4342. (function (jsPDFAPI) {
  4343. 'use strict';
  4344. var annotationPlugin = {
  4345. /**
  4346. * An array of arrays, indexed by <em>pageNumber</em>.
  4347. */
  4348. annotations: [],
  4349. f2: function f2(number) {
  4350. return number.toFixed(2);
  4351. },
  4352. notEmpty: function notEmpty(obj) {
  4353. if (typeof obj != 'undefined') {
  4354. if (obj != '') {
  4355. return true;
  4356. }
  4357. }
  4358. }
  4359. };
  4360. jsPDF.API.annotationPlugin = annotationPlugin;
  4361. jsPDF.API.events.push(['addPage', function (info) {
  4362. this.annotationPlugin.annotations[info.pageNumber] = [];
  4363. }]);
  4364. jsPDFAPI.events.push(['putPage', function (info) {
  4365. //TODO store annotations in pageContext so reorder/remove will not affect them.
  4366. var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
  4367. var found = false;
  4368. for (var a = 0; a < pageAnnos.length && !found; a++) {
  4369. var anno = pageAnnos[a];
  4370. switch (anno.type) {
  4371. case 'link':
  4372. if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
  4373. found = true;
  4374. break;
  4375. }
  4376. case 'reference':
  4377. case 'text':
  4378. case 'freetext':
  4379. found = true;
  4380. break;
  4381. }
  4382. }
  4383. if (found == false) {
  4384. return;
  4385. }
  4386. this.internal.write("/Annots [");
  4387. var f2 = this.annotationPlugin.f2;
  4388. var k = this.internal.scaleFactor;
  4389. var pageHeight = this.internal.pageSize.height;
  4390. var pageInfo = this.internal.getPageInfo(info.pageNumber);
  4391. for (var a = 0; a < pageAnnos.length; a++) {
  4392. var anno = pageAnnos[a];
  4393. switch (anno.type) {
  4394. case 'reference':
  4395. // References to Widget Anotations (for AcroForm Fields)
  4396. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  4397. break;
  4398. case 'text':
  4399. // Create a an object for both the text and the popup
  4400. var objText = this.internal.newAdditionalObject();
  4401. var objPopup = this.internal.newAdditionalObject();
  4402. var title = anno.title || 'Note';
  4403. 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) + "] ";
  4404. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4405. line += ' /Popup ' + objPopup.objId + " 0 R";
  4406. line += ' /P ' + pageInfo.objId + " 0 R";
  4407. line += ' /T (' + title + ') >>';
  4408. objText.content = line;
  4409. var parent = objText.objId + ' 0 R';
  4410. var popoff = 30;
  4411. 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) + "] ";
  4412. //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) + "] ";
  4413. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  4414. if (anno.open) {
  4415. line += ' /Open true';
  4416. }
  4417. line += ' >>';
  4418. objPopup.content = line;
  4419. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  4420. break;
  4421. case 'freetext':
  4422. 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) + "] ";
  4423. var color = anno.color || '#000000';
  4424. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4425. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  4426. line += ' /Border [0 0 0]';
  4427. line += ' >>';
  4428. this.internal.write(line);
  4429. break;
  4430. case 'link':
  4431. if (anno.options.name) {
  4432. var loc = this.annotations._nameMap[anno.options.name];
  4433. anno.options.pageNumber = loc.page;
  4434. anno.options.top = loc.y;
  4435. } else {
  4436. if (!anno.options.top) {
  4437. anno.options.top = 0;
  4438. }
  4439. }
  4440. //var pageHeight = this.internal.pageSize.height * this.internal.scaleFactor;
  4441. 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) + "] ";
  4442. var line = '';
  4443. if (anno.options.url) {
  4444. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  4445. } else if (anno.options.pageNumber) {
  4446. // first page is 0
  4447. var info = this.internal.getPageInfo(anno.options.pageNumber);
  4448. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  4449. anno.options.magFactor = anno.options.magFactor || "XYZ";
  4450. switch (anno.options.magFactor) {
  4451. case 'Fit':
  4452. line += ' /Fit]';
  4453. break;
  4454. case 'FitH':
  4455. //anno.options.top = anno.options.top || f2(pageHeight * k);
  4456. line += ' /FitH ' + anno.options.top + ']';
  4457. break;
  4458. case 'FitV':
  4459. anno.options.left = anno.options.left || 0;
  4460. line += ' /FitV ' + anno.options.left + ']';
  4461. break;
  4462. case 'XYZ':
  4463. default:
  4464. var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
  4465. anno.options.left = anno.options.left || 0;
  4466. // 0 or null zoom will not change zoom factor
  4467. if (typeof anno.options.zoom === 'undefined') {
  4468. anno.options.zoom = 0;
  4469. }
  4470. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  4471. break;
  4472. }
  4473. } else {
  4474. // TODO error - should not be here
  4475. }
  4476. if (line != '') {
  4477. line += " >>";
  4478. this.internal.write(line);
  4479. }
  4480. break;
  4481. }
  4482. }
  4483. this.internal.write("]");
  4484. }]);
  4485. jsPDFAPI.createAnnotation = function (options) {
  4486. switch (options.type) {
  4487. case 'link':
  4488. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  4489. break;
  4490. case 'text':
  4491. case 'freetext':
  4492. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
  4493. break;
  4494. }
  4495. };
  4496. /**
  4497. * valid options
  4498. * <li> pageNumber or url [required]
  4499. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4500. */
  4501. jsPDFAPI.link = function (x, y, w, h, options) {
  4502. 'use strict';
  4503. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4504. x: x,
  4505. y: y,
  4506. w: w,
  4507. h: h,
  4508. options: options,
  4509. type: 'link'
  4510. });
  4511. };
  4512. /**
  4513. * valid options
  4514. * <li> pageNumber or url [required]
  4515. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4516. */
  4517. jsPDFAPI.link = function (x, y, w, h, options) {
  4518. 'use strict';
  4519. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4520. x: x,
  4521. y: y,
  4522. w: w,
  4523. h: h,
  4524. options: options,
  4525. type: 'link'
  4526. });
  4527. };
  4528. /**
  4529. * Currently only supports single line text.
  4530. * Returns the width of the text/link
  4531. */
  4532. jsPDFAPI.textWithLink = function (text, x, y, options) {
  4533. 'use strict';
  4534. var width = this.getTextWidth(text);
  4535. var height = this.internal.getLineHeight();
  4536. this.text(text, x, y);
  4537. //TODO We really need the text baseline height to do this correctly.
  4538. // Or ability to draw text on top, bottom, center, or baseline.
  4539. y += height * .2;
  4540. this.link(x, y - height, width, height, options);
  4541. return width;
  4542. };
  4543. //TODO move into external library
  4544. jsPDFAPI.getTextWidth = function (text) {
  4545. 'use strict';
  4546. var fontSize = this.internal.getFontSize();
  4547. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  4548. return txtWidth;
  4549. };
  4550. //TODO move into external library
  4551. jsPDFAPI.getLineHeight = function () {
  4552. return this.internal.getLineHeight();
  4553. };
  4554. return this;
  4555. })(jsPDF.API);
  4556. /**
  4557. * jsPDF Autoprint Plugin
  4558. *
  4559. * Licensed under the MIT License.
  4560. * http://opensource.org/licenses/mit-license
  4561. */
  4562. /**
  4563. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  4564. * Reader.
  4565. *
  4566. * @returns {jsPDF}
  4567. * @name autoPrint
  4568. * @example
  4569. * var doc = new jsPDF()
  4570. * doc.text(10, 10, 'This is a test')
  4571. * doc.autoPrint()
  4572. * doc.save('autoprint.pdf')
  4573. */
  4574. (function (jsPDFAPI) {
  4575. 'use strict';
  4576. jsPDFAPI.autoPrint = function () {
  4577. 'use strict';
  4578. var refAutoPrintTag;
  4579. this.internal.events.subscribe('postPutResources', function () {
  4580. refAutoPrintTag = this.internal.newObject();
  4581. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  4582. });
  4583. this.internal.events.subscribe("putCatalog", function () {
  4584. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  4585. });
  4586. return this;
  4587. };
  4588. })(jsPDF.API);
  4589. /**
  4590. * jsPDF Canvas PlugIn
  4591. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4592. *
  4593. * Licensed under the MIT License.
  4594. * http://opensource.org/licenses/mit-license
  4595. */
  4596. /**
  4597. * This plugin mimics the HTML5 Canvas
  4598. *
  4599. * The goal is to provide a way for current canvas users to print directly to a PDF.
  4600. */
  4601. (function (jsPDFAPI) {
  4602. 'use strict';
  4603. jsPDFAPI.events.push(['initialized', function () {
  4604. this.canvas.pdf = this;
  4605. }]);
  4606. jsPDFAPI.canvas = {
  4607. getContext: function getContext(name) {
  4608. this.pdf.context2d._canvas = this;
  4609. return this.pdf.context2d;
  4610. },
  4611. style: {}
  4612. };
  4613. Object.defineProperty(jsPDFAPI.canvas, 'width', {
  4614. get: function get() {
  4615. return this._width;
  4616. },
  4617. set: function set(value) {
  4618. this._width = value;
  4619. this.getContext('2d').pageWrapX = value + 1;
  4620. }
  4621. });
  4622. Object.defineProperty(jsPDFAPI.canvas, 'height', {
  4623. get: function get() {
  4624. return this._height;
  4625. },
  4626. set: function set(value) {
  4627. this._height = value;
  4628. this.getContext('2d').pageWrapY = value + 1;
  4629. }
  4630. });
  4631. return this;
  4632. })(jsPDF.API);
  4633. /** ====================================================================
  4634. * jsPDF Cell plugin
  4635. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  4636. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  4637. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  4638. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  4639. * 2014 James Hall, james@parall.ax
  4640. * 2014 Diego Casorran, https://github.com/diegocr
  4641. *
  4642. *
  4643. * ====================================================================
  4644. */
  4645. (function (jsPDFAPI) {
  4646. 'use strict';
  4647. /*jslint browser:true */
  4648. /*global document: false, jsPDF */
  4649. var fontName,
  4650. fontSize,
  4651. fontStyle,
  4652. padding = 3,
  4653. margin = 13,
  4654. headerFunction,
  4655. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
  4656. pages = 1,
  4657. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  4658. lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
  4659. },
  4660. getLastCellPosition = function getLastCellPosition() {
  4661. return lastCellPos;
  4662. },
  4663. NO_MARGINS = { left: 0, top: 0, bottom: 0 };
  4664. jsPDFAPI.setHeaderFunction = function (func) {
  4665. headerFunction = func;
  4666. };
  4667. jsPDFAPI.getTextDimensions = function (txt) {
  4668. fontName = this.internal.getFont().fontName;
  4669. fontSize = this.table_font_size || this.internal.getFontSize();
  4670. fontStyle = this.internal.getFont().fontStyle;
  4671. // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
  4672. var px2pt = 0.264583 * 72 / 25.4,
  4673. dimensions,
  4674. text;
  4675. text = document.createElement('font');
  4676. text.id = "jsPDFCell";
  4677. try {
  4678. text.style.fontStyle = fontStyle;
  4679. } catch (e) {
  4680. text.style.fontWeight = fontStyle;
  4681. }
  4682. text.style.fontName = fontName;
  4683. text.style.fontSize = fontSize + 'pt';
  4684. try {
  4685. text.textContent = txt;
  4686. } catch (e) {
  4687. text.innerText = txt;
  4688. }
  4689. document.body.appendChild(text);
  4690. dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
  4691. document.body.removeChild(text);
  4692. return dimensions;
  4693. };
  4694. jsPDFAPI.cellAddPage = function () {
  4695. var margins = this.margins || NO_MARGINS;
  4696. this.addPage();
  4697. setLastCellPosition(margins.left, margins.top, undefined, undefined);
  4698. //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  4699. pages += 1;
  4700. };
  4701. jsPDFAPI.cellInitialize = function () {
  4702. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
  4703. pages = 1;
  4704. };
  4705. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  4706. var curCell = getLastCellPosition();
  4707. var pgAdded = false;
  4708. // If this is not the first cell, we must change its position
  4709. if (curCell.ln !== undefined) {
  4710. if (curCell.ln === ln) {
  4711. //Same line
  4712. x = curCell.x + curCell.w;
  4713. y = curCell.y;
  4714. } else {
  4715. //New line
  4716. var margins = this.margins || NO_MARGINS;
  4717. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
  4718. this.cellAddPage();
  4719. pgAdded = true;
  4720. if (this.printHeaders && this.tableHeaderRow) {
  4721. this.printHeaderRow(ln, true);
  4722. }
  4723. }
  4724. //We ignore the passed y: the lines may have different heights
  4725. y = getLastCellPosition().y + getLastCellPosition().h;
  4726. if (pgAdded) y = margin + 10;
  4727. }
  4728. }
  4729. if (txt[0] !== undefined) {
  4730. if (this.printingHeaderRow) {
  4731. this.rect(x, y, w, h, 'FD');
  4732. } else {
  4733. this.rect(x, y, w, h);
  4734. }
  4735. if (align === 'right') {
  4736. if (!(txt instanceof Array)) {
  4737. txt = [txt];
  4738. }
  4739. for (var i = 0; i < txt.length; i++) {
  4740. var currentLine = txt[i];
  4741. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
  4742. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  4743. }
  4744. } else {
  4745. this.text(txt, x + padding, y + this.internal.getLineHeight());
  4746. }
  4747. }
  4748. setLastCellPosition(x, y, w, h, ln);
  4749. return this;
  4750. };
  4751. /**
  4752. * Return the maximum value from an array
  4753. * @param array
  4754. * @param comparisonFn
  4755. * @returns {*}
  4756. */
  4757. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  4758. var max = array[0],
  4759. i,
  4760. ln,
  4761. item;
  4762. for (i = 0, ln = array.length; i < ln; i += 1) {
  4763. item = array[i];
  4764. if (comparisonFn) {
  4765. if (comparisonFn(max, item) === -1) {
  4766. max = item;
  4767. }
  4768. } else {
  4769. if (item > max) {
  4770. max = item;
  4771. }
  4772. }
  4773. }
  4774. return max;
  4775. };
  4776. /**
  4777. * Create a table from a set of data.
  4778. * @param {Integer} [x] : left-position for top-left corner of table
  4779. * @param {Integer} [y] top-position for top-left corner of table
  4780. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  4781. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  4782. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  4783. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  4784. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  4785. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  4786. */
  4787. jsPDFAPI.table = function (x, y, data, headers, config) {
  4788. if (!data) {
  4789. throw 'No data for PDF table';
  4790. }
  4791. var headerNames = [],
  4792. headerPrompts = [],
  4793. header,
  4794. i,
  4795. ln,
  4796. cln,
  4797. columnMatrix = {},
  4798. columnWidths = {},
  4799. columnData,
  4800. column,
  4801. columnMinWidths = [],
  4802. j,
  4803. tableHeaderConfigs = [],
  4804. model,
  4805. jln,
  4806. func,
  4807. //set up defaults. If a value is provided in config, defaults will be overwritten:
  4808. autoSize = false,
  4809. printHeaders = true,
  4810. fontSize = 12,
  4811. margins = NO_MARGINS;
  4812. margins.width = this.internal.pageSize.width;
  4813. if (config) {
  4814. //override config defaults if the user has specified non-default behavior:
  4815. if (config.autoSize === true) {
  4816. autoSize = true;
  4817. }
  4818. if (config.printHeaders === false) {
  4819. printHeaders = false;
  4820. }
  4821. if (config.fontSize) {
  4822. fontSize = config.fontSize;
  4823. }
  4824. if (config.css && typeof config.css['font-size'] !== "undefined") {
  4825. fontSize = config.css['font-size'] * 16;
  4826. }
  4827. if (config.margins) {
  4828. margins = config.margins;
  4829. }
  4830. }
  4831. /**
  4832. * @property {Number} lnMod
  4833. * Keep track of the current line number modifier used when creating cells
  4834. */
  4835. this.lnMod = 0;
  4836. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
  4837. this.printHeaders = printHeaders;
  4838. this.margins = margins;
  4839. this.setFontSize(fontSize);
  4840. this.table_font_size = fontSize;
  4841. // Set header values
  4842. if (headers === undefined || headers === null) {
  4843. // No headers defined so we derive from data
  4844. headerNames = Object.keys(data[0]);
  4845. } else if (headers[0] && typeof headers[0] !== 'string') {
  4846. var px2pt = 0.264583 * 72 / 25.4;
  4847. // Split header configs into names and prompts
  4848. for (i = 0, ln = headers.length; i < ln; i += 1) {
  4849. header = headers[i];
  4850. headerNames.push(header.name);
  4851. headerPrompts.push(header.prompt);
  4852. columnWidths[header.name] = header.width * px2pt;
  4853. }
  4854. } else {
  4855. headerNames = headers;
  4856. }
  4857. if (autoSize) {
  4858. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  4859. func = function func(rec) {
  4860. return rec[header];
  4861. };
  4862. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4863. header = headerNames[i];
  4864. columnMatrix[header] = data.map(func);
  4865. // get header width
  4866. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
  4867. column = columnMatrix[header];
  4868. // get cell widths
  4869. for (j = 0, cln = column.length; j < cln; j += 1) {
  4870. columnData = column[j];
  4871. columnMinWidths.push(this.getTextDimensions(columnData).w);
  4872. }
  4873. // get final column width
  4874. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
  4875. //have to reset
  4876. columnMinWidths = [];
  4877. }
  4878. }
  4879. // -- Construct the table
  4880. if (printHeaders) {
  4881. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
  4882. // Construct the header row
  4883. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4884. header = headerNames[i];
  4885. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  4886. }
  4887. // Store the table header config
  4888. this.setTableHeaderRow(tableHeaderConfigs);
  4889. // Print the header for the start of the table
  4890. this.printHeaderRow(1, false);
  4891. }
  4892. // Construct the data rows
  4893. for (i = 0, ln = data.length; i < ln; i += 1) {
  4894. var lineHeight;
  4895. model = data[i];
  4896. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  4897. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  4898. header = headerNames[j];
  4899. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  4900. }
  4901. }
  4902. this.lastCellPos = lastCellPos;
  4903. this.table_x = x;
  4904. this.table_y = y;
  4905. return this;
  4906. };
  4907. /**
  4908. * Calculate the height for containing the highest column
  4909. * @param {String[]} headerNames is the header, used as keys to the data
  4910. * @param {Integer[]} columnWidths is size of each column
  4911. * @param {Object[]} model is the line of data we want to calculate the height of
  4912. */
  4913. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  4914. var header,
  4915. lineHeight = 0;
  4916. for (var j = 0; j < headerNames.length; j++) {
  4917. header = headerNames[j];
  4918. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  4919. var h = this.internal.getLineHeight() * model[header].length + padding;
  4920. if (h > lineHeight) lineHeight = h;
  4921. }
  4922. return lineHeight;
  4923. };
  4924. /**
  4925. * Store the config for outputting a table header
  4926. * @param {Object[]} config
  4927. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  4928. * except the ln parameter is excluded
  4929. */
  4930. jsPDFAPI.setTableHeaderRow = function (config) {
  4931. this.tableHeaderRow = config;
  4932. };
  4933. /**
  4934. * Output the store header row
  4935. * @param lineNumber The line number to output the header at
  4936. */
  4937. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  4938. if (!this.tableHeaderRow) {
  4939. throw 'Property tableHeaderRow does not exist.';
  4940. }
  4941. var tableHeaderCell, tmpArray, i, ln;
  4942. this.printingHeaderRow = true;
  4943. if (headerFunction !== undefined) {
  4944. var position = headerFunction(this, pages);
  4945. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  4946. }
  4947. this.setFontStyle('bold');
  4948. var tempHeaderConf = [];
  4949. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  4950. this.setFillColor(200, 200, 200);
  4951. tableHeaderCell = this.tableHeaderRow[i];
  4952. if (new_page) {
  4953. this.margins.top = margin;
  4954. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  4955. tempHeaderConf.push(tableHeaderCell);
  4956. }
  4957. tmpArray = [].concat(tableHeaderCell);
  4958. this.cell.apply(this, tmpArray.concat(lineNumber));
  4959. }
  4960. if (tempHeaderConf.length > 0) {
  4961. this.setTableHeaderRow(tempHeaderConf);
  4962. }
  4963. this.setFontStyle('normal');
  4964. this.printingHeaderRow = false;
  4965. };
  4966. })(jsPDF.API);
  4967. /**
  4968. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4969. *
  4970. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  4971. */
  4972. /**
  4973. * This plugin mimics the HTML5 Canvas's context2d.
  4974. *
  4975. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  4976. */
  4977. /**
  4978. * TODO implement stroke opacity (refactor from fill() method )
  4979. * TODO transform angle and radii parameters
  4980. */
  4981. /**
  4982. * require('jspdf.js'); require('lib/css_colors.js');
  4983. */
  4984. (function (jsPDFAPI) {
  4985. 'use strict';
  4986. jsPDFAPI.events.push(['initialized', function () {
  4987. this.context2d.pdf = this;
  4988. this.context2d.internal.pdf = this;
  4989. this.context2d.ctx = new context();
  4990. this.context2d.ctxStack = [];
  4991. this.context2d.path = [];
  4992. }]);
  4993. jsPDFAPI.context2d = {
  4994. pageWrapXEnabled: false,
  4995. pageWrapYEnabled: false,
  4996. pageWrapX: 9999999,
  4997. pageWrapY: 9999999,
  4998. ctx: new context(),
  4999. f2: function f2(number) {
  5000. return number.toFixed(2);
  5001. },
  5002. fillRect: function fillRect(x, y, w, h) {
  5003. if (this._isFillTransparent()) {
  5004. return;
  5005. }
  5006. x = this._wrapX(x);
  5007. y = this._wrapY(y);
  5008. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5009. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5010. },
  5011. strokeRect: function strokeRect(x, y, w, h) {
  5012. if (this._isStrokeTransparent()) {
  5013. return;
  5014. }
  5015. x = this._wrapX(x);
  5016. y = this._wrapY(y);
  5017. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5018. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
  5019. },
  5020. /**
  5021. * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  5022. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  5023. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  5024. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  5025. * @param x
  5026. * @param y
  5027. * @param w
  5028. * @param h
  5029. */
  5030. clearRect: function clearRect(x, y, w, h) {
  5031. if (this.ctx.ignoreClearRect) {
  5032. return;
  5033. }
  5034. x = this._wrapX(x);
  5035. y = this._wrapY(y);
  5036. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5037. this.save();
  5038. this.setFillStyle('#ffffff');
  5039. //TODO This is hack to fill with white.
  5040. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5041. this.restore();
  5042. },
  5043. save: function save() {
  5044. this.ctx._fontSize = this.pdf.internal.getFontSize();
  5045. var ctx = new context();
  5046. ctx.copy(this.ctx);
  5047. this.ctxStack.push(this.ctx);
  5048. this.ctx = ctx;
  5049. },
  5050. restore: function restore() {
  5051. this.ctx = this.ctxStack.pop();
  5052. this.setFillStyle(this.ctx.fillStyle);
  5053. this.setStrokeStyle(this.ctx.strokeStyle);
  5054. this.setFont(this.ctx.font);
  5055. this.pdf.setFontSize(this.ctx._fontSize);
  5056. this.setLineCap(this.ctx.lineCap);
  5057. this.setLineWidth(this.ctx.lineWidth);
  5058. this.setLineJoin(this.ctx.lineJoin);
  5059. },
  5060. rect: function rect(x, y, w, h) {
  5061. this.moveTo(x, y);
  5062. this.lineTo(x + w, y);
  5063. this.lineTo(x + w, y + h);
  5064. this.lineTo(x, y + h);
  5065. this.lineTo(x, y); //TODO not needed
  5066. this.closePath();
  5067. },
  5068. beginPath: function beginPath() {
  5069. this.path = [];
  5070. },
  5071. closePath: function closePath() {
  5072. this.path.push({
  5073. type: 'close'
  5074. });
  5075. },
  5076. _getRgba: function _getRgba(style) {
  5077. // get the decimal values of r, g, and b;
  5078. var rgba = {};
  5079. if (this.internal.rxTransparent.test(style)) {
  5080. rgba.r = 0;
  5081. rgba.g = 0;
  5082. rgba.b = 0;
  5083. rgba.a = 0;
  5084. } else {
  5085. var m = this.internal.rxRgb.exec(style);
  5086. if (m != null) {
  5087. rgba.r = parseInt(m[1]);
  5088. rgba.g = parseInt(m[2]);
  5089. rgba.b = parseInt(m[3]);
  5090. rgba.a = 1;
  5091. } else {
  5092. m = this.internal.rxRgba.exec(style);
  5093. if (m != null) {
  5094. rgba.r = parseInt(m[1]);
  5095. rgba.g = parseInt(m[2]);
  5096. rgba.b = parseInt(m[3]);
  5097. rgba.a = parseFloat(m[4]);
  5098. } else {
  5099. rgba.a = 1;
  5100. if (style.charAt(0) != '#') {
  5101. style = CssColors.colorNameToHex(style);
  5102. if (!style) {
  5103. style = '#000000';
  5104. }
  5105. } else {}
  5106. if (style.length === 4) {
  5107. rgba.r = style.substring(1, 2);
  5108. rgba.r += r;
  5109. rgba.g = style.substring(2, 3);
  5110. rgba.g += g;
  5111. rgba.b = style.substring(3, 4);
  5112. rgba.b += b;
  5113. } else {
  5114. rgba.r = style.substring(1, 3);
  5115. rgba.g = style.substring(3, 5);
  5116. rgba.b = style.substring(5, 7);
  5117. }
  5118. rgba.r = parseInt(rgba.r, 16);
  5119. rgba.g = parseInt(rgba.g, 16);
  5120. rgba.b = parseInt(rgba.b, 16);
  5121. }
  5122. }
  5123. }
  5124. rgba.style = style;
  5125. return rgba;
  5126. },
  5127. setFillStyle: function setFillStyle(style) {
  5128. // get the decimal values of r, g, and b;
  5129. var r, g, b, a;
  5130. if (this.internal.rxTransparent.test(style)) {
  5131. r = 0;
  5132. g = 0;
  5133. b = 0;
  5134. a = 0;
  5135. } else {
  5136. var m = this.internal.rxRgb.exec(style);
  5137. if (m != null) {
  5138. r = parseInt(m[1]);
  5139. g = parseInt(m[2]);
  5140. b = parseInt(m[3]);
  5141. a = 1;
  5142. } else {
  5143. m = this.internal.rxRgba.exec(style);
  5144. if (m != null) {
  5145. r = parseInt(m[1]);
  5146. g = parseInt(m[2]);
  5147. b = parseInt(m[3]);
  5148. a = parseFloat(m[4]);
  5149. } else {
  5150. a = 1;
  5151. if (style.charAt(0) != '#') {
  5152. style = CssColors.colorNameToHex(style);
  5153. if (!style) {
  5154. style = '#000000';
  5155. }
  5156. } else {}
  5157. if (style.length === 4) {
  5158. r = style.substring(1, 2);
  5159. r += r;
  5160. g = style.substring(2, 3);
  5161. g += g;
  5162. b = style.substring(3, 4);
  5163. b += b;
  5164. } else {
  5165. r = style.substring(1, 3);
  5166. g = style.substring(3, 5);
  5167. b = style.substring(5, 7);
  5168. }
  5169. r = parseInt(r, 16);
  5170. g = parseInt(g, 16);
  5171. b = parseInt(b, 16);
  5172. }
  5173. }
  5174. }
  5175. this.ctx.fillStyle = style;
  5176. this.ctx._isFillTransparent = a == 0;
  5177. this.ctx._fillOpacity = a;
  5178. this.pdf.setFillColor(r, g, b, {
  5179. a: a
  5180. });
  5181. this.pdf.setTextColor(r, g, b, {
  5182. a: a
  5183. });
  5184. },
  5185. setStrokeStyle: function setStrokeStyle(style) {
  5186. var rgba = this._getRgba(style);
  5187. this.ctx.strokeStyle = rgba.style;
  5188. this.ctx._isStrokeTransparent = rgba.a == 0;
  5189. this.ctx._strokeOpacity = rgba.a;
  5190. //TODO jsPDF to handle rgba
  5191. if (rgba.a === 0) {
  5192. this.pdf.setDrawColor(255, 255, 255);
  5193. } else if (rgba.a === 1) {
  5194. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5195. } else {
  5196. //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
  5197. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  5198. }
  5199. },
  5200. fillText: function fillText(text, x, y, maxWidth) {
  5201. if (this._isFillTransparent()) {
  5202. return;
  5203. }
  5204. x = this._wrapX(x);
  5205. y = this._wrapY(y);
  5206. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5207. x = xpt[0];
  5208. y = xpt[1];
  5209. var rads = this._matrix_rotation(this.ctx._transform);
  5210. var degs = rads * 57.2958;
  5211. //TODO only push the clip if it has not been applied to the current PDF context
  5212. if (this.ctx._clip_path.length > 0) {
  5213. var lines;
  5214. if (window.outIntercept) {
  5215. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5216. } else {
  5217. lines = this.internal.getCurrentPage();
  5218. }
  5219. lines.push("q");
  5220. var origPath = this.path;
  5221. this.path = this.ctx._clip_path;
  5222. this.ctx._clip_path = [];
  5223. this._fill(null, true);
  5224. this.ctx._clip_path = this.path;
  5225. this.path = origPath;
  5226. }
  5227. // We only use X axis as scale hint
  5228. var scale = 1;
  5229. try {
  5230. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5231. } catch (e) {
  5232. console.warn(e);
  5233. }
  5234. // In some cases the transform was very small (5.715760606202283e-17). Most likely a canvg rounding error.
  5235. if (scale < .01) {
  5236. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5237. } else {
  5238. var oldSize = this.pdf.internal.getFontSize();
  5239. this.pdf.setFontSize(oldSize * scale);
  5240. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  5241. this.pdf.setFontSize(oldSize);
  5242. }
  5243. if (this.ctx._clip_path.length > 0) {
  5244. lines.push('Q');
  5245. }
  5246. },
  5247. strokeText: function strokeText(text, x, y, maxWidth) {
  5248. if (this._isStrokeTransparent()) {
  5249. return;
  5250. }
  5251. x = this._wrapX(x);
  5252. y = this._wrapY(y);
  5253. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5254. x = xpt[0];
  5255. y = xpt[1];
  5256. var rads = this._matrix_rotation(this.ctx._transform);
  5257. var degs = rads * 57.2958;
  5258. //TODO only push the clip if it has not been applied to the current PDF context
  5259. if (this.ctx._clip_path.length > 0) {
  5260. var lines;
  5261. if (window.outIntercept) {
  5262. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5263. } else {
  5264. lines = this.internal.getCurrentPage();
  5265. }
  5266. lines.push("q");
  5267. var origPath = this.path;
  5268. this.path = this.ctx._clip_path;
  5269. this.ctx._clip_path = [];
  5270. this._fill(null, true);
  5271. this.ctx._clip_path = this.path;
  5272. this.path = origPath;
  5273. }
  5274. var scale = 1;
  5275. // We only use the X axis as scale hint
  5276. try {
  5277. scale = this._matrix_decompose(this._getTransform()).scale[0];
  5278. } catch (e) {
  5279. console.warn(e);
  5280. }
  5281. if (scale === 1) {
  5282. this.pdf.text(text, x, this._getBaseline(y), {
  5283. stroke: true
  5284. }, degs);
  5285. } else {
  5286. var oldSize = this.pdf.internal.getFontSize();
  5287. this.pdf.setFontSize(oldSize * scale);
  5288. this.pdf.text(text, x, this._getBaseline(y), {
  5289. stroke: true
  5290. }, degs);
  5291. this.pdf.setFontSize(oldSize);
  5292. }
  5293. if (this.ctx._clip_path.length > 0) {
  5294. lines.push('Q');
  5295. }
  5296. },
  5297. setFont: function setFont(font) {
  5298. this.ctx.font = font;
  5299. //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
  5300. var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
  5301. m = rx.exec(font);
  5302. if (m != null) {
  5303. var fontStyle = m[1];
  5304. var fontVariant = m[2];
  5305. var fontWeight = m[3];
  5306. var fontSize = m[4];
  5307. var fontSizeUnit = m[5];
  5308. var fontFamily = m[6];
  5309. if ('px' === fontSizeUnit) {
  5310. fontSize = Math.floor(parseFloat(fontSize));
  5311. // fontSize = fontSize * 1.25;
  5312. } else if ('em' === fontSizeUnit) {
  5313. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5314. } else {
  5315. fontSize = Math.floor(parseFloat(fontSize));
  5316. }
  5317. this.pdf.setFontSize(fontSize);
  5318. if (fontWeight === 'bold' || fontWeight === '700') {
  5319. this.pdf.setFontStyle('bold');
  5320. } else {
  5321. if (fontStyle === 'italic') {
  5322. this.pdf.setFontStyle('italic');
  5323. } else {
  5324. this.pdf.setFontStyle('normal');
  5325. }
  5326. }
  5327. var name = fontFamily;
  5328. var parts = name.toLowerCase().split(/\s*,\s*/);
  5329. var jsPdfFontName;
  5330. if (parts.indexOf('arial') != -1) {
  5331. jsPdfFontName = 'Arial';
  5332. } else if (parts.indexOf('verdana') != -1) {
  5333. jsPdfFontName = 'Verdana';
  5334. } else if (parts.indexOf('helvetica') != -1) {
  5335. jsPdfFontName = 'Helvetica';
  5336. } else if (parts.indexOf('sans-serif') != -1) {
  5337. jsPdfFontName = 'sans-serif';
  5338. } else if (parts.indexOf('fixed') != -1) {
  5339. jsPdfFontName = 'Fixed';
  5340. } else if (parts.indexOf('monospace') != -1) {
  5341. jsPdfFontName = 'Monospace';
  5342. } else if (parts.indexOf('terminal') != -1) {
  5343. jsPdfFontName = 'Terminal';
  5344. } else if (parts.indexOf('courier') != -1) {
  5345. jsPdfFontName = 'Courier';
  5346. } else if (parts.indexOf('times') != -1) {
  5347. jsPdfFontName = 'Times';
  5348. } else if (parts.indexOf('cursive') != -1) {
  5349. jsPdfFontName = 'Cursive';
  5350. } else if (parts.indexOf('fantasy') != -1) {
  5351. jsPdfFontName = 'Fantasy';
  5352. } else if (parts.indexOf('serif') != -1) {
  5353. jsPdfFontName = 'Serif';
  5354. } else {
  5355. jsPdfFontName = 'Serif';
  5356. }
  5357. //TODO check more cases
  5358. var style;
  5359. if ('bold' === fontWeight) {
  5360. style = 'bold';
  5361. } else {
  5362. style = 'normal';
  5363. }
  5364. this.pdf.setFont(jsPdfFontName, style);
  5365. } else {
  5366. var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
  5367. var m = rx.exec(font);
  5368. if (m != null) {
  5369. var size = m[1];
  5370. var unit = m[2];
  5371. var name = m[3];
  5372. var style = m[4];
  5373. if (!style) {
  5374. style = 'normal';
  5375. }
  5376. if ('em' === fontSizeUnit) {
  5377. size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5378. } else {
  5379. size = Math.floor(parseFloat(size));
  5380. }
  5381. this.pdf.setFontSize(size);
  5382. this.pdf.setFont(name, style);
  5383. }
  5384. }
  5385. },
  5386. setTextBaseline: function setTextBaseline(baseline) {
  5387. this.ctx.textBaseline = baseline;
  5388. },
  5389. getTextBaseline: function getTextBaseline() {
  5390. return this.ctx.textBaseline;
  5391. },
  5392. //TODO implement textAlign
  5393. setTextAlign: function setTextAlign(align) {
  5394. this.ctx.textAlign = align;
  5395. },
  5396. getTextAlign: function getTextAlign() {
  5397. return this.ctx.textAlign;
  5398. },
  5399. setLineWidth: function setLineWidth(width) {
  5400. this.ctx.lineWidth = width;
  5401. this.pdf.setLineWidth(width);
  5402. },
  5403. setLineCap: function setLineCap(style) {
  5404. this.ctx.lineCap = style;
  5405. this.pdf.setLineCap(style);
  5406. },
  5407. setLineJoin: function setLineJoin(style) {
  5408. this.ctx.lineJoin = style;
  5409. this.pdf.setLineJoin(style);
  5410. },
  5411. moveTo: function moveTo(x, y) {
  5412. x = this._wrapX(x);
  5413. y = this._wrapY(y);
  5414. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5415. x = xpt[0];
  5416. y = xpt[1];
  5417. var obj = {
  5418. type: 'mt',
  5419. x: x,
  5420. y: y
  5421. };
  5422. this.path.push(obj);
  5423. },
  5424. _wrapX: function _wrapX(x) {
  5425. if (this.pageWrapXEnabled) {
  5426. return x % this.pageWrapX;
  5427. } else {
  5428. return x;
  5429. }
  5430. },
  5431. _wrapY: function _wrapY(y) {
  5432. if (this.pageWrapYEnabled) {
  5433. this._gotoPage(this._page(y));
  5434. return (y - this.lastBreak) % this.pageWrapY;
  5435. } else {
  5436. return y;
  5437. }
  5438. },
  5439. transform: function transform(a, b, c, d, e, f) {
  5440. //TODO apply to current transformation instead of replacing
  5441. this.ctx._transform = [a, b, c, d, e, f];
  5442. },
  5443. setTransform: function setTransform(a, b, c, d, e, f) {
  5444. this.ctx._transform = [a, b, c, d, e, f];
  5445. },
  5446. _getTransform: function _getTransform() {
  5447. return this.ctx._transform;
  5448. },
  5449. lastBreak: 0,
  5450. // Y Position of page breaks.
  5451. pageBreaks: [],
  5452. // returns: One-based Page Number
  5453. // Should only be used if pageWrapYEnabled is true
  5454. _page: function _page(y) {
  5455. if (this.pageWrapYEnabled) {
  5456. this.lastBreak = 0;
  5457. var manualBreaks = 0;
  5458. var autoBreaks = 0;
  5459. for (var i = 0; i < this.pageBreaks.length; i++) {
  5460. if (y >= this.pageBreaks[i]) {
  5461. manualBreaks++;
  5462. if (this.lastBreak === 0) {
  5463. autoBreaks++;
  5464. }
  5465. var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
  5466. this.lastBreak = this.pageBreaks[i];
  5467. var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
  5468. autoBreaks += pagesSinceLastBreak;
  5469. }
  5470. }
  5471. if (this.lastBreak === 0) {
  5472. var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
  5473. autoBreaks += pagesSinceLastBreak;
  5474. }
  5475. return autoBreaks + manualBreaks;
  5476. } else {
  5477. return this.pdf.internal.getCurrentPageInfo().pageNumber;
  5478. }
  5479. },
  5480. _gotoPage: function _gotoPage(pageOneBased) {
  5481. // This is a stub to be overriden if needed
  5482. },
  5483. lineTo: function lineTo(x, y) {
  5484. x = this._wrapX(x);
  5485. y = this._wrapY(y);
  5486. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5487. x = xpt[0];
  5488. y = xpt[1];
  5489. var obj = {
  5490. type: 'lt',
  5491. x: x,
  5492. y: y
  5493. };
  5494. this.path.push(obj);
  5495. },
  5496. bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
  5497. x1 = this._wrapX(x1);
  5498. y1 = this._wrapY(y1);
  5499. x2 = this._wrapX(x2);
  5500. y2 = this._wrapY(y2);
  5501. x = this._wrapX(x);
  5502. y = this._wrapY(y);
  5503. var xpt;
  5504. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5505. x = xpt[0];
  5506. y = xpt[1];
  5507. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5508. x1 = xpt[0];
  5509. y1 = xpt[1];
  5510. xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
  5511. x2 = xpt[0];
  5512. y2 = xpt[1];
  5513. var obj = {
  5514. type: 'bct',
  5515. x1: x1,
  5516. y1: y1,
  5517. x2: x2,
  5518. y2: y2,
  5519. x: x,
  5520. y: y
  5521. };
  5522. this.path.push(obj);
  5523. },
  5524. quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
  5525. x1 = this._wrapX(x1);
  5526. y1 = this._wrapY(y1);
  5527. x = this._wrapX(x);
  5528. y = this._wrapY(y);
  5529. var xpt;
  5530. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5531. x = xpt[0];
  5532. y = xpt[1];
  5533. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5534. x1 = xpt[0];
  5535. y1 = xpt[1];
  5536. var obj = {
  5537. type: 'qct',
  5538. x1: x1,
  5539. y1: y1,
  5540. x: x,
  5541. y: y
  5542. };
  5543. this.path.push(obj);
  5544. },
  5545. arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
  5546. x = this._wrapX(x);
  5547. y = this._wrapY(y);
  5548. if (!this._matrix_is_identity(this.ctx._transform)) {
  5549. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5550. x = xpt[0];
  5551. y = xpt[1];
  5552. var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
  5553. var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
  5554. radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
  5555. //TODO angles need to be transformed
  5556. }
  5557. var obj = {
  5558. type: 'arc',
  5559. x: x,
  5560. y: y,
  5561. radius: radius,
  5562. startAngle: startAngle,
  5563. endAngle: endAngle,
  5564. anticlockwise: anticlockwise
  5565. };
  5566. this.path.push(obj);
  5567. },
  5568. drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
  5569. if (x2 !== undefined) {
  5570. x = x2;
  5571. y = y2;
  5572. w = w2;
  5573. h = h2;
  5574. }
  5575. x = this._wrapX(x);
  5576. y = this._wrapY(y);
  5577. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5578. var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
  5579. // TODO implement source clipping and image scaling
  5580. var format;
  5581. var rx = /data:image\/(\w+).*/i;
  5582. var m = rx.exec(img);
  5583. if (m != null) {
  5584. format = m[1];
  5585. } else {
  5586. // format = "jpeg";
  5587. format = "png";
  5588. }
  5589. this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
  5590. },
  5591. /**
  5592. * Multiply the first matrix by the second
  5593. * @param m1
  5594. * @param m2
  5595. * @returns {*[]}
  5596. * @private
  5597. */
  5598. _matrix_multiply: function _matrix_multiply(m2, m1) {
  5599. var sx = m1[0];
  5600. var shy = m1[1];
  5601. var shx = m1[2];
  5602. var sy = m1[3];
  5603. var tx = m1[4];
  5604. var ty = m1[5];
  5605. var t0 = sx * m2[0] + shy * m2[2];
  5606. var t2 = shx * m2[0] + sy * m2[2];
  5607. var t4 = tx * m2[0] + ty * m2[2] + m2[4];
  5608. shy = sx * m2[1] + shy * m2[3];
  5609. sy = shx * m2[1] + sy * m2[3];
  5610. ty = tx * m2[1] + ty * m2[3] + m2[5];
  5611. sx = t0;
  5612. shx = t2;
  5613. tx = t4;
  5614. return [sx, shy, shx, sy, tx, ty];
  5615. },
  5616. _matrix_rotation: function _matrix_rotation(m) {
  5617. return Math.atan2(m[2], m[0]);
  5618. },
  5619. _matrix_decompose: function _matrix_decompose(matrix) {
  5620. var a = matrix[0];
  5621. var b = matrix[1];
  5622. var c = matrix[2];
  5623. var d = matrix[3];
  5624. var scaleX = Math.sqrt(a * a + b * b);
  5625. a /= scaleX;
  5626. b /= scaleX;
  5627. var shear = a * c + b * d;
  5628. c -= a * shear;
  5629. d -= b * shear;
  5630. var scaleY = Math.sqrt(c * c + d * d);
  5631. c /= scaleY;
  5632. d /= scaleY;
  5633. shear /= scaleY;
  5634. if (a * d < b * c) {
  5635. a = -a;
  5636. b = -b;
  5637. shear = -shear;
  5638. scaleX = -scaleX;
  5639. }
  5640. return {
  5641. scale: [scaleX, 0, 0, scaleY, 0, 0],
  5642. translate: [1, 0, 0, 1, matrix[4], matrix[5]],
  5643. rotate: [a, b, -b, a, 0, 0],
  5644. skew: [1, 0, shear, 1, 0, 0]
  5645. };
  5646. },
  5647. _matrix_map_point: function _matrix_map_point(m1, pt) {
  5648. var sx = m1[0];
  5649. var shy = m1[1];
  5650. var shx = m1[2];
  5651. var sy = m1[3];
  5652. var tx = m1[4];
  5653. var ty = m1[5];
  5654. var px = pt[0];
  5655. var py = pt[1];
  5656. var x = px * sx + py * shx + tx;
  5657. var y = px * shy + py * sy + ty;
  5658. return [x, y];
  5659. },
  5660. _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
  5661. var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
  5662. return { x: xpt[0], y: xpt[1] };
  5663. },
  5664. _matrix_map_rect: function _matrix_map_rect(m1, rect) {
  5665. var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
  5666. var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
  5667. return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
  5668. },
  5669. _matrix_is_identity: function _matrix_is_identity(m1) {
  5670. if (m1[0] != 1) {
  5671. return false;
  5672. }
  5673. if (m1[1] != 0) {
  5674. return false;
  5675. }
  5676. if (m1[2] != 0) {
  5677. return false;
  5678. }
  5679. if (m1[3] != 1) {
  5680. return false;
  5681. }
  5682. if (m1[4] != 0) {
  5683. return false;
  5684. }
  5685. if (m1[5] != 0) {
  5686. return false;
  5687. }
  5688. return true;
  5689. },
  5690. rotate: function rotate(angle) {
  5691. var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
  5692. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5693. },
  5694. scale: function scale(sx, sy) {
  5695. var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
  5696. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5697. },
  5698. translate: function translate(x, y) {
  5699. var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
  5700. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5701. },
  5702. stroke: function stroke() {
  5703. if (this.ctx._clip_path.length > 0) {
  5704. var lines;
  5705. if (window.outIntercept) {
  5706. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5707. } else {
  5708. lines = this.internal.getCurrentPage();
  5709. }
  5710. lines.push("q");
  5711. var origPath = this.path;
  5712. this.path = this.ctx._clip_path;
  5713. this.ctx._clip_path = [];
  5714. this._stroke(true);
  5715. this.ctx._clip_path = this.path;
  5716. this.path = origPath;
  5717. this._stroke(false);
  5718. lines.push("Q");
  5719. } else {
  5720. this._stroke(false);
  5721. }
  5722. },
  5723. _stroke: function _stroke(isClip) {
  5724. if (!isClip && this._isStrokeTransparent()) {
  5725. return;
  5726. }
  5727. //TODO opacity
  5728. var moves = [];
  5729. var closed = false;
  5730. var xPath = this.path;
  5731. for (var i = 0; i < xPath.length; i++) {
  5732. var pt = xPath[i];
  5733. switch (pt.type) {
  5734. case 'mt':
  5735. moves.push({ start: pt, deltas: [], abs: [] });
  5736. break;
  5737. case 'lt':
  5738. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5739. moves[moves.length - 1].deltas.push(delta);
  5740. moves[moves.length - 1].abs.push(pt);
  5741. break;
  5742. case 'bct':
  5743. 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];
  5744. moves[moves.length - 1].deltas.push(delta);
  5745. break;
  5746. case 'qct':
  5747. // convert to bezier
  5748. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5749. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5750. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5751. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5752. var x3 = pt.x;
  5753. var y3 = pt.y;
  5754. 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];
  5755. moves[moves.length - 1].deltas.push(delta);
  5756. break;
  5757. case 'arc':
  5758. //TODO this was hack to avoid out-of-bounds issue
  5759. // No move-to before drawing the arc
  5760. if (moves.length == 0) {
  5761. moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
  5762. }
  5763. moves[moves.length - 1].arc = true;
  5764. moves[moves.length - 1].abs.push(pt);
  5765. break;
  5766. case 'close':
  5767. closed = true;
  5768. break;
  5769. }
  5770. }
  5771. for (var i = 0; i < moves.length; i++) {
  5772. var style;
  5773. if (i == moves.length - 1) {
  5774. style = 's';
  5775. } else {
  5776. style = null;
  5777. }
  5778. if (moves[i].arc) {
  5779. var arcs = moves[i].abs;
  5780. for (var ii = 0; ii < arcs.length; ii++) {
  5781. var arc = arcs[ii];
  5782. var start = arc.startAngle * 360 / (2 * Math.PI);
  5783. var end = arc.endAngle * 360 / (2 * Math.PI);
  5784. var x = arc.x;
  5785. var y = arc.y;
  5786. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
  5787. }
  5788. } else {
  5789. var x = moves[i].start.x;
  5790. var y = moves[i].start.y;
  5791. if (!isClip) {
  5792. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5793. } else {
  5794. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5795. this.pdf.clip_fixed();
  5796. }
  5797. }
  5798. }
  5799. },
  5800. _isFillTransparent: function _isFillTransparent() {
  5801. return this.ctx._isFillTransparent || this.globalAlpha == 0;
  5802. },
  5803. _isStrokeTransparent: function _isStrokeTransparent() {
  5804. return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
  5805. },
  5806. fill: function fill(fillRule) {
  5807. //evenodd or nonzero (default)
  5808. if (this.ctx._clip_path.length > 0) {
  5809. var lines;
  5810. if (window.outIntercept) {
  5811. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5812. } else {
  5813. lines = this.internal.getCurrentPage();
  5814. }
  5815. lines.push("q");
  5816. var origPath = this.path;
  5817. this.path = this.ctx._clip_path;
  5818. this.ctx._clip_path = [];
  5819. this._fill(fillRule, true);
  5820. this.ctx._clip_path = this.path;
  5821. this.path = origPath;
  5822. this._fill(fillRule, false);
  5823. lines.push('Q');
  5824. } else {
  5825. this._fill(fillRule, false);
  5826. }
  5827. },
  5828. _fill: function _fill(fillRule, isClip) {
  5829. if (this._isFillTransparent()) {
  5830. return;
  5831. }
  5832. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5833. var lines;
  5834. if (window.outIntercept) {
  5835. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5836. } else {
  5837. lines = this.internal.getCurrentPage();
  5838. }
  5839. // if (this.ctx._clip_path.length > 0) {
  5840. // lines.push('q');
  5841. // var oldPath = this.path;
  5842. // this.path = this.ctx._clip_path;
  5843. // this.ctx._clip_path = [];
  5844. // this._fill(fillRule, true);
  5845. // this.ctx._clip_path = this.path;
  5846. // this.path = oldPath;
  5847. // }
  5848. var moves = [];
  5849. var outInterceptOld = window.outIntercept;
  5850. if (v2Support) {
  5851. // Blend and Mask
  5852. switch (this.ctx.globalCompositeOperation) {
  5853. case 'normal':
  5854. case 'source-over':
  5855. break;
  5856. case 'destination-in':
  5857. case 'destination-out':
  5858. //TODO this need to be added to the current group or page
  5859. // define a mask stream
  5860. var obj = this.pdf.internal.newStreamObject();
  5861. // define a mask state
  5862. var obj2 = this.pdf.internal.newObject2();
  5863. obj2.push('<</Type /ExtGState');
  5864. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5865. obj2.push('>>');
  5866. // add mask to page resources
  5867. var gsName = 'MASK' + obj2.objId;
  5868. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5869. var instruction = '/' + gsName + ' gs';
  5870. // add mask to page, group, or stream
  5871. lines.splice(0, 0, 'q');
  5872. lines.splice(1, 0, instruction);
  5873. lines.push('Q');
  5874. window.outIntercept = obj;
  5875. break;
  5876. default:
  5877. var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
  5878. if (dictionaryEntry) {
  5879. this.pdf.internal.out(dictionaryEntry + ' gs');
  5880. }
  5881. break;
  5882. }
  5883. }
  5884. var alpha = this.ctx.globalAlpha;
  5885. if (this.ctx._fillOpacity < 1) {
  5886. // TODO combine this with global opacity
  5887. alpha = this.ctx._fillOpacity;
  5888. }
  5889. //TODO check for an opacity graphics state that was already created
  5890. //TODO do not set opacity if current value is already active
  5891. if (v2Support) {
  5892. var objOpac = this.pdf.internal.newObject2();
  5893. objOpac.push('<</Type /ExtGState');
  5894. //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
  5895. //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
  5896. objOpac.push('/CA ' + alpha); // Stroke
  5897. objOpac.push('/ca ' + alpha); // Not Stroke
  5898. objOpac.push('>>');
  5899. var gsName = 'GS_O_' + objOpac.objId;
  5900. this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
  5901. this.pdf.internal.out('/' + gsName + ' gs');
  5902. }
  5903. var xPath = this.path;
  5904. for (var i = 0; i < xPath.length; i++) {
  5905. var pt = xPath[i];
  5906. switch (pt.type) {
  5907. case 'mt':
  5908. moves.push({ start: pt, deltas: [], abs: [] });
  5909. break;
  5910. case 'lt':
  5911. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5912. moves[moves.length - 1].deltas.push(delta);
  5913. moves[moves.length - 1].abs.push(pt);
  5914. break;
  5915. case 'bct':
  5916. 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];
  5917. moves[moves.length - 1].deltas.push(delta);
  5918. break;
  5919. case 'qct':
  5920. // convert to bezier
  5921. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5922. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5923. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5924. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5925. var x3 = pt.x;
  5926. var y3 = pt.y;
  5927. 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];
  5928. moves[moves.length - 1].deltas.push(delta);
  5929. break;
  5930. case 'arc':
  5931. //TODO this was hack to avoid out-of-bounds issue when drawing circle
  5932. // No move-to before drawing the arc
  5933. if (moves.length === 0) {
  5934. moves.push({ deltas: [], abs: [] });
  5935. }
  5936. moves[moves.length - 1].arc = true;
  5937. moves[moves.length - 1].abs.push(pt);
  5938. break;
  5939. case 'close':
  5940. moves.push({ close: true });
  5941. break;
  5942. }
  5943. }
  5944. for (var i = 0; i < moves.length; i++) {
  5945. var style;
  5946. if (i == moves.length - 1) {
  5947. style = 'f';
  5948. if (fillRule === 'evenodd') {
  5949. style += '*';
  5950. }
  5951. } else {
  5952. style = null;
  5953. }
  5954. if (moves[i].close) {
  5955. this.pdf.internal.out('h');
  5956. this.pdf.internal.out('f');
  5957. } else if (moves[i].arc) {
  5958. if (moves[i].start) {
  5959. this.internal.move2(this, moves[i].start.x, moves[i].start.y);
  5960. }
  5961. var arcs = moves[i].abs;
  5962. for (var ii = 0; ii < arcs.length; ii++) {
  5963. var arc = arcs[ii];
  5964. //TODO lines deltas were getting in here
  5965. if (typeof arc.startAngle !== 'undefined') {
  5966. var start = arc.startAngle * 360 / (2 * Math.PI);
  5967. var end = arc.endAngle * 360 / (2 * Math.PI);
  5968. var x = arc.x;
  5969. var y = arc.y;
  5970. if (ii === 0) {
  5971. this.internal.move2(this, x, y);
  5972. }
  5973. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
  5974. if (ii === arcs.length - 1) {
  5975. // The original arc move did not occur because of the algorithm
  5976. if (moves[i].start) {
  5977. var x = moves[i].start.x;
  5978. var y = moves[i].start.y;
  5979. this.internal.line2(c2d, x, y);
  5980. }
  5981. }
  5982. } else {
  5983. this.internal.line2(c2d, arc.x, arc.y);
  5984. }
  5985. }
  5986. } else {
  5987. var x = moves[i].start.x;
  5988. var y = moves[i].start.y;
  5989. if (!isClip) {
  5990. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5991. } else {
  5992. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5993. this.pdf.clip_fixed();
  5994. }
  5995. }
  5996. }
  5997. window.outIntercept = outInterceptOld;
  5998. // if (this.ctx._clip_path.length > 0) {
  5999. // lines.push('Q');
  6000. // }
  6001. },
  6002. pushMask: function pushMask() {
  6003. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  6004. if (!v2Support) {
  6005. console.log('jsPDF v2 not enabled');
  6006. return;
  6007. }
  6008. // define a mask stream
  6009. var obj = this.pdf.internal.newStreamObject();
  6010. // define a mask state
  6011. var obj2 = this.pdf.internal.newObject2();
  6012. obj2.push('<</Type /ExtGState');
  6013. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  6014. obj2.push('>>');
  6015. // add mask to page resources
  6016. var gsName = 'MASK' + obj2.objId;
  6017. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  6018. var instruction = '/' + gsName + ' gs';
  6019. this.pdf.internal.out(instruction);
  6020. },
  6021. clip: function clip() {
  6022. //TODO do we reset the path, or just copy it?
  6023. if (this.ctx._clip_path.length > 0) {
  6024. for (var i = 0; i < this.path.length; i++) {
  6025. this.ctx._clip_path.push(this.path[i]);
  6026. }
  6027. } else {
  6028. this.ctx._clip_path = this.path;
  6029. }
  6030. this.path = [];
  6031. },
  6032. measureText: function measureText(text) {
  6033. var pdf = this.pdf;
  6034. return {
  6035. getWidth: function getWidth() {
  6036. var fontSize = pdf.internal.getFontSize();
  6037. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  6038. // Convert points to pixels
  6039. txtWidth *= 1.3333;
  6040. return txtWidth;
  6041. },
  6042. get width() {
  6043. return this.getWidth(text);
  6044. }
  6045. };
  6046. },
  6047. _getBaseline: function _getBaseline(y) {
  6048. var height = parseInt(this.pdf.internal.getFontSize());
  6049. // TODO Get descent from font descriptor
  6050. var descent = height * .25;
  6051. switch (this.ctx.textBaseline) {
  6052. case 'bottom':
  6053. return y - descent;
  6054. case 'top':
  6055. return y + height;
  6056. case 'hanging':
  6057. return y + height - descent;
  6058. case 'middle':
  6059. return y + height / 2 - descent;
  6060. case 'ideographic':
  6061. // TODO not implemented
  6062. return y;
  6063. case 'alphabetic':
  6064. default:
  6065. return y;
  6066. }
  6067. }
  6068. };
  6069. var c2d = jsPDFAPI.context2d;
  6070. // accessor methods
  6071. Object.defineProperty(c2d, 'fillStyle', {
  6072. set: function set(value) {
  6073. this.setFillStyle(value);
  6074. },
  6075. get: function get() {
  6076. return this.ctx.fillStyle;
  6077. }
  6078. });
  6079. Object.defineProperty(c2d, 'strokeStyle', {
  6080. set: function set(value) {
  6081. this.setStrokeStyle(value);
  6082. },
  6083. get: function get() {
  6084. return this.ctx.strokeStyle;
  6085. }
  6086. });
  6087. Object.defineProperty(c2d, 'lineWidth', {
  6088. set: function set(value) {
  6089. this.setLineWidth(value);
  6090. },
  6091. get: function get() {
  6092. return this.ctx.lineWidth;
  6093. }
  6094. });
  6095. Object.defineProperty(c2d, 'lineCap', {
  6096. set: function set(val) {
  6097. this.setLineCap(val);
  6098. },
  6099. get: function get() {
  6100. return this.ctx.lineCap;
  6101. }
  6102. });
  6103. Object.defineProperty(c2d, 'lineJoin', {
  6104. set: function set(val) {
  6105. this.setLineJoin(val);
  6106. },
  6107. get: function get() {
  6108. return this.ctx.lineJoin;
  6109. }
  6110. });
  6111. Object.defineProperty(c2d, 'miterLimit', {
  6112. set: function set(val) {
  6113. this.ctx.miterLimit = val;
  6114. },
  6115. get: function get() {
  6116. return this.ctx.miterLimit;
  6117. }
  6118. });
  6119. Object.defineProperty(c2d, 'textBaseline', {
  6120. set: function set(value) {
  6121. this.setTextBaseline(value);
  6122. },
  6123. get: function get() {
  6124. return this.getTextBaseline();
  6125. }
  6126. });
  6127. Object.defineProperty(c2d, 'textAlign', {
  6128. set: function set(value) {
  6129. this.setTextAlign(value);
  6130. },
  6131. get: function get() {
  6132. return this.getTextAlign();
  6133. }
  6134. });
  6135. Object.defineProperty(c2d, 'font', {
  6136. set: function set(value) {
  6137. this.setFont(value);
  6138. },
  6139. get: function get() {
  6140. return this.ctx.font;
  6141. }
  6142. });
  6143. Object.defineProperty(c2d, 'globalCompositeOperation', {
  6144. set: function set(value) {
  6145. this.ctx.globalCompositeOperation = value;
  6146. },
  6147. get: function get() {
  6148. return this.ctx.globalCompositeOperation;
  6149. }
  6150. });
  6151. Object.defineProperty(c2d, 'globalAlpha', {
  6152. set: function set(value) {
  6153. this.ctx.globalAlpha = value;
  6154. },
  6155. get: function get() {
  6156. return this.ctx.globalAlpha;
  6157. }
  6158. });
  6159. // Not HTML API
  6160. Object.defineProperty(c2d, 'ignoreClearRect', {
  6161. set: function set(value) {
  6162. this.ctx.ignoreClearRect = value;
  6163. },
  6164. get: function get() {
  6165. return this.ctx.ignoreClearRect;
  6166. }
  6167. });
  6168. // End Not HTML API
  6169. c2d.internal = {};
  6170. c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  6171. c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  6172. c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  6173. // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
  6174. c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
  6175. var includeMove = true;
  6176. var k = this.pdf.internal.scaleFactor;
  6177. var pageHeight = this.pdf.internal.pageSize.height;
  6178. var f2 = this.pdf.internal.f2;
  6179. var a1r = a1 * (Math.PI / 180);
  6180. var a2r = a2 * (Math.PI / 180);
  6181. var curves = this.createArc(r, a1r, a2r, anticlockwise);
  6182. var pathData = null;
  6183. for (var i = 0; i < curves.length; i++) {
  6184. var curve = curves[i];
  6185. if (includeMove && i === 0) {
  6186. 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(' '));
  6187. } else {
  6188. 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(' '));
  6189. }
  6190. //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
  6191. c2d._lastPoint = { x: xc, y: yc };
  6192. // 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'
  6193. }
  6194. if (style !== null) {
  6195. this.pdf.internal.out(this.pdf.internal.getStyle(style));
  6196. }
  6197. };
  6198. /**
  6199. *
  6200. * @param x Edge point X
  6201. * @param y Edge point Y
  6202. * @param r Radius
  6203. * @param a1 start angle
  6204. * @param a2 end angle
  6205. * @param anticlockwise
  6206. * @param style
  6207. * @param isClip
  6208. */
  6209. c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
  6210. // we need to convert from cartesian to polar here methinks.
  6211. var centerX = x; // + r;
  6212. var centerY = y;
  6213. if (!isClip) {
  6214. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
  6215. } else {
  6216. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
  6217. this.pdf.clip_fixed();
  6218. }
  6219. };
  6220. c2d.internal.move2 = function (c2d, x, y) {
  6221. var k = this.pdf.internal.scaleFactor;
  6222. var pageHeight = this.pdf.internal.pageSize.height;
  6223. var f2 = this.pdf.internal.f2;
  6224. this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
  6225. c2d._lastPoint = { x: x, y: y };
  6226. };
  6227. c2d.internal.line2 = function (c2d, dx, dy) {
  6228. var k = this.pdf.internal.scaleFactor;
  6229. var pageHeight = this.pdf.internal.pageSize.height;
  6230. var f2 = this.pdf.internal.f2;
  6231. //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
  6232. var pt = { x: dx, y: dy };
  6233. this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
  6234. //this.pdf.internal.out('f');
  6235. c2d._lastPoint = pt;
  6236. };
  6237. /**
  6238. * 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.
  6239. *
  6240. * 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.
  6241. */
  6242. c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
  6243. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
  6244. var twoPI = Math.PI * 2;
  6245. var piOverTwo = Math.PI / 2.0;
  6246. // normalize startAngle, endAngle to [0, 2PI]
  6247. var startAngleN = startAngle;
  6248. if (startAngleN < twoPI || startAngleN > twoPI) {
  6249. startAngleN = startAngleN % twoPI;
  6250. }
  6251. if (startAngleN < 0) {
  6252. startAngleN = twoPI + startAngleN;
  6253. }
  6254. while (startAngle > endAngle) {
  6255. startAngle = startAngle - twoPI;
  6256. }
  6257. var totalAngle = Math.abs(endAngle - startAngle);
  6258. if (totalAngle < twoPI) {
  6259. if (anticlockwise) {
  6260. totalAngle = twoPI - totalAngle;
  6261. }
  6262. }
  6263. // Compute the sequence of arc curves, up to PI/2 at a time.
  6264. var curves = [];
  6265. var sgn = anticlockwise ? -1 : +1;
  6266. var a1 = startAngleN;
  6267. for (; totalAngle > EPSILON;) {
  6268. var remain = sgn * Math.min(totalAngle, piOverTwo);
  6269. var a2 = a1 + remain;
  6270. curves.push(this.createSmallArc(radius, a1, a2));
  6271. totalAngle -= Math.abs(a2 - a1);
  6272. a1 = a2;
  6273. }
  6274. return curves;
  6275. };
  6276. c2d.internal.getCurrentPage = function () {
  6277. return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
  6278. };
  6279. /**
  6280. * 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.
  6281. *
  6282. * 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.
  6283. *
  6284. * 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.
  6285. */
  6286. c2d.internal.createSmallArc = function (r, a1, a2) {
  6287. // Compute all four points for an arc that subtends the same total angle
  6288. // but is centered on the X-axis
  6289. var a = (a2 - a1) / 2.0;
  6290. var x4 = r * Math.cos(a);
  6291. var y4 = r * Math.sin(a);
  6292. var x1 = x4;
  6293. var y1 = -y4;
  6294. var q1 = x1 * x1 + y1 * y1;
  6295. var q2 = q1 + x1 * x4 + y1 * y4;
  6296. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  6297. var x2 = x1 - k2 * y1;
  6298. var y2 = y1 + k2 * x1;
  6299. var x3 = x2;
  6300. var y3 = -y2;
  6301. // Find the arc points' actual locations by computing x1,y1 and x4,y4
  6302. // and rotating the control points by a + a1
  6303. var ar = a + a1;
  6304. var cos_ar = Math.cos(ar);
  6305. var sin_ar = Math.sin(ar);
  6306. return {
  6307. x1: r * Math.cos(a1),
  6308. y1: r * Math.sin(a1),
  6309. x2: x2 * cos_ar - y2 * sin_ar,
  6310. y2: x2 * sin_ar + y2 * cos_ar,
  6311. x3: x3 * cos_ar - y3 * sin_ar,
  6312. y3: x3 * sin_ar + y3 * cos_ar,
  6313. x4: r * Math.cos(a2),
  6314. y4: r * Math.sin(a2)
  6315. };
  6316. };
  6317. function context() {
  6318. this._isStrokeTransparent = false;
  6319. this._strokeOpacity = 1;
  6320. this.strokeStyle = '#000000';
  6321. this.fillStyle = '#000000';
  6322. this._isFillTransparent = false;
  6323. this._fillOpacity = 1;
  6324. this.font = "12pt times";
  6325. this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
  6326. this.textAlign = 'start';
  6327. this.lineWidth = 1;
  6328. this.lineJoin = 'miter'; // round, bevel, miter
  6329. this.lineCap = 'butt'; // butt, round, square
  6330. this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
  6331. this.globalCompositeOperation = 'normal';
  6332. this.globalAlpha = 1.0;
  6333. this._clip_path = [];
  6334. // TODO miter limit //default 10
  6335. // Not HTML API
  6336. this.ignoreClearRect = false;
  6337. this.copy = function (ctx) {
  6338. this._isStrokeTransparent = ctx._isStrokeTransparent;
  6339. this._strokeOpacity = ctx._strokeOpacity;
  6340. this.strokeStyle = ctx.strokeStyle;
  6341. this._isFillTransparent = ctx._isFillTransparent;
  6342. this._fillOpacity = ctx._fillOpacity;
  6343. this.fillStyle = ctx.fillStyle;
  6344. this.font = ctx.font;
  6345. this.lineWidth = ctx.lineWidth;
  6346. this.lineJoin = ctx.lineJoin;
  6347. this.lineCap = ctx.lineCap;
  6348. this.textBaseline = ctx.textBaseline;
  6349. this.textAlign = ctx.textAlign;
  6350. this._fontSize = ctx._fontSize;
  6351. this._transform = ctx._transform.slice(0);
  6352. this.globalCompositeOperation = ctx.globalCompositeOperation;
  6353. this.globalAlpha = ctx.globalAlpha;
  6354. this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
  6355. // Not HTML API
  6356. this.ignoreClearRect = ctx.ignoreClearRect;
  6357. };
  6358. }
  6359. return this;
  6360. })(jsPDF.API);
  6361. /** @preserve
  6362. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  6363. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  6364. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  6365. * 2014 Diego Casorran, https://github.com/diegocr
  6366. * 2014 Daniel Husar, https://github.com/danielhusar
  6367. * 2014 Wolfgang Gassler, https://github.com/woolfg
  6368. * 2014 Steven Spungin, https://github.com/flamenco
  6369. *
  6370. *
  6371. * ====================================================================
  6372. */
  6373. (function (jsPDFAPI) {
  6374. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  6375. clone = function () {
  6376. return function (obj) {
  6377. Clone.prototype = obj;
  6378. return new Clone();
  6379. };
  6380. function Clone() {}
  6381. }();
  6382. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  6383. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  6384. i = 0;
  6385. l = array.length;
  6386. fragment = void 0;
  6387. lTrimmed = false;
  6388. rTrimmed = false;
  6389. while (!lTrimmed && i !== l) {
  6390. fragment = array[i] = array[i].trimLeft();
  6391. if (fragment) {
  6392. lTrimmed = true;
  6393. }
  6394. i++;
  6395. }
  6396. i = l - 1;
  6397. while (l && !rTrimmed && i !== -1) {
  6398. fragment = array[i] = array[i].trimRight();
  6399. if (fragment) {
  6400. rTrimmed = true;
  6401. }
  6402. i--;
  6403. }
  6404. r = /\s+$/g;
  6405. trailingSpace = true;
  6406. i = 0;
  6407. while (i !== l) {
  6408. // Leave the line breaks intact
  6409. if (array[i] != "\u2028") {
  6410. fragment = array[i].replace(/\s+/g, " ");
  6411. if (trailingSpace) {
  6412. fragment = fragment.trimLeft();
  6413. }
  6414. if (fragment) {
  6415. trailingSpace = r.test(fragment);
  6416. }
  6417. array[i] = fragment;
  6418. }
  6419. i++;
  6420. }
  6421. return array;
  6422. };
  6423. Renderer = function Renderer(pdf, x, y, settings) {
  6424. this.pdf = pdf;
  6425. this.x = x;
  6426. this.y = y;
  6427. this.settings = settings;
  6428. //list of functions which are called after each element-rendering process
  6429. this.watchFunctions = [];
  6430. this.init();
  6431. return this;
  6432. };
  6433. ResolveFont = function ResolveFont(css_font_family_string) {
  6434. var name, part, parts;
  6435. name = void 0;
  6436. parts = css_font_family_string.split(",");
  6437. part = parts.shift();
  6438. while (!name && part) {
  6439. name = FontNameDB[part.trim().toLowerCase()];
  6440. part = parts.shift();
  6441. }
  6442. return name;
  6443. };
  6444. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  6445. //IE8 issues
  6446. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  6447. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  6448. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  6449. }
  6450. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  6451. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  6452. }
  6453. var normal, undef, value;
  6454. undef = void 0;
  6455. normal = 16.00;
  6456. value = UnitedNumberMap[css_line_height_string];
  6457. if (value) {
  6458. return value;
  6459. }
  6460. value = {
  6461. "xx-small": 9,
  6462. "x-small": 11,
  6463. small: 13,
  6464. medium: 16,
  6465. large: 19,
  6466. "x-large": 23,
  6467. "xx-large": 28,
  6468. auto: 0
  6469. }[{ css_line_height_string: css_line_height_string }];
  6470. if (value !== undef) {
  6471. return UnitedNumberMap[css_line_height_string] = value / normal;
  6472. }
  6473. if (value = parseFloat(css_line_height_string)) {
  6474. return UnitedNumberMap[css_line_height_string] = value / normal;
  6475. }
  6476. value = css_line_height_string.match(/([\d\.]+)(px)/);
  6477. if (value.length === 3) {
  6478. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  6479. }
  6480. return UnitedNumberMap[css_line_height_string] = 1;
  6481. };
  6482. GetCSS = function GetCSS(element) {
  6483. var css, tmp, computedCSSElement;
  6484. computedCSSElement = function (el) {
  6485. var compCSS;
  6486. compCSS = function (el) {
  6487. if (document.defaultView && document.defaultView.getComputedStyle) {
  6488. return document.defaultView.getComputedStyle(el, null);
  6489. } else if (el.currentStyle) {
  6490. return el.currentStyle;
  6491. } else {
  6492. return el.style;
  6493. }
  6494. }(el);
  6495. return function (prop) {
  6496. prop = prop.replace(/-\D/g, function (match) {
  6497. return match.charAt(1).toUpperCase();
  6498. });
  6499. return compCSS[prop];
  6500. };
  6501. }(element);
  6502. css = {};
  6503. tmp = void 0;
  6504. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  6505. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  6506. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  6507. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  6508. if (tmp === "bold") {
  6509. if (css["font-style"] === "normal") {
  6510. css["font-style"] = tmp;
  6511. } else {
  6512. css["font-style"] = tmp + css["font-style"];
  6513. }
  6514. }
  6515. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  6516. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  6517. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  6518. tmp = css["display"] === "block";
  6519. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  6520. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  6521. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  6522. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  6523. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  6524. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  6525. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  6526. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  6527. css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
  6528. //float and clearing of floats
  6529. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  6530. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  6531. css["color"] = computedCSSElement("color");
  6532. return css;
  6533. };
  6534. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  6535. var handlers, i, isHandledElsewhere, l, t;
  6536. isHandledElsewhere = false;
  6537. i = void 0;
  6538. l = void 0;
  6539. t = void 0;
  6540. handlers = elementHandlers["#" + element.id];
  6541. if (handlers) {
  6542. if (typeof handlers === "function") {
  6543. isHandledElsewhere = handlers(element, renderer);
  6544. } else {
  6545. i = 0;
  6546. l = handlers.length;
  6547. while (!isHandledElsewhere && i !== l) {
  6548. isHandledElsewhere = handlers[i](element, renderer);
  6549. i++;
  6550. }
  6551. }
  6552. }
  6553. handlers = elementHandlers[element.nodeName];
  6554. if (!isHandledElsewhere && handlers) {
  6555. if (typeof handlers === "function") {
  6556. isHandledElsewhere = handlers(element, renderer);
  6557. } else {
  6558. i = 0;
  6559. l = handlers.length;
  6560. while (!isHandledElsewhere && i !== l) {
  6561. isHandledElsewhere = handlers[i](element, renderer);
  6562. i++;
  6563. }
  6564. }
  6565. }
  6566. return isHandledElsewhere;
  6567. };
  6568. tableToJson = function tableToJson(table, renderer) {
  6569. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  6570. data = [];
  6571. headers = [];
  6572. i = 0;
  6573. l = table.rows[0].cells.length;
  6574. table_with = table.clientWidth;
  6575. while (i < l) {
  6576. cell = table.rows[0].cells[i];
  6577. headers[i] = {
  6578. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  6579. prompt: cell.textContent.replace(/\r?\n/g, ''),
  6580. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
  6581. };
  6582. i++;
  6583. }
  6584. i = 1;
  6585. while (i < table.rows.length) {
  6586. tableRow = table.rows[i];
  6587. rowData = {};
  6588. j = 0;
  6589. while (j < tableRow.cells.length) {
  6590. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  6591. j++;
  6592. }
  6593. data.push(rowData);
  6594. i++;
  6595. }
  6596. return table_obj = {
  6597. rows: data,
  6598. headers: headers
  6599. };
  6600. };
  6601. var SkipNode = {
  6602. SCRIPT: 1,
  6603. STYLE: 1,
  6604. NOSCRIPT: 1,
  6605. OBJECT: 1,
  6606. EMBED: 1,
  6607. SELECT: 1
  6608. };
  6609. var listCount = 1;
  6610. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  6611. var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
  6612. cns = element.childNodes;
  6613. cn = void 0;
  6614. fragmentCSS = GetCSS(element);
  6615. isBlock = fragmentCSS.display === "block";
  6616. if (isBlock) {
  6617. renderer.setBlockBoundary();
  6618. renderer.setBlockStyle(fragmentCSS);
  6619. }
  6620. px2pt = 0.264583 * 72 / 25.4;
  6621. i = 0;
  6622. l = cns.length;
  6623. while (i < l) {
  6624. cn = cns[i];
  6625. if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
  6626. //execute all watcher functions to e.g. reset floating
  6627. renderer.executeWatchFunctions(cn);
  6628. /*** HEADER rendering **/
  6629. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  6630. var header = cn;
  6631. //store old top margin
  6632. var oldMarginTop = renderer.pdf.margins_doc.top;
  6633. //subscribe for new page event and render header first on every page
  6634. renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
  6635. //set current y position to old margin
  6636. renderer.y = oldMarginTop;
  6637. //render all child nodes of the header element
  6638. _DrillForContent(header, renderer, elementHandlers);
  6639. //set margin to old margin + rendered header + 10 space to prevent overlapping
  6640. //important for other plugins (e.g. table) to start rendering at correct position after header
  6641. renderer.pdf.margins_doc.top = renderer.y + 10;
  6642. renderer.y += 10;
  6643. }, false);
  6644. }
  6645. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  6646. if (~cn.textContent.indexOf("ADD_PAGE")) {
  6647. renderer.pdf.addPage();
  6648. renderer.y = renderer.pdf.margins_doc.top;
  6649. }
  6650. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  6651. /*** IMAGE RENDERING ***/
  6652. var cached_image;
  6653. if (cn.nodeName === "IMG") {
  6654. var url = cn.getAttribute("src");
  6655. cached_image = images[renderer.pdf.sHashCode(url) || url];
  6656. }
  6657. if (cached_image) {
  6658. if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  6659. renderer.pdf.addPage();
  6660. renderer.y = renderer.pdf.margins_doc.top;
  6661. //check if we have to set back some values due to e.g. header rendering for new page
  6662. renderer.executeWatchFunctions(cn);
  6663. }
  6664. var imagesCSS = GetCSS(cn);
  6665. var imageX = renderer.x;
  6666. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
  6667. //define additional paddings, margins which have to be taken into account for margin calculations
  6668. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  6669. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  6670. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  6671. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
  6672. //if float is set to right, move the image to the right border
  6673. //add space if margin is set
  6674. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  6675. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  6676. } else {
  6677. imageX += additionalSpaceLeft;
  6678. }
  6679. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  6680. cached_image = undefined;
  6681. //if the float prop is specified we have to float the text around the image
  6682. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  6683. //add functiont to set back coordinates after image rendering
  6684. renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
  6685. //undo drawing box adaptions which were set by floating
  6686. if (renderer.y >= thresholdY) {
  6687. renderer.x += diffX;
  6688. renderer.settings.width += diffWidth;
  6689. return true;
  6690. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  6691. renderer.x += diffX;
  6692. renderer.y = thresholdY;
  6693. renderer.settings.width += diffWidth;
  6694. return true;
  6695. } else {
  6696. return false;
  6697. }
  6698. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
  6699. //reset floating by clear:both divs
  6700. //just set cursorY after the floating element
  6701. renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
  6702. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  6703. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  6704. renderer.y = yPositionAfterFloating;
  6705. return true;
  6706. } else {
  6707. return false;
  6708. }
  6709. } else {
  6710. return true;
  6711. }
  6712. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
  6713. //if floating is set we decrease the available width by the image width
  6714. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
  6715. //if left just add the image width to the X coordinate
  6716. if (imagesCSS['float'] === 'left') {
  6717. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  6718. }
  6719. } else {
  6720. //if no floating is set, move the rendering cursor after the image height
  6721. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  6722. }
  6723. /*** TABLE RENDERING ***/
  6724. } else if (cn.nodeName === "TABLE") {
  6725. table2json = tableToJson(cn, renderer);
  6726. renderer.y += 10;
  6727. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  6728. autoSize: false,
  6729. printHeaders: elementHandlers.printHeaders,
  6730. margins: renderer.pdf.margins_doc,
  6731. css: GetCSS(cn)
  6732. });
  6733. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  6734. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  6735. listCount = 1;
  6736. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6737. _DrillForContent(cn, renderer, elementHandlers);
  6738. }
  6739. renderer.y += 10;
  6740. } else if (cn.nodeName === "LI") {
  6741. var temp = renderer.x;
  6742. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  6743. renderer.y += 3;
  6744. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6745. _DrillForContent(cn, renderer, elementHandlers);
  6746. }
  6747. renderer.x = temp;
  6748. } else if (cn.nodeName === "BR") {
  6749. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  6750. renderer.addText("\u2028", clone(fragmentCSS));
  6751. } else {
  6752. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6753. _DrillForContent(cn, renderer, elementHandlers);
  6754. }
  6755. }
  6756. } else if (cn.nodeType === 3) {
  6757. var value = cn.nodeValue;
  6758. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  6759. if (cn.parentNode.parentNode.nodeName === "OL") {
  6760. value = listCount++ + '. ' + value;
  6761. } else {
  6762. var fontSize = fragmentCSS["font-size"];
  6763. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  6764. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  6765. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  6766. cb = function cb(x, y) {
  6767. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  6768. };
  6769. }
  6770. }
  6771. // Only add the text if the text node is in the body element
  6772. // Add compatibility with IE11
  6773. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  6774. renderer.addText(value, fragmentCSS);
  6775. }
  6776. } else if (typeof cn === "string") {
  6777. renderer.addText(cn, fragmentCSS);
  6778. }
  6779. }
  6780. i++;
  6781. }
  6782. elementHandlers.outY = renderer.y;
  6783. if (isBlock) {
  6784. return renderer.setBlockBoundary(cb);
  6785. }
  6786. };
  6787. images = {};
  6788. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  6789. var imgs = element.getElementsByTagName('img'),
  6790. l = imgs.length,
  6791. found_images,
  6792. x = 0;
  6793. function done() {
  6794. renderer.pdf.internal.events.publish('imagesLoaded');
  6795. cb(found_images);
  6796. }
  6797. function loadImage(url, width, height) {
  6798. if (!url) return;
  6799. var img = new Image();
  6800. found_images = ++x;
  6801. img.crossOrigin = '';
  6802. img.onerror = img.onload = function () {
  6803. if (img.complete) {
  6804. //to support data urls in images, set width and height
  6805. //as those values are not recognized automatically
  6806. if (img.src.indexOf('data:image/') === 0) {
  6807. img.width = width || img.width || 0;
  6808. img.height = height || img.height || 0;
  6809. }
  6810. //if valid image add to known images array
  6811. if (img.width + img.height) {
  6812. var hash = renderer.pdf.sHashCode(url) || url;
  6813. images[hash] = images[hash] || img;
  6814. }
  6815. }
  6816. if (! --x) {
  6817. done();
  6818. }
  6819. };
  6820. img.src = url;
  6821. }
  6822. while (l--) {
  6823. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  6824. }return x || done();
  6825. };
  6826. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  6827. //check if we can found a <footer> element
  6828. var footer = elem.getElementsByTagName("footer");
  6829. if (footer.length > 0) {
  6830. footer = footer[0];
  6831. //bad hack to get height of footer
  6832. //creat dummy out and check new y after fake rendering
  6833. var oldOut = renderer.pdf.internal.write;
  6834. var oldY = renderer.y;
  6835. renderer.pdf.internal.write = function () {};
  6836. _DrillForContent(footer, renderer, elementHandlers);
  6837. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  6838. renderer.y = oldY;
  6839. renderer.pdf.internal.write = oldOut;
  6840. //add 20% to prevent overlapping
  6841. renderer.pdf.margins_doc.bottom += footerHeight;
  6842. //Create function render header on every page
  6843. var renderFooter = function renderFooter(pageInfo) {
  6844. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
  6845. //set current y position to old margin
  6846. var oldPosition = renderer.y;
  6847. //render all child nodes of the header element
  6848. renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
  6849. renderer.pdf.margins_doc.bottom -= footerHeight;
  6850. //check if we have to add page numbers
  6851. var spans = footer.getElementsByTagName('span');
  6852. for (var i = 0; i < spans.length; ++i) {
  6853. //if we find some span element with class pageCounter, set the page
  6854. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  6855. spans[i].innerHTML = pageNumber;
  6856. }
  6857. //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  6858. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6859. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  6860. }
  6861. }
  6862. //render footer content
  6863. _DrillForContent(footer, renderer, elementHandlers);
  6864. //set bottom margin to previous height including the footer height
  6865. renderer.pdf.margins_doc.bottom += footerHeight;
  6866. //important for other plugins (e.g. table) to start rendering at correct position after header
  6867. renderer.y = oldPosition;
  6868. };
  6869. //check if footer contains totalPages which should be replace at the disoposal of the document
  6870. var spans = footer.getElementsByTagName('span');
  6871. for (var i = 0; i < spans.length; ++i) {
  6872. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6873. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  6874. }
  6875. }
  6876. //register event to render footer on every new page
  6877. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
  6878. //render footer on first page
  6879. renderFooter();
  6880. //prevent footer rendering
  6881. SkipNode['FOOTER'] = 1;
  6882. }
  6883. };
  6884. process = function process(pdf, element, x, y, settings, callback) {
  6885. if (!element) return false;
  6886. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  6887. if (typeof element === "string") {
  6888. element = function (element) {
  6889. var $frame, $hiddendiv, framename, visuallyhidden;
  6890. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  6891. 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;";
  6892. $hiddendiv = document.createElement('div');
  6893. $hiddendiv.style.cssText = visuallyhidden;
  6894. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  6895. document.body.appendChild($hiddendiv);
  6896. $frame = window.frames[framename];
  6897. $frame.document.open();
  6898. $frame.document.writeln(element);
  6899. $frame.document.close();
  6900. return $frame.document.body;
  6901. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  6902. }
  6903. var r = new Renderer(pdf, x, y, settings),
  6904. out;
  6905. // 1. load images
  6906. // 2. prepare optional footer elements
  6907. // 3. render content
  6908. loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
  6909. checkForFooter(element, r, settings.elementHandlers);
  6910. _DrillForContent(element, r, settings.elementHandlers);
  6911. //send event dispose for final taks (e.g. footer totalpage replacement)
  6912. r.pdf.internal.events.publish('htmlRenderingFinished');
  6913. out = r.dispose();
  6914. if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  6915. });
  6916. return out || { x: r.x, y: r.y };
  6917. };
  6918. Renderer.prototype.init = function () {
  6919. this.paragraph = {
  6920. text: [],
  6921. style: []
  6922. };
  6923. return this.pdf.internal.write("q");
  6924. };
  6925. Renderer.prototype.dispose = function () {
  6926. this.pdf.internal.write("Q");
  6927. return {
  6928. x: this.x,
  6929. y: this.y,
  6930. ready: true
  6931. };
  6932. };
  6933. //Checks if we have to execute some watcher functions
  6934. //e.g. to end text floating around an image
  6935. Renderer.prototype.executeWatchFunctions = function (el) {
  6936. var ret = false;
  6937. var narray = [];
  6938. if (this.watchFunctions.length > 0) {
  6939. for (var i = 0; i < this.watchFunctions.length; ++i) {
  6940. if (this.watchFunctions[i](el) === true) {
  6941. ret = true;
  6942. } else {
  6943. narray.push(this.watchFunctions[i]);
  6944. }
  6945. }
  6946. this.watchFunctions = narray;
  6947. }
  6948. return ret;
  6949. };
  6950. Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
  6951. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  6952. defaultFontSize = 12;
  6953. k = this.pdf.internal.scaleFactor;
  6954. fontMetricsCache = {};
  6955. ff = void 0;
  6956. fs = void 0;
  6957. fontMetrics = void 0;
  6958. fragment = void 0;
  6959. style = void 0;
  6960. fragmentSpecificMetrics = void 0;
  6961. fragmentLength = void 0;
  6962. fragmentChopped = void 0;
  6963. line = [];
  6964. lines = [line];
  6965. currentLineLength = 0;
  6966. maxLineLength = this.settings.width;
  6967. while (fragments.length) {
  6968. fragment = fragments.shift();
  6969. style = styles.shift();
  6970. if (fragment) {
  6971. ff = style["font-family"];
  6972. fs = style["font-style"];
  6973. fontMetrics = fontMetricsCache[ff + fs];
  6974. if (!fontMetrics) {
  6975. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  6976. fontMetricsCache[ff + fs] = fontMetrics;
  6977. }
  6978. fragmentSpecificMetrics = {
  6979. widths: fontMetrics.widths,
  6980. kerning: fontMetrics.kerning,
  6981. fontSize: style["font-size"] * defaultFontSize,
  6982. textIndent: currentLineLength
  6983. };
  6984. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6985. if (fragment == "\u2028") {
  6986. line = [];
  6987. lines.push(line);
  6988. } else if (currentLineLength + fragmentLength > maxLineLength) {
  6989. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  6990. line.push([fragmentChopped.shift(), style]);
  6991. while (fragmentChopped.length) {
  6992. line = [[fragmentChopped.shift(), style]];
  6993. lines.push(line);
  6994. }
  6995. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6996. } else {
  6997. line.push([fragment, style]);
  6998. currentLineLength += fragmentLength;
  6999. }
  7000. }
  7001. }
  7002. //if text alignment was set, set margin/indent of each line
  7003. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  7004. for (var i = 0; i < lines.length; ++i) {
  7005. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  7006. //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  7007. if (i > 0) {
  7008. lines[i][0][1] = clone(lines[i][0][1]);
  7009. }
  7010. var space = maxLineLength - length;
  7011. if (style['text-align'] === 'right') {
  7012. lines[i][0][1]['margin-left'] = space;
  7013. //if alignment is not right, it has to be center so split the space to the left and the right
  7014. } else if (style['text-align'] === 'center') {
  7015. lines[i][0][1]['margin-left'] = space / 2;
  7016. //if justify was set, calculate the word spacing and define in by using the css property
  7017. } else if (style['text-align'] === 'justify') {
  7018. var countSpaces = lines[i][0][0].split(' ').length - 1;
  7019. lines[i][0][1]['word-spacing'] = space / countSpaces;
  7020. //ignore the last line in justify mode
  7021. if (i === lines.length - 1) {
  7022. lines[i][0][1]['word-spacing'] = 0;
  7023. }
  7024. }
  7025. }
  7026. }
  7027. return lines;
  7028. };
  7029. Renderer.prototype.RenderTextFragment = function (text, style) {
  7030. var defaultFontSize, font, maxLineHeight;
  7031. maxLineHeight = 0;
  7032. defaultFontSize = 12;
  7033. if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  7034. this.pdf.internal.write("ET", "Q");
  7035. this.pdf.addPage();
  7036. this.y = this.pdf.margins_doc.top;
  7037. this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
  7038. //move cursor by one line on new page
  7039. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  7040. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7041. }
  7042. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  7043. // text color
  7044. var pdfTextColor = this.getPdfColor(style["color"]);
  7045. if (pdfTextColor !== this.lastTextColor) {
  7046. this.pdf.internal.write(pdfTextColor);
  7047. this.lastTextColor = pdfTextColor;
  7048. }
  7049. //set the word spacing for e.g. justify style
  7050. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  7051. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  7052. }
  7053. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  7054. //set the word spacing back to neutral => 0
  7055. if (style['word-spacing'] !== undefined) {
  7056. this.pdf.internal.write(0, "Tw");
  7057. }
  7058. };
  7059. // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  7060. Renderer.prototype.getPdfColor = function (style) {
  7061. var textColor;
  7062. var r, g, b;
  7063. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  7064. var m = rx.exec(style);
  7065. if (m != null) {
  7066. r = parseInt(m[1]);
  7067. g = parseInt(m[2]);
  7068. b = parseInt(m[3]);
  7069. } else {
  7070. if (style.charAt(0) != '#') {
  7071. style = CssColors.colorNameToHex(style);
  7072. if (!style) {
  7073. style = '#000000';
  7074. }
  7075. }
  7076. r = style.substring(1, 3);
  7077. r = parseInt(r, 16);
  7078. g = style.substring(3, 5);
  7079. g = parseInt(g, 16);
  7080. b = style.substring(5, 7);
  7081. b = parseInt(b, 16);
  7082. }
  7083. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  7084. var hex = parseInt(r.substr(1), 16);
  7085. r = hex >> 16 & 255;
  7086. g = hex >> 8 & 255;
  7087. b = hex & 255;
  7088. }
  7089. var f3 = this.f3;
  7090. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  7091. textColor = f3(r / 255) + ' g';
  7092. } else {
  7093. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  7094. }
  7095. return textColor;
  7096. };
  7097. Renderer.prototype.f3 = function (number) {
  7098. return number.toFixed(3); // Ie, %.3f
  7099. }, Renderer.prototype.renderParagraph = function (cb) {
  7100. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  7101. fragments = PurgeWhiteSpace(this.paragraph.text);
  7102. styles = this.paragraph.style;
  7103. blockstyle = this.paragraph.blockstyle;
  7104. priorblockstyle = this.paragraph.priorblockstyle || {};
  7105. this.paragraph = {
  7106. text: [],
  7107. style: [],
  7108. blockstyle: {},
  7109. priorblockstyle: blockstyle
  7110. };
  7111. if (!fragments.join("").trim()) {
  7112. return;
  7113. }
  7114. lines = this.splitFragmentsIntoLines(fragments, styles);
  7115. line = void 0;
  7116. maxLineHeight = void 0;
  7117. defaultFontSize = 12;
  7118. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  7119. this.priorMarginBottom = this.priorMarginBottom || 0;
  7120. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7121. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  7122. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  7123. if (blockstyle['page-break-before'] === 'always') {
  7124. this.pdf.addPage();
  7125. this.y = 0;
  7126. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7127. }
  7128. out = this.pdf.internal.write;
  7129. i = void 0;
  7130. l = void 0;
  7131. this.y += paragraphspacing_before;
  7132. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7133. //stores the current indent of cursor position
  7134. var currentIndent = 0;
  7135. while (lines.length) {
  7136. line = lines.shift();
  7137. maxLineHeight = 0;
  7138. i = 0;
  7139. l = line.length;
  7140. while (i !== l) {
  7141. if (line[i][0].trim()) {
  7142. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  7143. fontSize = line[i][1]["font-size"] * 7;
  7144. }
  7145. i++;
  7146. }
  7147. //if we have to move the cursor to adapt the indent
  7148. var indentMove = 0;
  7149. var wantedIndent = 0;
  7150. //if a margin was added (by e.g. a text-alignment), move the cursor
  7151. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  7152. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  7153. indentMove = wantedIndent - currentIndent;
  7154. currentIndent = wantedIndent;
  7155. }
  7156. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
  7157. //move the cursor
  7158. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7159. i = 0;
  7160. l = line.length;
  7161. while (i !== l) {
  7162. if (line[i][0]) {
  7163. this.RenderTextFragment(line[i][0], line[i][1]);
  7164. }
  7165. i++;
  7166. }
  7167. this.y += maxLineHeight * fontToUnitRatio;
  7168. //if some watcher function was executed successful, so e.g. margin and widths were changed,
  7169. //reset line drawing and calculate position and lines again
  7170. //e.g. to stop text floating around an image
  7171. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  7172. var localFragments = [];
  7173. var localStyles = [];
  7174. //create fragment array of
  7175. lines.forEach(function (localLine) {
  7176. var i = 0;
  7177. var l = localLine.length;
  7178. while (i !== l) {
  7179. if (localLine[i][0]) {
  7180. localFragments.push(localLine[i][0] + ' ');
  7181. localStyles.push(localLine[i][1]);
  7182. }
  7183. ++i;
  7184. }
  7185. });
  7186. //split lines again due to possible coordinate changes
  7187. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
  7188. //reposition the current cursor
  7189. out("ET", "Q");
  7190. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7191. }
  7192. }
  7193. if (cb && typeof cb === "function") {
  7194. cb.call(this, this.x - 9, this.y - fontSize / 2);
  7195. }
  7196. out("ET", "Q");
  7197. return this.y += paragraphspacing_after;
  7198. };
  7199. Renderer.prototype.setBlockBoundary = function (cb) {
  7200. return this.renderParagraph(cb);
  7201. };
  7202. Renderer.prototype.setBlockStyle = function (css) {
  7203. return this.paragraph.blockstyle = css;
  7204. };
  7205. Renderer.prototype.addText = function (text, css) {
  7206. this.paragraph.text.push(text);
  7207. return this.paragraph.style.push(css);
  7208. };
  7209. FontNameDB = {
  7210. helvetica: "helvetica",
  7211. "sans-serif": "helvetica",
  7212. "times new roman": "times",
  7213. serif: "times",
  7214. times: "times",
  7215. monospace: "courier",
  7216. courier: "courier"
  7217. };
  7218. FontWeightMap = {
  7219. 100: "normal",
  7220. 200: "normal",
  7221. 300: "normal",
  7222. 400: "normal",
  7223. 500: "bold",
  7224. 600: "bold",
  7225. 700: "bold",
  7226. 800: "bold",
  7227. 900: "bold",
  7228. normal: "normal",
  7229. bold: "bold",
  7230. bolder: "bold",
  7231. lighter: "normal"
  7232. };
  7233. FontStyleMap = {
  7234. normal: "normal",
  7235. italic: "italic",
  7236. oblique: "italic"
  7237. };
  7238. TextAlignMap = {
  7239. left: "left",
  7240. right: "right",
  7241. center: "center",
  7242. justify: "justify"
  7243. };
  7244. FloatMap = {
  7245. none: 'none',
  7246. right: 'right',
  7247. left: 'left'
  7248. };
  7249. ClearMap = {
  7250. none: 'none',
  7251. both: 'both'
  7252. };
  7253. UnitedNumberMap = {
  7254. normal: 1
  7255. };
  7256. /**
  7257. * Converts HTML-formatted text into formatted PDF text.
  7258. *
  7259. * Notes:
  7260. * 2012-07-18
  7261. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  7262. * Plugin relies on jQuery for CSS extraction.
  7263. * Targeting HTML output from Markdown templating, which is a very simple
  7264. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  7265. * Images, tables are NOT supported.
  7266. *
  7267. * @public
  7268. * @function
  7269. * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  7270. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  7271. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  7272. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  7273. * @returns {Object} jsPDF instance
  7274. */
  7275. jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
  7276. "use strict";
  7277. this.margins_doc = margins || {
  7278. top: 0,
  7279. bottom: 0
  7280. };
  7281. if (!settings) settings = {};
  7282. if (!settings.elementHandlers) settings.elementHandlers = {};
  7283. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  7284. };
  7285. })(jsPDF.API);
  7286. /** ====================================================================
  7287. * jsPDF JavaScript plugin
  7288. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  7289. *
  7290. *
  7291. * ====================================================================
  7292. */
  7293. /*global jsPDF */
  7294. (function (jsPDFAPI) {
  7295. 'use strict';
  7296. var jsNamesObj, jsJsObj, text;
  7297. jsPDFAPI.addJS = function (txt) {
  7298. text = txt;
  7299. this.internal.events.subscribe('postPutResources', function (txt) {
  7300. jsNamesObj = this.internal.newObject();
  7301. this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
  7302. jsJsObj = this.internal.newObject();
  7303. this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
  7304. });
  7305. this.internal.events.subscribe('putCatalog', function () {
  7306. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  7307. this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  7308. }
  7309. });
  7310. return this;
  7311. };
  7312. })(jsPDF.API);
  7313. /**
  7314. * jsPDF Outline PlugIn
  7315. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7316. *
  7317. * Licensed under the MIT License.
  7318. * http://opensource.org/licenses/mit-license
  7319. */
  7320. /**
  7321. * Generates a PDF Outline
  7322. */
  7323. (function (jsPDFAPI) {
  7324. 'use strict';
  7325. jsPDFAPI.events.push(['postPutResources', function () {
  7326. var pdf = this;
  7327. var rx = /^(\d+) 0 obj$/;
  7328. // Write action goto objects for each page
  7329. // this.outline.destsGoto = [];
  7330. // for (var i = 0; i < totalPages; i++) {
  7331. // var id = pdf.internal.newObject();
  7332. // this.outline.destsGoto.push(id);
  7333. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  7334. // null null]/S/GoTo>> endobj");
  7335. // }
  7336. //
  7337. // for (var i = 0; i < dests.length; i++) {
  7338. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  7339. // R");
  7340. // }
  7341. //
  7342. if (this.outline.root.children.length > 0) {
  7343. var lines = pdf.outline.render().split(/\r\n/);
  7344. for (var i = 0; i < lines.length; i++) {
  7345. var line = lines[i];
  7346. var m = rx.exec(line);
  7347. if (m != null) {
  7348. var oid = m[1];
  7349. pdf.internal.newObjectDeferredBegin(oid);
  7350. }
  7351. pdf.internal.write(line);
  7352. }
  7353. }
  7354. // This code will write named destination for each page reference
  7355. // (page_1, etc)
  7356. if (this.outline.createNamedDestinations) {
  7357. var totalPages = this.internal.pages.length;
  7358. // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  7359. // follow 5, 7, 9, etc
  7360. // Write destination objects for each page
  7361. var dests = [];
  7362. for (var i = 0; i < totalPages; i++) {
  7363. var id = pdf.internal.newObject();
  7364. dests.push(id);
  7365. var info = pdf.internal.getPageInfo(i + 1);
  7366. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  7367. }
  7368. // assign a name for each destination
  7369. var names2Oid = pdf.internal.newObject();
  7370. pdf.internal.write('<< /Names [ ');
  7371. for (var i = 0; i < dests.length; i++) {
  7372. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  7373. }
  7374. pdf.internal.write(' ] >>', 'endobj');
  7375. // var kids = pdf.internal.newObject();
  7376. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  7377. // pdf.internal.write(' ] >>', 'endobj');
  7378. var namesOid = pdf.internal.newObject();
  7379. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  7380. pdf.internal.write('>>', 'endobj');
  7381. }
  7382. }]);
  7383. jsPDFAPI.events.push(['putCatalog', function () {
  7384. var pdf = this;
  7385. if (pdf.outline.root.children.length > 0) {
  7386. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  7387. if (this.outline.createNamedDestinations) {
  7388. pdf.internal.write("/Names " + namesOid + " 0 R");
  7389. }
  7390. // Open with Bookmarks showing
  7391. // pdf.internal.write("/PageMode /UseOutlines");
  7392. }
  7393. }]);
  7394. jsPDFAPI.events.push(['initialized', function () {
  7395. var pdf = this;
  7396. pdf.outline = {
  7397. createNamedDestinations: false,
  7398. root: {
  7399. children: []
  7400. }
  7401. };
  7402. var namesOid;
  7403. var destsGoto = [];
  7404. /**
  7405. * Options: pageNumber
  7406. */
  7407. pdf.outline.add = function (parent, title, options) {
  7408. var item = {
  7409. title: title,
  7410. options: options,
  7411. children: []
  7412. };
  7413. if (parent == null) {
  7414. parent = this.root;
  7415. }
  7416. parent.children.push(item);
  7417. return item;
  7418. };
  7419. pdf.outline.render = function () {
  7420. this.ctx = {};
  7421. this.ctx.val = '';
  7422. this.ctx.pdf = pdf;
  7423. this.genIds_r(this.root);
  7424. this.renderRoot(this.root);
  7425. this.renderItems(this.root);
  7426. return this.ctx.val;
  7427. };
  7428. pdf.outline.genIds_r = function (node) {
  7429. node.id = pdf.internal.newObjectDeferred();
  7430. for (var i = 0; i < node.children.length; i++) {
  7431. this.genIds_r(node.children[i]);
  7432. }
  7433. };
  7434. pdf.outline.renderRoot = function (node) {
  7435. this.objStart(node);
  7436. this.line('/Type /Outlines');
  7437. if (node.children.length > 0) {
  7438. this.line('/First ' + this.makeRef(node.children[0]));
  7439. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  7440. }
  7441. this.line('/Count ' + this.count_r({
  7442. count: 0
  7443. }, node));
  7444. this.objEnd();
  7445. };
  7446. pdf.outline.renderItems = function (node) {
  7447. for (var i = 0; i < node.children.length; i++) {
  7448. var item = node.children[i];
  7449. this.objStart(item);
  7450. this.line('/Title ' + this.makeString(item.title));
  7451. this.line('/Parent ' + this.makeRef(node));
  7452. if (i > 0) {
  7453. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  7454. }
  7455. if (i < node.children.length - 1) {
  7456. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  7457. }
  7458. if (item.children.length > 0) {
  7459. this.line('/First ' + this.makeRef(item.children[0]));
  7460. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  7461. }
  7462. var count = this.count = this.count_r({
  7463. count: 0
  7464. }, item);
  7465. if (count > 0) {
  7466. this.line('/Count ' + count);
  7467. }
  7468. if (item.options) {
  7469. if (item.options.pageNumber) {
  7470. // Explicit Destination
  7471. //WARNING this assumes page ids are 3,5,7, etc.
  7472. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  7473. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7474. // this line does not work on all clients (pageNumber instead of page ref)
  7475. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7476. // Named Destination
  7477. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  7478. // Action Destination
  7479. // var id = pdf.internal.newObject();
  7480. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  7481. // this.line('/A ' + id + ' 0 R' );
  7482. }
  7483. }
  7484. this.objEnd();
  7485. }
  7486. for (var i = 0; i < node.children.length; i++) {
  7487. var item = node.children[i];
  7488. this.renderItems(item);
  7489. }
  7490. };
  7491. pdf.outline.line = function (text) {
  7492. this.ctx.val += text + '\r\n';
  7493. };
  7494. pdf.outline.makeRef = function (node) {
  7495. return node.id + ' 0 R';
  7496. };
  7497. pdf.outline.makeString = function (val) {
  7498. return '(' + pdf.internal.pdfEscape(val) + ')';
  7499. };
  7500. pdf.outline.objStart = function (node) {
  7501. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  7502. };
  7503. pdf.outline.objEnd = function (node) {
  7504. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  7505. };
  7506. pdf.outline.count_r = function (ctx, node) {
  7507. for (var i = 0; i < node.children.length; i++) {
  7508. ctx.count++;
  7509. this.count_r(ctx, node.children[i]);
  7510. }
  7511. return ctx.count;
  7512. };
  7513. }]);
  7514. return this;
  7515. })(jsPDF.API);
  7516. /**@preserve
  7517. * ====================================================================
  7518. * jsPDF PNG PlugIn
  7519. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  7520. *
  7521. *
  7522. * ====================================================================
  7523. */
  7524. (function (jsPDFAPI) {
  7525. 'use strict';
  7526. /*
  7527. * @see http://www.w3.org/TR/PNG-Chunks.html
  7528. *
  7529. Color Allowed Interpretation
  7530. Type Bit Depths
  7531. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  7532. 2 8,16 Each pixel is an R,G,B triple.
  7533. 3 1,2,4,8 Each pixel is a palette index;
  7534. a PLTE chunk must appear.
  7535. 4 8,16 Each pixel is a grayscale sample,
  7536. followed by an alpha sample.
  7537. 6 8,16 Each pixel is an R,G,B triple,
  7538. followed by an alpha sample.
  7539. */
  7540. /*
  7541. * PNG filter method types
  7542. *
  7543. * @see http://www.w3.org/TR/PNG-Filters.html
  7544. * @see http://www.libpng.org/pub/png/book/chapter09.html
  7545. *
  7546. * This is what the value 'Predictor' in decode params relates to
  7547. *
  7548. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  7549. * 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.
  7550. *
  7551. 0 None
  7552. 1 Sub
  7553. 2 Up
  7554. 3 Average
  7555. 4 Paeth
  7556. */
  7557. var doesNotHavePngJS = function doesNotHavePngJS() {
  7558. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  7559. },
  7560. canCompress = function canCompress(value) {
  7561. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  7562. },
  7563. hasCompressionJS = function hasCompressionJS() {
  7564. var inst = typeof Deflater === 'function';
  7565. if (!inst) throw new Error("requires deflate.js for compression");
  7566. return inst;
  7567. },
  7568. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  7569. var level = 5,
  7570. filter_method = filterUp;
  7571. switch (compression) {
  7572. case jsPDFAPI.image_compression.FAST:
  7573. level = 3;
  7574. filter_method = filterSub;
  7575. break;
  7576. case jsPDFAPI.image_compression.MEDIUM:
  7577. level = 6;
  7578. filter_method = filterAverage;
  7579. break;
  7580. case jsPDFAPI.image_compression.SLOW:
  7581. level = 9;
  7582. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  7583. break;
  7584. }
  7585. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  7586. var header = new Uint8Array(createZlibHeader(level));
  7587. var checksum = adler32(bytes);
  7588. var deflate = new Deflater(level);
  7589. var a = deflate.append(bytes);
  7590. var cBytes = deflate.flush();
  7591. var len = header.length + a.length + cBytes.length;
  7592. var cmpd = new Uint8Array(len + 4);
  7593. cmpd.set(header);
  7594. cmpd.set(a, header.length);
  7595. cmpd.set(cBytes, header.length + a.length);
  7596. cmpd[len++] = checksum >>> 24 & 0xff;
  7597. cmpd[len++] = checksum >>> 16 & 0xff;
  7598. cmpd[len++] = checksum >>> 8 & 0xff;
  7599. cmpd[len++] = checksum & 0xff;
  7600. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  7601. },
  7602. createZlibHeader = function createZlibHeader(bytes, level) {
  7603. /*
  7604. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  7605. */
  7606. var cm = 8;
  7607. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  7608. var cmf = cinfo << 4 | cm;
  7609. var hdr = cmf << 8;
  7610. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  7611. hdr |= flevel << 6;
  7612. hdr |= 0; //FDICT
  7613. hdr += 31 - hdr % 31;
  7614. return [cmf, hdr & 0xff & 0xff];
  7615. },
  7616. adler32 = function adler32(array, param) {
  7617. var adler = 1;
  7618. var s1 = adler & 0xffff,
  7619. s2 = adler >>> 16 & 0xffff;
  7620. var len = array.length;
  7621. var tlen;
  7622. var i = 0;
  7623. while (len > 0) {
  7624. tlen = len > param ? param : len;
  7625. len -= tlen;
  7626. do {
  7627. s1 += array[i++];
  7628. s2 += s1;
  7629. } while (--tlen);
  7630. s1 %= 65521;
  7631. s2 %= 65521;
  7632. }
  7633. return (s2 << 16 | s1) >>> 0;
  7634. },
  7635. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  7636. var lines = bytes.length / lineLength,
  7637. result = new Uint8Array(bytes.length + lines),
  7638. filter_methods = getFilterMethods(),
  7639. i = 0,
  7640. line,
  7641. prevLine,
  7642. offset;
  7643. for (; i < lines; i++) {
  7644. offset = i * lineLength;
  7645. line = bytes.subarray(offset, offset + lineLength);
  7646. if (filter_method) {
  7647. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  7648. } else {
  7649. var j = 0,
  7650. len = filter_methods.length,
  7651. results = [];
  7652. for (; j < len; j++) {
  7653. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  7654. }var ind = getIndexOfSmallestSum(results.concat());
  7655. result.set(results[ind], offset + i);
  7656. }
  7657. prevLine = line;
  7658. }
  7659. return result;
  7660. },
  7661. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  7662. /*var result = new Uint8Array(line.length + 1);
  7663. result[0] = 0;
  7664. result.set(line, 1);*/
  7665. var result = Array.apply([], line);
  7666. result.unshift(0);
  7667. return result;
  7668. },
  7669. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  7670. var result = [],
  7671. i = 0,
  7672. len = line.length,
  7673. left;
  7674. result[0] = 1;
  7675. for (; i < len; i++) {
  7676. left = line[i - colorsPerPixel] || 0;
  7677. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  7678. }
  7679. return result;
  7680. },
  7681. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  7682. var result = [],
  7683. i = 0,
  7684. len = line.length,
  7685. up;
  7686. result[0] = 2;
  7687. for (; i < len; i++) {
  7688. up = prevLine && prevLine[i] || 0;
  7689. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  7690. }
  7691. return result;
  7692. },
  7693. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  7694. var result = [],
  7695. i = 0,
  7696. len = line.length,
  7697. left,
  7698. up;
  7699. result[0] = 3;
  7700. for (; i < len; i++) {
  7701. left = line[i - colorsPerPixel] || 0;
  7702. up = prevLine && prevLine[i] || 0;
  7703. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  7704. }
  7705. return result;
  7706. },
  7707. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  7708. var result = [],
  7709. i = 0,
  7710. len = line.length,
  7711. left,
  7712. up,
  7713. upLeft,
  7714. paeth;
  7715. result[0] = 4;
  7716. for (; i < len; i++) {
  7717. left = line[i - colorsPerPixel] || 0;
  7718. up = prevLine && prevLine[i] || 0;
  7719. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  7720. paeth = paethPredictor(left, up, upLeft);
  7721. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  7722. }
  7723. return result;
  7724. },
  7725. paethPredictor = function paethPredictor(left, up, upLeft) {
  7726. var p = left + up - upLeft,
  7727. pLeft = Math.abs(p - left),
  7728. pUp = Math.abs(p - up),
  7729. pUpLeft = Math.abs(p - upLeft);
  7730. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  7731. },
  7732. getFilterMethods = function getFilterMethods() {
  7733. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  7734. },
  7735. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  7736. var i = 0,
  7737. len = arrays.length,
  7738. sum,
  7739. min,
  7740. ind;
  7741. while (i < len) {
  7742. sum = absSum(arrays[i].slice(1));
  7743. if (sum < min || !min) {
  7744. min = sum;
  7745. ind = i;
  7746. }
  7747. i++;
  7748. }
  7749. return ind;
  7750. },
  7751. absSum = function absSum(array) {
  7752. var i = 0,
  7753. len = array.length,
  7754. sum = 0;
  7755. while (i < len) {
  7756. sum += Math.abs(array[i++]);
  7757. }return sum;
  7758. },
  7759. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  7760. var predictor;
  7761. switch (compression) {
  7762. case jsPDFAPI.image_compression.FAST:
  7763. predictor = 11;
  7764. break;
  7765. case jsPDFAPI.image_compression.MEDIUM:
  7766. predictor = 13;
  7767. break;
  7768. case jsPDFAPI.image_compression.SLOW:
  7769. predictor = 14;
  7770. break;
  7771. default:
  7772. predictor = 12;
  7773. break;
  7774. }
  7775. return predictor;
  7776. },
  7777. logImg = function logImg(img) {
  7778. console.log("width: " + img.width);
  7779. console.log("height: " + img.height);
  7780. console.log("bits: " + img.bits);
  7781. console.log("colorType: " + img.colorType);
  7782. console.log("transparency:");
  7783. console.log(img.transparency);
  7784. console.log("text:");
  7785. console.log(img.text);
  7786. console.log("compressionMethod: " + img.compressionMethod);
  7787. console.log("filterMethod: " + img.filterMethod);
  7788. console.log("interlaceMethod: " + img.interlaceMethod);
  7789. console.log("imgData:");
  7790. console.log(img.imgData);
  7791. console.log("palette:");
  7792. console.log(img.palette);
  7793. console.log("colors: " + img.colors);
  7794. console.log("colorSpace: " + img.colorSpace);
  7795. console.log("pixelBitlength: " + img.pixelBitlength);
  7796. console.log("hasAlphaChannel: " + img.hasAlphaChannel);
  7797. };
  7798. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  7799. 'use strict';
  7800. var colorSpace = this.color_spaces.DEVICE_RGB,
  7801. decode = this.decode.FLATE_DECODE,
  7802. bpc = 8,
  7803. img,
  7804. dp,
  7805. trns,
  7806. colors,
  7807. pal,
  7808. smask;
  7809. /* if(this.isString(imageData)) {
  7810. }*/
  7811. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  7812. if (this.isArrayBufferView(imageData)) {
  7813. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  7814. img = new PNG(imageData);
  7815. imageData = img.imgData;
  7816. bpc = img.bits;
  7817. colorSpace = img.colorSpace;
  7818. colors = img.colors;
  7819. //logImg(img);
  7820. /*
  7821. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  7822. *
  7823. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  7824. *
  7825. * Extract alpha to create two separate images, using the alpha as a sMask
  7826. */
  7827. if ([4, 6].indexOf(img.colorType) !== -1) {
  7828. /*
  7829. * processes 8 bit RGBA and grayscale + alpha images
  7830. */
  7831. if (img.bits === 8) {
  7832. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  7833. len = pixels.length,
  7834. imgData = new Uint8Array(len * img.colors),
  7835. alphaData = new Uint8Array(len),
  7836. pDiff = img.pixelBitlength - img.bits,
  7837. i = 0,
  7838. n = 0,
  7839. pixel,
  7840. pbl;
  7841. for (; i < len; i++) {
  7842. pixel = pixels[i];
  7843. pbl = 0;
  7844. while (pbl < pDiff) {
  7845. imgData[n++] = pixel >>> pbl & 0xff;
  7846. pbl = pbl + img.bits;
  7847. }
  7848. alphaData[i] = pixel >>> pbl & 0xff;
  7849. }
  7850. }
  7851. /*
  7852. * processes 16 bit RGBA and grayscale + alpha images
  7853. */
  7854. if (img.bits === 16) {
  7855. var pixels = new Uint32Array(img.decodePixels().buffer),
  7856. len = pixels.length,
  7857. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  7858. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  7859. hasColors = img.colors > 1,
  7860. i = 0,
  7861. n = 0,
  7862. a = 0,
  7863. pixel;
  7864. while (i < len) {
  7865. pixel = pixels[i++];
  7866. imgData[n++] = pixel >>> 0 & 0xFF;
  7867. if (hasColors) {
  7868. imgData[n++] = pixel >>> 16 & 0xFF;
  7869. pixel = pixels[i++];
  7870. imgData[n++] = pixel >>> 0 & 0xFF;
  7871. }
  7872. alphaData[a++] = pixel >>> 16 & 0xFF;
  7873. }
  7874. bpc = 8;
  7875. }
  7876. if (canCompress(compression)) {
  7877. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  7878. smask = compressBytes(alphaData, img.width, 1, compression);
  7879. } else {
  7880. imageData = imgData;
  7881. smask = alphaData;
  7882. decode = null;
  7883. }
  7884. }
  7885. /*
  7886. * Indexed png. Each pixel is a palette index.
  7887. */
  7888. if (img.colorType === 3) {
  7889. colorSpace = this.color_spaces.INDEXED;
  7890. pal = img.palette;
  7891. if (img.transparency.indexed) {
  7892. var trans = img.transparency.indexed;
  7893. var total = 0,
  7894. i = 0,
  7895. len = trans.length;
  7896. for (; i < len; ++i) {
  7897. total += trans[i];
  7898. }total = total / 255;
  7899. /*
  7900. * a single color is specified as 100% transparent (0),
  7901. * so we set trns to use a /Mask with that index
  7902. */
  7903. if (total === len - 1 && trans.indexOf(0) !== -1) {
  7904. trns = [trans.indexOf(0)];
  7905. /*
  7906. * there's more than one colour within the palette that specifies
  7907. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  7908. */
  7909. } else if (total !== len) {
  7910. var pixels = img.decodePixels(),
  7911. alphaData = new Uint8Array(pixels.length),
  7912. i = 0,
  7913. len = pixels.length;
  7914. for (; i < len; i++) {
  7915. alphaData[i] = trans[pixels[i]];
  7916. }smask = compressBytes(alphaData, img.width, 1);
  7917. }
  7918. }
  7919. }
  7920. var predictor = getPredictorFromCompression(compression);
  7921. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
  7922. //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  7923. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  7924. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  7925. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  7926. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  7927. }
  7928. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  7929. };
  7930. })(jsPDF.API);
  7931. /**
  7932. * jsPDF Autoprint Plugin
  7933. *
  7934. * Licensed under the MIT License.
  7935. * http://opensource.org/licenses/mit-license
  7936. */
  7937. (function (jsPDFAPI) {
  7938. 'use strict';
  7939. jsPDFAPI.autoPrint = function () {
  7940. 'use strict';
  7941. var refAutoPrintTag;
  7942. this.internal.events.subscribe('postPutResources', function () {
  7943. refAutoPrintTag = this.internal.newObject();
  7944. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  7945. });
  7946. this.internal.events.subscribe("putCatalog", function () {
  7947. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  7948. });
  7949. return this;
  7950. };
  7951. })(jsPDF.API);
  7952. /** @preserve
  7953. * jsPDF split_text_to_size plugin - MIT license.
  7954. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7955. * 2014 Diego Casorran, https://github.com/diegocr
  7956. */
  7957. /**
  7958. *
  7959. * ====================================================================
  7960. */
  7961. (function (API) {
  7962. 'use strict';
  7963. /**
  7964. Returns an array of length matching length of the 'word' string, with each
  7965. cell ocupied by the width of the char in that position.
  7966. @function
  7967. @param word {String}
  7968. @param widths {Object}
  7969. @param kerning {Object}
  7970. @returns {Array}
  7971. */
  7972. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  7973. if (!options) {
  7974. options = {};
  7975. }
  7976. var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
  7977. widthsFractionOf = widths.fof ? widths.fof : 1,
  7978. kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
  7979. kerningFractionOf = kerning.fof ? kerning.fof : 1;
  7980. // console.log("widths, kergnings", widths, kerning)
  7981. var i,
  7982. l,
  7983. char_code,
  7984. prior_char_code = 0 // for kerning
  7985. ,
  7986. default_char_width = widths[0] || widthsFractionOf,
  7987. output = [];
  7988. for (i = 0, l = text.length; i < l; i++) {
  7989. char_code = text.charCodeAt(i);
  7990. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  7991. prior_char_code = char_code;
  7992. }
  7993. return output;
  7994. };
  7995. var getArraySum = function getArraySum(array) {
  7996. var i = array.length,
  7997. output = 0;
  7998. while (i) {
  7999. i--;
  8000. output += array[i];
  8001. }
  8002. return output;
  8003. };
  8004. /**
  8005. Returns a widths of string in a given font, if the font size is set as 1 point.
  8006. In other words, this is "proportional" value. For 1 unit of font size, the length
  8007. of the string will be that much.
  8008. Multiply by font size to get actual width in *points*
  8009. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  8010. @public
  8011. @function
  8012. @param
  8013. @returns {Type}
  8014. */
  8015. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  8016. return getArraySum(getCharWidthsArray.call(this, text, options));
  8017. };
  8018. /**
  8019. returns array of lines
  8020. */
  8021. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  8022. var answer = [];
  8023. // 1st, chop off the piece that can fit on the hanging line.
  8024. var i = 0,
  8025. l = word.length,
  8026. workingLen = 0;
  8027. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  8028. workingLen += widths_array[i];i++;
  8029. }
  8030. // this is first line.
  8031. answer.push(word.slice(0, i));
  8032. // 2nd. Split the rest into maxLen pieces.
  8033. var startOfLine = i;
  8034. workingLen = 0;
  8035. while (i !== l) {
  8036. if (workingLen + widths_array[i] > maxLen) {
  8037. answer.push(word.slice(startOfLine, i));
  8038. workingLen = 0;
  8039. startOfLine = i;
  8040. }
  8041. workingLen += widths_array[i];i++;
  8042. }
  8043. if (startOfLine !== i) {
  8044. answer.push(word.slice(startOfLine, i));
  8045. }
  8046. return answer;
  8047. };
  8048. // Note, all sizing inputs for this function must be in "font measurement units"
  8049. // By default, for PDF, it's "point".
  8050. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  8051. // at this time works only on Western scripts, ones with space char
  8052. // separating the words. Feel free to expand.
  8053. if (!options) {
  8054. options = {};
  8055. }
  8056. var line = [],
  8057. lines = [line],
  8058. line_length = options.textIndent || 0,
  8059. separator_length = 0,
  8060. current_word_length = 0,
  8061. word,
  8062. widths_array,
  8063. words = text.split(' '),
  8064. spaceCharWidth = getCharWidthsArray(' ', options)[0],
  8065. i,
  8066. l,
  8067. tmp,
  8068. lineIndent;
  8069. if (options.lineIndent === -1) {
  8070. lineIndent = words[0].length + 2;
  8071. } else {
  8072. lineIndent = options.lineIndent || 0;
  8073. }
  8074. if (lineIndent) {
  8075. var pad = Array(lineIndent).join(" "),
  8076. wrds = [];
  8077. words.map(function (wrd) {
  8078. wrd = wrd.split(/\s*\n/);
  8079. if (wrd.length > 1) {
  8080. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  8081. return (idx && wrd.length ? "\n" : "") + wrd;
  8082. }));
  8083. } else {
  8084. wrds.push(wrd[0]);
  8085. }
  8086. });
  8087. words = wrds;
  8088. lineIndent = getStringUnitWidth(pad, options);
  8089. }
  8090. for (i = 0, l = words.length; i < l; i++) {
  8091. var force = 0;
  8092. word = words[i];
  8093. if (lineIndent && word[0] == "\n") {
  8094. word = word.substr(1);
  8095. force = 1;
  8096. }
  8097. widths_array = getCharWidthsArray(word, options);
  8098. current_word_length = getArraySum(widths_array);
  8099. if (line_length + separator_length + current_word_length > maxlen || force) {
  8100. if (current_word_length > maxlen) {
  8101. // this happens when you have space-less long URLs for example.
  8102. // we just chop these to size. We do NOT insert hiphens
  8103. tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
  8104. // first line we add to existing line object
  8105. line.push(tmp.shift()); // it's ok to have extra space indicator there
  8106. // last line we make into new line object
  8107. line = [tmp.pop()];
  8108. // lines in the middle we apped to lines object as whole lines
  8109. while (tmp.length) {
  8110. lines.push([tmp.shift()]); // single fragment occupies whole line
  8111. }
  8112. current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
  8113. } else {
  8114. // just put it on a new line
  8115. line = [word];
  8116. }
  8117. // now we attach new line to lines
  8118. lines.push(line);
  8119. line_length = current_word_length + lineIndent;
  8120. separator_length = spaceCharWidth;
  8121. } else {
  8122. line.push(word);
  8123. line_length += separator_length + current_word_length;
  8124. separator_length = spaceCharWidth;
  8125. }
  8126. }
  8127. if (lineIndent) {
  8128. var postProcess = function postProcess(ln, idx) {
  8129. return (idx ? pad : '') + ln.join(" ");
  8130. };
  8131. } else {
  8132. var postProcess = function postProcess(ln) {
  8133. return ln.join(" ");
  8134. };
  8135. }
  8136. return lines.map(postProcess);
  8137. };
  8138. /**
  8139. Splits a given string into an array of strings. Uses 'size' value
  8140. (in measurement units declared as default for the jsPDF instance)
  8141. and the font's "widths" and "Kerning" tables, where available, to
  8142. determine display length of a given string for a given font.
  8143. We use character's 100% of unit size (height) as width when Width
  8144. table or other default width is not available.
  8145. @public
  8146. @function
  8147. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  8148. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  8149. @param options {Object} Optional flags needed for chopper to do the right thing.
  8150. @returns {Array} with strings chopped to size.
  8151. */
  8152. API.splitTextToSize = function (text, maxlen, options) {
  8153. 'use strict';
  8154. if (!options) {
  8155. options = {};
  8156. }
  8157. var fsize = options.fontSize || this.internal.getFontSize(),
  8158. newOptions = function (options) {
  8159. var widths = { 0: 1 },
  8160. kerning = {};
  8161. if (!options.widths || !options.kerning) {
  8162. var f = this.internal.getFont(options.fontName, options.fontStyle),
  8163. encoding = 'Unicode';
  8164. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  8165. // Actual JavaScript-native String's 16bit char codes used.
  8166. // no multi-byte logic here
  8167. if (f.metadata[encoding]) {
  8168. return {
  8169. widths: f.metadata[encoding].widths || widths,
  8170. kerning: f.metadata[encoding].kerning || kerning
  8171. };
  8172. }
  8173. } else {
  8174. return {
  8175. widths: options.widths,
  8176. kerning: options.kerning
  8177. };
  8178. }
  8179. // then use default values
  8180. return {
  8181. widths: widths,
  8182. kerning: kerning
  8183. };
  8184. }.call(this, options);
  8185. // first we split on end-of-line chars
  8186. var paragraphs;
  8187. if (Array.isArray(text)) {
  8188. paragraphs = text;
  8189. } else {
  8190. paragraphs = text.split(/\r?\n/);
  8191. }
  8192. // now we convert size (max length of line) into "font size units"
  8193. // at present time, the "font size unit" is always 'point'
  8194. // 'proportional' means, "in proportion to font size"
  8195. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
  8196. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  8197. // this may change in the future?
  8198. // until then, proportional_maxlen is likely to be in 'points'
  8199. // If first line is to be indented (shorter or longer) than maxLen
  8200. // we indicate that by using CSS-style "text-indent" option.
  8201. // here it's in font units too (which is likely 'points')
  8202. // it can be negative (which makes the first line longer than maxLen)
  8203. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  8204. newOptions.lineIndent = options.lineIndent;
  8205. var i,
  8206. l,
  8207. output = [];
  8208. for (i = 0, l = paragraphs.length; i < l; i++) {
  8209. output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
  8210. }
  8211. return output;
  8212. };
  8213. })(jsPDF.API);
  8214. /** @preserve
  8215. jsPDF standard_fonts_metrics plugin
  8216. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8217. MIT license.
  8218. */
  8219. /**
  8220. *
  8221. * ====================================================================
  8222. */
  8223. (function (API) {
  8224. 'use strict';
  8225. /*
  8226. # reference (Python) versions of 'compress' and 'uncompress'
  8227. # only 'uncompress' function is featured lower as JavaScript
  8228. # if you want to unit test "roundtrip", just transcribe the reference
  8229. # 'compress' function from Python into JavaScript
  8230. def compress(data):
  8231. keys = '0123456789abcdef'
  8232. values = 'klmnopqrstuvwxyz'
  8233. mapping = dict(zip(keys, values))
  8234. vals = []
  8235. for key in data.keys():
  8236. value = data[key]
  8237. try:
  8238. keystring = hex(key)[2:]
  8239. keystring = keystring[:-1] + mapping[keystring[-1:]]
  8240. except:
  8241. keystring = key.join(["'","'"])
  8242. #print('Keystring is %s' % keystring)
  8243. try:
  8244. if value < 0:
  8245. valuestring = hex(value)[3:]
  8246. numberprefix = '-'
  8247. else:
  8248. valuestring = hex(value)[2:]
  8249. numberprefix = ''
  8250. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  8251. except:
  8252. if type(value) == dict:
  8253. valuestring = compress(value)
  8254. else:
  8255. raise Exception("Don't know what to do with value type %s" % type(value))
  8256. vals.append(keystring+valuestring)
  8257. return '{' + ''.join(vals) + '}'
  8258. def uncompress(data):
  8259. decoded = '0123456789abcdef'
  8260. encoded = 'klmnopqrstuvwxyz'
  8261. mapping = dict(zip(encoded, decoded))
  8262. sign = +1
  8263. stringmode = False
  8264. stringparts = []
  8265. output = {}
  8266. activeobject = output
  8267. parentchain = []
  8268. keyparts = ''
  8269. valueparts = ''
  8270. key = None
  8271. ending = set(encoded)
  8272. i = 1
  8273. l = len(data) - 1 # stripping starting, ending {}
  8274. while i != l: # stripping {}
  8275. # -, {, }, ' are special.
  8276. ch = data[i]
  8277. i += 1
  8278. if ch == "'":
  8279. if stringmode:
  8280. # end of string mode
  8281. stringmode = False
  8282. key = ''.join(stringparts)
  8283. else:
  8284. # start of string mode
  8285. stringmode = True
  8286. stringparts = []
  8287. elif stringmode == True:
  8288. #print("Adding %s to stringpart" % ch)
  8289. stringparts.append(ch)
  8290. elif ch == '{':
  8291. # start of object
  8292. parentchain.append( [activeobject, key] )
  8293. activeobject = {}
  8294. key = None
  8295. #DEBUG = True
  8296. elif ch == '}':
  8297. # end of object
  8298. parent, key = parentchain.pop()
  8299. parent[key] = activeobject
  8300. key = None
  8301. activeobject = parent
  8302. #DEBUG = False
  8303. elif ch == '-':
  8304. sign = -1
  8305. else:
  8306. # must be number
  8307. if key == None:
  8308. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  8309. if ch in ending:
  8310. #debug("End of key")
  8311. keyparts += mapping[ch]
  8312. key = int(keyparts, 16) * sign
  8313. sign = +1
  8314. keyparts = ''
  8315. else:
  8316. keyparts += ch
  8317. else:
  8318. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  8319. if ch in ending:
  8320. #debug("End of value")
  8321. valueparts += mapping[ch]
  8322. activeobject[key] = int(valueparts, 16) * sign
  8323. sign = +1
  8324. key = None
  8325. valueparts = ''
  8326. else:
  8327. valueparts += ch
  8328. #debug(activeobject)
  8329. return output
  8330. */
  8331. /**
  8332. Uncompresses data compressed into custom, base16-like format.
  8333. @public
  8334. @function
  8335. @param
  8336. @returns {Type}
  8337. */
  8338. var uncompress = function uncompress(data) {
  8339. var decoded = '0123456789abcdef',
  8340. encoded = 'klmnopqrstuvwxyz',
  8341. mapping = {};
  8342. for (var i = 0; i < encoded.length; i++) {
  8343. mapping[encoded[i]] = decoded[i];
  8344. }
  8345. var undef,
  8346. output = {},
  8347. sign = 1,
  8348. stringparts // undef. will be [] in string mode
  8349. ,
  8350. activeobject = output,
  8351. parentchain = [],
  8352. parent_key_pair,
  8353. keyparts = '',
  8354. valueparts = '',
  8355. key // undef. will be Truthy when Key is resolved.
  8356. ,
  8357. datalen = data.length - 1 // stripping ending }
  8358. ,
  8359. ch;
  8360. i = 1; // stripping starting {
  8361. while (i != datalen) {
  8362. // - { } ' are special.
  8363. ch = data[i];
  8364. i += 1;
  8365. if (ch == "'") {
  8366. if (stringparts) {
  8367. // end of string mode
  8368. key = stringparts.join('');
  8369. stringparts = undef;
  8370. } else {
  8371. // start of string mode
  8372. stringparts = [];
  8373. }
  8374. } else if (stringparts) {
  8375. stringparts.push(ch);
  8376. } else if (ch == '{') {
  8377. // start of object
  8378. parentchain.push([activeobject, key]);
  8379. activeobject = {};
  8380. key = undef;
  8381. } else if (ch == '}') {
  8382. // end of object
  8383. parent_key_pair = parentchain.pop();
  8384. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  8385. key = undef;
  8386. activeobject = parent_key_pair[0];
  8387. } else if (ch == '-') {
  8388. sign = -1;
  8389. } else {
  8390. // must be number
  8391. if (key === undef) {
  8392. if (mapping.hasOwnProperty(ch)) {
  8393. keyparts += mapping[ch];
  8394. key = parseInt(keyparts, 16) * sign;
  8395. sign = +1;
  8396. keyparts = '';
  8397. } else {
  8398. keyparts += ch;
  8399. }
  8400. } else {
  8401. if (mapping.hasOwnProperty(ch)) {
  8402. valueparts += mapping[ch];
  8403. activeobject[key] = parseInt(valueparts, 16) * sign;
  8404. sign = +1;
  8405. key = undef;
  8406. valueparts = '';
  8407. } else {
  8408. valueparts += ch;
  8409. }
  8410. }
  8411. }
  8412. } // end while
  8413. return output;
  8414. };
  8415. // encoding = 'Unicode'
  8416. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  8417. // Actual 16bit char codes used.
  8418. // no multi-byte logic here
  8419. // Unicode characters to WinAnsiEncoding:
  8420. // {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}
  8421. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  8422. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  8423. // as well as give strings with some (supported by these fonts) Unicode characters and
  8424. // these will be mapped to win cp1252
  8425. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  8426. var encodingBlock = {
  8427. 'codePages': ['WinAnsiEncoding'],
  8428. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  8429. },
  8430. encodings = { 'Unicode': {
  8431. 'Courier': encodingBlock,
  8432. 'Courier-Bold': encodingBlock,
  8433. 'Courier-BoldOblique': encodingBlock,
  8434. 'Courier-Oblique': encodingBlock,
  8435. 'Helvetica': encodingBlock,
  8436. 'Helvetica-Bold': encodingBlock,
  8437. 'Helvetica-BoldOblique': encodingBlock,
  8438. 'Helvetica-Oblique': encodingBlock,
  8439. 'Times-Roman': encodingBlock,
  8440. 'Times-Bold': encodingBlock,
  8441. 'Times-BoldItalic': encodingBlock,
  8442. 'Times-Italic': encodingBlock
  8443. // , 'Symbol'
  8444. // , 'ZapfDingbats'
  8445. } }
  8446. /**
  8447. Resources:
  8448. Font metrics data is reprocessed derivative of contents of
  8449. "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
  8450. Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
  8451. This file and the 14 PostScript(R) AFM files it accompanies may be used,
  8452. copied, and distributed for any purpose and without charge, with or without
  8453. modification, provided that all copyright notices are retained; that the AFM
  8454. files are not distributed without this file; that all modifications to this
  8455. file or any of the AFM files are prominently noted in the modified file(s);
  8456. and that this paragraph is not modified. Adobe Systems has no responsibility
  8457. or obligation to support the use of the AFM files.
  8458. */
  8459. ,
  8460. fontMetrics = { 'Unicode': {
  8461. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  8462. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  8463. // width is 476/1000 or 47.6% of its height (regardless of font size)
  8464. // At this time this value applies to "widths" and "kerning" numbers.
  8465. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  8466. // key 'fof' represents the "fontMetricsFractionOf" value
  8467. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8468. '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}}}"),
  8469. '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}}}"),
  8470. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8471. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8472. '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}}}")
  8473. //, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
  8474. , '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}}}"),
  8475. '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}}}")
  8476. //, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
  8477. , 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8478. '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}}}"),
  8479. '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}}}"),
  8480. '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}}}")
  8481. } };
  8482. /*
  8483. This event handler is fired when a new jsPDF object is initialized
  8484. This event handler appends metrics data to standard fonts within
  8485. that jsPDF instance. The metrics are mapped over Unicode character
  8486. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  8487. standard PDF fonts.
  8488. Future:
  8489. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  8490. char codes to StandardEncoding character codes. The encoding table is to be used
  8491. somewhere around "pdfEscape" call.
  8492. */
  8493. API.events.push(['addFont', function (font) {
  8494. var metrics,
  8495. unicode_section,
  8496. encoding = 'Unicode',
  8497. encodingBlock;
  8498. metrics = fontMetrics[encoding][font.PostScriptName];
  8499. if (metrics) {
  8500. if (font.metadata[encoding]) {
  8501. unicode_section = font.metadata[encoding];
  8502. } else {
  8503. unicode_section = font.metadata[encoding] = {};
  8504. }
  8505. unicode_section.widths = metrics.widths;
  8506. unicode_section.kerning = metrics.kerning;
  8507. }
  8508. encodingBlock = encodings[encoding][font.PostScriptName];
  8509. if (encodingBlock) {
  8510. if (font.metadata[encoding]) {
  8511. unicode_section = font.metadata[encoding];
  8512. } else {
  8513. unicode_section = font.metadata[encoding] = {};
  8514. }
  8515. unicode_section.encoding = encodingBlock;
  8516. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  8517. font.encoding = encodingBlock.codePages[0];
  8518. }
  8519. }
  8520. }]); // end of adding event handler
  8521. })(jsPDF.API);
  8522. /** @preserve
  8523. jsPDF SVG plugin
  8524. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8525. */
  8526. /**
  8527. *
  8528. * ====================================================================
  8529. */
  8530. (function (jsPDFAPI) {
  8531. 'use strict';
  8532. /**
  8533. Parses SVG XML and converts only some of the SVG elements into
  8534. PDF elements.
  8535. Supports:
  8536. paths
  8537. @public
  8538. @function
  8539. @param
  8540. @returns {Type}
  8541. */
  8542. jsPDFAPI.addSVG = function (svgtext, x, y, w, h) {
  8543. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  8544. var undef;
  8545. if (x === undef || y === undef) {
  8546. throw new Error("addSVG needs values for 'x' and 'y'");
  8547. }
  8548. function InjectCSS(cssbody, document) {
  8549. var styletag = document.createElement('style');
  8550. styletag.type = 'text/css';
  8551. if (styletag.styleSheet) {
  8552. // ie
  8553. styletag.styleSheet.cssText = cssbody;
  8554. } else {
  8555. // others
  8556. styletag.appendChild(document.createTextNode(cssbody));
  8557. }
  8558. document.getElementsByTagName("head")[0].appendChild(styletag);
  8559. }
  8560. function createWorkerNode(document) {
  8561. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  8562. ,
  8563. frame = document.createElement('iframe');
  8564. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  8565. frame.name = frameID;
  8566. frame.setAttribute("width", 0);
  8567. frame.setAttribute("height", 0);
  8568. frame.setAttribute("frameborder", "0");
  8569. frame.setAttribute("scrolling", "no");
  8570. frame.setAttribute("seamless", "seamless");
  8571. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  8572. document.body.appendChild(frame);
  8573. return frame;
  8574. }
  8575. function attachSVGToWorkerNode(svgtext, frame) {
  8576. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  8577. framedoc.write(svgtext);
  8578. framedoc.close();
  8579. return framedoc.getElementsByTagName('svg')[0];
  8580. }
  8581. function convertPathToPDFLinesArgs(path) {
  8582. 'use strict';
  8583. // we will use 'lines' method call. it needs:
  8584. // - starting coordinate pair
  8585. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  8586. // - scale array [horizontal, vertical] ratios
  8587. // - style (stroke, fill, both)
  8588. var x = parseFloat(path[1]),
  8589. y = parseFloat(path[2]),
  8590. vectors = [],
  8591. position = 3,
  8592. len = path.length;
  8593. while (position < len) {
  8594. if (path[position] === 'c') {
  8595. 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])]);
  8596. position += 7;
  8597. } else if (path[position] === 'l') {
  8598. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  8599. position += 3;
  8600. } else {
  8601. position += 1;
  8602. }
  8603. }
  8604. return [x, y, vectors];
  8605. }
  8606. var workernode = createWorkerNode(document),
  8607. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  8608. scale = [1, 1],
  8609. svgw = parseFloat(svgnode.getAttribute('width')),
  8610. svgh = parseFloat(svgnode.getAttribute('height'));
  8611. if (svgw && svgh) {
  8612. // setting both w and h makes image stretch to size.
  8613. // this may distort the image, but fits your demanded size
  8614. if (w && h) {
  8615. scale = [w / svgw, h / svgh];
  8616. }
  8617. // if only one is set, that value is set as max and SVG
  8618. // is scaled proportionately.
  8619. else if (w) {
  8620. scale = [w / svgw, w / svgw];
  8621. } else if (h) {
  8622. scale = [h / svgh, h / svgh];
  8623. }
  8624. }
  8625. var i,
  8626. l,
  8627. tmp,
  8628. linesargs,
  8629. items = svgnode.childNodes;
  8630. for (i = 0, l = items.length; i < l; i++) {
  8631. tmp = items[i];
  8632. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  8633. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
  8634. // path start x coordinate
  8635. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  8636. // path start y coordinate
  8637. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  8638. // the rest of lines are vectors. these will adjust with scale value auto.
  8639. this.lines.call(this, linesargs[2] // lines
  8640. , linesargs[0] // starting x
  8641. , linesargs[1] // starting y
  8642. , scale);
  8643. }
  8644. }
  8645. // clean up
  8646. // workernode.parentNode.removeChild(workernode)
  8647. return this;
  8648. };
  8649. })(jsPDF.API);
  8650. /** ====================================================================
  8651. * jsPDF total_pages plugin
  8652. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  8653. *
  8654. *
  8655. * ====================================================================
  8656. */
  8657. (function (jsPDFAPI) {
  8658. 'use strict';
  8659. jsPDFAPI.putTotalPages = function (pageExpression) {
  8660. 'use strict';
  8661. var replaceExpression = new RegExp(pageExpression, 'g');
  8662. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  8663. for (var i = 0; i < this.internal.pages[n].length; i++) {
  8664. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
  8665. }
  8666. }
  8667. return this;
  8668. };
  8669. })(jsPDF.API);
  8670. /** ====================================================================
  8671. * jsPDF XMP metadata plugin
  8672. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  8673. *
  8674. *
  8675. * ====================================================================
  8676. */
  8677. /*global jsPDF */
  8678. /**
  8679. * Adds XMP formatted metadata to PDF
  8680. *
  8681. * @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.
  8682. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  8683. * @function
  8684. * @returns {jsPDF}
  8685. * @methodOf jsPDF#
  8686. * @name addMetadata
  8687. */
  8688. (function (jsPDFAPI) {
  8689. 'use strict';
  8690. var xmpmetadata = "";
  8691. var xmpnamespaceuri = "";
  8692. var metadata_object_number = "";
  8693. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  8694. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  8695. xmpmetadata = metadata;
  8696. this.internal.events.subscribe('postPutResources', function () {
  8697. if (!xmpmetadata) {
  8698. metadata_object_number = "";
  8699. } else {
  8700. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  8701. 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>';
  8702. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  8703. var xmpmeta_ending = '</x:xmpmeta>';
  8704. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  8705. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  8706. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  8707. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  8708. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  8709. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  8710. metadata_object_number = this.internal.newObject();
  8711. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  8712. this.internal.write('stream');
  8713. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  8714. this.internal.write('endstream');
  8715. this.internal.write('endobj');
  8716. }
  8717. });
  8718. this.internal.events.subscribe('putCatalog', function () {
  8719. if (metadata_object_number) {
  8720. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  8721. }
  8722. });
  8723. return this;
  8724. };
  8725. })(jsPDF.API);
  8726. /* Blob.js
  8727. * A Blob implementation.
  8728. * 2014-07-24
  8729. *
  8730. * By Eli Grey, http://eligrey.com
  8731. * By Devin Samarin, https://github.com/dsamarin
  8732. * License: X11/MIT
  8733. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  8734. */
  8735. /*global self, unescape */
  8736. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  8737. plusplus: true */
  8738. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  8739. (function (view) {
  8740. "use strict";
  8741. view.URL = view.URL || view.webkitURL;
  8742. if (view.Blob && view.URL) {
  8743. try {
  8744. new Blob;
  8745. return;
  8746. } catch (e) {}
  8747. }
  8748. // Internally we use a BlobBuilder implementation to base Blob off of
  8749. // in order to support older browsers that only have BlobBuilder
  8750. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  8751. var
  8752. get_class = function(object) {
  8753. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  8754. }
  8755. , FakeBlobBuilder = function BlobBuilder() {
  8756. this.data = [];
  8757. }
  8758. , FakeBlob = function Blob(data, type, encoding) {
  8759. this.data = data;
  8760. this.size = data.length;
  8761. this.type = type;
  8762. this.encoding = encoding;
  8763. }
  8764. , FBB_proto = FakeBlobBuilder.prototype
  8765. , FB_proto = FakeBlob.prototype
  8766. , FileReaderSync = view.FileReaderSync
  8767. , FileException = function(type) {
  8768. this.code = this[this.name = type];
  8769. }
  8770. , file_ex_codes = (
  8771. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
  8772. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  8773. ).split(" ")
  8774. , file_ex_code = file_ex_codes.length
  8775. , real_URL = view.URL || view.webkitURL || view
  8776. , real_create_object_URL = real_URL.createObjectURL
  8777. , real_revoke_object_URL = real_URL.revokeObjectURL
  8778. , URL = real_URL
  8779. , btoa = view.btoa
  8780. , atob = view.atob
  8781. , ArrayBuffer = view.ArrayBuffer
  8782. , Uint8Array = view.Uint8Array
  8783. , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;
  8784. FakeBlob.fake = FB_proto.fake = true;
  8785. while (file_ex_code--) {
  8786. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  8787. }
  8788. // Polyfill URL
  8789. if (!real_URL.createObjectURL) {
  8790. URL = view.URL = function(uri) {
  8791. var
  8792. uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8793. , uri_origin;
  8794. uri_info.href = uri;
  8795. if (!("origin" in uri_info)) {
  8796. if (uri_info.protocol.toLowerCase() === "data:") {
  8797. uri_info.origin = null;
  8798. } else {
  8799. uri_origin = uri.match(origin);
  8800. uri_info.origin = uri_origin && uri_origin[1];
  8801. }
  8802. }
  8803. return uri_info;
  8804. };
  8805. }
  8806. URL.createObjectURL = function(blob) {
  8807. var
  8808. type = blob.type
  8809. , data_URI_header;
  8810. if (type === null) {
  8811. type = "application/octet-stream";
  8812. }
  8813. if (blob instanceof FakeBlob) {
  8814. data_URI_header = "data:" + type;
  8815. if (blob.encoding === "base64") {
  8816. return data_URI_header + ";base64," + blob.data;
  8817. } else if (blob.encoding === "URI") {
  8818. return data_URI_header + "," + decodeURIComponent(blob.data);
  8819. } if (btoa) {
  8820. return data_URI_header + ";base64," + btoa(blob.data);
  8821. } else {
  8822. return data_URI_header + "," + encodeURIComponent(blob.data);
  8823. }
  8824. } else if (real_create_object_URL) {
  8825. return real_create_object_URL.call(real_URL, blob);
  8826. }
  8827. };
  8828. URL.revokeObjectURL = function(object_URL) {
  8829. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  8830. real_revoke_object_URL.call(real_URL, object_URL);
  8831. }
  8832. };
  8833. FBB_proto.append = function(data/*, endings*/) {
  8834. var bb = this.data;
  8835. // decode data to a binary string
  8836. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  8837. var
  8838. str = ""
  8839. , buf = new Uint8Array(data)
  8840. , i = 0
  8841. , buf_len = buf.length;
  8842. for (; i < buf_len; i++) {
  8843. str += String.fromCharCode(buf[i]);
  8844. }
  8845. bb.push(str);
  8846. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  8847. if (FileReaderSync) {
  8848. var fr = new FileReaderSync;
  8849. bb.push(fr.readAsBinaryString(data));
  8850. } else {
  8851. // async FileReader won't work as BlobBuilder is sync
  8852. throw new FileException("NOT_READABLE_ERR");
  8853. }
  8854. } else if (data instanceof FakeBlob) {
  8855. if (data.encoding === "base64" && atob) {
  8856. bb.push(atob(data.data));
  8857. } else if (data.encoding === "URI") {
  8858. bb.push(decodeURIComponent(data.data));
  8859. } else if (data.encoding === "raw") {
  8860. bb.push(data.data);
  8861. }
  8862. } else {
  8863. if (typeof data !== "string") {
  8864. data += ""; // convert unsupported types to strings
  8865. }
  8866. // decode UTF-16 to binary string
  8867. bb.push(unescape(encodeURIComponent(data)));
  8868. }
  8869. };
  8870. FBB_proto.getBlob = function(type) {
  8871. if (!arguments.length) {
  8872. type = null;
  8873. }
  8874. return new FakeBlob(this.data.join(""), type, "raw");
  8875. };
  8876. FBB_proto.toString = function() {
  8877. return "[object BlobBuilder]";
  8878. };
  8879. FB_proto.slice = function(start, end, type) {
  8880. var args = arguments.length;
  8881. if (args < 3) {
  8882. type = null;
  8883. }
  8884. return new FakeBlob(
  8885. this.data.slice(start, args > 1 ? end : this.data.length)
  8886. , type
  8887. , this.encoding
  8888. );
  8889. };
  8890. FB_proto.toString = function() {
  8891. return "[object Blob]";
  8892. };
  8893. FB_proto.close = function() {
  8894. this.size = 0;
  8895. delete this.data;
  8896. };
  8897. return FakeBlobBuilder;
  8898. }(view));
  8899. view.Blob = function(blobParts, options) {
  8900. var type = options ? (options.type || "") : "";
  8901. var builder = new BlobBuilder();
  8902. if (blobParts) {
  8903. for (var i = 0, len = blobParts.length; i < len; i++) {
  8904. if (Uint8Array && blobParts[i] instanceof Uint8Array) {
  8905. builder.append(blobParts[i].buffer);
  8906. }
  8907. else {
  8908. builder.append(blobParts[i]);
  8909. }
  8910. }
  8911. }
  8912. var blob = builder.getBlob(type);
  8913. if (!blob.slice && blob.webkitSlice) {
  8914. blob.slice = blob.webkitSlice;
  8915. }
  8916. return blob;
  8917. };
  8918. var getPrototypeOf = Object.getPrototypeOf || function(object) {
  8919. return object.__proto__;
  8920. };
  8921. view.Blob.prototype = getPrototypeOf(new view.Blob());
  8922. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
  8923. /* FileSaver.js
  8924. * A saveAs() FileSaver implementation.
  8925. * 1.1.20151003
  8926. *
  8927. * By Eli Grey, http://eligrey.com
  8928. * License: MIT
  8929. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  8930. */
  8931. /*global self */
  8932. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  8933. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  8934. var saveAs = saveAs || (function(view) {
  8935. "use strict";
  8936. // IE <10 is explicitly unsupported
  8937. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  8938. return;
  8939. }
  8940. var
  8941. doc = view.document
  8942. // only get URL when necessary in case Blob.js hasn't overridden it yet
  8943. , get_URL = function() {
  8944. return view.URL || view.webkitURL || view;
  8945. }
  8946. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8947. , can_use_save_link = "download" in save_link
  8948. , click = function(node) {
  8949. var event = new MouseEvent("click");
  8950. node.dispatchEvent(event);
  8951. }
  8952. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  8953. , webkit_req_fs = view.webkitRequestFileSystem
  8954. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  8955. , throw_outside = function(ex) {
  8956. (view.setImmediate || view.setTimeout)(function() {
  8957. throw ex;
  8958. }, 0);
  8959. }
  8960. , force_saveable_type = "application/octet-stream"
  8961. , fs_min_size = 0
  8962. // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  8963. // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  8964. // for the reasoning behind the timeout and revocation flow
  8965. , arbitrary_revoke_timeout = 500 // in ms
  8966. , revoke = function(file) {
  8967. var revoker = function() {
  8968. if (typeof file === "string") { // file is an object URL
  8969. get_URL().revokeObjectURL(file);
  8970. } else { // file is a File
  8971. file.remove();
  8972. }
  8973. };
  8974. if (view.chrome) {
  8975. revoker();
  8976. } else {
  8977. setTimeout(revoker, arbitrary_revoke_timeout);
  8978. }
  8979. }
  8980. , dispatch = function(filesaver, event_types, event) {
  8981. event_types = [].concat(event_types);
  8982. var i = event_types.length;
  8983. while (i--) {
  8984. var listener = filesaver["on" + event_types[i]];
  8985. if (typeof listener === "function") {
  8986. try {
  8987. listener.call(filesaver, event || filesaver);
  8988. } catch (ex) {
  8989. throw_outside(ex);
  8990. }
  8991. }
  8992. }
  8993. }
  8994. , auto_bom = function(blob) {
  8995. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  8996. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  8997. return new Blob(["\ufeff", blob], {type: blob.type});
  8998. }
  8999. return blob;
  9000. }
  9001. , FileSaver = function(blob, name, no_auto_bom) {
  9002. if (!no_auto_bom) {
  9003. blob = auto_bom(blob);
  9004. }
  9005. // First try a.download, then web filesystem, then object URLs
  9006. var
  9007. filesaver = this
  9008. , type = blob.type
  9009. , blob_changed = false
  9010. , object_url
  9011. , target_view
  9012. , dispatch_all = function() {
  9013. dispatch(filesaver, "writestart progress write writeend".split(" "));
  9014. }
  9015. // on any filesys errors revert to saving with object URLs
  9016. , fs_error = function() {
  9017. if (target_view && is_safari && typeof FileReader !== "undefined") {
  9018. // Safari doesn't allow downloading of blob urls
  9019. var reader = new FileReader();
  9020. reader.onloadend = function() {
  9021. var base64Data = reader.result;
  9022. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  9023. filesaver.readyState = filesaver.DONE;
  9024. dispatch_all();
  9025. };
  9026. reader.readAsDataURL(blob);
  9027. filesaver.readyState = filesaver.INIT;
  9028. return;
  9029. }
  9030. // don't create more object URLs than needed
  9031. if (blob_changed || !object_url) {
  9032. object_url = get_URL().createObjectURL(blob);
  9033. }
  9034. if (target_view) {
  9035. target_view.location.href = object_url;
  9036. } else {
  9037. var new_tab = view.open(object_url, "_blank");
  9038. if (new_tab == undefined && is_safari) {
  9039. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  9040. view.location.href = object_url;
  9041. }
  9042. }
  9043. filesaver.readyState = filesaver.DONE;
  9044. dispatch_all();
  9045. revoke(object_url);
  9046. }
  9047. , abortable = function(func) {
  9048. return function() {
  9049. if (filesaver.readyState !== filesaver.DONE) {
  9050. return func.apply(this, arguments);
  9051. }
  9052. };
  9053. }
  9054. , create_if_not_found = {create: true, exclusive: false}
  9055. , slice;
  9056. filesaver.readyState = filesaver.INIT;
  9057. if (!name) {
  9058. name = "download";
  9059. }
  9060. if (can_use_save_link) {
  9061. object_url = get_URL().createObjectURL(blob);
  9062. setTimeout(function() {
  9063. save_link.href = object_url;
  9064. save_link.download = name;
  9065. click(save_link);
  9066. dispatch_all();
  9067. revoke(object_url);
  9068. filesaver.readyState = filesaver.DONE;
  9069. });
  9070. return;
  9071. }
  9072. // Object and web filesystem URLs have a problem saving in Google Chrome when
  9073. // viewed in a tab, so I force save with application/octet-stream
  9074. // http://code.google.com/p/chromium/issues/detail?id=91158
  9075. // Update: Google errantly closed 91158, I submitted it again:
  9076. // https://code.google.com/p/chromium/issues/detail?id=389642
  9077. if (view.chrome && type && type !== force_saveable_type) {
  9078. slice = blob.slice || blob.webkitSlice;
  9079. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  9080. blob_changed = true;
  9081. }
  9082. // Since I can't be sure that the guessed media type will trigger a download
  9083. // in WebKit, I append .download to the filename.
  9084. // https://bugs.webkit.org/show_bug.cgi?id=65440
  9085. if (webkit_req_fs && name !== "download") {
  9086. name += ".download";
  9087. }
  9088. if (type === force_saveable_type || webkit_req_fs) {
  9089. target_view = view;
  9090. }
  9091. if (!req_fs) {
  9092. fs_error();
  9093. return;
  9094. }
  9095. fs_min_size += blob.size;
  9096. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  9097. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  9098. var save = function() {
  9099. dir.getFile(name, create_if_not_found, abortable(function(file) {
  9100. file.createWriter(abortable(function(writer) {
  9101. writer.onwriteend = function(event) {
  9102. target_view.location.href = file.toURL();
  9103. filesaver.readyState = filesaver.DONE;
  9104. dispatch(filesaver, "writeend", event);
  9105. revoke(file);
  9106. };
  9107. writer.onerror = function() {
  9108. var error = writer.error;
  9109. if (error.code !== error.ABORT_ERR) {
  9110. fs_error();
  9111. }
  9112. };
  9113. "writestart progress write abort".split(" ").forEach(function(event) {
  9114. writer["on" + event] = filesaver["on" + event];
  9115. });
  9116. writer.write(blob);
  9117. filesaver.abort = function() {
  9118. writer.abort();
  9119. filesaver.readyState = filesaver.DONE;
  9120. };
  9121. filesaver.readyState = filesaver.WRITING;
  9122. }), fs_error);
  9123. }), fs_error);
  9124. };
  9125. dir.getFile(name, {create: false}, abortable(function(file) {
  9126. // delete file if it already exists
  9127. file.remove();
  9128. save();
  9129. }), abortable(function(ex) {
  9130. if (ex.code === ex.NOT_FOUND_ERR) {
  9131. save();
  9132. } else {
  9133. fs_error();
  9134. }
  9135. }));
  9136. }), fs_error);
  9137. }), fs_error);
  9138. }
  9139. , FS_proto = FileSaver.prototype
  9140. , saveAs = function(blob, name, no_auto_bom) {
  9141. return new FileSaver(blob, name, no_auto_bom);
  9142. };
  9143. // IE 10+ (native saveAs)
  9144. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  9145. return function(blob, name, no_auto_bom) {
  9146. if (!no_auto_bom) {
  9147. blob = auto_bom(blob);
  9148. }
  9149. return navigator.msSaveOrOpenBlob(blob, name || "download");
  9150. };
  9151. }
  9152. FS_proto.abort = function() {
  9153. var filesaver = this;
  9154. filesaver.readyState = filesaver.DONE;
  9155. dispatch(filesaver, "abort");
  9156. };
  9157. FS_proto.readyState = FS_proto.INIT = 0;
  9158. FS_proto.WRITING = 1;
  9159. FS_proto.DONE = 2;
  9160. FS_proto.error =
  9161. FS_proto.onwritestart =
  9162. FS_proto.onprogress =
  9163. FS_proto.onwrite =
  9164. FS_proto.onabort =
  9165. FS_proto.onerror =
  9166. FS_proto.onwriteend =
  9167. null;
  9168. return saveAs;
  9169. }(
  9170. typeof self !== "undefined" && self
  9171. || typeof window !== "undefined" && window
  9172. || undefined.content
  9173. ));
  9174. // `self` is undefined in Firefox for Android content script context
  9175. // while `this` is nsIContentFrameMessageManager
  9176. // with an attribute `content` that corresponds to the window
  9177. if (typeof module !== "undefined" && module.exports) {
  9178. module.exports.saveAs = saveAs;
  9179. } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  9180. define([], function() {
  9181. return saveAs;
  9182. });
  9183. }
  9184. /*
  9185. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  9186. *
  9187. * Licensed under the MIT License.
  9188. * http://opensource.org/licenses/mit-license
  9189. */
  9190. void function(global, callback) {
  9191. if (typeof module === 'object') {
  9192. module.exports = callback();
  9193. } else if (typeof define === 'function') {
  9194. define(callback);
  9195. } else {
  9196. global.adler32cs = callback();
  9197. }
  9198. }(jsPDF, function() {
  9199. var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
  9200. typeof Uint8Array === 'function';
  9201. var _Buffer = null, _isBuffer = (function() {
  9202. if (!_hasArrayBuffer)
  9203. return function _isBuffer() { return false };
  9204. try {
  9205. var buffer = {};
  9206. if (typeof buffer.Buffer === 'function')
  9207. _Buffer = buffer.Buffer;
  9208. } catch (error) {}
  9209. return function _isBuffer(value) {
  9210. return value instanceof ArrayBuffer ||
  9211. _Buffer !== null && value instanceof _Buffer;
  9212. };
  9213. }());
  9214. var _utf8ToBinary = (function() {
  9215. if (_Buffer !== null) {
  9216. return function _utf8ToBinary(utf8String) {
  9217. return new _Buffer(utf8String, 'utf8').toString('binary');
  9218. };
  9219. } else {
  9220. return function _utf8ToBinary(utf8String) {
  9221. return unescape(encodeURIComponent(utf8String));
  9222. };
  9223. }
  9224. }());
  9225. var MOD = 65521;
  9226. var _update = function _update(checksum, binaryString) {
  9227. var a = checksum & 0xFFFF, b = checksum >>> 16;
  9228. for (var i = 0, length = binaryString.length; i < length; i++) {
  9229. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  9230. b = (b + a) % MOD;
  9231. }
  9232. return (b << 16 | a) >>> 0;
  9233. };
  9234. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  9235. var a = checksum & 0xFFFF, b = checksum >>> 16;
  9236. for (var i = 0, length = uint8Array.length, x; i < length; i++) {
  9237. a = (a + uint8Array[i]) % MOD;
  9238. b = (b + a) % MOD;
  9239. }
  9240. return (b << 16 | a) >>> 0
  9241. };
  9242. var exports = {};
  9243. var Adler32 = exports.Adler32 = (function() {
  9244. var ctor = function Adler32(checksum) {
  9245. if (!(this instanceof ctor)) {
  9246. throw new TypeError(
  9247. 'Constructor cannot called be as a function.');
  9248. }
  9249. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  9250. throw new Error(
  9251. 'First arguments needs to be a finite number.');
  9252. }
  9253. this.checksum = checksum >>> 0;
  9254. };
  9255. var proto = ctor.prototype = {};
  9256. proto.constructor = ctor;
  9257. ctor.from = function(from) {
  9258. from.prototype = proto;
  9259. return from;
  9260. }(function from(binaryString) {
  9261. if (!(this instanceof ctor)) {
  9262. throw new TypeError(
  9263. 'Constructor cannot called be as a function.');
  9264. }
  9265. if (binaryString == null)
  9266. throw new Error('First argument needs to be a string.');
  9267. this.checksum = _update(1, binaryString.toString());
  9268. });
  9269. ctor.fromUtf8 = function(fromUtf8) {
  9270. fromUtf8.prototype = proto;
  9271. return fromUtf8;
  9272. }(function fromUtf8(utf8String) {
  9273. if (!(this instanceof ctor)) {
  9274. throw new TypeError(
  9275. 'Constructor cannot called be as a function.');
  9276. }
  9277. if (utf8String == null)
  9278. throw new Error('First argument needs to be a string.');
  9279. var binaryString = _utf8ToBinary(utf8String.toString());
  9280. this.checksum = _update(1, binaryString);
  9281. });
  9282. if (_hasArrayBuffer) {
  9283. ctor.fromBuffer = function(fromBuffer) {
  9284. fromBuffer.prototype = proto;
  9285. return fromBuffer;
  9286. }(function fromBuffer(buffer) {
  9287. if (!(this instanceof ctor)) {
  9288. throw new TypeError(
  9289. 'Constructor cannot called be as a function.');
  9290. }
  9291. if (!_isBuffer(buffer))
  9292. throw new Error('First argument needs to be ArrayBuffer.');
  9293. var array = new Uint8Array(buffer);
  9294. return this.checksum = _updateUint8Array(1, array);
  9295. });
  9296. }
  9297. proto.update = function update(binaryString) {
  9298. if (binaryString == null)
  9299. throw new Error('First argument needs to be a string.');
  9300. binaryString = binaryString.toString();
  9301. return this.checksum = _update(this.checksum, binaryString);
  9302. };
  9303. proto.updateUtf8 = function updateUtf8(utf8String) {
  9304. if (utf8String == null)
  9305. throw new Error('First argument needs to be a string.');
  9306. var binaryString = _utf8ToBinary(utf8String.toString());
  9307. return this.checksum = _update(this.checksum, binaryString);
  9308. };
  9309. if (_hasArrayBuffer) {
  9310. proto.updateBuffer = function updateBuffer(buffer) {
  9311. if (!_isBuffer(buffer))
  9312. throw new Error('First argument needs to be ArrayBuffer.');
  9313. var array = new Uint8Array(buffer);
  9314. return this.checksum = _updateUint8Array(this.checksum, array);
  9315. };
  9316. }
  9317. proto.clone = function clone() {
  9318. return new Adler32(this.checksum);
  9319. };
  9320. return ctor;
  9321. }());
  9322. exports.from = function from(binaryString) {
  9323. if (binaryString == null)
  9324. throw new Error('First argument needs to be a string.');
  9325. return _update(1, binaryString.toString());
  9326. };
  9327. exports.fromUtf8 = function fromUtf8(utf8String) {
  9328. if (utf8String == null)
  9329. throw new Error('First argument needs to be a string.');
  9330. var binaryString = _utf8ToBinary(utf8String.toString());
  9331. return _update(1, binaryString);
  9332. };
  9333. if (_hasArrayBuffer) {
  9334. exports.fromBuffer = function fromBuffer(buffer) {
  9335. if (!_isBuffer(buffer))
  9336. throw new Error('First argument need to be ArrayBuffer.');
  9337. var array = new Uint8Array(buffer);
  9338. return _updateUint8Array(1, array);
  9339. };
  9340. }
  9341. return exports;
  9342. });
  9343. /**
  9344. * CssColors
  9345. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  9346. *
  9347. * Licensed under the MIT License.
  9348. * http://opensource.org/licenses/mit-license
  9349. */
  9350. /**
  9351. * Usage CssColors('red');
  9352. * Returns RGB hex color with '#' prefix
  9353. */
  9354. var CssColors = {};
  9355. CssColors._colorsTable = {
  9356. "aliceblue" : "#f0f8ff",
  9357. "antiquewhite" : "#faebd7",
  9358. "aqua" : "#00ffff",
  9359. "aquamarine" : "#7fffd4",
  9360. "azure" : "#f0ffff",
  9361. "beige" : "#f5f5dc",
  9362. "bisque" : "#ffe4c4",
  9363. "black" : "#000000",
  9364. "blanchedalmond" : "#ffebcd",
  9365. "blue" : "#0000ff",
  9366. "blueviolet" : "#8a2be2",
  9367. "brown" : "#a52a2a",
  9368. "burlywood" : "#deb887",
  9369. "cadetblue" : "#5f9ea0",
  9370. "chartreuse" : "#7fff00",
  9371. "chocolate" : "#d2691e",
  9372. "coral" : "#ff7f50",
  9373. "cornflowerblue" : "#6495ed",
  9374. "cornsilk" : "#fff8dc",
  9375. "crimson" : "#dc143c",
  9376. "cyan" : "#00ffff",
  9377. "darkblue" : "#00008b",
  9378. "darkcyan" : "#008b8b",
  9379. "darkgoldenrod" : "#b8860b",
  9380. "darkgray" : "#a9a9a9",
  9381. "darkgreen" : "#006400",
  9382. "darkkhaki" : "#bdb76b",
  9383. "darkmagenta" : "#8b008b",
  9384. "darkolivegreen" : "#556b2f",
  9385. "darkorange" : "#ff8c00",
  9386. "darkorchid" : "#9932cc",
  9387. "darkred" : "#8b0000",
  9388. "darksalmon" : "#e9967a",
  9389. "darkseagreen" : "#8fbc8f",
  9390. "darkslateblue" : "#483d8b",
  9391. "darkslategray" : "#2f4f4f",
  9392. "darkturquoise" : "#00ced1",
  9393. "darkviolet" : "#9400d3",
  9394. "deeppink" : "#ff1493",
  9395. "deepskyblue" : "#00bfff",
  9396. "dimgray" : "#696969",
  9397. "dodgerblue" : "#1e90ff",
  9398. "firebrick" : "#b22222",
  9399. "floralwhite" : "#fffaf0",
  9400. "forestgreen" : "#228b22",
  9401. "fuchsia" : "#ff00ff",
  9402. "gainsboro" : "#dcdcdc",
  9403. "ghostwhite" : "#f8f8ff",
  9404. "gold" : "#ffd700",
  9405. "goldenrod" : "#daa520",
  9406. "gray" : "#808080",
  9407. "green" : "#008000",
  9408. "greenyellow" : "#adff2f",
  9409. "honeydew" : "#f0fff0",
  9410. "hotpink" : "#ff69b4",
  9411. "indianred " : "#cd5c5c",
  9412. "indigo" : "#4b0082",
  9413. "ivory" : "#fffff0",
  9414. "khaki" : "#f0e68c",
  9415. "lavender" : "#e6e6fa",
  9416. "lavenderblush" : "#fff0f5",
  9417. "lawngreen" : "#7cfc00",
  9418. "lemonchiffon" : "#fffacd",
  9419. "lightblue" : "#add8e6",
  9420. "lightcoral" : "#f08080",
  9421. "lightcyan" : "#e0ffff",
  9422. "lightgoldenrodyellow" : "#fafad2",
  9423. "lightgrey" : "#d3d3d3",
  9424. "lightgreen" : "#90ee90",
  9425. "lightpink" : "#ffb6c1",
  9426. "lightsalmon" : "#ffa07a",
  9427. "lightseagreen" : "#20b2aa",
  9428. "lightskyblue" : "#87cefa",
  9429. "lightslategray" : "#778899",
  9430. "lightsteelblue" : "#b0c4de",
  9431. "lightyellow" : "#ffffe0",
  9432. "lime" : "#00ff00",
  9433. "limegreen" : "#32cd32",
  9434. "linen" : "#faf0e6",
  9435. "magenta" : "#ff00ff",
  9436. "maroon" : "#800000",
  9437. "mediumaquamarine" : "#66cdaa",
  9438. "mediumblue" : "#0000cd",
  9439. "mediumorchid" : "#ba55d3",
  9440. "mediumpurple" : "#9370d8",
  9441. "mediumseagreen" : "#3cb371",
  9442. "mediumslateblue" : "#7b68ee",
  9443. "mediumspringgreen" : "#00fa9a",
  9444. "mediumturquoise" : "#48d1cc",
  9445. "mediumvioletred" : "#c71585",
  9446. "midnightblue" : "#191970",
  9447. "mintcream" : "#f5fffa",
  9448. "mistyrose" : "#ffe4e1",
  9449. "moccasin" : "#ffe4b5",
  9450. "navajowhite" : "#ffdead",
  9451. "navy" : "#000080",
  9452. "oldlace" : "#fdf5e6",
  9453. "olive" : "#808000",
  9454. "olivedrab" : "#6b8e23",
  9455. "orange" : "#ffa500",
  9456. "orangered" : "#ff4500",
  9457. "orchid" : "#da70d6",
  9458. "palegoldenrod" : "#eee8aa",
  9459. "palegreen" : "#98fb98",
  9460. "paleturquoise" : "#afeeee",
  9461. "palevioletred" : "#d87093",
  9462. "papayawhip" : "#ffefd5",
  9463. "peachpuff" : "#ffdab9",
  9464. "peru" : "#cd853f",
  9465. "pink" : "#ffc0cb",
  9466. "plum" : "#dda0dd",
  9467. "powderblue" : "#b0e0e6",
  9468. "purple" : "#800080",
  9469. "red" : "#ff0000",
  9470. "rosybrown" : "#bc8f8f",
  9471. "royalblue" : "#4169e1",
  9472. "saddlebrown" : "#8b4513",
  9473. "salmon" : "#fa8072",
  9474. "sandybrown" : "#f4a460",
  9475. "seagreen" : "#2e8b57",
  9476. "seashell" : "#fff5ee",
  9477. "sienna" : "#a0522d",
  9478. "silver" : "#c0c0c0",
  9479. "skyblue" : "#87ceeb",
  9480. "slateblue" : "#6a5acd",
  9481. "slategray" : "#708090",
  9482. "snow" : "#fffafa",
  9483. "springgreen" : "#00ff7f",
  9484. "steelblue" : "#4682b4",
  9485. "tan" : "#d2b48c",
  9486. "teal" : "#008080",
  9487. "thistle" : "#d8bfd8",
  9488. "tomato" : "#ff6347",
  9489. "turquoise" : "#40e0d0",
  9490. "violet" : "#ee82ee",
  9491. "wheat" : "#f5deb3",
  9492. "white" : "#ffffff",
  9493. "whitesmoke" : "#f5f5f5",
  9494. "yellow" : "#ffff00",
  9495. "yellowgreen" : "#9acd32"
  9496. };
  9497. CssColors.colorNameToHex = function(color) {
  9498. color = color.toLowerCase();
  9499. if (typeof this._colorsTable[color] != 'undefined')
  9500. return this._colorsTable[color];
  9501. return false;
  9502. };
  9503. /*
  9504. Deflate.js - https://github.com/gildas-lormeau/zip.js
  9505. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  9506. Redistribution and use in source and binary forms, with or without
  9507. modification, are permitted provided that the following conditions are met:
  9508. 1. Redistributions of source code must retain the above copyright notice,
  9509. this list of conditions and the following disclaimer.
  9510. 2. Redistributions in binary form must reproduce the above copyright
  9511. notice, this list of conditions and the following disclaimer in
  9512. the documentation and/or other materials provided with the distribution.
  9513. 3. The names of the authors may not be used to endorse or promote products
  9514. derived from this software without specific prior written permission.
  9515. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  9516. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9517. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  9518. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  9519. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9520. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  9521. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  9522. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  9523. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  9524. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9525. */
  9526. /*
  9527. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  9528. * JZlib is based on zlib-1.1.3, so all credit should go authors
  9529. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  9530. * and contributors of zlib.
  9531. */
  9532. var Deflater = (function(obj) {
  9533. // Global
  9534. var MAX_BITS = 15;
  9535. var D_CODES = 30;
  9536. var BL_CODES = 19;
  9537. var LENGTH_CODES = 29;
  9538. var LITERALS = 256;
  9539. var L_CODES = (LITERALS + 1 + LENGTH_CODES);
  9540. var HEAP_SIZE = (2 * L_CODES + 1);
  9541. var END_BLOCK = 256;
  9542. // Bit length codes must not exceed MAX_BL_BITS bits
  9543. var MAX_BL_BITS = 7;
  9544. // repeat previous bit length 3-6 times (2 bits of repeat count)
  9545. var REP_3_6 = 16;
  9546. // repeat a zero length 3-10 times (3 bits of repeat count)
  9547. var REPZ_3_10 = 17;
  9548. // repeat a zero length 11-138 times (7 bits of repeat count)
  9549. var REPZ_11_138 = 18;
  9550. // The lengths of the bit length codes are sent in order of decreasing
  9551. // probability, to avoid transmitting the lengths for unused bit
  9552. // length codes.
  9553. var Buf_size = 8 * 2;
  9554. // JZlib version : "1.0.2"
  9555. var Z_DEFAULT_COMPRESSION = -1;
  9556. // compression strategy
  9557. var Z_FILTERED = 1;
  9558. var Z_HUFFMAN_ONLY = 2;
  9559. var Z_DEFAULT_STRATEGY = 0;
  9560. var Z_NO_FLUSH = 0;
  9561. var Z_PARTIAL_FLUSH = 1;
  9562. var Z_FULL_FLUSH = 3;
  9563. var Z_FINISH = 4;
  9564. var Z_OK = 0;
  9565. var Z_STREAM_END = 1;
  9566. var Z_NEED_DICT = 2;
  9567. var Z_STREAM_ERROR = -2;
  9568. var Z_DATA_ERROR = -3;
  9569. var Z_BUF_ERROR = -5;
  9570. // Tree
  9571. // see definition of array dist_code below
  9572. 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,
  9573. 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,
  9574. 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,
  9575. 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,
  9576. 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,
  9577. 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,
  9578. 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,
  9579. 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,
  9580. 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,
  9581. 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,
  9582. 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,
  9583. 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,
  9584. 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,
  9585. 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 ];
  9586. function Tree() {
  9587. var that = this;
  9588. // dyn_tree; // the dynamic tree
  9589. // max_code; // largest code with non zero frequency
  9590. // stat_desc; // the corresponding static tree
  9591. // Compute the optimal bit lengths for a tree and update the total bit
  9592. // length
  9593. // for the current block.
  9594. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  9595. // above are the tree nodes sorted by increasing frequency.
  9596. // OUT assertions: the field len is set to the optimal bit length, the
  9597. // array bl_count contains the frequencies for each bit length.
  9598. // The length opt_len is updated; static_len is also updated if stree is
  9599. // not null.
  9600. function gen_bitlen(s) {
  9601. var tree = that.dyn_tree;
  9602. var stree = that.stat_desc.static_tree;
  9603. var extra = that.stat_desc.extra_bits;
  9604. var base = that.stat_desc.extra_base;
  9605. var max_length = that.stat_desc.max_length;
  9606. var h; // heap index
  9607. var n, m; // iterate over the tree elements
  9608. var bits; // bit length
  9609. var xbits; // extra bits
  9610. var f; // frequency
  9611. var overflow = 0; // number of elements with bit length too large
  9612. for (bits = 0; bits <= MAX_BITS; bits++)
  9613. s.bl_count[bits] = 0;
  9614. // In a first pass, compute the optimal bit lengths (which may
  9615. // overflow in the case of the bit length tree).
  9616. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  9617. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9618. n = s.heap[h];
  9619. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  9620. if (bits > max_length) {
  9621. bits = max_length;
  9622. overflow++;
  9623. }
  9624. tree[n * 2 + 1] = bits;
  9625. // We overwrite tree[n*2+1] which is no longer needed
  9626. if (n > that.max_code)
  9627. continue; // not a leaf node
  9628. s.bl_count[bits]++;
  9629. xbits = 0;
  9630. if (n >= base)
  9631. xbits = extra[n - base];
  9632. f = tree[n * 2];
  9633. s.opt_len += f * (bits + xbits);
  9634. if (stree)
  9635. s.static_len += f * (stree[n * 2 + 1] + xbits);
  9636. }
  9637. if (overflow === 0)
  9638. return;
  9639. // This happens for example on obj2 and pic of the Calgary corpus
  9640. // Find the first bit length which could increase:
  9641. do {
  9642. bits = max_length - 1;
  9643. while (s.bl_count[bits] === 0)
  9644. bits--;
  9645. s.bl_count[bits]--; // move one leaf down the tree
  9646. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  9647. s.bl_count[max_length]--;
  9648. // The brother of the overflow item also moves one step up,
  9649. // but this does not affect bl_count[max_length]
  9650. overflow -= 2;
  9651. } while (overflow > 0);
  9652. for (bits = max_length; bits !== 0; bits--) {
  9653. n = s.bl_count[bits];
  9654. while (n !== 0) {
  9655. m = s.heap[--h];
  9656. if (m > that.max_code)
  9657. continue;
  9658. if (tree[m * 2 + 1] != bits) {
  9659. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  9660. tree[m * 2 + 1] = bits;
  9661. }
  9662. n--;
  9663. }
  9664. }
  9665. }
  9666. // Reverse the first len bits of a code, using straightforward code (a
  9667. // faster
  9668. // method would use a table)
  9669. // IN assertion: 1 <= len <= 15
  9670. function bi_reverse(code, // the value to invert
  9671. len // its bit length
  9672. ) {
  9673. var res = 0;
  9674. do {
  9675. res |= code & 1;
  9676. code >>>= 1;
  9677. res <<= 1;
  9678. } while (--len > 0);
  9679. return res >>> 1;
  9680. }
  9681. // Generate the codes for a given tree and bit counts (which need not be
  9682. // optimal).
  9683. // IN assertion: the array bl_count contains the bit length statistics for
  9684. // the given tree and the field len is set for all tree elements.
  9685. // OUT assertion: the field code is set for all tree elements of non
  9686. // zero code length.
  9687. function gen_codes(tree, // the tree to decorate
  9688. max_code, // largest code with non zero frequency
  9689. bl_count // number of codes at each bit length
  9690. ) {
  9691. var next_code = []; // next code value for each
  9692. // bit length
  9693. var code = 0; // running code value
  9694. var bits; // bit index
  9695. var n; // code index
  9696. var len;
  9697. // The distribution counts are first used to generate the code values
  9698. // without bit reversal.
  9699. for (bits = 1; bits <= MAX_BITS; bits++) {
  9700. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  9701. }
  9702. // Check that the bit counts in bl_count are consistent. The last code
  9703. // must be all ones.
  9704. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9705. // "inconsistent bit counts");
  9706. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9707. for (n = 0; n <= max_code; n++) {
  9708. len = tree[n * 2 + 1];
  9709. if (len === 0)
  9710. continue;
  9711. // Now reverse the bits
  9712. tree[n * 2] = bi_reverse(next_code[len]++, len);
  9713. }
  9714. }
  9715. // Construct one Huffman tree and assigns the code bit strings and lengths.
  9716. // Update the total bit length for the current block.
  9717. // IN assertion: the field freq is set for all tree elements.
  9718. // OUT assertions: the fields len and code are set to the optimal bit length
  9719. // and corresponding code. The length opt_len is updated; static_len is
  9720. // also updated if stree is not null. The field max_code is set.
  9721. that.build_tree = function(s) {
  9722. var tree = that.dyn_tree;
  9723. var stree = that.stat_desc.static_tree;
  9724. var elems = that.stat_desc.elems;
  9725. var n, m; // iterate over heap elements
  9726. var max_code = -1; // largest code with non zero frequency
  9727. var node; // new node being created
  9728. // Construct the initial heap, with least frequent element in
  9729. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9730. // heap[0] is not used.
  9731. s.heap_len = 0;
  9732. s.heap_max = HEAP_SIZE;
  9733. for (n = 0; n < elems; n++) {
  9734. if (tree[n * 2] !== 0) {
  9735. s.heap[++s.heap_len] = max_code = n;
  9736. s.depth[n] = 0;
  9737. } else {
  9738. tree[n * 2 + 1] = 0;
  9739. }
  9740. }
  9741. // The pkzip format requires that at least one distance code exists,
  9742. // and that at least one bit should be sent even if there is only one
  9743. // possible code. So to avoid special checks later on we force at least
  9744. // two codes of non zero frequency.
  9745. while (s.heap_len < 2) {
  9746. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  9747. tree[node * 2] = 1;
  9748. s.depth[node] = 0;
  9749. s.opt_len--;
  9750. if (stree)
  9751. s.static_len -= stree[node * 2 + 1];
  9752. // node is 0 or 1 so it does not have extra bits
  9753. }
  9754. that.max_code = max_code;
  9755. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9756. // establish sub-heaps of increasing lengths:
  9757. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  9758. s.pqdownheap(tree, n);
  9759. // Construct the Huffman tree by repeatedly combining the least two
  9760. // frequent nodes.
  9761. node = elems; // next internal node of the tree
  9762. do {
  9763. // n = node of least frequency
  9764. n = s.heap[1];
  9765. s.heap[1] = s.heap[s.heap_len--];
  9766. s.pqdownheap(tree, 1);
  9767. m = s.heap[1]; // m = node of next least frequency
  9768. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  9769. s.heap[--s.heap_max] = m;
  9770. // Create a new node father of n and m
  9771. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  9772. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  9773. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  9774. // and insert the new node in the heap
  9775. s.heap[1] = node++;
  9776. s.pqdownheap(tree, 1);
  9777. } while (s.heap_len >= 2);
  9778. s.heap[--s.heap_max] = s.heap[1];
  9779. // At this point, the fields freq and dad are set. We can now
  9780. // generate the bit lengths.
  9781. gen_bitlen(s);
  9782. // The field len is now set, we can generate the bit codes
  9783. gen_codes(tree, that.max_code, s.bl_count);
  9784. };
  9785. }
  9786. 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,
  9787. 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,
  9788. 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,
  9789. 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,
  9790. 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,
  9791. 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,
  9792. 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 ];
  9793. 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 ];
  9794. 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,
  9795. 24576 ];
  9796. // Mapping from a distance to a distance code. dist is the distance - 1 and
  9797. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  9798. // used.
  9799. Tree.d_code = function(dist) {
  9800. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  9801. };
  9802. // extra bits for each length code
  9803. 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 ];
  9804. // extra bits for each distance code
  9805. 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 ];
  9806. // extra bits for each bit length code
  9807. Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
  9808. Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9809. // StaticTree
  9810. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  9811. var that = this;
  9812. that.static_tree = static_tree;
  9813. that.extra_bits = extra_bits;
  9814. that.extra_base = extra_base;
  9815. that.elems = elems;
  9816. that.max_length = max_length;
  9817. }
  9818. 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,
  9819. 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,
  9820. 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,
  9821. 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,
  9822. 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,
  9823. 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,
  9824. 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,
  9825. 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,
  9826. 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,
  9827. 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,
  9828. 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,
  9829. 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,
  9830. 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,
  9831. 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,
  9832. 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,
  9833. 99, 8, 227, 8 ];
  9834. 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,
  9835. 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
  9836. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9837. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  9838. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9839. // Deflate
  9840. var MAX_MEM_LEVEL = 9;
  9841. var DEF_MEM_LEVEL = 8;
  9842. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  9843. var that = this;
  9844. that.good_length = good_length;
  9845. that.max_lazy = max_lazy;
  9846. that.nice_length = nice_length;
  9847. that.max_chain = max_chain;
  9848. that.func = func;
  9849. }
  9850. var STORED = 0;
  9851. var FAST = 1;
  9852. var SLOW = 2;
  9853. 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),
  9854. 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),
  9855. new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
  9856. var z_errmsg = [ "need dictionary", // Z_NEED_DICT
  9857. // 2
  9858. "stream end", // Z_STREAM_END 1
  9859. "", // Z_OK 0
  9860. "", // Z_ERRNO (-1)
  9861. "stream error", // Z_STREAM_ERROR (-2)
  9862. "data error", // Z_DATA_ERROR (-3)
  9863. "", // Z_MEM_ERROR (-4)
  9864. "buffer error", // Z_BUF_ERROR (-5)
  9865. "",// Z_VERSION_ERROR (-6)
  9866. "" ];
  9867. // block not completed, need more input or more output
  9868. var NeedMore = 0;
  9869. // block flush performed
  9870. var BlockDone = 1;
  9871. // finish started, need only more output at next deflate
  9872. var FinishStarted = 2;
  9873. // finish done, accept no more input or output
  9874. var FinishDone = 3;
  9875. // preset dictionary flag in zlib header
  9876. var PRESET_DICT = 0x20;
  9877. var INIT_STATE = 42;
  9878. var BUSY_STATE = 113;
  9879. var FINISH_STATE = 666;
  9880. // The deflate compression method
  9881. var Z_DEFLATED = 8;
  9882. var STORED_BLOCK = 0;
  9883. var STATIC_TREES = 1;
  9884. var DYN_TREES = 2;
  9885. var MIN_MATCH = 3;
  9886. var MAX_MATCH = 258;
  9887. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  9888. function smaller(tree, n, m, depth) {
  9889. var tn2 = tree[n * 2];
  9890. var tm2 = tree[m * 2];
  9891. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  9892. }
  9893. function Deflate() {
  9894. var that = this;
  9895. var strm; // pointer back to this zlib stream
  9896. var status; // as the name implies
  9897. // pending_buf; // output still pending
  9898. var pending_buf_size; // size of pending_buf
  9899. // pending_out; // next pending byte to output to the stream
  9900. // pending; // nb of bytes in the pending buffer
  9901. var method; // STORED (for zip only) or DEFLATED
  9902. var last_flush; // value of flush param for previous deflate call
  9903. var w_size; // LZ77 window size (32K by default)
  9904. var w_bits; // log2(w_size) (8..16)
  9905. var w_mask; // w_size - 1
  9906. var window;
  9907. // Sliding window. Input bytes are read into the second half of the window,
  9908. // and move to the first half later to keep a dictionary of at least wSize
  9909. // bytes. With this organization, matches are limited to a distance of
  9910. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  9911. // performed with a length multiple of the block size. Also, it limits
  9912. // the window size to 64K, which is quite useful on MSDOS.
  9913. // To do: use the user input buffer as sliding window.
  9914. var window_size;
  9915. // Actual size of window: 2*wSize, except when the user input buffer
  9916. // is directly used as sliding window.
  9917. var prev;
  9918. // Link to older string with same hash index. To limit the size of this
  9919. // array to 64K, this link is maintained only for the last 32K strings.
  9920. // An index in this array is thus a window index modulo 32K.
  9921. var head; // Heads of the hash chains or NIL.
  9922. var ins_h; // hash index of string to be inserted
  9923. var hash_size; // number of elements in hash table
  9924. var hash_bits; // log2(hash_size)
  9925. var hash_mask; // hash_size-1
  9926. // Number of bits by which ins_h must be shifted at each input
  9927. // step. It must be such that after MIN_MATCH steps, the oldest
  9928. // byte no longer takes part in the hash key, that is:
  9929. // hash_shift * MIN_MATCH >= hash_bits
  9930. var hash_shift;
  9931. // Window position at the beginning of the current output block. Gets
  9932. // negative when the window is moved backwards.
  9933. var block_start;
  9934. var match_length; // length of best match
  9935. var prev_match; // previous match
  9936. var match_available; // set if previous match exists
  9937. var strstart; // start of string to insert
  9938. var match_start; // start of matching string
  9939. var lookahead; // number of valid bytes ahead in window
  9940. // Length of the best match at previous step. Matches not greater than this
  9941. // are discarded. This is used in the lazy match evaluation.
  9942. var prev_length;
  9943. // To speed up deflation, hash chains are never searched beyond this
  9944. // length. A higher limit improves compression ratio but degrades the speed.
  9945. var max_chain_length;
  9946. // Attempt to find a better match only when the current match is strictly
  9947. // smaller than this value. This mechanism is used only for compression
  9948. // levels >= 4.
  9949. var max_lazy_match;
  9950. // Insert new strings in the hash table only if the match length is not
  9951. // greater than this length. This saves time but degrades compression.
  9952. // max_insert_length is used only for compression levels <= 3.
  9953. var level; // compression level (1..9)
  9954. var strategy; // favor or force Huffman coding
  9955. // Use a faster search when the previous match is longer than this
  9956. var good_match;
  9957. // Stop searching when current match exceeds this
  9958. var nice_match;
  9959. var dyn_ltree; // literal and length tree
  9960. var dyn_dtree; // distance tree
  9961. var bl_tree; // Huffman tree for bit lengths
  9962. var l_desc = new Tree(); // desc for literal tree
  9963. var d_desc = new Tree(); // desc for distance tree
  9964. var bl_desc = new Tree(); // desc for bit length tree
  9965. // that.heap_len; // number of elements in the heap
  9966. // that.heap_max; // element of largest frequency
  9967. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  9968. // The same heap array is used to build all trees.
  9969. // Depth of each subtree used as tie breaker for trees of equal frequency
  9970. that.depth = [];
  9971. var l_buf; // index for literals or lengths */
  9972. // Size of match buffer for literals/lengths. There are 4 reasons for
  9973. // limiting lit_bufsize to 64K:
  9974. // - frequencies can be kept in 16 bit counters
  9975. // - if compression is not successful for the first block, all input
  9976. // data is still in the window so we can still emit a stored block even
  9977. // when input comes from standard input. (This can also be done for
  9978. // all blocks if lit_bufsize is not greater than 32K.)
  9979. // - if compression is not successful for a file smaller than 64K, we can
  9980. // even emit a stored file instead of a stored block (saving 5 bytes).
  9981. // This is applicable only for zip (not gzip or zlib).
  9982. // - creating new Huffman trees less frequently may not provide fast
  9983. // adaptation to changes in the input data statistics. (Take for
  9984. // example a binary file with poorly compressible code followed by
  9985. // a highly compressible string table.) Smaller buffer sizes give
  9986. // fast adaptation but have of course the overhead of transmitting
  9987. // trees more frequently.
  9988. // - I can't count above 4
  9989. var lit_bufsize;
  9990. var last_lit; // running index in l_buf
  9991. // Buffer for distances. To simplify the code, d_buf and l_buf have
  9992. // the same number of elements. To use different lengths, an extra flag
  9993. // array would be necessary.
  9994. var d_buf; // index of pendig_buf
  9995. // that.opt_len; // bit length of current block with optimal trees
  9996. // that.static_len; // bit length of current block with static trees
  9997. var matches; // number of string matches in current block
  9998. var last_eob_len; // bit length of EOB code for last block
  9999. // Output buffer. bits are inserted starting at the bottom (least
  10000. // significant bits).
  10001. var bi_buf;
  10002. // Number of valid bits in bi_buf. All bits above the last valid bit
  10003. // are always zero.
  10004. var bi_valid;
  10005. // number of codes at each bit length for an optimal tree
  10006. that.bl_count = [];
  10007. // heap used to build the Huffman trees
  10008. that.heap = [];
  10009. dyn_ltree = [];
  10010. dyn_dtree = [];
  10011. bl_tree = [];
  10012. function lm_init() {
  10013. var i;
  10014. window_size = 2 * w_size;
  10015. head[hash_size - 1] = 0;
  10016. for (i = 0; i < hash_size - 1; i++) {
  10017. head[i] = 0;
  10018. }
  10019. // Set the default configuration parameters:
  10020. max_lazy_match = config_table[level].max_lazy;
  10021. good_match = config_table[level].good_length;
  10022. nice_match = config_table[level].nice_length;
  10023. max_chain_length = config_table[level].max_chain;
  10024. strstart = 0;
  10025. block_start = 0;
  10026. lookahead = 0;
  10027. match_length = prev_length = MIN_MATCH - 1;
  10028. match_available = 0;
  10029. ins_h = 0;
  10030. }
  10031. function init_block() {
  10032. var i;
  10033. // Initialize the trees.
  10034. for (i = 0; i < L_CODES; i++)
  10035. dyn_ltree[i * 2] = 0;
  10036. for (i = 0; i < D_CODES; i++)
  10037. dyn_dtree[i * 2] = 0;
  10038. for (i = 0; i < BL_CODES; i++)
  10039. bl_tree[i * 2] = 0;
  10040. dyn_ltree[END_BLOCK * 2] = 1;
  10041. that.opt_len = that.static_len = 0;
  10042. last_lit = matches = 0;
  10043. }
  10044. // Initialize the tree data structures for a new zlib stream.
  10045. function tr_init() {
  10046. l_desc.dyn_tree = dyn_ltree;
  10047. l_desc.stat_desc = StaticTree.static_l_desc;
  10048. d_desc.dyn_tree = dyn_dtree;
  10049. d_desc.stat_desc = StaticTree.static_d_desc;
  10050. bl_desc.dyn_tree = bl_tree;
  10051. bl_desc.stat_desc = StaticTree.static_bl_desc;
  10052. bi_buf = 0;
  10053. bi_valid = 0;
  10054. last_eob_len = 8; // enough lookahead for inflate
  10055. // Initialize the first block of the first file:
  10056. init_block();
  10057. }
  10058. // Restore the heap property by moving down the tree starting at node k,
  10059. // exchanging a node with the smallest of its two sons if necessary,
  10060. // stopping
  10061. // when the heap property is re-established (each father smaller than its
  10062. // two sons).
  10063. that.pqdownheap = function(tree, // the tree to restore
  10064. k // node to move down
  10065. ) {
  10066. var heap = that.heap;
  10067. var v = heap[k];
  10068. var j = k << 1; // left son of k
  10069. while (j <= that.heap_len) {
  10070. // Set j to the smallest of the two sons:
  10071. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  10072. j++;
  10073. }
  10074. // Exit if v is smaller than both sons
  10075. if (smaller(tree, v, heap[j], that.depth))
  10076. break;
  10077. // Exchange v with the smallest son
  10078. heap[k] = heap[j];
  10079. k = j;
  10080. // And continue down the tree, setting j to the left son of k
  10081. j <<= 1;
  10082. }
  10083. heap[k] = v;
  10084. };
  10085. // Scan a literal or distance tree to determine the frequencies of the codes
  10086. // in the bit length tree.
  10087. function scan_tree(tree,// the tree to be scanned
  10088. max_code // and its largest code of non zero frequency
  10089. ) {
  10090. var n; // iterates over all tree elements
  10091. var prevlen = -1; // last emitted length
  10092. var curlen; // length of current code
  10093. var nextlen = tree[0 * 2 + 1]; // length of next code
  10094. var count = 0; // repeat count of the current code
  10095. var max_count = 7; // max repeat count
  10096. var min_count = 4; // min repeat count
  10097. if (nextlen === 0) {
  10098. max_count = 138;
  10099. min_count = 3;
  10100. }
  10101. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  10102. for (n = 0; n <= max_code; n++) {
  10103. curlen = nextlen;
  10104. nextlen = tree[(n + 1) * 2 + 1];
  10105. if (++count < max_count && curlen == nextlen) {
  10106. continue;
  10107. } else if (count < min_count) {
  10108. bl_tree[curlen * 2] += count;
  10109. } else if (curlen !== 0) {
  10110. if (curlen != prevlen)
  10111. bl_tree[curlen * 2]++;
  10112. bl_tree[REP_3_6 * 2]++;
  10113. } else if (count <= 10) {
  10114. bl_tree[REPZ_3_10 * 2]++;
  10115. } else {
  10116. bl_tree[REPZ_11_138 * 2]++;
  10117. }
  10118. count = 0;
  10119. prevlen = curlen;
  10120. if (nextlen === 0) {
  10121. max_count = 138;
  10122. min_count = 3;
  10123. } else if (curlen == nextlen) {
  10124. max_count = 6;
  10125. min_count = 3;
  10126. } else {
  10127. max_count = 7;
  10128. min_count = 4;
  10129. }
  10130. }
  10131. }
  10132. // Construct the Huffman tree for the bit lengths and return the index in
  10133. // bl_order of the last bit length code to send.
  10134. function build_bl_tree() {
  10135. var max_blindex; // index of last bit length code of non zero freq
  10136. // Determine the bit length frequencies for literal and distance trees
  10137. scan_tree(dyn_ltree, l_desc.max_code);
  10138. scan_tree(dyn_dtree, d_desc.max_code);
  10139. // Build the bit length tree:
  10140. bl_desc.build_tree(that);
  10141. // opt_len now includes the length of the tree representations, except
  10142. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  10143. // counts.
  10144. // Determine the number of bit length codes to send. The pkzip format
  10145. // requires that at least 4 bit length codes be sent. (appnote.txt says
  10146. // 3 but the actual value used is 4.)
  10147. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  10148. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  10149. break;
  10150. }
  10151. // Update opt_len to include the bit length tree and counts
  10152. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  10153. return max_blindex;
  10154. }
  10155. // Output a byte on the stream.
  10156. // IN assertion: there is enough room in pending_buf.
  10157. function put_byte(p) {
  10158. that.pending_buf[that.pending++] = p;
  10159. }
  10160. function put_short(w) {
  10161. put_byte(w & 0xff);
  10162. put_byte((w >>> 8) & 0xff);
  10163. }
  10164. function putShortMSB(b) {
  10165. put_byte((b >> 8) & 0xff);
  10166. put_byte((b & 0xff) & 0xff);
  10167. }
  10168. function send_bits(value, length) {
  10169. var val, len = length;
  10170. if (bi_valid > Buf_size - len) {
  10171. val = value;
  10172. // bi_buf |= (val << bi_valid);
  10173. bi_buf |= ((val << bi_valid) & 0xffff);
  10174. put_short(bi_buf);
  10175. bi_buf = val >>> (Buf_size - bi_valid);
  10176. bi_valid += len - Buf_size;
  10177. } else {
  10178. // bi_buf |= (value) << bi_valid;
  10179. bi_buf |= (((value) << bi_valid) & 0xffff);
  10180. bi_valid += len;
  10181. }
  10182. }
  10183. function send_code(c, tree) {
  10184. var c2 = c * 2;
  10185. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  10186. }
  10187. // Send a literal or distance tree in compressed form, using the codes in
  10188. // bl_tree.
  10189. function send_tree(tree,// the tree to be sent
  10190. max_code // and its largest code of non zero frequency
  10191. ) {
  10192. var n; // iterates over all tree elements
  10193. var prevlen = -1; // last emitted length
  10194. var curlen; // length of current code
  10195. var nextlen = tree[0 * 2 + 1]; // length of next code
  10196. var count = 0; // repeat count of the current code
  10197. var max_count = 7; // max repeat count
  10198. var min_count = 4; // min repeat count
  10199. if (nextlen === 0) {
  10200. max_count = 138;
  10201. min_count = 3;
  10202. }
  10203. for (n = 0; n <= max_code; n++) {
  10204. curlen = nextlen;
  10205. nextlen = tree[(n + 1) * 2 + 1];
  10206. if (++count < max_count && curlen == nextlen) {
  10207. continue;
  10208. } else if (count < min_count) {
  10209. do {
  10210. send_code(curlen, bl_tree);
  10211. } while (--count !== 0);
  10212. } else if (curlen !== 0) {
  10213. if (curlen != prevlen) {
  10214. send_code(curlen, bl_tree);
  10215. count--;
  10216. }
  10217. send_code(REP_3_6, bl_tree);
  10218. send_bits(count - 3, 2);
  10219. } else if (count <= 10) {
  10220. send_code(REPZ_3_10, bl_tree);
  10221. send_bits(count - 3, 3);
  10222. } else {
  10223. send_code(REPZ_11_138, bl_tree);
  10224. send_bits(count - 11, 7);
  10225. }
  10226. count = 0;
  10227. prevlen = curlen;
  10228. if (nextlen === 0) {
  10229. max_count = 138;
  10230. min_count = 3;
  10231. } else if (curlen == nextlen) {
  10232. max_count = 6;
  10233. min_count = 3;
  10234. } else {
  10235. max_count = 7;
  10236. min_count = 4;
  10237. }
  10238. }
  10239. }
  10240. // Send the header for a block using dynamic Huffman trees: the counts, the
  10241. // lengths of the bit length codes, the literal tree and the distance tree.
  10242. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  10243. function send_all_trees(lcodes, dcodes, blcodes) {
  10244. var rank; // index in bl_order
  10245. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  10246. send_bits(dcodes - 1, 5);
  10247. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  10248. for (rank = 0; rank < blcodes; rank++) {
  10249. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  10250. }
  10251. send_tree(dyn_ltree, lcodes - 1); // literal tree
  10252. send_tree(dyn_dtree, dcodes - 1); // distance tree
  10253. }
  10254. // Flush the bit buffer, keeping at most 7 bits in it.
  10255. function bi_flush() {
  10256. if (bi_valid == 16) {
  10257. put_short(bi_buf);
  10258. bi_buf = 0;
  10259. bi_valid = 0;
  10260. } else if (bi_valid >= 8) {
  10261. put_byte(bi_buf & 0xff);
  10262. bi_buf >>>= 8;
  10263. bi_valid -= 8;
  10264. }
  10265. }
  10266. // Send one empty static block to give enough lookahead for inflate.
  10267. // This takes 10 bits, of which 7 may remain in the bit buffer.
  10268. // The current inflate code requires 9 bits of lookahead. If the
  10269. // last two codes for the previous block (real code plus EOB) were coded
  10270. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  10271. // the last real code. In this case we send two empty static blocks instead
  10272. // of one. (There are no problems if the previous block is stored or fixed.)
  10273. // To simplify the code, we assume the worst case of last real code encoded
  10274. // on one bit only.
  10275. function _tr_align() {
  10276. send_bits(STATIC_TREES << 1, 3);
  10277. send_code(END_BLOCK, StaticTree.static_ltree);
  10278. bi_flush();
  10279. // Of the 10 bits for the empty block, we have already sent
  10280. // (10 - bi_valid) bits. The lookahead for the last real code (before
  10281. // the EOB of the previous block) was thus at least one plus the length
  10282. // of the EOB plus what we have just sent of the empty static block.
  10283. if (1 + last_eob_len + 10 - bi_valid < 9) {
  10284. send_bits(STATIC_TREES << 1, 3);
  10285. send_code(END_BLOCK, StaticTree.static_ltree);
  10286. bi_flush();
  10287. }
  10288. last_eob_len = 7;
  10289. }
  10290. // Save the match info and tally the frequency counts. Return true if
  10291. // the current block must be flushed.
  10292. function _tr_tally(dist, // distance of matched string
  10293. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  10294. ) {
  10295. var out_length, in_length, dcode;
  10296. that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
  10297. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  10298. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  10299. last_lit++;
  10300. if (dist === 0) {
  10301. // lc is the unmatched char
  10302. dyn_ltree[lc * 2]++;
  10303. } else {
  10304. matches++;
  10305. // Here, lc is the match length - MIN_MATCH
  10306. dist--; // dist = match distance - 1
  10307. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  10308. dyn_dtree[Tree.d_code(dist) * 2]++;
  10309. }
  10310. if ((last_lit & 0x1fff) === 0 && level > 2) {
  10311. // Compute an upper bound for the compressed length
  10312. out_length = last_lit * 8;
  10313. in_length = strstart - block_start;
  10314. for (dcode = 0; dcode < D_CODES; dcode++) {
  10315. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  10316. }
  10317. out_length >>>= 3;
  10318. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  10319. return true;
  10320. }
  10321. return (last_lit == lit_bufsize - 1);
  10322. // We avoid equality with lit_bufsize because of wraparound at 64K
  10323. // on 16 bit machines and because stored blocks are restricted to
  10324. // 64K-1 bytes.
  10325. }
  10326. // Send the block data compressed using the given Huffman trees
  10327. function compress_block(ltree, dtree) {
  10328. var dist; // distance of matched string
  10329. var lc; // match length or unmatched char (if dist === 0)
  10330. var lx = 0; // running index in l_buf
  10331. var code; // the code to send
  10332. var extra; // number of extra bits to send
  10333. if (last_lit !== 0) {
  10334. do {
  10335. dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
  10336. lc = (that.pending_buf[l_buf + lx]) & 0xff;
  10337. lx++;
  10338. if (dist === 0) {
  10339. send_code(lc, ltree); // send a literal byte
  10340. } else {
  10341. // Here, lc is the match length - MIN_MATCH
  10342. code = Tree._length_code[lc];
  10343. send_code(code + LITERALS + 1, ltree); // send the length
  10344. // code
  10345. extra = Tree.extra_lbits[code];
  10346. if (extra !== 0) {
  10347. lc -= Tree.base_length[code];
  10348. send_bits(lc, extra); // send the extra length bits
  10349. }
  10350. dist--; // dist is now the match distance - 1
  10351. code = Tree.d_code(dist);
  10352. send_code(code, dtree); // send the distance code
  10353. extra = Tree.extra_dbits[code];
  10354. if (extra !== 0) {
  10355. dist -= Tree.base_dist[code];
  10356. send_bits(dist, extra); // send the extra distance bits
  10357. }
  10358. } // literal or match pair ?
  10359. // Check that the overlay between pending_buf and d_buf+l_buf is
  10360. // ok:
  10361. } while (lx < last_lit);
  10362. }
  10363. send_code(END_BLOCK, ltree);
  10364. last_eob_len = ltree[END_BLOCK * 2 + 1];
  10365. }
  10366. // Flush the bit buffer and align the output on a byte boundary
  10367. function bi_windup() {
  10368. if (bi_valid > 8) {
  10369. put_short(bi_buf);
  10370. } else if (bi_valid > 0) {
  10371. put_byte(bi_buf & 0xff);
  10372. }
  10373. bi_buf = 0;
  10374. bi_valid = 0;
  10375. }
  10376. // Copy a stored block, storing first the length and its
  10377. // one's complement if requested.
  10378. function copy_block(buf, // the input data
  10379. len, // its length
  10380. header // true if block header must be written
  10381. ) {
  10382. bi_windup(); // align on byte boundary
  10383. last_eob_len = 8; // enough lookahead for inflate
  10384. if (header) {
  10385. put_short(len);
  10386. put_short(~len);
  10387. }
  10388. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  10389. that.pending += len;
  10390. }
  10391. // Send a stored block
  10392. function _tr_stored_block(buf, // input block
  10393. stored_len, // length of input block
  10394. eof // true if this is the last block for a file
  10395. ) {
  10396. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  10397. copy_block(buf, stored_len, true); // with header
  10398. }
  10399. // Determine the best encoding for the current block: dynamic trees, static
  10400. // trees or store, and output the encoded block to the zip file.
  10401. function _tr_flush_block(buf, // input block, or NULL if too old
  10402. stored_len, // length of input block
  10403. eof // true if this is the last block for a file
  10404. ) {
  10405. var opt_lenb, static_lenb;// opt_len and static_len in bytes
  10406. var max_blindex = 0; // index of last bit length code of non zero freq
  10407. // Build the Huffman trees unless a stored block is forced
  10408. if (level > 0) {
  10409. // Construct the literal and distance trees
  10410. l_desc.build_tree(that);
  10411. d_desc.build_tree(that);
  10412. // At this point, opt_len and static_len are the total bit lengths
  10413. // of
  10414. // the compressed block data, excluding the tree representations.
  10415. // Build the bit length tree for the above two trees, and get the
  10416. // index
  10417. // in bl_order of the last bit length code to send.
  10418. max_blindex = build_bl_tree();
  10419. // Determine the best encoding. Compute first the block length in
  10420. // bytes
  10421. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  10422. static_lenb = (that.static_len + 3 + 7) >>> 3;
  10423. if (static_lenb <= opt_lenb)
  10424. opt_lenb = static_lenb;
  10425. } else {
  10426. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  10427. }
  10428. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  10429. // 4: two words for the lengths
  10430. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10431. // Otherwise we can't have processed more than WSIZE input bytes
  10432. // since
  10433. // the last block flush, because compression would have been
  10434. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10435. // transform a block into a stored block.
  10436. _tr_stored_block(buf, stored_len, eof);
  10437. } else if (static_lenb == opt_lenb) {
  10438. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  10439. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  10440. } else {
  10441. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  10442. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  10443. compress_block(dyn_ltree, dyn_dtree);
  10444. }
  10445. // The above check is made mod 2^32, for files larger than 512 MB
  10446. // and uLong implemented on 32 bits.
  10447. init_block();
  10448. if (eof) {
  10449. bi_windup();
  10450. }
  10451. }
  10452. function flush_block_only(eof) {
  10453. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  10454. block_start = strstart;
  10455. strm.flush_pending();
  10456. }
  10457. // Fill the window when the lookahead becomes insufficient.
  10458. // Updates strstart and lookahead.
  10459. //
  10460. // IN assertion: lookahead < MIN_LOOKAHEAD
  10461. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  10462. // At least one byte has been read, or avail_in === 0; reads are
  10463. // performed for at least two bytes (required for the zip translate_eol
  10464. // option -- not supported here).
  10465. function fill_window() {
  10466. var n, m;
  10467. var p;
  10468. var more; // Amount of free space at the end of the window.
  10469. do {
  10470. more = (window_size - lookahead - strstart);
  10471. // Deal with !@#$% 64K limit:
  10472. if (more === 0 && strstart === 0 && lookahead === 0) {
  10473. more = w_size;
  10474. } else if (more == -1) {
  10475. // Very unlikely, but possible on 16 bit machine if strstart ==
  10476. // 0
  10477. // and lookahead == 1 (input done one byte at time)
  10478. more--;
  10479. // If the window is almost full and there is insufficient
  10480. // lookahead,
  10481. // move the upper half to the lower one to make room in the
  10482. // upper half.
  10483. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  10484. window.set(window.subarray(w_size, w_size + w_size), 0);
  10485. match_start -= w_size;
  10486. strstart -= w_size; // we now have strstart >= MAX_DIST
  10487. block_start -= w_size;
  10488. // Slide the hash table (could be avoided with 32 bit values
  10489. // at the expense of memory usage). We slide even when level ==
  10490. // 0
  10491. // to keep the hash table consistent if we switch back to level
  10492. // > 0
  10493. // later. (Using level 0 permanently is not an optimal usage of
  10494. // zlib, so we don't care about this pathological case.)
  10495. n = hash_size;
  10496. p = n;
  10497. do {
  10498. m = (head[--p] & 0xffff);
  10499. head[p] = (m >= w_size ? m - w_size : 0);
  10500. } while (--n !== 0);
  10501. n = w_size;
  10502. p = n;
  10503. do {
  10504. m = (prev[--p] & 0xffff);
  10505. prev[p] = (m >= w_size ? m - w_size : 0);
  10506. // If n is not on any hash chain, prev[n] is garbage but
  10507. // its value will never be used.
  10508. } while (--n !== 0);
  10509. more += w_size;
  10510. }
  10511. if (strm.avail_in === 0)
  10512. return;
  10513. // If there was no sliding:
  10514. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  10515. // more == window_size - lookahead - strstart
  10516. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  10517. // => more >= window_size - 2*WSIZE + 2
  10518. // In the BIG_MEM or MMAP case (not yet supported),
  10519. // window_size == input_size + MIN_LOOKAHEAD &&
  10520. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  10521. // Otherwise, window_size == 2*WSIZE so more >= 2.
  10522. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  10523. n = strm.read_buf(window, strstart + lookahead, more);
  10524. lookahead += n;
  10525. // Initialize the hash value now that we have some input:
  10526. if (lookahead >= MIN_MATCH) {
  10527. ins_h = window[strstart] & 0xff;
  10528. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10529. }
  10530. // If the whole input has less than MIN_MATCH bytes, ins_h is
  10531. // garbage,
  10532. // but this is not important since only literal bytes will be
  10533. // emitted.
  10534. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  10535. }
  10536. // Copy without compression as much as possible from the input stream,
  10537. // return
  10538. // the current block state.
  10539. // This function does not insert new strings in the dictionary since
  10540. // uncompressible data is probably not useful. This function is used
  10541. // only for the level=0 compression option.
  10542. // NOTE: this function should be optimized to avoid extra copying from
  10543. // window to pending_buf.
  10544. function deflate_stored(flush) {
  10545. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  10546. // to pending_buf_size, and each stored block has a 5 byte header:
  10547. var max_block_size = 0xffff;
  10548. var max_start;
  10549. if (max_block_size > pending_buf_size - 5) {
  10550. max_block_size = pending_buf_size - 5;
  10551. }
  10552. // Copy as much as possible from input to output:
  10553. while (true) {
  10554. // Fill the window as much as possible:
  10555. if (lookahead <= 1) {
  10556. fill_window();
  10557. if (lookahead === 0 && flush == Z_NO_FLUSH)
  10558. return NeedMore;
  10559. if (lookahead === 0)
  10560. break; // flush the current block
  10561. }
  10562. strstart += lookahead;
  10563. lookahead = 0;
  10564. // Emit a stored block if pending_buf will be full:
  10565. max_start = block_start + max_block_size;
  10566. if (strstart === 0 || strstart >= max_start) {
  10567. // strstart === 0 is possible when wraparound on 16-bit machine
  10568. lookahead = (strstart - max_start);
  10569. strstart = max_start;
  10570. flush_block_only(false);
  10571. if (strm.avail_out === 0)
  10572. return NeedMore;
  10573. }
  10574. // Flush if we may have to slide, otherwise block_start may become
  10575. // negative and the data will be gone:
  10576. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  10577. flush_block_only(false);
  10578. if (strm.avail_out === 0)
  10579. return NeedMore;
  10580. }
  10581. }
  10582. flush_block_only(flush == Z_FINISH);
  10583. if (strm.avail_out === 0)
  10584. return (flush == Z_FINISH) ? FinishStarted : NeedMore;
  10585. return flush == Z_FINISH ? FinishDone : BlockDone;
  10586. }
  10587. function longest_match(cur_match) {
  10588. var chain_length = max_chain_length; // max hash chain length
  10589. var scan = strstart; // current string
  10590. var match; // matched string
  10591. var len; // length of current match
  10592. var best_len = prev_length; // best match length so far
  10593. var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  10594. var _nice_match = nice_match;
  10595. // Stop when cur_match becomes <= limit. To simplify the code,
  10596. // we prevent matches with the string of window index 0.
  10597. var wmask = w_mask;
  10598. var strend = strstart + MAX_MATCH;
  10599. var scan_end1 = window[scan + best_len - 1];
  10600. var scan_end = window[scan + best_len];
  10601. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  10602. // 16.
  10603. // It is easy to get rid of this optimization if necessary.
  10604. // Do not waste too much time if we already have a good match:
  10605. if (prev_length >= good_match) {
  10606. chain_length >>= 2;
  10607. }
  10608. // Do not look for matches beyond the end of the input. This is
  10609. // necessary
  10610. // to make deflate deterministic.
  10611. if (_nice_match > lookahead)
  10612. _nice_match = lookahead;
  10613. do {
  10614. match = cur_match;
  10615. // Skip to next match if the match length cannot increase
  10616. // or if the match length is less than 2:
  10617. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
  10618. || window[++match] != window[scan + 1])
  10619. continue;
  10620. // The check at best_len-1 can be removed because it will be made
  10621. // again later. (This heuristic is not always a win.)
  10622. // It is not necessary to compare scan[2] and match[2] since they
  10623. // are always equal when the other bytes match, given that
  10624. // the hash keys are equal and that HASH_BITS >= 8.
  10625. scan += 2;
  10626. match++;
  10627. // We check for insufficient lookahead only every 8th comparison;
  10628. // the 256th check will be made at strstart+258.
  10629. do {
  10630. } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10631. && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10632. && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  10633. len = MAX_MATCH - (strend - scan);
  10634. scan = strend - MAX_MATCH;
  10635. if (len > best_len) {
  10636. match_start = cur_match;
  10637. best_len = len;
  10638. if (len >= _nice_match)
  10639. break;
  10640. scan_end1 = window[scan + best_len - 1];
  10641. scan_end = window[scan + best_len];
  10642. }
  10643. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  10644. if (best_len <= lookahead)
  10645. return best_len;
  10646. return lookahead;
  10647. }
  10648. // Compress as much as possible from the input stream, return the current
  10649. // block state.
  10650. // This function does not perform lazy evaluation of matches and inserts
  10651. // new strings in the dictionary only for unmatched strings or for short
  10652. // matches. It is used only for the fast compression options.
  10653. function deflate_fast(flush) {
  10654. // short hash_head = 0; // head of the hash chain
  10655. var hash_head = 0; // head of the hash chain
  10656. var bflush; // set if current block must be flushed
  10657. while (true) {
  10658. // Make sure that we always have enough lookahead, except
  10659. // at the end of the input file. We need MAX_MATCH bytes
  10660. // for the next match, plus MIN_MATCH bytes to insert the
  10661. // string following the next match.
  10662. if (lookahead < MIN_LOOKAHEAD) {
  10663. fill_window();
  10664. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10665. return NeedMore;
  10666. }
  10667. if (lookahead === 0)
  10668. break; // flush the current block
  10669. }
  10670. // Insert the string window[strstart .. strstart+2] in the
  10671. // dictionary, and set hash_head to the head of the hash chain:
  10672. if (lookahead >= MIN_MATCH) {
  10673. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10674. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10675. hash_head = (head[ins_h] & 0xffff);
  10676. prev[strstart & w_mask] = head[ins_h];
  10677. head[ins_h] = strstart;
  10678. }
  10679. // Find the longest match, discarding those <= prev_length.
  10680. // At this point we have always match_length < MIN_MATCH
  10681. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10682. // To simplify the code, we prevent matches with the string
  10683. // of window index 0 (in particular we have to avoid a match
  10684. // of the string with itself at the start of the input file).
  10685. if (strategy != Z_HUFFMAN_ONLY) {
  10686. match_length = longest_match(hash_head);
  10687. }
  10688. // longest_match() sets match_start
  10689. }
  10690. if (match_length >= MIN_MATCH) {
  10691. // check_match(strstart, match_start, match_length);
  10692. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  10693. lookahead -= match_length;
  10694. // Insert new strings in the hash table only if the match length
  10695. // is not too large. This saves time but degrades compression.
  10696. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  10697. match_length--; // string at strstart already in hash table
  10698. do {
  10699. strstart++;
  10700. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10701. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10702. hash_head = (head[ins_h] & 0xffff);
  10703. prev[strstart & w_mask] = head[ins_h];
  10704. head[ins_h] = strstart;
  10705. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  10706. // always MIN_MATCH bytes ahead.
  10707. } while (--match_length !== 0);
  10708. strstart++;
  10709. } else {
  10710. strstart += match_length;
  10711. match_length = 0;
  10712. ins_h = window[strstart] & 0xff;
  10713. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10714. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  10715. // not
  10716. // matter since it will be recomputed at next deflate call.
  10717. }
  10718. } else {
  10719. // No match, output a literal byte
  10720. bflush = _tr_tally(0, window[strstart] & 0xff);
  10721. lookahead--;
  10722. strstart++;
  10723. }
  10724. if (bflush) {
  10725. flush_block_only(false);
  10726. if (strm.avail_out === 0)
  10727. return NeedMore;
  10728. }
  10729. }
  10730. flush_block_only(flush == Z_FINISH);
  10731. if (strm.avail_out === 0) {
  10732. if (flush == Z_FINISH)
  10733. return FinishStarted;
  10734. else
  10735. return NeedMore;
  10736. }
  10737. return flush == Z_FINISH ? FinishDone : BlockDone;
  10738. }
  10739. // Same as above, but achieves better compression. We use a lazy
  10740. // evaluation for matches: a match is finally adopted only if there is
  10741. // no better match at the next window position.
  10742. function deflate_slow(flush) {
  10743. // short hash_head = 0; // head of hash chain
  10744. var hash_head = 0; // head of hash chain
  10745. var bflush; // set if current block must be flushed
  10746. var max_insert;
  10747. // Process the input block.
  10748. while (true) {
  10749. // Make sure that we always have enough lookahead, except
  10750. // at the end of the input file. We need MAX_MATCH bytes
  10751. // for the next match, plus MIN_MATCH bytes to insert the
  10752. // string following the next match.
  10753. if (lookahead < MIN_LOOKAHEAD) {
  10754. fill_window();
  10755. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10756. return NeedMore;
  10757. }
  10758. if (lookahead === 0)
  10759. break; // flush the current block
  10760. }
  10761. // Insert the string window[strstart .. strstart+2] in the
  10762. // dictionary, and set hash_head to the head of the hash chain:
  10763. if (lookahead >= MIN_MATCH) {
  10764. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10765. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10766. hash_head = (head[ins_h] & 0xffff);
  10767. prev[strstart & w_mask] = head[ins_h];
  10768. head[ins_h] = strstart;
  10769. }
  10770. // Find the longest match, discarding those <= prev_length.
  10771. prev_length = match_length;
  10772. prev_match = match_start;
  10773. match_length = MIN_MATCH - 1;
  10774. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10775. // To simplify the code, we prevent matches with the string
  10776. // of window index 0 (in particular we have to avoid a match
  10777. // of the string with itself at the start of the input file).
  10778. if (strategy != Z_HUFFMAN_ONLY) {
  10779. match_length = longest_match(hash_head);
  10780. }
  10781. // longest_match() sets match_start
  10782. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  10783. // If prev_match is also MIN_MATCH, match_start is garbage
  10784. // but we will ignore the current match anyway.
  10785. match_length = MIN_MATCH - 1;
  10786. }
  10787. }
  10788. // If there was a match at the previous step and the current
  10789. // match is not better, output the previous match:
  10790. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  10791. max_insert = strstart + lookahead - MIN_MATCH;
  10792. // Do not insert strings in hash table beyond this.
  10793. // check_match(strstart-1, prev_match, prev_length);
  10794. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  10795. // Insert in hash table all strings up to the end of the match.
  10796. // strstart-1 and strstart are already inserted. If there is not
  10797. // enough lookahead, the last two strings are not inserted in
  10798. // the hash table.
  10799. lookahead -= prev_length - 1;
  10800. prev_length -= 2;
  10801. do {
  10802. if (++strstart <= max_insert) {
  10803. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10804. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10805. hash_head = (head[ins_h] & 0xffff);
  10806. prev[strstart & w_mask] = head[ins_h];
  10807. head[ins_h] = strstart;
  10808. }
  10809. } while (--prev_length !== 0);
  10810. match_available = 0;
  10811. match_length = MIN_MATCH - 1;
  10812. strstart++;
  10813. if (bflush) {
  10814. flush_block_only(false);
  10815. if (strm.avail_out === 0)
  10816. return NeedMore;
  10817. }
  10818. } else if (match_available !== 0) {
  10819. // If there was no match at the previous position, output a
  10820. // single literal. If there was a match but the current match
  10821. // is longer, truncate the previous match to a single literal.
  10822. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10823. if (bflush) {
  10824. flush_block_only(false);
  10825. }
  10826. strstart++;
  10827. lookahead--;
  10828. if (strm.avail_out === 0)
  10829. return NeedMore;
  10830. } else {
  10831. // There is no previous match to compare with, wait for
  10832. // the next step to decide.
  10833. match_available = 1;
  10834. strstart++;
  10835. lookahead--;
  10836. }
  10837. }
  10838. if (match_available !== 0) {
  10839. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10840. match_available = 0;
  10841. }
  10842. flush_block_only(flush == Z_FINISH);
  10843. if (strm.avail_out === 0) {
  10844. if (flush == Z_FINISH)
  10845. return FinishStarted;
  10846. else
  10847. return NeedMore;
  10848. }
  10849. return flush == Z_FINISH ? FinishDone : BlockDone;
  10850. }
  10851. function deflateReset(strm) {
  10852. strm.total_in = strm.total_out = 0;
  10853. strm.msg = null; //
  10854. that.pending = 0;
  10855. that.pending_out = 0;
  10856. status = BUSY_STATE;
  10857. last_flush = Z_NO_FLUSH;
  10858. tr_init();
  10859. lm_init();
  10860. return Z_OK;
  10861. }
  10862. that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
  10863. if (!_method)
  10864. _method = Z_DEFLATED;
  10865. if (!memLevel)
  10866. memLevel = DEF_MEM_LEVEL;
  10867. if (!_strategy)
  10868. _strategy = Z_DEFAULT_STRATEGY;
  10869. // byte[] my_version=ZLIB_VERSION;
  10870. //
  10871. // if (!version || version[0] != my_version[0]
  10872. // || stream_size != sizeof(z_stream)) {
  10873. // return Z_VERSION_ERROR;
  10874. // }
  10875. strm.msg = null;
  10876. if (_level == Z_DEFAULT_COMPRESSION)
  10877. _level = 6;
  10878. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  10879. || _strategy > Z_HUFFMAN_ONLY) {
  10880. return Z_STREAM_ERROR;
  10881. }
  10882. strm.dstate = that;
  10883. w_bits = bits;
  10884. w_size = 1 << w_bits;
  10885. w_mask = w_size - 1;
  10886. hash_bits = memLevel + 7;
  10887. hash_size = 1 << hash_bits;
  10888. hash_mask = hash_size - 1;
  10889. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  10890. window = new Uint8Array(w_size * 2);
  10891. prev = [];
  10892. head = [];
  10893. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  10894. // We overlay pending_buf and d_buf+l_buf. This works since the average
  10895. // output size for (length,distance) codes is <= 24 bits.
  10896. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  10897. pending_buf_size = lit_bufsize * 4;
  10898. d_buf = Math.floor(lit_bufsize / 2);
  10899. l_buf = (1 + 2) * lit_bufsize;
  10900. level = _level;
  10901. strategy = _strategy;
  10902. method = _method & 0xff;
  10903. return deflateReset(strm);
  10904. };
  10905. that.deflateEnd = function() {
  10906. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  10907. return Z_STREAM_ERROR;
  10908. }
  10909. // Deallocate in reverse order of allocations:
  10910. that.pending_buf = null;
  10911. head = null;
  10912. prev = null;
  10913. window = null;
  10914. // free
  10915. that.dstate = null;
  10916. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  10917. };
  10918. that.deflateParams = function(strm, _level, _strategy) {
  10919. var err = Z_OK;
  10920. if (_level == Z_DEFAULT_COMPRESSION) {
  10921. _level = 6;
  10922. }
  10923. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  10924. return Z_STREAM_ERROR;
  10925. }
  10926. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  10927. // Flush the last buffer:
  10928. err = strm.deflate(Z_PARTIAL_FLUSH);
  10929. }
  10930. if (level != _level) {
  10931. level = _level;
  10932. max_lazy_match = config_table[level].max_lazy;
  10933. good_match = config_table[level].good_length;
  10934. nice_match = config_table[level].nice_length;
  10935. max_chain_length = config_table[level].max_chain;
  10936. }
  10937. strategy = _strategy;
  10938. return err;
  10939. };
  10940. that.deflateSetDictionary = function(strm, dictionary, dictLength) {
  10941. var length = dictLength;
  10942. var n, index = 0;
  10943. if (!dictionary || status != INIT_STATE)
  10944. return Z_STREAM_ERROR;
  10945. if (length < MIN_MATCH)
  10946. return Z_OK;
  10947. if (length > w_size - MIN_LOOKAHEAD) {
  10948. length = w_size - MIN_LOOKAHEAD;
  10949. index = dictLength - length; // use the tail of the dictionary
  10950. }
  10951. window.set(dictionary.subarray(index, index + length), 0);
  10952. strstart = length;
  10953. block_start = length;
  10954. // Insert all strings in the hash table (except for the last two bytes).
  10955. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  10956. // call of fill_window.
  10957. ins_h = window[0] & 0xff;
  10958. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  10959. for (n = 0; n <= length - MIN_MATCH; n++) {
  10960. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10961. prev[n & w_mask] = head[ins_h];
  10962. head[ins_h] = n;
  10963. }
  10964. return Z_OK;
  10965. };
  10966. that.deflate = function(_strm, flush) {
  10967. var i, header, level_flags, old_flush, bstate;
  10968. if (flush > Z_FINISH || flush < 0) {
  10969. return Z_STREAM_ERROR;
  10970. }
  10971. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
  10972. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  10973. return Z_STREAM_ERROR;
  10974. }
  10975. if (_strm.avail_out === 0) {
  10976. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10977. return Z_BUF_ERROR;
  10978. }
  10979. strm = _strm; // just in case
  10980. old_flush = last_flush;
  10981. last_flush = flush;
  10982. // Write the zlib header
  10983. if (status == INIT_STATE) {
  10984. header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  10985. level_flags = ((level - 1) & 0xff) >> 1;
  10986. if (level_flags > 3)
  10987. level_flags = 3;
  10988. header |= (level_flags << 6);
  10989. if (strstart !== 0)
  10990. header |= PRESET_DICT;
  10991. header += 31 - (header % 31);
  10992. status = BUSY_STATE;
  10993. putShortMSB(header);
  10994. }
  10995. // Flush as much pending output as possible
  10996. if (that.pending !== 0) {
  10997. strm.flush_pending();
  10998. if (strm.avail_out === 0) {
  10999. // console.log(" avail_out==0");
  11000. // Since avail_out is 0, deflate will be called again with
  11001. // more output space, but possibly with both pending and
  11002. // avail_in equal to zero. There won't be anything to do,
  11003. // but this is not an error situation so make sure we
  11004. // return OK instead of BUF_ERROR at next call of deflate:
  11005. last_flush = -1;
  11006. return Z_OK;
  11007. }
  11008. // Make sure there is something to do and avoid duplicate
  11009. // consecutive
  11010. // flushes. For repeated and useless calls with Z_FINISH, we keep
  11011. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  11012. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  11013. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  11014. return Z_BUF_ERROR;
  11015. }
  11016. // User must not provide more input after the first FINISH:
  11017. if (status == FINISH_STATE && strm.avail_in !== 0) {
  11018. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  11019. return Z_BUF_ERROR;
  11020. }
  11021. // Start a new block or continue the current one.
  11022. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
  11023. bstate = -1;
  11024. switch (config_table[level].func) {
  11025. case STORED:
  11026. bstate = deflate_stored(flush);
  11027. break;
  11028. case FAST:
  11029. bstate = deflate_fast(flush);
  11030. break;
  11031. case SLOW:
  11032. bstate = deflate_slow(flush);
  11033. break;
  11034. default:
  11035. }
  11036. if (bstate == FinishStarted || bstate == FinishDone) {
  11037. status = FINISH_STATE;
  11038. }
  11039. if (bstate == NeedMore || bstate == FinishStarted) {
  11040. if (strm.avail_out === 0) {
  11041. last_flush = -1; // avoid BUF_ERROR next call, see above
  11042. }
  11043. return Z_OK;
  11044. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  11045. // of deflate should use the same flush parameter to make sure
  11046. // that the flush is complete. So we don't have to output an
  11047. // empty block here, this will be done at next call. This also
  11048. // ensures that for a very small output buffer, we emit at most
  11049. // one empty block.
  11050. }
  11051. if (bstate == BlockDone) {
  11052. if (flush == Z_PARTIAL_FLUSH) {
  11053. _tr_align();
  11054. } else { // FULL_FLUSH or SYNC_FLUSH
  11055. _tr_stored_block(0, 0, false);
  11056. // For a full flush, this empty block will be recognized
  11057. // as a special marker by inflate_sync().
  11058. if (flush == Z_FULL_FLUSH) {
  11059. // state.head[s.hash_size-1]=0;
  11060. for (i = 0; i < hash_size/*-1*/; i++)
  11061. // forget history
  11062. head[i] = 0;
  11063. }
  11064. }
  11065. strm.flush_pending();
  11066. if (strm.avail_out === 0) {
  11067. last_flush = -1; // avoid BUF_ERROR at next call, see above
  11068. return Z_OK;
  11069. }
  11070. }
  11071. }
  11072. if (flush != Z_FINISH)
  11073. return Z_OK;
  11074. return Z_STREAM_END;
  11075. };
  11076. }
  11077. // ZStream
  11078. function ZStream() {
  11079. var that = this;
  11080. that.next_in_index = 0;
  11081. that.next_out_index = 0;
  11082. // that.next_in; // next input byte
  11083. that.avail_in = 0; // number of bytes available at next_in
  11084. that.total_in = 0; // total nb of input bytes read so far
  11085. // that.next_out; // next output byte should be put there
  11086. that.avail_out = 0; // remaining free space at next_out
  11087. that.total_out = 0; // total nb of bytes output so far
  11088. // that.msg;
  11089. // that.dstate;
  11090. }
  11091. ZStream.prototype = {
  11092. deflateInit : function(level, bits) {
  11093. var that = this;
  11094. that.dstate = new Deflate();
  11095. if (!bits)
  11096. bits = MAX_BITS;
  11097. return that.dstate.deflateInit(that, level, bits);
  11098. },
  11099. deflate : function(flush) {
  11100. var that = this;
  11101. if (!that.dstate) {
  11102. return Z_STREAM_ERROR;
  11103. }
  11104. return that.dstate.deflate(that, flush);
  11105. },
  11106. deflateEnd : function() {
  11107. var that = this;
  11108. if (!that.dstate)
  11109. return Z_STREAM_ERROR;
  11110. var ret = that.dstate.deflateEnd();
  11111. that.dstate = null;
  11112. return ret;
  11113. },
  11114. deflateParams : function(level, strategy) {
  11115. var that = this;
  11116. if (!that.dstate)
  11117. return Z_STREAM_ERROR;
  11118. return that.dstate.deflateParams(that, level, strategy);
  11119. },
  11120. deflateSetDictionary : function(dictionary, dictLength) {
  11121. var that = this;
  11122. if (!that.dstate)
  11123. return Z_STREAM_ERROR;
  11124. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  11125. },
  11126. // Read a new buffer from the current input stream, update the
  11127. // total number of bytes read. All deflate() input goes through
  11128. // this function so some applications may wish to modify it to avoid
  11129. // allocating a large strm->next_in buffer and copying from it.
  11130. // (See also flush_pending()).
  11131. read_buf : function(buf, start, size) {
  11132. var that = this;
  11133. var len = that.avail_in;
  11134. if (len > size)
  11135. len = size;
  11136. if (len === 0)
  11137. return 0;
  11138. that.avail_in -= len;
  11139. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  11140. that.next_in_index += len;
  11141. that.total_in += len;
  11142. return len;
  11143. },
  11144. // Flush as much pending output as possible. All deflate() output goes
  11145. // through this function so some applications may wish to modify it
  11146. // to avoid allocating a large strm->next_out buffer and copying into it.
  11147. // (See also read_buf()).
  11148. flush_pending : function() {
  11149. var that = this;
  11150. var len = that.dstate.pending;
  11151. if (len > that.avail_out)
  11152. len = that.avail_out;
  11153. if (len === 0)
  11154. return;
  11155. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  11156. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  11157. // len)) {
  11158. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  11159. // that.next_out_index + ", " + len);
  11160. // console.log("avail_out=" + that.avail_out);
  11161. // }
  11162. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  11163. that.next_out_index += len;
  11164. that.dstate.pending_out += len;
  11165. that.total_out += len;
  11166. that.avail_out -= len;
  11167. that.dstate.pending -= len;
  11168. if (that.dstate.pending === 0) {
  11169. that.dstate.pending_out = 0;
  11170. }
  11171. }
  11172. };
  11173. // Deflater
  11174. return function Deflater(level) {
  11175. var that = this;
  11176. var z = new ZStream();
  11177. var bufsize = 512;
  11178. var flush = Z_NO_FLUSH;
  11179. var buf = new Uint8Array(bufsize);
  11180. if (typeof level == "undefined")
  11181. level = Z_DEFAULT_COMPRESSION;
  11182. z.deflateInit(level);
  11183. z.next_out = buf;
  11184. that.append = function(data, onprogress) {
  11185. var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
  11186. if (!data.length)
  11187. return;
  11188. z.next_in_index = 0;
  11189. z.next_in = data;
  11190. z.avail_in = data.length;
  11191. do {
  11192. z.next_out_index = 0;
  11193. z.avail_out = bufsize;
  11194. err = z.deflate(flush);
  11195. if (err != Z_OK)
  11196. throw "deflating: " + z.msg;
  11197. if (z.next_out_index)
  11198. if (z.next_out_index == bufsize)
  11199. buffers.push(new Uint8Array(buf));
  11200. else
  11201. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11202. bufferSize += z.next_out_index;
  11203. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  11204. onprogress(z.next_in_index);
  11205. lastIndex = z.next_in_index;
  11206. }
  11207. } while (z.avail_in > 0 || z.avail_out === 0);
  11208. array = new Uint8Array(bufferSize);
  11209. buffers.forEach(function(chunk) {
  11210. array.set(chunk, bufferIndex);
  11211. bufferIndex += chunk.length;
  11212. });
  11213. return array;
  11214. };
  11215. that.flush = function() {
  11216. var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
  11217. do {
  11218. z.next_out_index = 0;
  11219. z.avail_out = bufsize;
  11220. err = z.deflate(Z_FINISH);
  11221. if (err != Z_STREAM_END && err != Z_OK)
  11222. throw "deflating: " + z.msg;
  11223. if (bufsize - z.avail_out > 0)
  11224. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  11225. bufferSize += z.next_out_index;
  11226. } while (z.avail_in > 0 || z.avail_out === 0);
  11227. z.deflateEnd();
  11228. array = new Uint8Array(bufferSize);
  11229. buffers.forEach(function(chunk) {
  11230. array.set(chunk, bufferIndex);
  11231. bufferIndex += chunk.length;
  11232. });
  11233. return array;
  11234. };
  11235. };
  11236. })(undefined);
  11237. /*
  11238. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  11239. Copyright (c) 2016 Niklas von Hertzen
  11240. Released under License
  11241. */
  11242. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e();}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  11243. (function (global){
  11244. /*! http://mths.be/punycode v1.2.4 by @mathias */
  11245. (function(root) {
  11246. /** Detect free variables */
  11247. var freeExports = typeof exports == 'object' && exports;
  11248. var freeModule = typeof module == 'object' && module &&
  11249. module.exports == freeExports && module;
  11250. var freeGlobal = typeof global == 'object' && global;
  11251. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  11252. root = freeGlobal;
  11253. }
  11254. /**
  11255. * The `punycode` object.
  11256. * @name punycode
  11257. * @type Object
  11258. */
  11259. var punycode,
  11260. /** Highest positive signed 32-bit float value */
  11261. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  11262. /** Bootstring parameters */
  11263. base = 36,
  11264. tMin = 1,
  11265. tMax = 26,
  11266. skew = 38,
  11267. damp = 700,
  11268. initialBias = 72,
  11269. initialN = 128, // 0x80
  11270. delimiter = '-', // '\x2D'
  11271. /** Regular expressions */
  11272. regexPunycode = /^xn--/,
  11273. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  11274. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  11275. /** Error messages */
  11276. errors = {
  11277. 'overflow': 'Overflow: input needs wider integers to process',
  11278. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  11279. 'invalid-input': 'Invalid input'
  11280. },
  11281. /** Convenience shortcuts */
  11282. baseMinusTMin = base - tMin,
  11283. floor = Math.floor,
  11284. stringFromCharCode = String.fromCharCode,
  11285. /** Temporary variable */
  11286. key;
  11287. /*--------------------------------------------------------------------------*/
  11288. /**
  11289. * A generic error utility function.
  11290. * @private
  11291. * @param {String} type The error type.
  11292. * @returns {Error} Throws a `RangeError` with the applicable error message.
  11293. */
  11294. function error(type) {
  11295. throw RangeError(errors[type]);
  11296. }
  11297. /**
  11298. * A generic `Array#map` utility function.
  11299. * @private
  11300. * @param {Array} array The array to iterate over.
  11301. * @param {Function} callback The function that gets called for every array
  11302. * item.
  11303. * @returns {Array} A new array of values returned by the callback function.
  11304. */
  11305. function map(array, fn) {
  11306. var length = array.length;
  11307. while (length--) {
  11308. array[length] = fn(array[length]);
  11309. }
  11310. return array;
  11311. }
  11312. /**
  11313. * A simple `Array#map`-like wrapper to work with domain name strings.
  11314. * @private
  11315. * @param {String} domain The domain name.
  11316. * @param {Function} callback The function that gets called for every
  11317. * character.
  11318. * @returns {Array} A new string of characters returned by the callback
  11319. * function.
  11320. */
  11321. function mapDomain(string, fn) {
  11322. return map(string.split(regexSeparators), fn).join('.');
  11323. }
  11324. /**
  11325. * Creates an array containing the numeric code points of each Unicode
  11326. * character in the string. While JavaScript uses UCS-2 internally,
  11327. * this function will convert a pair of surrogate halves (each of which
  11328. * UCS-2 exposes as separate characters) into a single code point,
  11329. * matching UTF-16.
  11330. * @see `punycode.ucs2.encode`
  11331. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11332. * @memberOf punycode.ucs2
  11333. * @name decode
  11334. * @param {String} string The Unicode input string (UCS-2).
  11335. * @returns {Array} The new array of code points.
  11336. */
  11337. function ucs2decode(string) {
  11338. var output = [],
  11339. counter = 0,
  11340. length = string.length,
  11341. value,
  11342. extra;
  11343. while (counter < length) {
  11344. value = string.charCodeAt(counter++);
  11345. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11346. // high surrogate, and there is a next character
  11347. extra = string.charCodeAt(counter++);
  11348. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11349. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11350. } else {
  11351. // unmatched surrogate; only append this code unit, in case the next
  11352. // code unit is the high surrogate of a surrogate pair
  11353. output.push(value);
  11354. counter--;
  11355. }
  11356. } else {
  11357. output.push(value);
  11358. }
  11359. }
  11360. return output;
  11361. }
  11362. /**
  11363. * Creates a string based on an array of numeric code points.
  11364. * @see `punycode.ucs2.decode`
  11365. * @memberOf punycode.ucs2
  11366. * @name encode
  11367. * @param {Array} codePoints The array of numeric code points.
  11368. * @returns {String} The new Unicode string (UCS-2).
  11369. */
  11370. function ucs2encode(array) {
  11371. return map(array, function(value) {
  11372. var output = '';
  11373. if (value > 0xFFFF) {
  11374. value -= 0x10000;
  11375. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11376. value = 0xDC00 | value & 0x3FF;
  11377. }
  11378. output += stringFromCharCode(value);
  11379. return output;
  11380. }).join('');
  11381. }
  11382. /**
  11383. * Converts a basic code point into a digit/integer.
  11384. * @see `digitToBasic()`
  11385. * @private
  11386. * @param {Number} codePoint The basic numeric code point value.
  11387. * @returns {Number} The numeric value of a basic code point (for use in
  11388. * representing integers) in the range `0` to `base - 1`, or `base` if
  11389. * the code point does not represent a value.
  11390. */
  11391. function basicToDigit(codePoint) {
  11392. if (codePoint - 48 < 10) {
  11393. return codePoint - 22;
  11394. }
  11395. if (codePoint - 65 < 26) {
  11396. return codePoint - 65;
  11397. }
  11398. if (codePoint - 97 < 26) {
  11399. return codePoint - 97;
  11400. }
  11401. return base;
  11402. }
  11403. /**
  11404. * Converts a digit/integer into a basic code point.
  11405. * @see `basicToDigit()`
  11406. * @private
  11407. * @param {Number} digit The numeric value of a basic code point.
  11408. * @returns {Number} The basic code point whose value (when used for
  11409. * representing integers) is `digit`, which needs to be in the range
  11410. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11411. * used; else, the lowercase form is used. The behavior is undefined
  11412. * if `flag` is non-zero and `digit` has no uppercase form.
  11413. */
  11414. function digitToBasic(digit, flag) {
  11415. // 0..25 map to ASCII a..z or A..Z
  11416. // 26..35 map to ASCII 0..9
  11417. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11418. }
  11419. /**
  11420. * Bias adaptation function as per section 3.4 of RFC 3492.
  11421. * http://tools.ietf.org/html/rfc3492#section-3.4
  11422. * @private
  11423. */
  11424. function adapt(delta, numPoints, firstTime) {
  11425. var k = 0;
  11426. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11427. delta += floor(delta / numPoints);
  11428. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  11429. delta = floor(delta / baseMinusTMin);
  11430. }
  11431. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11432. }
  11433. /**
  11434. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11435. * symbols.
  11436. * @memberOf punycode
  11437. * @param {String} input The Punycode string of ASCII-only symbols.
  11438. * @returns {String} The resulting string of Unicode symbols.
  11439. */
  11440. function decode(input) {
  11441. // Don't use UCS-2
  11442. var output = [],
  11443. inputLength = input.length,
  11444. out,
  11445. i = 0,
  11446. n = initialN,
  11447. bias = initialBias,
  11448. basic,
  11449. j,
  11450. index,
  11451. oldi,
  11452. w,
  11453. k,
  11454. digit,
  11455. t,
  11456. /** Cached calculation results */
  11457. baseMinusT;
  11458. // Handle the basic code points: let `basic` be the number of input code
  11459. // points before the last delimiter, or `0` if there is none, then copy
  11460. // the first basic code points to the output.
  11461. basic = input.lastIndexOf(delimiter);
  11462. if (basic < 0) {
  11463. basic = 0;
  11464. }
  11465. for (j = 0; j < basic; ++j) {
  11466. // if it's not a basic code point
  11467. if (input.charCodeAt(j) >= 0x80) {
  11468. error('not-basic');
  11469. }
  11470. output.push(input.charCodeAt(j));
  11471. }
  11472. // Main decoding loop: start just after the last delimiter if any basic code
  11473. // points were copied; start at the beginning otherwise.
  11474. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  11475. // `index` is the index of the next character to be consumed.
  11476. // Decode a generalized variable-length integer into `delta`,
  11477. // which gets added to `i`. The overflow checking is easier
  11478. // if we increase `i` as we go, then subtract off its starting
  11479. // value at the end to obtain `delta`.
  11480. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  11481. if (index >= inputLength) {
  11482. error('invalid-input');
  11483. }
  11484. digit = basicToDigit(input.charCodeAt(index++));
  11485. if (digit >= base || digit > floor((maxInt - i) / w)) {
  11486. error('overflow');
  11487. }
  11488. i += digit * w;
  11489. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11490. if (digit < t) {
  11491. break;
  11492. }
  11493. baseMinusT = base - t;
  11494. if (w > floor(maxInt / baseMinusT)) {
  11495. error('overflow');
  11496. }
  11497. w *= baseMinusT;
  11498. }
  11499. out = output.length + 1;
  11500. bias = adapt(i - oldi, out, oldi == 0);
  11501. // `i` was supposed to wrap around from `out` to `0`,
  11502. // incrementing `n` each time, so we'll fix that now:
  11503. if (floor(i / out) > maxInt - n) {
  11504. error('overflow');
  11505. }
  11506. n += floor(i / out);
  11507. i %= out;
  11508. // Insert `n` at position `i` of the output
  11509. output.splice(i++, 0, n);
  11510. }
  11511. return ucs2encode(output);
  11512. }
  11513. /**
  11514. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  11515. * symbols.
  11516. * @memberOf punycode
  11517. * @param {String} input The string of Unicode symbols.
  11518. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  11519. */
  11520. function encode(input) {
  11521. var n,
  11522. delta,
  11523. handledCPCount,
  11524. basicLength,
  11525. bias,
  11526. j,
  11527. m,
  11528. q,
  11529. k,
  11530. t,
  11531. currentValue,
  11532. output = [],
  11533. /** `inputLength` will hold the number of code points in `input`. */
  11534. inputLength,
  11535. /** Cached calculation results */
  11536. handledCPCountPlusOne,
  11537. baseMinusT,
  11538. qMinusT;
  11539. // Convert the input in UCS-2 to Unicode
  11540. input = ucs2decode(input);
  11541. // Cache the length
  11542. inputLength = input.length;
  11543. // Initialize the state
  11544. n = initialN;
  11545. delta = 0;
  11546. bias = initialBias;
  11547. // Handle the basic code points
  11548. for (j = 0; j < inputLength; ++j) {
  11549. currentValue = input[j];
  11550. if (currentValue < 0x80) {
  11551. output.push(stringFromCharCode(currentValue));
  11552. }
  11553. }
  11554. handledCPCount = basicLength = output.length;
  11555. // `handledCPCount` is the number of code points that have been handled;
  11556. // `basicLength` is the number of basic code points.
  11557. // Finish the basic string - if it is not empty - with a delimiter
  11558. if (basicLength) {
  11559. output.push(delimiter);
  11560. }
  11561. // Main encoding loop:
  11562. while (handledCPCount < inputLength) {
  11563. // All non-basic code points < n have been handled already. Find the next
  11564. // larger one:
  11565. for (m = maxInt, j = 0; j < inputLength; ++j) {
  11566. currentValue = input[j];
  11567. if (currentValue >= n && currentValue < m) {
  11568. m = currentValue;
  11569. }
  11570. }
  11571. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  11572. // but guard against overflow
  11573. handledCPCountPlusOne = handledCPCount + 1;
  11574. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  11575. error('overflow');
  11576. }
  11577. delta += (m - n) * handledCPCountPlusOne;
  11578. n = m;
  11579. for (j = 0; j < inputLength; ++j) {
  11580. currentValue = input[j];
  11581. if (currentValue < n && ++delta > maxInt) {
  11582. error('overflow');
  11583. }
  11584. if (currentValue == n) {
  11585. // Represent delta as a generalized variable-length integer
  11586. for (q = delta, k = base; /* no condition */; k += base) {
  11587. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11588. if (q < t) {
  11589. break;
  11590. }
  11591. qMinusT = q - t;
  11592. baseMinusT = base - t;
  11593. output.push(
  11594. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  11595. );
  11596. q = floor(qMinusT / baseMinusT);
  11597. }
  11598. output.push(stringFromCharCode(digitToBasic(q, 0)));
  11599. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  11600. delta = 0;
  11601. ++handledCPCount;
  11602. }
  11603. }
  11604. ++delta;
  11605. ++n;
  11606. }
  11607. return output.join('');
  11608. }
  11609. /**
  11610. * Converts a Punycode string representing a domain name to Unicode. Only the
  11611. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  11612. * matter if you call it on a string that has already been converted to
  11613. * Unicode.
  11614. * @memberOf punycode
  11615. * @param {String} domain The Punycode domain name to convert to Unicode.
  11616. * @returns {String} The Unicode representation of the given Punycode
  11617. * string.
  11618. */
  11619. function toUnicode(domain) {
  11620. return mapDomain(domain, function(string) {
  11621. return regexPunycode.test(string)
  11622. ? decode(string.slice(4).toLowerCase())
  11623. : string;
  11624. });
  11625. }
  11626. /**
  11627. * Converts a Unicode string representing a domain name to Punycode. Only the
  11628. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  11629. * matter if you call it with a domain that's already in ASCII.
  11630. * @memberOf punycode
  11631. * @param {String} domain The domain name to convert, as a Unicode string.
  11632. * @returns {String} The Punycode representation of the given domain name.
  11633. */
  11634. function toASCII(domain) {
  11635. return mapDomain(domain, function(string) {
  11636. return regexNonASCII.test(string)
  11637. ? 'xn--' + encode(string)
  11638. : string;
  11639. });
  11640. }
  11641. /*--------------------------------------------------------------------------*/
  11642. /** Define the public API */
  11643. punycode = {
  11644. /**
  11645. * A string representing the current Punycode.js version number.
  11646. * @memberOf punycode
  11647. * @type String
  11648. */
  11649. 'version': '1.2.4',
  11650. /**
  11651. * An object of methods to convert from JavaScript's internal character
  11652. * representation (UCS-2) to Unicode code points, and back.
  11653. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11654. * @memberOf punycode
  11655. * @type Object
  11656. */
  11657. 'ucs2': {
  11658. 'decode': ucs2decode,
  11659. 'encode': ucs2encode
  11660. },
  11661. 'decode': decode,
  11662. 'encode': encode,
  11663. 'toASCII': toASCII,
  11664. 'toUnicode': toUnicode
  11665. };
  11666. /** Expose `punycode` */
  11667. // Some AMD build optimizers, like r.js, check for specific condition patterns
  11668. // like the following:
  11669. if (
  11670. typeof define == 'function' &&
  11671. typeof define.amd == 'object' &&
  11672. define.amd
  11673. ) {
  11674. define('punycode', function() {
  11675. return punycode;
  11676. });
  11677. } else if (freeExports && !freeExports.nodeType) {
  11678. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  11679. freeModule.exports = punycode;
  11680. } else { // in Narwhal or RingoJS v0.7.0-
  11681. for (key in punycode) {
  11682. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  11683. }
  11684. }
  11685. } else { // in Rhino or a web browser
  11686. root.punycode = punycode;
  11687. }
  11688. }(this));
  11689. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
  11690. },{}],2:[function(_dereq_,module,exports){
  11691. var log = _dereq_('./log');
  11692. function restoreOwnerScroll(ownerDocument, x, y) {
  11693. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  11694. ownerDocument.defaultView.scrollTo(x, y);
  11695. }
  11696. }
  11697. function cloneCanvasContents(canvas, clonedCanvas) {
  11698. try {
  11699. if (clonedCanvas) {
  11700. clonedCanvas.width = canvas.width;
  11701. clonedCanvas.height = canvas.height;
  11702. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  11703. }
  11704. } catch(e) {
  11705. log("Unable to copy canvas content from", canvas, e);
  11706. }
  11707. }
  11708. function cloneNode(node, javascriptEnabled) {
  11709. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  11710. var child = node.firstChild;
  11711. while(child) {
  11712. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  11713. clone.appendChild(cloneNode(child, javascriptEnabled));
  11714. }
  11715. child = child.nextSibling;
  11716. }
  11717. if (node.nodeType === 1) {
  11718. clone._scrollTop = node.scrollTop;
  11719. clone._scrollLeft = node.scrollLeft;
  11720. if (node.nodeName === "CANVAS") {
  11721. cloneCanvasContents(node, clone);
  11722. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  11723. clone.value = node.value;
  11724. }
  11725. }
  11726. return clone;
  11727. }
  11728. function initNode(node) {
  11729. if (node.nodeType === 1) {
  11730. node.scrollTop = node._scrollTop;
  11731. node.scrollLeft = node._scrollLeft;
  11732. var child = node.firstChild;
  11733. while(child) {
  11734. initNode(child);
  11735. child = child.nextSibling;
  11736. }
  11737. }
  11738. }
  11739. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  11740. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  11741. var container = containerDocument.createElement("iframe");
  11742. container.className = "html2canvas-container";
  11743. container.style.visibility = "hidden";
  11744. container.style.position = "fixed";
  11745. container.style.left = "-10000px";
  11746. container.style.top = "0px";
  11747. container.style.border = "0";
  11748. container.width = width;
  11749. container.height = height;
  11750. container.scrolling = "no"; // ios won't scroll without it
  11751. containerDocument.body.appendChild(container);
  11752. return new Promise(function(resolve) {
  11753. var documentClone = container.contentWindow.document;
  11754. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  11755. if window url is about:blank, we can assign the url to current by writing onto the document
  11756. */
  11757. container.contentWindow.onload = container.onload = function() {
  11758. var interval = setInterval(function() {
  11759. if (documentClone.body.childNodes.length > 0) {
  11760. initNode(documentClone.documentElement);
  11761. clearInterval(interval);
  11762. if (options.type === "view") {
  11763. container.contentWindow.scrollTo(x, y);
  11764. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  11765. documentClone.documentElement.style.top = (-y) + "px";
  11766. documentClone.documentElement.style.left = (-x) + "px";
  11767. documentClone.documentElement.style.position = 'absolute';
  11768. }
  11769. }
  11770. resolve(container);
  11771. }
  11772. }, 50);
  11773. };
  11774. documentClone.open();
  11775. documentClone.write("<!DOCTYPE html><html></html>");
  11776. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  11777. restoreOwnerScroll(ownerDocument, x, y);
  11778. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  11779. documentClone.close();
  11780. });
  11781. };
  11782. },{"./log":13}],3:[function(_dereq_,module,exports){
  11783. // http://dev.w3.org/csswg/css-color/
  11784. function Color(value) {
  11785. this.r = 0;
  11786. this.g = 0;
  11787. this.b = 0;
  11788. this.a = null;
  11789. var result = this.fromArray(value) ||
  11790. this.namedColor(value) ||
  11791. this.rgb(value) ||
  11792. this.rgba(value) ||
  11793. this.hex6(value) ||
  11794. this.hex3(value);
  11795. }
  11796. Color.prototype.darken = function(amount) {
  11797. var a = 1 - amount;
  11798. return new Color([
  11799. Math.round(this.r * a),
  11800. Math.round(this.g * a),
  11801. Math.round(this.b * a),
  11802. this.a
  11803. ]);
  11804. };
  11805. Color.prototype.isTransparent = function() {
  11806. return this.a === 0;
  11807. };
  11808. Color.prototype.isBlack = function() {
  11809. return this.r === 0 && this.g === 0 && this.b === 0;
  11810. };
  11811. Color.prototype.fromArray = function(array) {
  11812. if (Array.isArray(array)) {
  11813. this.r = Math.min(array[0], 255);
  11814. this.g = Math.min(array[1], 255);
  11815. this.b = Math.min(array[2], 255);
  11816. if (array.length > 3) {
  11817. this.a = array[3];
  11818. }
  11819. }
  11820. return (Array.isArray(array));
  11821. };
  11822. var _hex3 = /^#([a-f0-9]{3})$/i;
  11823. Color.prototype.hex3 = function(value) {
  11824. var match = null;
  11825. if ((match = value.match(_hex3)) !== null) {
  11826. this.r = parseInt(match[1][0] + match[1][0], 16);
  11827. this.g = parseInt(match[1][1] + match[1][1], 16);
  11828. this.b = parseInt(match[1][2] + match[1][2], 16);
  11829. }
  11830. return match !== null;
  11831. };
  11832. var _hex6 = /^#([a-f0-9]{6})$/i;
  11833. Color.prototype.hex6 = function(value) {
  11834. var match = null;
  11835. if ((match = value.match(_hex6)) !== null) {
  11836. this.r = parseInt(match[1].substring(0, 2), 16);
  11837. this.g = parseInt(match[1].substring(2, 4), 16);
  11838. this.b = parseInt(match[1].substring(4, 6), 16);
  11839. }
  11840. return match !== null;
  11841. };
  11842. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  11843. Color.prototype.rgb = function(value) {
  11844. var match = null;
  11845. if ((match = value.match(_rgb)) !== null) {
  11846. this.r = Number(match[1]);
  11847. this.g = Number(match[2]);
  11848. this.b = Number(match[3]);
  11849. }
  11850. return match !== null;
  11851. };
  11852. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  11853. Color.prototype.rgba = function(value) {
  11854. var match = null;
  11855. if ((match = value.match(_rgba)) !== null) {
  11856. this.r = Number(match[1]);
  11857. this.g = Number(match[2]);
  11858. this.b = Number(match[3]);
  11859. this.a = Number(match[4]);
  11860. }
  11861. return match !== null;
  11862. };
  11863. Color.prototype.toString = function() {
  11864. return this.a !== null && this.a !== 1 ?
  11865. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  11866. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  11867. };
  11868. Color.prototype.namedColor = function(value) {
  11869. value = value.toLowerCase();
  11870. var color = colors[value];
  11871. if (color) {
  11872. this.r = color[0];
  11873. this.g = color[1];
  11874. this.b = color[2];
  11875. } else if (value === "transparent") {
  11876. this.r = this.g = this.b = this.a = 0;
  11877. return true;
  11878. }
  11879. return !!color;
  11880. };
  11881. Color.prototype.isColor = true;
  11882. // 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}, {}))
  11883. var colors = {
  11884. "aliceblue": [240, 248, 255],
  11885. "antiquewhite": [250, 235, 215],
  11886. "aqua": [0, 255, 255],
  11887. "aquamarine": [127, 255, 212],
  11888. "azure": [240, 255, 255],
  11889. "beige": [245, 245, 220],
  11890. "bisque": [255, 228, 196],
  11891. "black": [0, 0, 0],
  11892. "blanchedalmond": [255, 235, 205],
  11893. "blue": [0, 0, 255],
  11894. "blueviolet": [138, 43, 226],
  11895. "brown": [165, 42, 42],
  11896. "burlywood": [222, 184, 135],
  11897. "cadetblue": [95, 158, 160],
  11898. "chartreuse": [127, 255, 0],
  11899. "chocolate": [210, 105, 30],
  11900. "coral": [255, 127, 80],
  11901. "cornflowerblue": [100, 149, 237],
  11902. "cornsilk": [255, 248, 220],
  11903. "crimson": [220, 20, 60],
  11904. "cyan": [0, 255, 255],
  11905. "darkblue": [0, 0, 139],
  11906. "darkcyan": [0, 139, 139],
  11907. "darkgoldenrod": [184, 134, 11],
  11908. "darkgray": [169, 169, 169],
  11909. "darkgreen": [0, 100, 0],
  11910. "darkgrey": [169, 169, 169],
  11911. "darkkhaki": [189, 183, 107],
  11912. "darkmagenta": [139, 0, 139],
  11913. "darkolivegreen": [85, 107, 47],
  11914. "darkorange": [255, 140, 0],
  11915. "darkorchid": [153, 50, 204],
  11916. "darkred": [139, 0, 0],
  11917. "darksalmon": [233, 150, 122],
  11918. "darkseagreen": [143, 188, 143],
  11919. "darkslateblue": [72, 61, 139],
  11920. "darkslategray": [47, 79, 79],
  11921. "darkslategrey": [47, 79, 79],
  11922. "darkturquoise": [0, 206, 209],
  11923. "darkviolet": [148, 0, 211],
  11924. "deeppink": [255, 20, 147],
  11925. "deepskyblue": [0, 191, 255],
  11926. "dimgray": [105, 105, 105],
  11927. "dimgrey": [105, 105, 105],
  11928. "dodgerblue": [30, 144, 255],
  11929. "firebrick": [178, 34, 34],
  11930. "floralwhite": [255, 250, 240],
  11931. "forestgreen": [34, 139, 34],
  11932. "fuchsia": [255, 0, 255],
  11933. "gainsboro": [220, 220, 220],
  11934. "ghostwhite": [248, 248, 255],
  11935. "gold": [255, 215, 0],
  11936. "goldenrod": [218, 165, 32],
  11937. "gray": [128, 128, 128],
  11938. "green": [0, 128, 0],
  11939. "greenyellow": [173, 255, 47],
  11940. "grey": [128, 128, 128],
  11941. "honeydew": [240, 255, 240],
  11942. "hotpink": [255, 105, 180],
  11943. "indianred": [205, 92, 92],
  11944. "indigo": [75, 0, 130],
  11945. "ivory": [255, 255, 240],
  11946. "khaki": [240, 230, 140],
  11947. "lavender": [230, 230, 250],
  11948. "lavenderblush": [255, 240, 245],
  11949. "lawngreen": [124, 252, 0],
  11950. "lemonchiffon": [255, 250, 205],
  11951. "lightblue": [173, 216, 230],
  11952. "lightcoral": [240, 128, 128],
  11953. "lightcyan": [224, 255, 255],
  11954. "lightgoldenrodyellow": [250, 250, 210],
  11955. "lightgray": [211, 211, 211],
  11956. "lightgreen": [144, 238, 144],
  11957. "lightgrey": [211, 211, 211],
  11958. "lightpink": [255, 182, 193],
  11959. "lightsalmon": [255, 160, 122],
  11960. "lightseagreen": [32, 178, 170],
  11961. "lightskyblue": [135, 206, 250],
  11962. "lightslategray": [119, 136, 153],
  11963. "lightslategrey": [119, 136, 153],
  11964. "lightsteelblue": [176, 196, 222],
  11965. "lightyellow": [255, 255, 224],
  11966. "lime": [0, 255, 0],
  11967. "limegreen": [50, 205, 50],
  11968. "linen": [250, 240, 230],
  11969. "magenta": [255, 0, 255],
  11970. "maroon": [128, 0, 0],
  11971. "mediumaquamarine": [102, 205, 170],
  11972. "mediumblue": [0, 0, 205],
  11973. "mediumorchid": [186, 85, 211],
  11974. "mediumpurple": [147, 112, 219],
  11975. "mediumseagreen": [60, 179, 113],
  11976. "mediumslateblue": [123, 104, 238],
  11977. "mediumspringgreen": [0, 250, 154],
  11978. "mediumturquoise": [72, 209, 204],
  11979. "mediumvioletred": [199, 21, 133],
  11980. "midnightblue": [25, 25, 112],
  11981. "mintcream": [245, 255, 250],
  11982. "mistyrose": [255, 228, 225],
  11983. "moccasin": [255, 228, 181],
  11984. "navajowhite": [255, 222, 173],
  11985. "navy": [0, 0, 128],
  11986. "oldlace": [253, 245, 230],
  11987. "olive": [128, 128, 0],
  11988. "olivedrab": [107, 142, 35],
  11989. "orange": [255, 165, 0],
  11990. "orangered": [255, 69, 0],
  11991. "orchid": [218, 112, 214],
  11992. "palegoldenrod": [238, 232, 170],
  11993. "palegreen": [152, 251, 152],
  11994. "paleturquoise": [175, 238, 238],
  11995. "palevioletred": [219, 112, 147],
  11996. "papayawhip": [255, 239, 213],
  11997. "peachpuff": [255, 218, 185],
  11998. "peru": [205, 133, 63],
  11999. "pink": [255, 192, 203],
  12000. "plum": [221, 160, 221],
  12001. "powderblue": [176, 224, 230],
  12002. "purple": [128, 0, 128],
  12003. "rebeccapurple": [102, 51, 153],
  12004. "red": [255, 0, 0],
  12005. "rosybrown": [188, 143, 143],
  12006. "royalblue": [65, 105, 225],
  12007. "saddlebrown": [139, 69, 19],
  12008. "salmon": [250, 128, 114],
  12009. "sandybrown": [244, 164, 96],
  12010. "seagreen": [46, 139, 87],
  12011. "seashell": [255, 245, 238],
  12012. "sienna": [160, 82, 45],
  12013. "silver": [192, 192, 192],
  12014. "skyblue": [135, 206, 235],
  12015. "slateblue": [106, 90, 205],
  12016. "slategray": [112, 128, 144],
  12017. "slategrey": [112, 128, 144],
  12018. "snow": [255, 250, 250],
  12019. "springgreen": [0, 255, 127],
  12020. "steelblue": [70, 130, 180],
  12021. "tan": [210, 180, 140],
  12022. "teal": [0, 128, 128],
  12023. "thistle": [216, 191, 216],
  12024. "tomato": [255, 99, 71],
  12025. "turquoise": [64, 224, 208],
  12026. "violet": [238, 130, 238],
  12027. "wheat": [245, 222, 179],
  12028. "white": [255, 255, 255],
  12029. "whitesmoke": [245, 245, 245],
  12030. "yellow": [255, 255, 0],
  12031. "yellowgreen": [154, 205, 50]
  12032. };
  12033. module.exports = Color;
  12034. },{}],4:[function(_dereq_,module,exports){
  12035. var Support = _dereq_('./support');
  12036. var CanvasRenderer = _dereq_('./renderers/canvas');
  12037. var ImageLoader = _dereq_('./imageloader');
  12038. var NodeParser = _dereq_('./nodeparser');
  12039. var NodeContainer = _dereq_('./nodecontainer');
  12040. var log = _dereq_('./log');
  12041. var utils = _dereq_('./utils');
  12042. var createWindowClone = _dereq_('./clone');
  12043. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  12044. var getBounds = utils.getBounds;
  12045. var html2canvasNodeAttribute = "data-html2canvas-node";
  12046. var html2canvasCloneIndex = 0;
  12047. function html2canvas(nodeList, options) {
  12048. var index = html2canvasCloneIndex++;
  12049. options = options || {};
  12050. if (options.logging) {
  12051. log.options.logging = true;
  12052. log.options.start = Date.now();
  12053. }
  12054. options.async = typeof(options.async) === "undefined" ? true : options.async;
  12055. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  12056. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  12057. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  12058. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  12059. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  12060. options.strict = !!options.strict;
  12061. if (typeof(nodeList) === "string") {
  12062. if (typeof(options.proxy) !== "string") {
  12063. return Promise.reject("Proxy must be used when rendering url");
  12064. }
  12065. var width = options.width != null ? options.width : window.innerWidth;
  12066. var height = options.height != null ? options.height : window.innerHeight;
  12067. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  12068. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  12069. });
  12070. }
  12071. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  12072. node.setAttribute(html2canvasNodeAttribute + index, index);
  12073. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  12074. if (typeof(options.onrendered) === "function") {
  12075. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  12076. options.onrendered(canvas);
  12077. }
  12078. return canvas;
  12079. });
  12080. }
  12081. html2canvas.CanvasRenderer = CanvasRenderer;
  12082. html2canvas.NodeContainer = NodeContainer;
  12083. html2canvas.log = log;
  12084. html2canvas.utils = utils;
  12085. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  12086. return Promise.reject("No canvas support");
  12087. } : html2canvas;
  12088. module.exports = html2canvasExport;
  12089. if (typeof(define) === 'function' && define.amd) {
  12090. define('html2canvas', [], function() {
  12091. return html2canvasExport;
  12092. });
  12093. }
  12094. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  12095. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  12096. log("Document cloned");
  12097. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  12098. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  12099. document.querySelector(selector).removeAttribute(attributeName);
  12100. var clonedWindow = container.contentWindow;
  12101. var node = clonedWindow.document.querySelector(selector);
  12102. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  12103. return oncloneHandler.then(function() {
  12104. return renderWindow(node, container, options, windowWidth, windowHeight);
  12105. });
  12106. });
  12107. }
  12108. function renderWindow(node, container, options, windowWidth, windowHeight) {
  12109. var clonedWindow = container.contentWindow;
  12110. var support = new Support(clonedWindow.document);
  12111. var imageLoader = new ImageLoader(options, support);
  12112. var bounds = getBounds(node);
  12113. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  12114. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  12115. var renderer = new options.renderer(width, height, imageLoader, options, document);
  12116. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  12117. return parser.ready.then(function() {
  12118. log("Finished rendering");
  12119. var canvas;
  12120. if (options.type === "view") {
  12121. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  12122. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  12123. canvas = renderer.canvas;
  12124. } else {
  12125. 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});
  12126. }
  12127. cleanupContainer(container, options);
  12128. return canvas;
  12129. });
  12130. }
  12131. function cleanupContainer(container, options) {
  12132. if (options.removeContainer) {
  12133. container.parentNode.removeChild(container);
  12134. log("Cleaned up container");
  12135. }
  12136. }
  12137. function crop(canvas, bounds) {
  12138. var croppedCanvas = document.createElement("canvas");
  12139. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  12140. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  12141. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  12142. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  12143. croppedCanvas.width = bounds.width;
  12144. croppedCanvas.height = bounds.height;
  12145. var width = x2-x1;
  12146. var height = y2-y1;
  12147. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  12148. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  12149. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  12150. return croppedCanvas;
  12151. }
  12152. function documentWidth (doc) {
  12153. return Math.max(
  12154. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  12155. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  12156. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  12157. );
  12158. }
  12159. function documentHeight (doc) {
  12160. return Math.max(
  12161. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  12162. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  12163. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  12164. );
  12165. }
  12166. function absoluteUrl(url) {
  12167. var link = document.createElement("a");
  12168. link.href = url;
  12169. link.href = link.href;
  12170. return link;
  12171. }
  12172. },{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
  12173. var log = _dereq_('./log');
  12174. var smallImage = _dereq_('./utils').smallImage;
  12175. function DummyImageContainer(src) {
  12176. this.src = src;
  12177. log("DummyImageContainer for", src);
  12178. if (!this.promise || !this.image) {
  12179. log("Initiating DummyImageContainer");
  12180. DummyImageContainer.prototype.image = new Image();
  12181. var image = this.image;
  12182. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  12183. image.onload = resolve;
  12184. image.onerror = reject;
  12185. image.src = smallImage();
  12186. if (image.complete === true) {
  12187. resolve(image);
  12188. }
  12189. });
  12190. }
  12191. }
  12192. module.exports = DummyImageContainer;
  12193. },{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
  12194. var smallImage = _dereq_('./utils').smallImage;
  12195. function Font(family, size) {
  12196. var container = document.createElement('div'),
  12197. img = document.createElement('img'),
  12198. span = document.createElement('span'),
  12199. sampleText = 'Hidden Text',
  12200. baseline,
  12201. middle;
  12202. container.style.visibility = "hidden";
  12203. container.style.fontFamily = family;
  12204. container.style.fontSize = size;
  12205. container.style.margin = 0;
  12206. container.style.padding = 0;
  12207. document.body.appendChild(container);
  12208. img.src = smallImage();
  12209. img.width = 1;
  12210. img.height = 1;
  12211. img.style.margin = 0;
  12212. img.style.padding = 0;
  12213. img.style.verticalAlign = "baseline";
  12214. span.style.fontFamily = family;
  12215. span.style.fontSize = size;
  12216. span.style.margin = 0;
  12217. span.style.padding = 0;
  12218. span.appendChild(document.createTextNode(sampleText));
  12219. container.appendChild(span);
  12220. container.appendChild(img);
  12221. baseline = (img.offsetTop - span.offsetTop) + 1;
  12222. container.removeChild(span);
  12223. container.appendChild(document.createTextNode(sampleText));
  12224. container.style.lineHeight = "normal";
  12225. img.style.verticalAlign = "super";
  12226. middle = (img.offsetTop-container.offsetTop) + 1;
  12227. document.body.removeChild(container);
  12228. this.baseline = baseline;
  12229. this.lineWidth = 1;
  12230. this.middle = middle;
  12231. }
  12232. module.exports = Font;
  12233. },{"./utils":26}],7:[function(_dereq_,module,exports){
  12234. var Font = _dereq_('./font');
  12235. function FontMetrics() {
  12236. this.data = {};
  12237. }
  12238. FontMetrics.prototype.getMetrics = function(family, size) {
  12239. if (this.data[family + "-" + size] === undefined) {
  12240. this.data[family + "-" + size] = new Font(family, size);
  12241. }
  12242. return this.data[family + "-" + size];
  12243. };
  12244. module.exports = FontMetrics;
  12245. },{"./font":6}],8:[function(_dereq_,module,exports){
  12246. var utils = _dereq_('./utils');
  12247. var getBounds = utils.getBounds;
  12248. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  12249. function FrameContainer(container, sameOrigin, options) {
  12250. this.image = null;
  12251. this.src = container;
  12252. var self = this;
  12253. var bounds = getBounds(container);
  12254. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  12255. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  12256. container.contentWindow.onload = container.onload = function() {
  12257. resolve(container);
  12258. };
  12259. } else {
  12260. resolve(container);
  12261. }
  12262. })).then(function(container) {
  12263. var html2canvas = _dereq_('./core');
  12264. 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});
  12265. }).then(function(canvas) {
  12266. return self.image = canvas;
  12267. });
  12268. }
  12269. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  12270. var container = this.src;
  12271. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  12272. };
  12273. module.exports = FrameContainer;
  12274. },{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
  12275. function GradientContainer(imageData) {
  12276. this.src = imageData.value;
  12277. this.colorStops = [];
  12278. this.type = null;
  12279. this.x0 = 0.5;
  12280. this.y0 = 0.5;
  12281. this.x1 = 0.5;
  12282. this.y1 = 0.5;
  12283. this.promise = Promise.resolve(true);
  12284. }
  12285. GradientContainer.TYPES = {
  12286. LINEAR: 1,
  12287. RADIAL: 2
  12288. };
  12289. // TODO: support hsl[a], negative %/length values
  12290. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12291. 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;
  12292. module.exports = GradientContainer;
  12293. },{}],10:[function(_dereq_,module,exports){
  12294. function ImageContainer(src, cors) {
  12295. this.src = src;
  12296. this.image = new Image();
  12297. var self = this;
  12298. this.tainted = null;
  12299. this.promise = new Promise(function(resolve, reject) {
  12300. self.image.onload = resolve;
  12301. self.image.onerror = reject;
  12302. if (cors) {
  12303. self.image.crossOrigin = "anonymous";
  12304. }
  12305. self.image.src = src;
  12306. if (self.image.complete === true) {
  12307. resolve(self.image);
  12308. }
  12309. });
  12310. }
  12311. module.exports = ImageContainer;
  12312. },{}],11:[function(_dereq_,module,exports){
  12313. var log = _dereq_('./log');
  12314. var ImageContainer = _dereq_('./imagecontainer');
  12315. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  12316. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  12317. var FrameContainer = _dereq_('./framecontainer');
  12318. var SVGContainer = _dereq_('./svgcontainer');
  12319. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  12320. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  12321. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  12322. var bind = _dereq_('./utils').bind;
  12323. function ImageLoader(options, support) {
  12324. this.link = null;
  12325. this.options = options;
  12326. this.support = support;
  12327. this.origin = this.getOrigin(window.location.href);
  12328. }
  12329. ImageLoader.prototype.findImages = function(nodes) {
  12330. var images = [];
  12331. nodes.reduce(function(imageNodes, container) {
  12332. switch(container.node.nodeName) {
  12333. case "IMG":
  12334. return imageNodes.concat([{
  12335. args: [container.node.src],
  12336. method: "url"
  12337. }]);
  12338. case "svg":
  12339. case "IFRAME":
  12340. return imageNodes.concat([{
  12341. args: [container.node],
  12342. method: container.node.nodeName
  12343. }]);
  12344. }
  12345. return imageNodes;
  12346. }, []).forEach(this.addImage(images, this.loadImage), this);
  12347. return images;
  12348. };
  12349. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  12350. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  12351. return images;
  12352. };
  12353. ImageLoader.prototype.addImage = function(images, callback) {
  12354. return function(newImage) {
  12355. newImage.args.forEach(function(image) {
  12356. if (!this.imageExists(images, image)) {
  12357. images.splice(0, 0, callback.call(this, newImage));
  12358. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  12359. }
  12360. }, this);
  12361. };
  12362. };
  12363. ImageLoader.prototype.hasImageBackground = function(imageData) {
  12364. return imageData.method !== "none";
  12365. };
  12366. ImageLoader.prototype.loadImage = function(imageData) {
  12367. if (imageData.method === "url") {
  12368. var src = imageData.args[0];
  12369. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  12370. return new SVGContainer(src);
  12371. } else if (src.match(/data:image\/.*;base64,/i)) {
  12372. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  12373. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  12374. return new ImageContainer(src, false);
  12375. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  12376. return new ImageContainer(src, true);
  12377. } else if (this.options.proxy) {
  12378. return new ProxyImageContainer(src, this.options.proxy);
  12379. } else {
  12380. return new DummyImageContainer(src);
  12381. }
  12382. } else if (imageData.method === "linear-gradient") {
  12383. return new LinearGradientContainer(imageData);
  12384. } else if (imageData.method === "gradient") {
  12385. return new WebkitGradientContainer(imageData);
  12386. } else if (imageData.method === "svg") {
  12387. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  12388. } else if (imageData.method === "IFRAME") {
  12389. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  12390. } else {
  12391. return new DummyImageContainer(imageData);
  12392. }
  12393. };
  12394. ImageLoader.prototype.isSVG = function(src) {
  12395. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  12396. };
  12397. ImageLoader.prototype.imageExists = function(images, src) {
  12398. return images.some(function(image) {
  12399. return image.src === src;
  12400. });
  12401. };
  12402. ImageLoader.prototype.isSameOrigin = function(url) {
  12403. return (this.getOrigin(url) === this.origin);
  12404. };
  12405. ImageLoader.prototype.getOrigin = function(url) {
  12406. var link = this.link || (this.link = document.createElement("a"));
  12407. link.href = url;
  12408. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  12409. return link.protocol + link.hostname + link.port;
  12410. };
  12411. ImageLoader.prototype.getPromise = function(container) {
  12412. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  12413. var dummy = new DummyImageContainer(container.src);
  12414. return dummy.promise.then(function(image) {
  12415. container.image = image;
  12416. });
  12417. });
  12418. };
  12419. ImageLoader.prototype.get = function(src) {
  12420. var found = null;
  12421. return this.images.some(function(img) {
  12422. return (found = img).src === src;
  12423. }) ? found : null;
  12424. };
  12425. ImageLoader.prototype.fetch = function(nodes) {
  12426. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  12427. this.images.forEach(function(image, index) {
  12428. image.promise.then(function() {
  12429. log("Succesfully loaded image #"+ (index+1), image);
  12430. }, function(e) {
  12431. log("Failed loading image #"+ (index+1), image, e);
  12432. });
  12433. });
  12434. this.ready = Promise.all(this.images.map(this.getPromise, this));
  12435. log("Finished searching images");
  12436. return this;
  12437. };
  12438. ImageLoader.prototype.timeout = function(container, timeout) {
  12439. var timer;
  12440. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  12441. timer = setTimeout(function() {
  12442. log("Timed out loading image", container);
  12443. reject(container);
  12444. }, timeout);
  12445. })]).then(function(container) {
  12446. clearTimeout(timer);
  12447. return container;
  12448. });
  12449. promise['catch'](function() {
  12450. clearTimeout(timer);
  12451. });
  12452. return promise;
  12453. };
  12454. module.exports = ImageLoader;
  12455. },{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./utils":26,"./webkitgradientcontainer":27}],12:[function(_dereq_,module,exports){
  12456. var GradientContainer = _dereq_('./gradientcontainer');
  12457. var Color = _dereq_('./color');
  12458. function LinearGradientContainer(imageData) {
  12459. GradientContainer.apply(this, arguments);
  12460. this.type = GradientContainer.TYPES.LINEAR;
  12461. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
  12462. !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
  12463. if (hasDirection) {
  12464. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  12465. switch(position) {
  12466. case "left":
  12467. this.x0 = 0;
  12468. this.x1 = 1;
  12469. break;
  12470. case "top":
  12471. this.y0 = 0;
  12472. this.y1 = 1;
  12473. break;
  12474. case "right":
  12475. this.x0 = 1;
  12476. this.x1 = 0;
  12477. break;
  12478. case "bottom":
  12479. this.y0 = 1;
  12480. this.y1 = 0;
  12481. break;
  12482. case "to":
  12483. var y0 = this.y0;
  12484. var x0 = this.x0;
  12485. this.y0 = this.y1;
  12486. this.x0 = this.x1;
  12487. this.x1 = x0;
  12488. this.y1 = y0;
  12489. break;
  12490. case "center":
  12491. break; // centered by default
  12492. // Firefox internally converts position keywords to percentages:
  12493. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  12494. default: // percentage or absolute length
  12495. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  12496. var ratio = parseFloat(position, 10) * 1e-2;
  12497. if (isNaN(ratio)) { // invalid or unhandled value
  12498. break;
  12499. }
  12500. if (index === 0) {
  12501. this.y0 = ratio;
  12502. this.y1 = 1 - this.y0;
  12503. } else {
  12504. this.x0 = ratio;
  12505. this.x1 = 1 - this.x0;
  12506. }
  12507. break;
  12508. }
  12509. }, this);
  12510. } else {
  12511. this.y0 = 0;
  12512. this.y1 = 1;
  12513. }
  12514. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  12515. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  12516. var value = +colorStopMatch[2];
  12517. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  12518. return {
  12519. color: new Color(colorStopMatch[1]),
  12520. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  12521. stop: unit === "%" ? value / 100 : null
  12522. };
  12523. });
  12524. if (this.colorStops[0].stop === null) {
  12525. this.colorStops[0].stop = 0;
  12526. }
  12527. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  12528. this.colorStops[this.colorStops.length - 1].stop = 1;
  12529. }
  12530. // calculates and fills-in explicit stop positions when omitted from rule
  12531. this.colorStops.forEach(function(colorStop, index) {
  12532. if (colorStop.stop === null) {
  12533. this.colorStops.slice(index).some(function(find, count) {
  12534. if (find.stop !== null) {
  12535. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  12536. return true;
  12537. } else {
  12538. return false;
  12539. }
  12540. }, this);
  12541. }
  12542. }, this);
  12543. }
  12544. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  12545. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12546. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  12547. module.exports = LinearGradientContainer;
  12548. },{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
  12549. var logger = function() {
  12550. if (logger.options.logging && window.console && window.console.log) {
  12551. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  12552. }
  12553. };
  12554. logger.options = {logging: false};
  12555. module.exports = logger;
  12556. },{}],14:[function(_dereq_,module,exports){
  12557. var Color = _dereq_('./color');
  12558. var utils = _dereq_('./utils');
  12559. var getBounds = utils.getBounds;
  12560. var parseBackgrounds = utils.parseBackgrounds;
  12561. var offsetBounds = utils.offsetBounds;
  12562. function NodeContainer(node, parent) {
  12563. this.node = node;
  12564. this.parent = parent;
  12565. this.stack = null;
  12566. this.bounds = null;
  12567. this.borders = null;
  12568. this.clip = [];
  12569. this.backgroundClip = [];
  12570. this.offsetBounds = null;
  12571. this.visible = null;
  12572. this.computedStyles = null;
  12573. this.colors = {};
  12574. this.styles = {};
  12575. this.backgroundImages = null;
  12576. this.transformData = null;
  12577. this.transformMatrix = null;
  12578. this.isPseudoElement = false;
  12579. this.opacity = null;
  12580. }
  12581. NodeContainer.prototype.cloneTo = function(stack) {
  12582. stack.visible = this.visible;
  12583. stack.borders = this.borders;
  12584. stack.bounds = this.bounds;
  12585. stack.clip = this.clip;
  12586. stack.backgroundClip = this.backgroundClip;
  12587. stack.computedStyles = this.computedStyles;
  12588. stack.styles = this.styles;
  12589. stack.backgroundImages = this.backgroundImages;
  12590. stack.opacity = this.opacity;
  12591. };
  12592. NodeContainer.prototype.getOpacity = function() {
  12593. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  12594. };
  12595. NodeContainer.prototype.assignStack = function(stack) {
  12596. this.stack = stack;
  12597. stack.children.push(this);
  12598. };
  12599. NodeContainer.prototype.isElementVisible = function() {
  12600. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  12601. this.css('display') !== "none" &&
  12602. this.css('visibility') !== "hidden" &&
  12603. !this.node.hasAttribute("data-html2canvas-ignore") &&
  12604. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  12605. );
  12606. };
  12607. NodeContainer.prototype.css = function(attribute) {
  12608. if (!this.computedStyles) {
  12609. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  12610. }
  12611. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  12612. };
  12613. NodeContainer.prototype.prefixedCss = function(attribute) {
  12614. var prefixes = ["webkit", "moz", "ms", "o"];
  12615. var value = this.css(attribute);
  12616. if (value === undefined) {
  12617. prefixes.some(function(prefix) {
  12618. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  12619. return value !== undefined;
  12620. }, this);
  12621. }
  12622. return value === undefined ? null : value;
  12623. };
  12624. NodeContainer.prototype.computedStyle = function(type) {
  12625. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  12626. };
  12627. NodeContainer.prototype.cssInt = function(attribute) {
  12628. var value = parseInt(this.css(attribute), 10);
  12629. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  12630. };
  12631. NodeContainer.prototype.color = function(attribute) {
  12632. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  12633. };
  12634. NodeContainer.prototype.cssFloat = function(attribute) {
  12635. var value = parseFloat(this.css(attribute));
  12636. return (isNaN(value)) ? 0 : value;
  12637. };
  12638. NodeContainer.prototype.fontWeight = function() {
  12639. var weight = this.css("fontWeight");
  12640. switch(parseInt(weight, 10)){
  12641. case 401:
  12642. weight = "bold";
  12643. break;
  12644. case 400:
  12645. weight = "normal";
  12646. break;
  12647. }
  12648. return weight;
  12649. };
  12650. NodeContainer.prototype.parseClip = function() {
  12651. var matches = this.css('clip').match(this.CLIP);
  12652. if (matches) {
  12653. return {
  12654. top: parseInt(matches[1], 10),
  12655. right: parseInt(matches[2], 10),
  12656. bottom: parseInt(matches[3], 10),
  12657. left: parseInt(matches[4], 10)
  12658. };
  12659. }
  12660. return null;
  12661. };
  12662. NodeContainer.prototype.parseBackgroundImages = function() {
  12663. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  12664. };
  12665. NodeContainer.prototype.cssList = function(property, index) {
  12666. var value = (this.css(property) || '').split(',');
  12667. value = value[index || 0] || value[0] || 'auto';
  12668. value = value.trim().split(' ');
  12669. if (value.length === 1) {
  12670. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  12671. }
  12672. return value;
  12673. };
  12674. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  12675. var size = this.cssList("backgroundSize", index);
  12676. var width, height;
  12677. if (isPercentage(size[0])) {
  12678. width = bounds.width * parseFloat(size[0]) / 100;
  12679. } else if (/contain|cover/.test(size[0])) {
  12680. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  12681. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  12682. } else {
  12683. width = parseInt(size[0], 10);
  12684. }
  12685. if (size[0] === 'auto' && size[1] === 'auto') {
  12686. height = image.height;
  12687. } else if (size[1] === 'auto') {
  12688. height = width / image.width * image.height;
  12689. } else if (isPercentage(size[1])) {
  12690. height = bounds.height * parseFloat(size[1]) / 100;
  12691. } else {
  12692. height = parseInt(size[1], 10);
  12693. }
  12694. if (size[0] === 'auto') {
  12695. width = height / image.height * image.width;
  12696. }
  12697. return {width: width, height: height};
  12698. };
  12699. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  12700. var position = this.cssList('backgroundPosition', index);
  12701. var left, top;
  12702. if (isPercentage(position[0])){
  12703. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  12704. } else {
  12705. left = parseInt(position[0], 10);
  12706. }
  12707. if (position[1] === 'auto') {
  12708. top = left / image.width * image.height;
  12709. } else if (isPercentage(position[1])){
  12710. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  12711. } else {
  12712. top = parseInt(position[1], 10);
  12713. }
  12714. if (position[0] === 'auto') {
  12715. left = top / image.height * image.width;
  12716. }
  12717. return {left: left, top: top};
  12718. };
  12719. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  12720. return this.cssList("backgroundRepeat", index)[0];
  12721. };
  12722. NodeContainer.prototype.parseTextShadows = function() {
  12723. var textShadow = this.css("textShadow");
  12724. var results = [];
  12725. if (textShadow && textShadow !== 'none') {
  12726. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  12727. for (var i = 0; shadows && (i < shadows.length); i++) {
  12728. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  12729. results.push({
  12730. color: new Color(s[0]),
  12731. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  12732. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  12733. blur: s[3] ? s[3].replace('px', '') : 0
  12734. });
  12735. }
  12736. }
  12737. return results;
  12738. };
  12739. NodeContainer.prototype.parseTransform = function() {
  12740. if (!this.transformData) {
  12741. if (this.hasTransform()) {
  12742. var offset = this.parseBounds();
  12743. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  12744. origin[0] += offset.left;
  12745. origin[1] += offset.top;
  12746. this.transformData = {
  12747. origin: origin,
  12748. matrix: this.parseTransformMatrix()
  12749. };
  12750. } else {
  12751. this.transformData = {
  12752. origin: [0, 0],
  12753. matrix: [1, 0, 0, 1, 0, 0]
  12754. };
  12755. }
  12756. }
  12757. return this.transformData;
  12758. };
  12759. NodeContainer.prototype.parseTransformMatrix = function() {
  12760. if (!this.transformMatrix) {
  12761. var transform = this.prefixedCss("transform");
  12762. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  12763. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  12764. }
  12765. return this.transformMatrix;
  12766. };
  12767. NodeContainer.prototype.parseBounds = function() {
  12768. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  12769. };
  12770. NodeContainer.prototype.hasTransform = function() {
  12771. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  12772. };
  12773. NodeContainer.prototype.getValue = function() {
  12774. var value = this.node.value || "";
  12775. if (this.node.tagName === "SELECT") {
  12776. value = selectionValue(this.node);
  12777. } else if (this.node.type === "password") {
  12778. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  12779. }
  12780. return value.length === 0 ? (this.node.placeholder || "") : value;
  12781. };
  12782. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  12783. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  12784. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  12785. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  12786. function selectionValue(node) {
  12787. var option = node.options[node.selectedIndex || 0];
  12788. return option ? (option.text || "") : "";
  12789. }
  12790. function parseMatrix(match) {
  12791. if (match && match[1] === "matrix") {
  12792. return match[2].split(",").map(function(s) {
  12793. return parseFloat(s.trim());
  12794. });
  12795. } else if (match && match[1] === "matrix3d") {
  12796. var matrix3d = match[2].split(",").map(function(s) {
  12797. return parseFloat(s.trim());
  12798. });
  12799. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  12800. }
  12801. }
  12802. function isPercentage(value) {
  12803. return value.toString().indexOf("%") !== -1;
  12804. }
  12805. function removePx(str) {
  12806. return str.replace("px", "");
  12807. }
  12808. function asFloat(str) {
  12809. return parseFloat(str);
  12810. }
  12811. module.exports = NodeContainer;
  12812. },{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
  12813. var log = _dereq_('./log');
  12814. var punycode = _dereq_('punycode');
  12815. var NodeContainer = _dereq_('./nodecontainer');
  12816. var TextContainer = _dereq_('./textcontainer');
  12817. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  12818. var FontMetrics = _dereq_('./fontmetrics');
  12819. var Color = _dereq_('./color');
  12820. var StackingContext = _dereq_('./stackingcontext');
  12821. var utils = _dereq_('./utils');
  12822. var bind = utils.bind;
  12823. var getBounds = utils.getBounds;
  12824. var parseBackgrounds = utils.parseBackgrounds;
  12825. var offsetBounds = utils.offsetBounds;
  12826. function NodeParser(element, renderer, support, imageLoader, options) {
  12827. log("Starting NodeParser");
  12828. this.renderer = renderer;
  12829. this.options = options;
  12830. this.range = null;
  12831. this.support = support;
  12832. this.renderQueue = [];
  12833. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  12834. var parent = new NodeContainer(element, null);
  12835. if (options.background) {
  12836. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  12837. }
  12838. if (element === element.ownerDocument.documentElement) {
  12839. // http://www.w3.org/TR/css3-background/#special-backgrounds
  12840. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  12841. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  12842. }
  12843. parent.visibile = parent.isElementVisible();
  12844. this.createPseudoHideStyles(element.ownerDocument);
  12845. this.disableAnimations(element.ownerDocument);
  12846. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  12847. return container.visible = container.isElementVisible();
  12848. }).map(this.getPseudoElements, this));
  12849. this.fontMetrics = new FontMetrics();
  12850. log("Fetched nodes, total:", this.nodes.length);
  12851. log("Calculate overflow clips");
  12852. this.calculateOverflowClips();
  12853. log("Start fetching images");
  12854. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  12855. this.ready = this.images.ready.then(bind(function() {
  12856. log("Images loaded, starting parsing");
  12857. log("Creating stacking contexts");
  12858. this.createStackingContexts();
  12859. log("Sorting stacking contexts");
  12860. this.sortStackingContexts(this.stack);
  12861. this.parse(this.stack);
  12862. log("Render queue created with " + this.renderQueue.length + " items");
  12863. return new Promise(bind(function(resolve) {
  12864. if (!options.async) {
  12865. this.renderQueue.forEach(this.paint, this);
  12866. resolve();
  12867. } else if (typeof(options.async) === "function") {
  12868. options.async.call(this, this.renderQueue, resolve);
  12869. } else if (this.renderQueue.length > 0){
  12870. this.renderIndex = 0;
  12871. this.asyncRenderer(this.renderQueue, resolve);
  12872. } else {
  12873. resolve();
  12874. }
  12875. }, this));
  12876. }, this));
  12877. }
  12878. NodeParser.prototype.calculateOverflowClips = function() {
  12879. this.nodes.forEach(function(container) {
  12880. if (isElement(container)) {
  12881. if (isPseudoElement(container)) {
  12882. container.appendToDOM();
  12883. }
  12884. container.borders = this.parseBorders(container);
  12885. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  12886. var cssClip = container.parseClip();
  12887. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  12888. clip.push([["rect",
  12889. container.bounds.left + cssClip.left,
  12890. container.bounds.top + cssClip.top,
  12891. cssClip.right - cssClip.left,
  12892. cssClip.bottom - cssClip.top
  12893. ]]);
  12894. }
  12895. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  12896. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  12897. if (isPseudoElement(container)) {
  12898. container.cleanDOM();
  12899. }
  12900. } else if (isTextNode(container)) {
  12901. container.clip = hasParentClip(container) ? container.parent.clip : [];
  12902. }
  12903. if (!isPseudoElement(container)) {
  12904. container.bounds = null;
  12905. }
  12906. }, this);
  12907. };
  12908. function hasParentClip(container) {
  12909. return container.parent && container.parent.clip.length;
  12910. }
  12911. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  12912. asyncTimer = asyncTimer || Date.now();
  12913. this.paint(queue[this.renderIndex++]);
  12914. if (queue.length === this.renderIndex) {
  12915. resolve();
  12916. } else if (asyncTimer + 20 > Date.now()) {
  12917. this.asyncRenderer(queue, resolve, asyncTimer);
  12918. } else {
  12919. setTimeout(bind(function() {
  12920. this.asyncRenderer(queue, resolve);
  12921. }, this), 0);
  12922. }
  12923. };
  12924. NodeParser.prototype.createPseudoHideStyles = function(document) {
  12925. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  12926. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  12927. };
  12928. NodeParser.prototype.disableAnimations = function(document) {
  12929. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  12930. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  12931. };
  12932. NodeParser.prototype.createStyles = function(document, styles) {
  12933. var hidePseudoElements = document.createElement('style');
  12934. hidePseudoElements.innerHTML = styles;
  12935. document.body.appendChild(hidePseudoElements);
  12936. };
  12937. NodeParser.prototype.getPseudoElements = function(container) {
  12938. var nodes = [[container]];
  12939. if (container.node.nodeType === Node.ELEMENT_NODE) {
  12940. var before = this.getPseudoElement(container, ":before");
  12941. var after = this.getPseudoElement(container, ":after");
  12942. if (before) {
  12943. nodes.push(before);
  12944. }
  12945. if (after) {
  12946. nodes.push(after);
  12947. }
  12948. }
  12949. return flatten(nodes);
  12950. };
  12951. function toCamelCase(str) {
  12952. return str.replace(/(\-[a-z])/g, function(match){
  12953. return match.toUpperCase().replace('-','');
  12954. });
  12955. }
  12956. NodeParser.prototype.getPseudoElement = function(container, type) {
  12957. var style = container.computedStyle(type);
  12958. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  12959. return null;
  12960. }
  12961. var content = stripQuotes(style.content);
  12962. var isImage = content.substr(0, 3) === 'url';
  12963. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  12964. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  12965. for (var i = style.length-1; i >= 0; i--) {
  12966. var property = toCamelCase(style.item(i));
  12967. pseudoNode.style[property] = style[property];
  12968. }
  12969. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  12970. if (isImage) {
  12971. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  12972. return [pseudoContainer];
  12973. } else {
  12974. var text = document.createTextNode(content);
  12975. pseudoNode.appendChild(text);
  12976. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  12977. }
  12978. };
  12979. NodeParser.prototype.getChildren = function(parentContainer) {
  12980. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  12981. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  12982. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  12983. }, this));
  12984. };
  12985. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  12986. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  12987. container.cloneTo(stack);
  12988. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  12989. parentStack.contexts.push(stack);
  12990. container.stack = stack;
  12991. };
  12992. NodeParser.prototype.createStackingContexts = function() {
  12993. this.nodes.forEach(function(container) {
  12994. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  12995. this.newStackingContext(container, true);
  12996. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  12997. this.newStackingContext(container, false);
  12998. } else {
  12999. container.assignStack(container.parent.stack);
  13000. }
  13001. }, this);
  13002. };
  13003. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  13004. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  13005. };
  13006. NodeParser.prototype.isRootElement = function(container) {
  13007. return container.parent === null;
  13008. };
  13009. NodeParser.prototype.sortStackingContexts = function(stack) {
  13010. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  13011. stack.contexts.forEach(this.sortStackingContexts, this);
  13012. };
  13013. NodeParser.prototype.parseTextBounds = function(container) {
  13014. return function(text, index, textList) {
  13015. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  13016. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  13017. var offset = textList.slice(0, index).join("").length;
  13018. return this.getRangeBounds(container.node, offset, text.length);
  13019. } else if (container.node && typeof(container.node.data) === "string") {
  13020. var replacementNode = container.node.splitText(text.length);
  13021. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  13022. container.node = replacementNode;
  13023. return bounds;
  13024. }
  13025. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  13026. container.node = container.node.splitText(text.length);
  13027. }
  13028. return {};
  13029. };
  13030. };
  13031. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  13032. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  13033. var parent = node.parentNode,
  13034. backupText = node.cloneNode(true);
  13035. wrapper.appendChild(node.cloneNode(true));
  13036. parent.replaceChild(wrapper, node);
  13037. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  13038. parent.replaceChild(backupText, wrapper);
  13039. return bounds;
  13040. };
  13041. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  13042. var range = this.range || (this.range = node.ownerDocument.createRange());
  13043. range.setStart(node, offset);
  13044. range.setEnd(node, offset + length);
  13045. return range.getBoundingClientRect();
  13046. };
  13047. function ClearTransform() {}
  13048. NodeParser.prototype.parse = function(stack) {
  13049. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  13050. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  13051. var descendantElements = stack.children.filter(isElement);
  13052. var descendantNonFloats = descendantElements.filter(not(isFloating));
  13053. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  13054. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  13055. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  13056. 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.
  13057. var text = stack.children.filter(isTextNode).filter(hasText);
  13058. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  13059. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  13060. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  13061. this.renderQueue.push(container);
  13062. if (isStackingContext(container)) {
  13063. this.parse(container);
  13064. this.renderQueue.push(new ClearTransform());
  13065. }
  13066. }, this);
  13067. };
  13068. NodeParser.prototype.paint = function(container) {
  13069. try {
  13070. if (container instanceof ClearTransform) {
  13071. this.renderer.ctx.restore();
  13072. } else if (isTextNode(container)) {
  13073. if (isPseudoElement(container.parent)) {
  13074. container.parent.appendToDOM();
  13075. }
  13076. this.paintText(container);
  13077. if (isPseudoElement(container.parent)) {
  13078. container.parent.cleanDOM();
  13079. }
  13080. } else {
  13081. this.paintNode(container);
  13082. }
  13083. } catch(e) {
  13084. log(e);
  13085. if (this.options.strict) {
  13086. throw e;
  13087. }
  13088. }
  13089. };
  13090. NodeParser.prototype.paintNode = function(container) {
  13091. if (isStackingContext(container)) {
  13092. this.renderer.setOpacity(container.opacity);
  13093. this.renderer.ctx.save();
  13094. if (container.hasTransform()) {
  13095. this.renderer.setTransform(container.parseTransform());
  13096. }
  13097. }
  13098. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  13099. this.paintCheckbox(container);
  13100. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  13101. this.paintRadio(container);
  13102. } else {
  13103. this.paintElement(container);
  13104. }
  13105. };
  13106. NodeParser.prototype.paintElement = function(container) {
  13107. var bounds = container.parseBounds();
  13108. this.renderer.clip(container.backgroundClip, function() {
  13109. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  13110. }, this);
  13111. this.renderer.clip(container.clip, function() {
  13112. this.renderer.renderBorders(container.borders.borders);
  13113. }, this);
  13114. this.renderer.clip(container.backgroundClip, function() {
  13115. switch (container.node.nodeName) {
  13116. case "svg":
  13117. case "IFRAME":
  13118. var imgContainer = this.images.get(container.node);
  13119. if (imgContainer) {
  13120. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  13121. } else {
  13122. log("Error loading <" + container.node.nodeName + ">", container.node);
  13123. }
  13124. break;
  13125. case "IMG":
  13126. var imageContainer = this.images.get(container.node.src);
  13127. if (imageContainer) {
  13128. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  13129. } else {
  13130. log("Error loading <img>", container.node.src);
  13131. }
  13132. break;
  13133. case "CANVAS":
  13134. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  13135. break;
  13136. case "SELECT":
  13137. case "INPUT":
  13138. case "TEXTAREA":
  13139. this.paintFormValue(container);
  13140. break;
  13141. }
  13142. }, this);
  13143. };
  13144. NodeParser.prototype.paintCheckbox = function(container) {
  13145. var b = container.parseBounds();
  13146. var size = Math.min(b.width, b.height);
  13147. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  13148. var r = [3, 3];
  13149. var radius = [r, r, r, r];
  13150. var borders = [1,1,1,1].map(function(w) {
  13151. return {color: new Color('#A5A5A5'), width: w};
  13152. });
  13153. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  13154. this.renderer.clip(container.backgroundClip, function() {
  13155. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  13156. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  13157. if (container.node.checked) {
  13158. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  13159. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  13160. }
  13161. }, this);
  13162. };
  13163. NodeParser.prototype.paintRadio = function(container) {
  13164. var bounds = container.parseBounds();
  13165. var size = Math.min(bounds.width, bounds.height) - 2;
  13166. this.renderer.clip(container.backgroundClip, function() {
  13167. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  13168. if (container.node.checked) {
  13169. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  13170. }
  13171. }, this);
  13172. };
  13173. NodeParser.prototype.paintFormValue = function(container) {
  13174. var value = container.getValue();
  13175. if (value.length > 0) {
  13176. var document = container.node.ownerDocument;
  13177. var wrapper = document.createElement('html2canvaswrapper');
  13178. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  13179. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  13180. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  13181. 'boxSizing', 'whiteSpace', 'wordWrap'];
  13182. properties.forEach(function(property) {
  13183. try {
  13184. wrapper.style[property] = container.css(property);
  13185. } catch(e) {
  13186. // Older IE has issues with "border"
  13187. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  13188. }
  13189. });
  13190. var bounds = container.parseBounds();
  13191. wrapper.style.position = "fixed";
  13192. wrapper.style.left = bounds.left + "px";
  13193. wrapper.style.top = bounds.top + "px";
  13194. wrapper.textContent = value;
  13195. document.body.appendChild(wrapper);
  13196. this.paintText(new TextContainer(wrapper.firstChild, container));
  13197. document.body.removeChild(wrapper);
  13198. }
  13199. };
  13200. NodeParser.prototype.paintText = function(container) {
  13201. container.applyTextTransform();
  13202. var characters = punycode.ucs2.decode(container.node.data);
  13203. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  13204. return punycode.ucs2.encode([character]);
  13205. });
  13206. var weight = container.parent.fontWeight();
  13207. var size = container.parent.css('fontSize');
  13208. var family = container.parent.css('fontFamily');
  13209. var shadows = container.parent.parseTextShadows();
  13210. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  13211. if (shadows.length) {
  13212. // TODO: support multiple text shadows
  13213. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  13214. } else {
  13215. this.renderer.clearShadow();
  13216. }
  13217. this.renderer.clip(container.parent.clip, function() {
  13218. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  13219. if (bounds) {
  13220. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  13221. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  13222. }
  13223. }, this);
  13224. }, this);
  13225. };
  13226. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  13227. switch(container.css("textDecoration").split(" ")[0]) {
  13228. case "underline":
  13229. // Draws a line at the baseline of the font
  13230. // 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
  13231. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13232. break;
  13233. case "overline":
  13234. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  13235. break;
  13236. case "line-through":
  13237. // TODO try and find exact position for line-through
  13238. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  13239. break;
  13240. }
  13241. };
  13242. var borderColorTransforms = {
  13243. inset: [
  13244. ["darken", 0.60],
  13245. ["darken", 0.10],
  13246. ["darken", 0.10],
  13247. ["darken", 0.60]
  13248. ]
  13249. };
  13250. NodeParser.prototype.parseBorders = function(container) {
  13251. var nodeBounds = container.parseBounds();
  13252. var radius = getBorderRadiusData(container);
  13253. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  13254. var style = container.css('border' + side + 'Style');
  13255. var color = container.color('border' + side + 'Color');
  13256. if (style === "inset" && color.isBlack()) {
  13257. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  13258. }
  13259. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  13260. return {
  13261. width: container.cssInt('border' + side + 'Width'),
  13262. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  13263. args: null
  13264. };
  13265. });
  13266. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  13267. return {
  13268. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  13269. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  13270. };
  13271. };
  13272. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  13273. return borders.map(function(border, borderSide) {
  13274. if (border.width > 0) {
  13275. var bx = nodeBounds.left;
  13276. var by = nodeBounds.top;
  13277. var bw = nodeBounds.width;
  13278. var bh = nodeBounds.height - (borders[2].width);
  13279. switch(borderSide) {
  13280. case 0:
  13281. // top border
  13282. bh = borders[0].width;
  13283. border.args = drawSide({
  13284. c1: [bx, by],
  13285. c2: [bx + bw, by],
  13286. c3: [bx + bw - borders[1].width, by + bh],
  13287. c4: [bx + borders[3].width, by + bh]
  13288. }, radius[0], radius[1],
  13289. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  13290. break;
  13291. case 1:
  13292. // right border
  13293. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  13294. bw = borders[1].width;
  13295. border.args = drawSide({
  13296. c1: [bx + bw, by],
  13297. c2: [bx + bw, by + bh + borders[2].width],
  13298. c3: [bx, by + bh],
  13299. c4: [bx, by + borders[0].width]
  13300. }, radius[1], radius[2],
  13301. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  13302. break;
  13303. case 2:
  13304. // bottom border
  13305. by = (by + nodeBounds.height) - (borders[2].width);
  13306. bh = borders[2].width;
  13307. border.args = drawSide({
  13308. c1: [bx + bw, by + bh],
  13309. c2: [bx, by + bh],
  13310. c3: [bx + borders[3].width, by],
  13311. c4: [bx + bw - borders[3].width, by]
  13312. }, radius[2], radius[3],
  13313. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  13314. break;
  13315. case 3:
  13316. // left border
  13317. bw = borders[3].width;
  13318. border.args = drawSide({
  13319. c1: [bx, by + bh + borders[2].width],
  13320. c2: [bx, by],
  13321. c3: [bx + bw, by + borders[0].width],
  13322. c4: [bx + bw, by + bh]
  13323. }, radius[3], radius[0],
  13324. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  13325. break;
  13326. }
  13327. }
  13328. return border;
  13329. });
  13330. }
  13331. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  13332. var backgroundClip = container.css('backgroundClip'),
  13333. borderArgs = [];
  13334. switch(backgroundClip) {
  13335. case "content-box":
  13336. case "padding-box":
  13337. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  13338. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  13339. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  13340. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  13341. break;
  13342. default:
  13343. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  13344. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  13345. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  13346. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  13347. break;
  13348. }
  13349. return borderArgs;
  13350. };
  13351. function getCurvePoints(x, y, r1, r2) {
  13352. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  13353. var ox = (r1) * kappa, // control point offset horizontal
  13354. oy = (r2) * kappa, // control point offset vertical
  13355. xm = x + r1, // x-middle
  13356. ym = y + r2; // y-middle
  13357. return {
  13358. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  13359. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  13360. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  13361. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  13362. };
  13363. }
  13364. function calculateCurvePoints(bounds, borderRadius, borders) {
  13365. var x = bounds.left,
  13366. y = bounds.top,
  13367. width = bounds.width,
  13368. height = bounds.height,
  13369. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  13370. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  13371. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  13372. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  13373. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  13374. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  13375. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  13376. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  13377. var topWidth = width - trh,
  13378. rightHeight = height - brv,
  13379. bottomWidth = width - brh,
  13380. leftHeight = height - blv;
  13381. return {
  13382. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  13383. 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),
  13384. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  13385. 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),
  13386. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  13387. 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),
  13388. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  13389. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  13390. };
  13391. }
  13392. function bezierCurve(start, startControl, endControl, end) {
  13393. var lerp = function (a, b, t) {
  13394. return {
  13395. x: a.x + (b.x - a.x) * t,
  13396. y: a.y + (b.y - a.y) * t
  13397. };
  13398. };
  13399. return {
  13400. start: start,
  13401. startControl: startControl,
  13402. endControl: endControl,
  13403. end: end,
  13404. subdivide: function(t) {
  13405. var ab = lerp(start, startControl, t),
  13406. bc = lerp(startControl, endControl, t),
  13407. cd = lerp(endControl, end, t),
  13408. abbc = lerp(ab, bc, t),
  13409. bccd = lerp(bc, cd, t),
  13410. dest = lerp(abbc, bccd, t);
  13411. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  13412. },
  13413. curveTo: function(borderArgs) {
  13414. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  13415. },
  13416. curveToReversed: function(borderArgs) {
  13417. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  13418. }
  13419. };
  13420. }
  13421. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  13422. var borderArgs = [];
  13423. if (radius1[0] > 0 || radius1[1] > 0) {
  13424. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  13425. outer1[1].curveTo(borderArgs);
  13426. } else {
  13427. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  13428. }
  13429. if (radius2[0] > 0 || radius2[1] > 0) {
  13430. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  13431. outer2[0].curveTo(borderArgs);
  13432. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  13433. inner2[0].curveToReversed(borderArgs);
  13434. } else {
  13435. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  13436. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  13437. }
  13438. if (radius1[0] > 0 || radius1[1] > 0) {
  13439. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  13440. inner1[1].curveToReversed(borderArgs);
  13441. } else {
  13442. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  13443. }
  13444. return borderArgs;
  13445. }
  13446. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  13447. if (radius1[0] > 0 || radius1[1] > 0) {
  13448. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  13449. corner1[0].curveTo(borderArgs);
  13450. corner1[1].curveTo(borderArgs);
  13451. } else {
  13452. borderArgs.push(["line", x, y]);
  13453. }
  13454. if (radius2[0] > 0 || radius2[1] > 0) {
  13455. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  13456. }
  13457. }
  13458. function negativeZIndex(container) {
  13459. return container.cssInt("zIndex") < 0;
  13460. }
  13461. function positiveZIndex(container) {
  13462. return container.cssInt("zIndex") > 0;
  13463. }
  13464. function zIndex0(container) {
  13465. return container.cssInt("zIndex") === 0;
  13466. }
  13467. function inlineLevel(container) {
  13468. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13469. }
  13470. function isStackingContext(container) {
  13471. return (container instanceof StackingContext);
  13472. }
  13473. function hasText(container) {
  13474. return container.node.data.trim().length > 0;
  13475. }
  13476. function noLetterSpacing(container) {
  13477. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  13478. }
  13479. function getBorderRadiusData(container) {
  13480. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  13481. var value = container.css('border' + side + 'Radius');
  13482. var arr = value.split(" ");
  13483. if (arr.length <= 1) {
  13484. arr[1] = arr[0];
  13485. }
  13486. return arr.map(asInt);
  13487. });
  13488. }
  13489. function renderableNode(node) {
  13490. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  13491. }
  13492. function isPositionedForStacking(container) {
  13493. var position = container.css("position");
  13494. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  13495. return zIndex !== "auto";
  13496. }
  13497. function isPositioned(container) {
  13498. return container.css("position") !== "static";
  13499. }
  13500. function isFloating(container) {
  13501. return container.css("float") !== "none";
  13502. }
  13503. function isInlineBlock(container) {
  13504. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13505. }
  13506. function not(callback) {
  13507. var context = this;
  13508. return function() {
  13509. return !callback.apply(context, arguments);
  13510. };
  13511. }
  13512. function isElement(container) {
  13513. return container.node.nodeType === Node.ELEMENT_NODE;
  13514. }
  13515. function isPseudoElement(container) {
  13516. return container.isPseudoElement === true;
  13517. }
  13518. function isTextNode(container) {
  13519. return container.node.nodeType === Node.TEXT_NODE;
  13520. }
  13521. function zIndexSort(contexts) {
  13522. return function(a, b) {
  13523. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  13524. };
  13525. }
  13526. function hasOpacity(container) {
  13527. return container.getOpacity() < 1;
  13528. }
  13529. function asInt(value) {
  13530. return parseInt(value, 10);
  13531. }
  13532. function getWidth(border) {
  13533. return border.width;
  13534. }
  13535. function nonIgnoredElement(nodeContainer) {
  13536. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  13537. }
  13538. function flatten(arrays) {
  13539. return [].concat.apply([], arrays);
  13540. }
  13541. function stripQuotes(content) {
  13542. var first = content.substr(0, 1);
  13543. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  13544. }
  13545. function getWords(characters) {
  13546. var words = [], i = 0, onWordBoundary = false, word;
  13547. while(characters.length) {
  13548. if (isWordBoundary(characters[i]) === onWordBoundary) {
  13549. word = characters.splice(0, i);
  13550. if (word.length) {
  13551. words.push(punycode.ucs2.encode(word));
  13552. }
  13553. onWordBoundary =! onWordBoundary;
  13554. i = 0;
  13555. } else {
  13556. i++;
  13557. }
  13558. if (i >= characters.length) {
  13559. word = characters.splice(0, i);
  13560. if (word.length) {
  13561. words.push(punycode.ucs2.encode(word));
  13562. }
  13563. }
  13564. }
  13565. return words;
  13566. }
  13567. function isWordBoundary(characterCode) {
  13568. return [
  13569. 32, // <space>
  13570. 13, // \r
  13571. 10, // \n
  13572. 9, // \t
  13573. 45 // -
  13574. ].indexOf(characterCode) !== -1;
  13575. }
  13576. function hasUnicode(string) {
  13577. return (/[^\u0000-\u00ff]/).test(string);
  13578. }
  13579. module.exports = NodeParser;
  13580. },{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
  13581. var XHR = _dereq_('./xhr');
  13582. var utils = _dereq_('./utils');
  13583. var log = _dereq_('./log');
  13584. var createWindowClone = _dereq_('./clone');
  13585. var decode64 = utils.decode64;
  13586. function Proxy(src, proxyUrl, document) {
  13587. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  13588. if (!proxyUrl) {
  13589. return Promise.reject("No proxy configured");
  13590. }
  13591. var callback = createCallback(supportsCORS);
  13592. var url = createProxyUrl(proxyUrl, src, callback);
  13593. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  13594. return decode64(response.content);
  13595. }));
  13596. }
  13597. var proxyCount = 0;
  13598. function ProxyURL(src, proxyUrl, document) {
  13599. var supportsCORSImage = ('crossOrigin' in new Image());
  13600. var callback = createCallback(supportsCORSImage);
  13601. var url = createProxyUrl(proxyUrl, src, callback);
  13602. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  13603. return "data:" + response.type + ";base64," + response.content;
  13604. }));
  13605. }
  13606. function jsonp(document, url, callback) {
  13607. return new Promise(function(resolve, reject) {
  13608. var s = document.createElement("script");
  13609. var cleanup = function() {
  13610. delete window.html2canvas.proxy[callback];
  13611. document.body.removeChild(s);
  13612. };
  13613. window.html2canvas.proxy[callback] = function(response) {
  13614. cleanup();
  13615. resolve(response);
  13616. };
  13617. s.src = url;
  13618. s.onerror = function(e) {
  13619. cleanup();
  13620. reject(e);
  13621. };
  13622. document.body.appendChild(s);
  13623. });
  13624. }
  13625. function createCallback(useCORS) {
  13626. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  13627. }
  13628. function createProxyUrl(proxyUrl, src, callback) {
  13629. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  13630. }
  13631. function documentFromHTML(src) {
  13632. return function(html) {
  13633. var parser = new DOMParser(), doc;
  13634. try {
  13635. doc = parser.parseFromString(html, "text/html");
  13636. } catch(e) {
  13637. log("DOMParser not supported, falling back to createHTMLDocument");
  13638. doc = document.implementation.createHTMLDocument("");
  13639. try {
  13640. doc.open();
  13641. doc.write(html);
  13642. doc.close();
  13643. } catch(ee) {
  13644. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  13645. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  13646. }
  13647. }
  13648. var b = doc.querySelector("base");
  13649. if (!b || !b.href.host) {
  13650. var base = doc.createElement("base");
  13651. base.href = src;
  13652. doc.head.insertBefore(base, doc.head.firstChild);
  13653. }
  13654. return doc;
  13655. };
  13656. }
  13657. function loadUrlDocument(src, proxy, document, width, height, options) {
  13658. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  13659. return createWindowClone(doc, document, width, height, options, 0, 0);
  13660. });
  13661. }
  13662. exports.Proxy = Proxy;
  13663. exports.ProxyURL = ProxyURL;
  13664. exports.loadUrlDocument = loadUrlDocument;
  13665. },{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
  13666. var ProxyURL = _dereq_('./proxy').ProxyURL;
  13667. function ProxyImageContainer(src, proxy) {
  13668. var link = document.createElement("a");
  13669. link.href = src;
  13670. src = link.href;
  13671. this.src = src;
  13672. this.image = new Image();
  13673. var self = this;
  13674. this.promise = new Promise(function(resolve, reject) {
  13675. self.image.crossOrigin = "Anonymous";
  13676. self.image.onload = resolve;
  13677. self.image.onerror = reject;
  13678. new ProxyURL(src, proxy, document).then(function(url) {
  13679. self.image.src = url;
  13680. })['catch'](reject);
  13681. });
  13682. }
  13683. module.exports = ProxyImageContainer;
  13684. },{"./proxy":16}],18:[function(_dereq_,module,exports){
  13685. var NodeContainer = _dereq_('./nodecontainer');
  13686. function PseudoElementContainer(node, parent, type) {
  13687. NodeContainer.call(this, node, parent);
  13688. this.isPseudoElement = true;
  13689. this.before = type === ":before";
  13690. }
  13691. PseudoElementContainer.prototype.cloneTo = function(stack) {
  13692. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  13693. stack.isPseudoElement = true;
  13694. stack.before = this.before;
  13695. };
  13696. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  13697. PseudoElementContainer.prototype.appendToDOM = function() {
  13698. if (this.before) {
  13699. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  13700. } else {
  13701. this.parent.node.appendChild(this.node);
  13702. }
  13703. this.parent.node.className += " " + this.getHideClass();
  13704. };
  13705. PseudoElementContainer.prototype.cleanDOM = function() {
  13706. this.node.parentNode.removeChild(this.node);
  13707. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  13708. };
  13709. PseudoElementContainer.prototype.getHideClass = function() {
  13710. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  13711. };
  13712. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  13713. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  13714. module.exports = PseudoElementContainer;
  13715. },{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
  13716. var log = _dereq_('./log');
  13717. function Renderer(width, height, images, options, document) {
  13718. this.width = width;
  13719. this.height = height;
  13720. this.images = images;
  13721. this.options = options;
  13722. this.document = document;
  13723. }
  13724. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  13725. var paddingLeft = container.cssInt('paddingLeft'),
  13726. paddingTop = container.cssInt('paddingTop'),
  13727. paddingRight = container.cssInt('paddingRight'),
  13728. paddingBottom = container.cssInt('paddingBottom'),
  13729. borders = borderData.borders;
  13730. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  13731. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  13732. this.drawImage(
  13733. imageContainer,
  13734. 0,
  13735. 0,
  13736. imageContainer.image.width || width,
  13737. imageContainer.image.height || height,
  13738. bounds.left + paddingLeft + borders[3].width,
  13739. bounds.top + paddingTop + borders[0].width,
  13740. width,
  13741. height
  13742. );
  13743. };
  13744. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  13745. if (bounds.height > 0 && bounds.width > 0) {
  13746. this.renderBackgroundColor(container, bounds);
  13747. this.renderBackgroundImage(container, bounds, borderData);
  13748. }
  13749. };
  13750. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  13751. var color = container.color("backgroundColor");
  13752. if (!color.isTransparent()) {
  13753. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  13754. }
  13755. };
  13756. Renderer.prototype.renderBorders = function(borders) {
  13757. borders.forEach(this.renderBorder, this);
  13758. };
  13759. Renderer.prototype.renderBorder = function(data) {
  13760. if (!data.color.isTransparent() && data.args !== null) {
  13761. this.drawShape(data.args, data.color);
  13762. }
  13763. };
  13764. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  13765. var backgroundImages = container.parseBackgroundImages();
  13766. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  13767. switch(backgroundImage.method) {
  13768. case "url":
  13769. var image = this.images.get(backgroundImage.args[0]);
  13770. if (image) {
  13771. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  13772. } else {
  13773. log("Error loading background-image", backgroundImage.args[0]);
  13774. }
  13775. break;
  13776. case "linear-gradient":
  13777. case "gradient":
  13778. var gradientImage = this.images.get(backgroundImage.value);
  13779. if (gradientImage) {
  13780. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  13781. } else {
  13782. log("Error loading background-image", backgroundImage.args[0]);
  13783. }
  13784. break;
  13785. case "none":
  13786. break;
  13787. default:
  13788. log("Unknown background-image type", backgroundImage.args[0]);
  13789. }
  13790. }, this);
  13791. };
  13792. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  13793. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  13794. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  13795. var repeat = container.parseBackgroundRepeat(index);
  13796. switch (repeat) {
  13797. case "repeat-x":
  13798. case "repeat no-repeat":
  13799. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  13800. break;
  13801. case "repeat-y":
  13802. case "no-repeat repeat":
  13803. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  13804. break;
  13805. case "no-repeat":
  13806. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  13807. break;
  13808. default:
  13809. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  13810. break;
  13811. }
  13812. };
  13813. module.exports = Renderer;
  13814. },{"./log":13}],20:[function(_dereq_,module,exports){
  13815. var Renderer = _dereq_('../renderer');
  13816. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  13817. var log = _dereq_('../log');
  13818. function CanvasRenderer(width, height) {
  13819. Renderer.apply(this, arguments);
  13820. this.canvas = this.options.canvas || this.document.createElement("canvas");
  13821. if (!this.options.canvas) {
  13822. this.canvas.width = width;
  13823. this.canvas.height = height;
  13824. }
  13825. this.ctx = this.canvas.getContext("2d");
  13826. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  13827. this.ctx.textBaseline = "bottom";
  13828. this.variables = {};
  13829. log("Initialized CanvasRenderer with size", width, "x", height);
  13830. }
  13831. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  13832. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  13833. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  13834. return this.ctx;
  13835. };
  13836. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  13837. this.setFillStyle(color).fillRect(left, top, width, height);
  13838. };
  13839. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  13840. this.setFillStyle(color);
  13841. this.ctx.beginPath();
  13842. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  13843. this.ctx.closePath();
  13844. this.ctx.fill();
  13845. };
  13846. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  13847. this.circle(left, top, size, color);
  13848. this.ctx.strokeStyle = strokeColor.toString();
  13849. this.ctx.stroke();
  13850. };
  13851. CanvasRenderer.prototype.drawShape = function(shape, color) {
  13852. this.shape(shape);
  13853. this.setFillStyle(color).fill();
  13854. };
  13855. CanvasRenderer.prototype.taints = function(imageContainer) {
  13856. if (imageContainer.tainted === null) {
  13857. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  13858. try {
  13859. this.taintCtx.getImageData(0, 0, 1, 1);
  13860. imageContainer.tainted = false;
  13861. } catch(e) {
  13862. this.taintCtx = document.createElement("canvas").getContext("2d");
  13863. imageContainer.tainted = true;
  13864. }
  13865. }
  13866. return imageContainer.tainted;
  13867. };
  13868. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  13869. if (!this.taints(imageContainer) || this.options.allowTaint) {
  13870. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  13871. }
  13872. };
  13873. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  13874. this.ctx.save();
  13875. shapes.filter(hasEntries).forEach(function(shape) {
  13876. this.shape(shape).clip();
  13877. }, this);
  13878. callback.call(context);
  13879. this.ctx.restore();
  13880. };
  13881. CanvasRenderer.prototype.shape = function(shape) {
  13882. this.ctx.beginPath();
  13883. shape.forEach(function(point, index) {
  13884. if (point[0] === "rect") {
  13885. this.ctx.rect.apply(this.ctx, point.slice(1));
  13886. } else {
  13887. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  13888. }
  13889. }, this);
  13890. this.ctx.closePath();
  13891. return this.ctx;
  13892. };
  13893. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  13894. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  13895. };
  13896. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  13897. this.setVariable("shadowColor", color.toString())
  13898. .setVariable("shadowOffsetY", offsetX)
  13899. .setVariable("shadowOffsetX", offsetY)
  13900. .setVariable("shadowBlur", blur);
  13901. };
  13902. CanvasRenderer.prototype.clearShadow = function() {
  13903. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  13904. };
  13905. CanvasRenderer.prototype.setOpacity = function(opacity) {
  13906. this.ctx.globalAlpha = opacity;
  13907. };
  13908. CanvasRenderer.prototype.setTransform = function(transform) {
  13909. this.ctx.translate(transform.origin[0], transform.origin[1]);
  13910. this.ctx.transform.apply(this.ctx, transform.matrix);
  13911. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  13912. };
  13913. CanvasRenderer.prototype.setVariable = function(property, value) {
  13914. if (this.variables[property] !== value) {
  13915. this.variables[property] = this.ctx[property] = value;
  13916. }
  13917. return this;
  13918. };
  13919. CanvasRenderer.prototype.text = function(text, left, bottom) {
  13920. this.ctx.fillText(text, left, bottom);
  13921. };
  13922. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  13923. var shape = [
  13924. ["line", Math.round(left), Math.round(top)],
  13925. ["line", Math.round(left + width), Math.round(top)],
  13926. ["line", Math.round(left + width), Math.round(height + top)],
  13927. ["line", Math.round(left), Math.round(height + top)]
  13928. ];
  13929. this.clip([shape], function() {
  13930. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  13931. }, this);
  13932. };
  13933. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  13934. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  13935. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  13936. this.ctx.translate(offsetX, offsetY);
  13937. this.ctx.fill();
  13938. this.ctx.translate(-offsetX, -offsetY);
  13939. };
  13940. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  13941. if (gradientImage instanceof LinearGradientContainer) {
  13942. var gradient = this.ctx.createLinearGradient(
  13943. bounds.left + bounds.width * gradientImage.x0,
  13944. bounds.top + bounds.height * gradientImage.y0,
  13945. bounds.left + bounds.width * gradientImage.x1,
  13946. bounds.top + bounds.height * gradientImage.y1);
  13947. gradientImage.colorStops.forEach(function(colorStop) {
  13948. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  13949. });
  13950. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  13951. }
  13952. };
  13953. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  13954. var image = imageContainer.image;
  13955. if(image.width === size.width && image.height === size.height) {
  13956. return image;
  13957. }
  13958. var ctx, canvas = document.createElement('canvas');
  13959. canvas.width = size.width;
  13960. canvas.height = size.height;
  13961. ctx = canvas.getContext("2d");
  13962. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  13963. return canvas;
  13964. };
  13965. function hasEntries(array) {
  13966. return array.length > 0;
  13967. }
  13968. module.exports = CanvasRenderer;
  13969. },{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
  13970. var NodeContainer = _dereq_('./nodecontainer');
  13971. function StackingContext(hasOwnStacking, opacity, element, parent) {
  13972. NodeContainer.call(this, element, parent);
  13973. this.ownStacking = hasOwnStacking;
  13974. this.contexts = [];
  13975. this.children = [];
  13976. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  13977. }
  13978. StackingContext.prototype = Object.create(NodeContainer.prototype);
  13979. StackingContext.prototype.getParentStack = function(context) {
  13980. var parentStack = (this.parent) ? this.parent.stack : null;
  13981. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  13982. };
  13983. module.exports = StackingContext;
  13984. },{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
  13985. function Support(document) {
  13986. this.rangeBounds = this.testRangeBounds(document);
  13987. this.cors = this.testCORS();
  13988. this.svg = this.testSVG();
  13989. }
  13990. Support.prototype.testRangeBounds = function(document) {
  13991. var range, testElement, rangeBounds, rangeHeight, support = false;
  13992. if (document.createRange) {
  13993. range = document.createRange();
  13994. if (range.getBoundingClientRect) {
  13995. testElement = document.createElement('boundtest');
  13996. testElement.style.height = "123px";
  13997. testElement.style.display = "block";
  13998. document.body.appendChild(testElement);
  13999. range.selectNode(testElement);
  14000. rangeBounds = range.getBoundingClientRect();
  14001. rangeHeight = rangeBounds.height;
  14002. if (rangeHeight === 123) {
  14003. support = true;
  14004. }
  14005. document.body.removeChild(testElement);
  14006. }
  14007. }
  14008. return support;
  14009. };
  14010. Support.prototype.testCORS = function() {
  14011. return typeof((new Image()).crossOrigin) !== "undefined";
  14012. };
  14013. Support.prototype.testSVG = function() {
  14014. var img = new Image();
  14015. var canvas = document.createElement("canvas");
  14016. var ctx = canvas.getContext("2d");
  14017. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  14018. try {
  14019. ctx.drawImage(img, 0, 0);
  14020. canvas.toDataURL();
  14021. } catch(e) {
  14022. return false;
  14023. }
  14024. return true;
  14025. };
  14026. module.exports = Support;
  14027. },{}],23:[function(_dereq_,module,exports){
  14028. var XHR = _dereq_('./xhr');
  14029. var decode64 = _dereq_('./utils').decode64;
  14030. function SVGContainer(src) {
  14031. this.src = src;
  14032. this.image = null;
  14033. var self = this;
  14034. this.promise = this.hasFabric().then(function() {
  14035. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  14036. }).then(function(svg) {
  14037. return new Promise(function(resolve) {
  14038. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  14039. });
  14040. });
  14041. }
  14042. SVGContainer.prototype.hasFabric = function() {
  14043. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  14044. };
  14045. SVGContainer.prototype.inlineFormatting = function(src) {
  14046. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  14047. };
  14048. SVGContainer.prototype.removeContentType = function(src) {
  14049. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  14050. };
  14051. SVGContainer.prototype.isInline = function(src) {
  14052. return (/^data:image\/svg\+xml/i.test(src));
  14053. };
  14054. SVGContainer.prototype.createCanvas = function(resolve) {
  14055. var self = this;
  14056. return function (objects, options) {
  14057. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  14058. self.image = canvas.lowerCanvasEl;
  14059. canvas
  14060. .setWidth(options.width)
  14061. .setHeight(options.height)
  14062. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  14063. .renderAll();
  14064. resolve(canvas.lowerCanvasEl);
  14065. };
  14066. };
  14067. SVGContainer.prototype.decode64 = function(str) {
  14068. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  14069. };
  14070. module.exports = SVGContainer;
  14071. },{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
  14072. var SVGContainer = _dereq_('./svgcontainer');
  14073. function SVGNodeContainer(node, _native) {
  14074. this.src = node;
  14075. this.image = null;
  14076. var self = this;
  14077. this.promise = _native ? new Promise(function(resolve, reject) {
  14078. self.image = new Image();
  14079. self.image.onload = resolve;
  14080. self.image.onerror = reject;
  14081. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  14082. if (self.image.complete === true) {
  14083. resolve(self.image);
  14084. }
  14085. }) : this.hasFabric().then(function() {
  14086. return new Promise(function(resolve) {
  14087. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  14088. });
  14089. });
  14090. }
  14091. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  14092. module.exports = SVGNodeContainer;
  14093. },{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
  14094. var NodeContainer = _dereq_('./nodecontainer');
  14095. function TextContainer(node, parent) {
  14096. NodeContainer.call(this, node, parent);
  14097. }
  14098. TextContainer.prototype = Object.create(NodeContainer.prototype);
  14099. TextContainer.prototype.applyTextTransform = function() {
  14100. this.node.data = this.transform(this.parent.css("textTransform"));
  14101. };
  14102. TextContainer.prototype.transform = function(transform) {
  14103. var text = this.node.data;
  14104. switch(transform){
  14105. case "lowercase":
  14106. return text.toLowerCase();
  14107. case "capitalize":
  14108. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  14109. case "uppercase":
  14110. return text.toUpperCase();
  14111. default:
  14112. return text;
  14113. }
  14114. };
  14115. function capitalize(m, p1, p2) {
  14116. if (m.length > 0) {
  14117. return p1 + p2.toUpperCase();
  14118. }
  14119. }
  14120. module.exports = TextContainer;
  14121. },{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
  14122. exports.smallImage = function smallImage() {
  14123. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  14124. };
  14125. exports.bind = function(callback, context) {
  14126. return function() {
  14127. return callback.apply(context, arguments);
  14128. };
  14129. };
  14130. /*
  14131. * base64-arraybuffer
  14132. * https://github.com/niklasvh/base64-arraybuffer
  14133. *
  14134. * Copyright (c) 2012 Niklas von Hertzen
  14135. * Licensed under the MIT license.
  14136. */
  14137. exports.decode64 = function(base64) {
  14138. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  14139. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  14140. var output = "";
  14141. for (i = 0; i < len; i+=4) {
  14142. encoded1 = chars.indexOf(base64[i]);
  14143. encoded2 = chars.indexOf(base64[i+1]);
  14144. encoded3 = chars.indexOf(base64[i+2]);
  14145. encoded4 = chars.indexOf(base64[i+3]);
  14146. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  14147. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  14148. byte3 = ((encoded3 & 3) << 6) | encoded4;
  14149. if (encoded3 === 64) {
  14150. output += String.fromCharCode(byte1);
  14151. } else if (encoded4 === 64 || encoded4 === -1) {
  14152. output += String.fromCharCode(byte1, byte2);
  14153. } else{
  14154. output += String.fromCharCode(byte1, byte2, byte3);
  14155. }
  14156. }
  14157. return output;
  14158. };
  14159. exports.getBounds = function(node) {
  14160. if (node.getBoundingClientRect) {
  14161. var clientRect = node.getBoundingClientRect();
  14162. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  14163. return {
  14164. top: clientRect.top,
  14165. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  14166. right: clientRect.left + width,
  14167. left: clientRect.left,
  14168. width: width,
  14169. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  14170. };
  14171. }
  14172. return {};
  14173. };
  14174. exports.offsetBounds = function(node) {
  14175. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  14176. return {
  14177. top: node.offsetTop + parent.top,
  14178. bottom: node.offsetTop + node.offsetHeight + parent.top,
  14179. right: node.offsetLeft + parent.left + node.offsetWidth,
  14180. left: node.offsetLeft + parent.left,
  14181. width: node.offsetWidth,
  14182. height: node.offsetHeight
  14183. };
  14184. };
  14185. exports.parseBackgrounds = function(backgroundImage) {
  14186. var whitespace = ' \r\n\t',
  14187. method, definition, prefix, prefix_i, block, results = [],
  14188. mode = 0, numParen = 0, quote, args;
  14189. var appendResult = function() {
  14190. if(method) {
  14191. if (definition.substr(0, 1) === '"') {
  14192. definition = definition.substr(1, definition.length - 2);
  14193. }
  14194. if (definition) {
  14195. args.push(definition);
  14196. }
  14197. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  14198. prefix = method.substr(0, prefix_i);
  14199. method = method.substr(prefix_i);
  14200. }
  14201. results.push({
  14202. prefix: prefix,
  14203. method: method.toLowerCase(),
  14204. value: block,
  14205. args: args,
  14206. image: null
  14207. });
  14208. }
  14209. args = [];
  14210. method = prefix = definition = block = '';
  14211. };
  14212. args = [];
  14213. method = prefix = definition = block = '';
  14214. backgroundImage.split("").forEach(function(c) {
  14215. if (mode === 0 && whitespace.indexOf(c) > -1) {
  14216. return;
  14217. }
  14218. switch(c) {
  14219. case '"':
  14220. if(!quote) {
  14221. quote = c;
  14222. } else if(quote === c) {
  14223. quote = null;
  14224. }
  14225. break;
  14226. case '(':
  14227. if(quote) {
  14228. break;
  14229. } else if(mode === 0) {
  14230. mode = 1;
  14231. block += c;
  14232. return;
  14233. } else {
  14234. numParen++;
  14235. }
  14236. break;
  14237. case ')':
  14238. if (quote) {
  14239. break;
  14240. } else if(mode === 1) {
  14241. if(numParen === 0) {
  14242. mode = 0;
  14243. block += c;
  14244. appendResult();
  14245. return;
  14246. } else {
  14247. numParen--;
  14248. }
  14249. }
  14250. break;
  14251. case ',':
  14252. if (quote) {
  14253. break;
  14254. } else if(mode === 0) {
  14255. appendResult();
  14256. return;
  14257. } else if (mode === 1) {
  14258. if (numParen === 0 && !method.match(/^url$/i)) {
  14259. args.push(definition);
  14260. definition = '';
  14261. block += c;
  14262. return;
  14263. }
  14264. }
  14265. break;
  14266. }
  14267. block += c;
  14268. if (mode === 0) {
  14269. method += c;
  14270. } else {
  14271. definition += c;
  14272. }
  14273. });
  14274. appendResult();
  14275. return results;
  14276. };
  14277. },{}],27:[function(_dereq_,module,exports){
  14278. var GradientContainer = _dereq_('./gradientcontainer');
  14279. function WebkitGradientContainer(imageData) {
  14280. GradientContainer.apply(this, arguments);
  14281. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  14282. }
  14283. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  14284. module.exports = WebkitGradientContainer;
  14285. },{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
  14286. function XHR(url) {
  14287. return new Promise(function(resolve, reject) {
  14288. var xhr = new XMLHttpRequest();
  14289. xhr.open('GET', url);
  14290. xhr.onload = function() {
  14291. if (xhr.status === 200) {
  14292. resolve(xhr.responseText);
  14293. } else {
  14294. reject(new Error(xhr.statusText));
  14295. }
  14296. };
  14297. xhr.onerror = function() {
  14298. reject(new Error("Network Error"));
  14299. };
  14300. xhr.send();
  14301. });
  14302. }
  14303. module.exports = XHR;
  14304. },{}]},{},[4])(4)
  14305. });
  14306. // Generated by CoffeeScript 1.4.0
  14307. /*
  14308. # PNG.js
  14309. # Copyright (c) 2011 Devon Govett
  14310. # MIT LICENSE
  14311. #
  14312. #
  14313. */
  14314. (function(global) {
  14315. var PNG;
  14316. PNG = (function() {
  14317. var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  14318. PNG.load = function(url, canvas, callback) {
  14319. var xhr,
  14320. _this = this;
  14321. if (typeof canvas === 'function') {
  14322. callback = canvas;
  14323. }
  14324. xhr = new XMLHttpRequest;
  14325. xhr.open("GET", url, true);
  14326. xhr.responseType = "arraybuffer";
  14327. xhr.onload = function() {
  14328. var data, png;
  14329. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  14330. png = new PNG(data);
  14331. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  14332. png.render(canvas);
  14333. }
  14334. return typeof callback === "function" ? callback(png) : void 0;
  14335. };
  14336. return xhr.send(null);
  14337. };
  14338. APNG_DISPOSE_OP_NONE = 0;
  14339. APNG_DISPOSE_OP_BACKGROUND = 1;
  14340. APNG_DISPOSE_OP_PREVIOUS = 2;
  14341. APNG_BLEND_OP_SOURCE = 0;
  14342. APNG_BLEND_OP_OVER = 1;
  14343. function PNG(data) {
  14344. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  14345. this.data = data;
  14346. this.pos = 8;
  14347. this.palette = [];
  14348. this.imgData = [];
  14349. this.transparency = {};
  14350. this.animation = null;
  14351. this.text = {};
  14352. frame = null;
  14353. while (true) {
  14354. chunkSize = this.readUInt32();
  14355. section = ((function() {
  14356. var _i, _results;
  14357. _results = [];
  14358. for (i = _i = 0; _i < 4; i = ++_i) {
  14359. _results.push(String.fromCharCode(this.data[this.pos++]));
  14360. }
  14361. return _results;
  14362. }).call(this)).join('');
  14363. switch (section) {
  14364. case 'IHDR':
  14365. this.width = this.readUInt32();
  14366. this.height = this.readUInt32();
  14367. this.bits = this.data[this.pos++];
  14368. this.colorType = this.data[this.pos++];
  14369. this.compressionMethod = this.data[this.pos++];
  14370. this.filterMethod = this.data[this.pos++];
  14371. this.interlaceMethod = this.data[this.pos++];
  14372. break;
  14373. case 'acTL':
  14374. this.animation = {
  14375. numFrames: this.readUInt32(),
  14376. numPlays: this.readUInt32() || Infinity,
  14377. frames: []
  14378. };
  14379. break;
  14380. case 'PLTE':
  14381. this.palette = this.read(chunkSize);
  14382. break;
  14383. case 'fcTL':
  14384. if (frame) {
  14385. this.animation.frames.push(frame);
  14386. }
  14387. this.pos += 4;
  14388. frame = {
  14389. width: this.readUInt32(),
  14390. height: this.readUInt32(),
  14391. xOffset: this.readUInt32(),
  14392. yOffset: this.readUInt32()
  14393. };
  14394. delayNum = this.readUInt16();
  14395. delayDen = this.readUInt16() || 100;
  14396. frame.delay = 1000 * delayNum / delayDen;
  14397. frame.disposeOp = this.data[this.pos++];
  14398. frame.blendOp = this.data[this.pos++];
  14399. frame.data = [];
  14400. break;
  14401. case 'IDAT':
  14402. case 'fdAT':
  14403. if (section === 'fdAT') {
  14404. this.pos += 4;
  14405. chunkSize -= 4;
  14406. }
  14407. data = (frame != null ? frame.data : void 0) || this.imgData;
  14408. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  14409. data.push(this.data[this.pos++]);
  14410. }
  14411. break;
  14412. case 'tRNS':
  14413. this.transparency = {};
  14414. switch (this.colorType) {
  14415. case 3:
  14416. palLen = this.palette.length/3;
  14417. this.transparency.indexed = this.read(chunkSize);
  14418. if(this.transparency.indexed.length > palLen)
  14419. throw new Error('More transparent colors than palette size');
  14420. /*
  14421. * According to the PNG spec trns should be increased to the same size as palette if shorter
  14422. */
  14423. //palShort = 255 - this.transparency.indexed.length;
  14424. palShort = palLen - this.transparency.indexed.length;
  14425. if (palShort > 0) {
  14426. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  14427. this.transparency.indexed.push(255);
  14428. }
  14429. }
  14430. break;
  14431. case 0:
  14432. this.transparency.grayscale = this.read(chunkSize)[0];
  14433. break;
  14434. case 2:
  14435. this.transparency.rgb = this.read(chunkSize);
  14436. }
  14437. break;
  14438. case 'tEXt':
  14439. text = this.read(chunkSize);
  14440. index = text.indexOf(0);
  14441. key = String.fromCharCode.apply(String, text.slice(0, index));
  14442. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  14443. break;
  14444. case 'IEND':
  14445. if (frame) {
  14446. this.animation.frames.push(frame);
  14447. }
  14448. this.colors = (function() {
  14449. switch (this.colorType) {
  14450. case 0:
  14451. case 3:
  14452. case 4:
  14453. return 1;
  14454. case 2:
  14455. case 6:
  14456. return 3;
  14457. }
  14458. }).call(this);
  14459. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  14460. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  14461. this.pixelBitlength = this.bits * colors;
  14462. this.colorSpace = (function() {
  14463. switch (this.colors) {
  14464. case 1:
  14465. return 'DeviceGray';
  14466. case 3:
  14467. return 'DeviceRGB';
  14468. }
  14469. }).call(this);
  14470. this.imgData = new Uint8Array(this.imgData);
  14471. return;
  14472. default:
  14473. this.pos += chunkSize;
  14474. }
  14475. this.pos += 4;
  14476. if (this.pos > this.data.length) {
  14477. throw new Error("Incomplete or corrupt PNG file");
  14478. }
  14479. }
  14480. return;
  14481. }
  14482. PNG.prototype.read = function(bytes) {
  14483. var i, _i, _results;
  14484. _results = [];
  14485. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  14486. _results.push(this.data[this.pos++]);
  14487. }
  14488. return _results;
  14489. };
  14490. PNG.prototype.readUInt32 = function() {
  14491. var b1, b2, b3, b4;
  14492. b1 = this.data[this.pos++] << 24;
  14493. b2 = this.data[this.pos++] << 16;
  14494. b3 = this.data[this.pos++] << 8;
  14495. b4 = this.data[this.pos++];
  14496. return b1 | b2 | b3 | b4;
  14497. };
  14498. PNG.prototype.readUInt16 = function() {
  14499. var b1, b2;
  14500. b1 = this.data[this.pos++] << 8;
  14501. b2 = this.data[this.pos++];
  14502. return b1 | b2;
  14503. };
  14504. PNG.prototype.decodePixels = function(data) {
  14505. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  14506. if (data == null) {
  14507. data = this.imgData;
  14508. }
  14509. if (data.length === 0) {
  14510. return new Uint8Array(0);
  14511. }
  14512. data = new FlateStream(data);
  14513. data = data.getBytes();
  14514. pixelBytes = this.pixelBitlength / 8;
  14515. scanlineLength = pixelBytes * this.width;
  14516. pixels = new Uint8Array(scanlineLength * this.height);
  14517. length = data.length;
  14518. row = 0;
  14519. pos = 0;
  14520. c = 0;
  14521. while (pos < length) {
  14522. switch (data[pos++]) {
  14523. case 0:
  14524. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  14525. pixels[c++] = data[pos++];
  14526. }
  14527. break;
  14528. case 1:
  14529. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  14530. abyte = data[pos++];
  14531. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14532. pixels[c++] = (abyte + left) % 256;
  14533. }
  14534. break;
  14535. case 2:
  14536. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  14537. abyte = data[pos++];
  14538. col = (i - (i % pixelBytes)) / pixelBytes;
  14539. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14540. pixels[c++] = (upper + abyte) % 256;
  14541. }
  14542. break;
  14543. case 3:
  14544. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  14545. abyte = data[pos++];
  14546. col = (i - (i % pixelBytes)) / pixelBytes;
  14547. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14548. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14549. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  14550. }
  14551. break;
  14552. case 4:
  14553. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  14554. abyte = data[pos++];
  14555. col = (i - (i % pixelBytes)) / pixelBytes;
  14556. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14557. if (row === 0) {
  14558. upper = upperLeft = 0;
  14559. } else {
  14560. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14561. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
  14562. }
  14563. p = left + upper - upperLeft;
  14564. pa = Math.abs(p - left);
  14565. pb = Math.abs(p - upper);
  14566. pc = Math.abs(p - upperLeft);
  14567. if (pa <= pb && pa <= pc) {
  14568. paeth = left;
  14569. } else if (pb <= pc) {
  14570. paeth = upper;
  14571. } else {
  14572. paeth = upperLeft;
  14573. }
  14574. pixels[c++] = (abyte + paeth) % 256;
  14575. }
  14576. break;
  14577. default:
  14578. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  14579. }
  14580. row++;
  14581. }
  14582. return pixels;
  14583. };
  14584. PNG.prototype.decodePalette = function() {
  14585. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  14586. palette = this.palette;
  14587. transparency = this.transparency.indexed || [];
  14588. ret = new Uint8Array((transparency.length || 0) + palette.length);
  14589. pos = 0;
  14590. length = palette.length;
  14591. c = 0;
  14592. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  14593. ret[pos++] = palette[i];
  14594. ret[pos++] = palette[i + 1];
  14595. ret[pos++] = palette[i + 2];
  14596. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  14597. }
  14598. return ret;
  14599. };
  14600. PNG.prototype.copyToImageData = function(imageData, pixels) {
  14601. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  14602. colors = this.colors;
  14603. palette = null;
  14604. alpha = this.hasAlphaChannel;
  14605. if (this.palette.length) {
  14606. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  14607. colors = 4;
  14608. alpha = true;
  14609. }
  14610. data = imageData.data || imageData;
  14611. length = data.length;
  14612. input = palette || pixels;
  14613. i = j = 0;
  14614. if (colors === 1) {
  14615. while (i < length) {
  14616. k = palette ? pixels[i / 4] * 4 : j;
  14617. v = input[k++];
  14618. data[i++] = v;
  14619. data[i++] = v;
  14620. data[i++] = v;
  14621. data[i++] = alpha ? input[k++] : 255;
  14622. j = k;
  14623. }
  14624. } else {
  14625. while (i < length) {
  14626. k = palette ? pixels[i / 4] * 4 : j;
  14627. data[i++] = input[k++];
  14628. data[i++] = input[k++];
  14629. data[i++] = input[k++];
  14630. data[i++] = alpha ? input[k++] : 255;
  14631. j = k;
  14632. }
  14633. }
  14634. };
  14635. PNG.prototype.decode = function() {
  14636. var ret;
  14637. ret = new Uint8Array(this.width * this.height * 4);
  14638. this.copyToImageData(ret, this.decodePixels());
  14639. return ret;
  14640. };
  14641. try {
  14642. scratchCanvas = global.document.createElement('canvas');
  14643. scratchCtx = scratchCanvas.getContext('2d');
  14644. } catch(e) {
  14645. return -1;
  14646. }
  14647. makeImage = function(imageData) {
  14648. var img;
  14649. scratchCtx.width = imageData.width;
  14650. scratchCtx.height = imageData.height;
  14651. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  14652. scratchCtx.putImageData(imageData, 0, 0);
  14653. img = new Image;
  14654. img.src = scratchCanvas.toDataURL();
  14655. return img;
  14656. };
  14657. PNG.prototype.decodeFrames = function(ctx) {
  14658. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  14659. if (!this.animation) {
  14660. return;
  14661. }
  14662. _ref = this.animation.frames;
  14663. _results = [];
  14664. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  14665. frame = _ref[i];
  14666. imageData = ctx.createImageData(frame.width, frame.height);
  14667. pixels = this.decodePixels(new Uint8Array(frame.data));
  14668. this.copyToImageData(imageData, pixels);
  14669. frame.imageData = imageData;
  14670. _results.push(frame.image = makeImage(imageData));
  14671. }
  14672. return _results;
  14673. };
  14674. PNG.prototype.renderFrame = function(ctx, number) {
  14675. var frame, frames, prev;
  14676. frames = this.animation.frames;
  14677. frame = frames[number];
  14678. prev = frames[number - 1];
  14679. if (number === 0) {
  14680. ctx.clearRect(0, 0, this.width, this.height);
  14681. }
  14682. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  14683. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  14684. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  14685. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  14686. }
  14687. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  14688. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  14689. }
  14690. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  14691. };
  14692. PNG.prototype.animate = function(ctx) {
  14693. var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
  14694. _this = this;
  14695. frameNumber = 0;
  14696. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  14697. return (doFrame = function() {
  14698. var f, frame;
  14699. f = frameNumber++ % numFrames;
  14700. frame = frames[f];
  14701. _this.renderFrame(ctx, f);
  14702. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  14703. return _this.animation._timeout = setTimeout(doFrame, frame.delay);
  14704. }
  14705. })();
  14706. };
  14707. PNG.prototype.stopAnimation = function() {
  14708. var _ref;
  14709. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  14710. };
  14711. PNG.prototype.render = function(canvas) {
  14712. var ctx, data;
  14713. if (canvas._png) {
  14714. canvas._png.stopAnimation();
  14715. }
  14716. canvas._png = this;
  14717. canvas.width = this.width;
  14718. canvas.height = this.height;
  14719. ctx = canvas.getContext("2d");
  14720. if (this.animation) {
  14721. this.decodeFrames(ctx);
  14722. return this.animate(ctx);
  14723. } else {
  14724. data = ctx.createImageData(this.width, this.height);
  14725. this.copyToImageData(data, this.decodePixels());
  14726. return ctx.putImageData(data, 0, 0);
  14727. }
  14728. };
  14729. return PNG;
  14730. })();
  14731. global.PNG = PNG;
  14732. })(typeof window !== "undefined" && window || undefined);
  14733. /*
  14734. * Extracted from pdf.js
  14735. * https://github.com/andreasgal/pdf.js
  14736. *
  14737. * Copyright (c) 2011 Mozilla Foundation
  14738. *
  14739. * Contributors: Andreas Gal <gal@mozilla.com>
  14740. * Chris G Jones <cjones@mozilla.com>
  14741. * Shaon Barman <shaon.barman@gmail.com>
  14742. * Vivien Nicolas <21@vingtetun.org>
  14743. * Justin D'Arcangelo <justindarc@gmail.com>
  14744. * Yury Delendik
  14745. *
  14746. *
  14747. */
  14748. var DecodeStream = (function() {
  14749. function constructor() {
  14750. this.pos = 0;
  14751. this.bufferLength = 0;
  14752. this.eof = false;
  14753. this.buffer = null;
  14754. }
  14755. constructor.prototype = {
  14756. ensureBuffer: function decodestream_ensureBuffer(requested) {
  14757. var buffer = this.buffer;
  14758. var current = buffer ? buffer.byteLength : 0;
  14759. if (requested < current)
  14760. return buffer;
  14761. var size = 512;
  14762. while (size < requested)
  14763. size <<= 1;
  14764. var buffer2 = new Uint8Array(size);
  14765. for (var i = 0; i < current; ++i)
  14766. buffer2[i] = buffer[i];
  14767. return this.buffer = buffer2;
  14768. },
  14769. getByte: function decodestream_getByte() {
  14770. var pos = this.pos;
  14771. while (this.bufferLength <= pos) {
  14772. if (this.eof)
  14773. return null;
  14774. this.readBlock();
  14775. }
  14776. return this.buffer[this.pos++];
  14777. },
  14778. getBytes: function decodestream_getBytes(length) {
  14779. var pos = this.pos;
  14780. if (length) {
  14781. this.ensureBuffer(pos + length);
  14782. var end = pos + length;
  14783. while (!this.eof && this.bufferLength < end)
  14784. this.readBlock();
  14785. var bufEnd = this.bufferLength;
  14786. if (end > bufEnd)
  14787. end = bufEnd;
  14788. } else {
  14789. while (!this.eof)
  14790. this.readBlock();
  14791. var end = this.bufferLength;
  14792. }
  14793. this.pos = end;
  14794. return this.buffer.subarray(pos, end);
  14795. },
  14796. lookChar: function decodestream_lookChar() {
  14797. var pos = this.pos;
  14798. while (this.bufferLength <= pos) {
  14799. if (this.eof)
  14800. return null;
  14801. this.readBlock();
  14802. }
  14803. return String.fromCharCode(this.buffer[this.pos]);
  14804. },
  14805. getChar: function decodestream_getChar() {
  14806. var pos = this.pos;
  14807. while (this.bufferLength <= pos) {
  14808. if (this.eof)
  14809. return null;
  14810. this.readBlock();
  14811. }
  14812. return String.fromCharCode(this.buffer[this.pos++]);
  14813. },
  14814. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  14815. var end = start + length;
  14816. while (this.bufferLength <= end && !this.eof)
  14817. this.readBlock();
  14818. return new Stream(this.buffer, start, length, dict);
  14819. },
  14820. skip: function decodestream_skip(n) {
  14821. if (!n)
  14822. n = 1;
  14823. this.pos += n;
  14824. },
  14825. reset: function decodestream_reset() {
  14826. this.pos = 0;
  14827. }
  14828. };
  14829. return constructor;
  14830. })();
  14831. var FlateStream = (function() {
  14832. if (typeof Uint32Array === 'undefined') {
  14833. return undefined;
  14834. }
  14835. var codeLenCodeMap = new Uint32Array([
  14836. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  14837. ]);
  14838. var lengthDecode = new Uint32Array([
  14839. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  14840. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  14841. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  14842. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  14843. ]);
  14844. var distDecode = new Uint32Array([
  14845. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  14846. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  14847. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  14848. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  14849. ]);
  14850. var fixedLitCodeTab = [new Uint32Array([
  14851. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  14852. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  14853. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  14854. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  14855. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  14856. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  14857. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  14858. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  14859. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  14860. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  14861. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  14862. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  14863. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  14864. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  14865. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  14866. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  14867. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  14868. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  14869. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  14870. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  14871. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  14872. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  14873. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  14874. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  14875. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  14876. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  14877. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  14878. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  14879. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  14880. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  14881. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  14882. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  14883. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  14884. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  14885. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  14886. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  14887. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  14888. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  14889. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  14890. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  14891. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  14892. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  14893. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  14894. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  14895. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  14896. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  14897. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  14898. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  14899. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  14900. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  14901. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  14902. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  14903. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  14904. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  14905. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  14906. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  14907. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  14908. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  14909. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  14910. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  14911. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  14912. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  14913. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  14914. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  14915. ]), 9];
  14916. var fixedDistCodeTab = [new Uint32Array([
  14917. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  14918. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  14919. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  14920. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  14921. ]), 5];
  14922. function error(e) {
  14923. throw new Error(e)
  14924. }
  14925. function constructor(bytes) {
  14926. //var bytes = stream.getBytes();
  14927. var bytesPos = 0;
  14928. var cmf = bytes[bytesPos++];
  14929. var flg = bytes[bytesPos++];
  14930. if (cmf == -1 || flg == -1)
  14931. error('Invalid header in flate stream');
  14932. if ((cmf & 0x0f) != 0x08)
  14933. error('Unknown compression method in flate stream');
  14934. if ((((cmf << 8) + flg) % 31) != 0)
  14935. error('Bad FCHECK in flate stream');
  14936. if (flg & 0x20)
  14937. error('FDICT bit set in flate stream');
  14938. this.bytes = bytes;
  14939. this.bytesPos = bytesPos;
  14940. this.codeSize = 0;
  14941. this.codeBuf = 0;
  14942. DecodeStream.call(this);
  14943. }
  14944. constructor.prototype = Object.create(DecodeStream.prototype);
  14945. constructor.prototype.getBits = function(bits) {
  14946. var codeSize = this.codeSize;
  14947. var codeBuf = this.codeBuf;
  14948. var bytes = this.bytes;
  14949. var bytesPos = this.bytesPos;
  14950. var b;
  14951. while (codeSize < bits) {
  14952. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14953. error('Bad encoding in flate stream');
  14954. codeBuf |= b << codeSize;
  14955. codeSize += 8;
  14956. }
  14957. b = codeBuf & ((1 << bits) - 1);
  14958. this.codeBuf = codeBuf >> bits;
  14959. this.codeSize = codeSize -= bits;
  14960. this.bytesPos = bytesPos;
  14961. return b;
  14962. };
  14963. constructor.prototype.getCode = function(table) {
  14964. var codes = table[0];
  14965. var maxLen = table[1];
  14966. var codeSize = this.codeSize;
  14967. var codeBuf = this.codeBuf;
  14968. var bytes = this.bytes;
  14969. var bytesPos = this.bytesPos;
  14970. while (codeSize < maxLen) {
  14971. var b;
  14972. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14973. error('Bad encoding in flate stream');
  14974. codeBuf |= (b << codeSize);
  14975. codeSize += 8;
  14976. }
  14977. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  14978. var codeLen = code >> 16;
  14979. var codeVal = code & 0xffff;
  14980. if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
  14981. error('Bad encoding in flate stream');
  14982. this.codeBuf = (codeBuf >> codeLen);
  14983. this.codeSize = (codeSize - codeLen);
  14984. this.bytesPos = bytesPos;
  14985. return codeVal;
  14986. };
  14987. constructor.prototype.generateHuffmanTable = function(lengths) {
  14988. var n = lengths.length;
  14989. // find max code length
  14990. var maxLen = 0;
  14991. for (var i = 0; i < n; ++i) {
  14992. if (lengths[i] > maxLen)
  14993. maxLen = lengths[i];
  14994. }
  14995. // build the table
  14996. var size = 1 << maxLen;
  14997. var codes = new Uint32Array(size);
  14998. for (var len = 1, code = 0, skip = 2;
  14999. len <= maxLen;
  15000. ++len, code <<= 1, skip <<= 1) {
  15001. for (var val = 0; val < n; ++val) {
  15002. if (lengths[val] == len) {
  15003. // bit-reverse the code
  15004. var code2 = 0;
  15005. var t = code;
  15006. for (var i = 0; i < len; ++i) {
  15007. code2 = (code2 << 1) | (t & 1);
  15008. t >>= 1;
  15009. }
  15010. // fill the table entries
  15011. for (var i = code2; i < size; i += skip)
  15012. codes[i] = (len << 16) | val;
  15013. ++code;
  15014. }
  15015. }
  15016. }
  15017. return [codes, maxLen];
  15018. };
  15019. constructor.prototype.readBlock = function() {
  15020. function repeat(stream, array, len, offset, what) {
  15021. var repeat = stream.getBits(len) + offset;
  15022. while (repeat-- > 0)
  15023. array[i++] = what;
  15024. }
  15025. // read block header
  15026. var hdr = this.getBits(3);
  15027. if (hdr & 1)
  15028. this.eof = true;
  15029. hdr >>= 1;
  15030. if (hdr == 0) { // uncompressed block
  15031. var bytes = this.bytes;
  15032. var bytesPos = this.bytesPos;
  15033. var b;
  15034. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15035. error('Bad block header in flate stream');
  15036. var blockLen = b;
  15037. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15038. error('Bad block header in flate stream');
  15039. blockLen |= (b << 8);
  15040. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15041. error('Bad block header in flate stream');
  15042. var check = b;
  15043. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  15044. error('Bad block header in flate stream');
  15045. check |= (b << 8);
  15046. if (check != (~blockLen & 0xffff))
  15047. error('Bad uncompressed block length in flate stream');
  15048. this.codeBuf = 0;
  15049. this.codeSize = 0;
  15050. var bufferLength = this.bufferLength;
  15051. var buffer = this.ensureBuffer(bufferLength + blockLen);
  15052. var end = bufferLength + blockLen;
  15053. this.bufferLength = end;
  15054. for (var n = bufferLength; n < end; ++n) {
  15055. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  15056. this.eof = true;
  15057. break;
  15058. }
  15059. buffer[n] = b;
  15060. }
  15061. this.bytesPos = bytesPos;
  15062. return;
  15063. }
  15064. var litCodeTable;
  15065. var distCodeTable;
  15066. if (hdr == 1) { // compressed block, fixed codes
  15067. litCodeTable = fixedLitCodeTab;
  15068. distCodeTable = fixedDistCodeTab;
  15069. } else if (hdr == 2) { // compressed block, dynamic codes
  15070. var numLitCodes = this.getBits(5) + 257;
  15071. var numDistCodes = this.getBits(5) + 1;
  15072. var numCodeLenCodes = this.getBits(4) + 4;
  15073. // build the code lengths code table
  15074. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  15075. var i = 0;
  15076. while (i < numCodeLenCodes)
  15077. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  15078. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  15079. // build the literal and distance code tables
  15080. var len = 0;
  15081. var i = 0;
  15082. var codes = numLitCodes + numDistCodes;
  15083. var codeLengths = new Array(codes);
  15084. while (i < codes) {
  15085. var code = this.getCode(codeLenCodeTab);
  15086. if (code == 16) {
  15087. repeat(this, codeLengths, 2, 3, len);
  15088. } else if (code == 17) {
  15089. repeat(this, codeLengths, 3, 3, len = 0);
  15090. } else if (code == 18) {
  15091. repeat(this, codeLengths, 7, 11, len = 0);
  15092. } else {
  15093. codeLengths[i++] = len = code;
  15094. }
  15095. }
  15096. litCodeTable =
  15097. this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  15098. distCodeTable =
  15099. this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  15100. } else {
  15101. error('Unknown block type in flate stream');
  15102. }
  15103. var buffer = this.buffer;
  15104. var limit = buffer ? buffer.length : 0;
  15105. var pos = this.bufferLength;
  15106. while (true) {
  15107. var code1 = this.getCode(litCodeTable);
  15108. if (code1 < 256) {
  15109. if (pos + 1 >= limit) {
  15110. buffer = this.ensureBuffer(pos + 1);
  15111. limit = buffer.length;
  15112. }
  15113. buffer[pos++] = code1;
  15114. continue;
  15115. }
  15116. if (code1 == 256) {
  15117. this.bufferLength = pos;
  15118. return;
  15119. }
  15120. code1 -= 257;
  15121. code1 = lengthDecode[code1];
  15122. var code2 = code1 >> 16;
  15123. if (code2 > 0)
  15124. code2 = this.getBits(code2);
  15125. var len = (code1 & 0xffff) + code2;
  15126. code1 = this.getCode(distCodeTable);
  15127. code1 = distDecode[code1];
  15128. code2 = code1 >> 16;
  15129. if (code2 > 0)
  15130. code2 = this.getBits(code2);
  15131. var dist = (code1 & 0xffff) + code2;
  15132. if (pos + len >= limit) {
  15133. buffer = this.ensureBuffer(pos + len);
  15134. limit = buffer.length;
  15135. }
  15136. for (var k = 0; k < len; ++k, ++pos)
  15137. buffer[pos] = buffer[pos - dist];
  15138. }
  15139. };
  15140. return constructor;
  15141. })();
  15142. /**
  15143. * JavaScript Polyfill functions for jsPDF
  15144. * Collected from public resources by
  15145. * https://github.com/diegocr
  15146. */
  15147. (function (global) {
  15148. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15149. if (typeof global.btoa === 'undefined') {
  15150. global.btoa = function(data) {
  15151. // discuss at: http://phpjs.org/functions/base64_encode/
  15152. // original by: Tyler Akins (http://rumkin.com)
  15153. // improved by: Bayron Guevara
  15154. // improved by: Thunder.m
  15155. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15156. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15157. // improved by: Rafal Kukawski (http://kukawski.pl)
  15158. // bugfixed by: Pellentesque Malesuada
  15159. // example 1: base64_encode('Kevin van Zonneveld');
  15160. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  15161. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
  15162. if (!data) {
  15163. return data;
  15164. }
  15165. do { // pack three octets into four hexets
  15166. o1 = data.charCodeAt(i++);
  15167. o2 = data.charCodeAt(i++);
  15168. o3 = data.charCodeAt(i++);
  15169. bits = o1 << 16 | o2 << 8 | o3;
  15170. h1 = bits >> 18 & 0x3f;
  15171. h2 = bits >> 12 & 0x3f;
  15172. h3 = bits >> 6 & 0x3f;
  15173. h4 = bits & 0x3f;
  15174. // use hexets to index into b64, and append result to encoded string
  15175. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  15176. } while (i < data.length);
  15177. enc = tmp_arr.join('');
  15178. var r = data.length % 3;
  15179. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  15180. };
  15181. }
  15182. if (typeof global.atob === 'undefined') {
  15183. global.atob = function(data) {
  15184. // discuss at: http://phpjs.org/functions/base64_decode/
  15185. // original by: Tyler Akins (http://rumkin.com)
  15186. // improved by: Thunder.m
  15187. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15188. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15189. // input by: Aman Gupta
  15190. // input by: Brett Zamir (http://brett-zamir.me)
  15191. // bugfixed by: Onno Marsman
  15192. // bugfixed by: Pellentesque Malesuada
  15193. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15194. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  15195. // returns 1: 'Kevin van Zonneveld'
  15196. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
  15197. if (!data) {
  15198. return data;
  15199. }
  15200. data += '';
  15201. do { // unpack four hexets into three octets using index points in b64
  15202. h1 = b64.indexOf(data.charAt(i++));
  15203. h2 = b64.indexOf(data.charAt(i++));
  15204. h3 = b64.indexOf(data.charAt(i++));
  15205. h4 = b64.indexOf(data.charAt(i++));
  15206. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  15207. o1 = bits >> 16 & 0xff;
  15208. o2 = bits >> 8 & 0xff;
  15209. o3 = bits & 0xff;
  15210. if (h3 == 64) {
  15211. tmp_arr[ac++] = String.fromCharCode(o1);
  15212. } else if (h4 == 64) {
  15213. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  15214. } else {
  15215. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  15216. }
  15217. } while (i < data.length);
  15218. dec = tmp_arr.join('');
  15219. return dec;
  15220. };
  15221. }
  15222. if (!Array.prototype.map) {
  15223. Array.prototype.map = function(fun /*, thisArg */) {
  15224. if (this === void 0 || this === null || typeof fun !== "function")
  15225. throw new TypeError();
  15226. var t = Object(this), len = t.length >>> 0, res = new Array(len);
  15227. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  15228. for (var i = 0; i < len; i++) {
  15229. // NOTE: Absolute correctness would demand Object.defineProperty
  15230. // be used. But this method is fairly new, and failure is
  15231. // possible only if Object.prototype or Array.prototype
  15232. // has a property |i| (very unlikely), so use a less-correct
  15233. // but more portable alternative.
  15234. if (i in t)
  15235. res[i] = fun.call(thisArg, t[i], i, t);
  15236. }
  15237. return res;
  15238. };
  15239. }
  15240. if(!Array.isArray) {
  15241. Array.isArray = function(arg) {
  15242. return Object.prototype.toString.call(arg) === '[object Array]';
  15243. };
  15244. }
  15245. if (!Array.prototype.forEach) {
  15246. Array.prototype.forEach = function(fun, thisArg) {
  15247. "use strict";
  15248. if (this === void 0 || this === null || typeof fun !== "function")
  15249. throw new TypeError();
  15250. var t = Object(this), len = t.length >>> 0;
  15251. for (var i = 0; i < len; i++) {
  15252. if (i in t)
  15253. fun.call(thisArg, t[i], i, t);
  15254. }
  15255. };
  15256. }
  15257. if (!Object.keys) {
  15258. Object.keys = (function () {
  15259. 'use strict';
  15260. var hasOwnProperty = Object.prototype.hasOwnProperty,
  15261. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  15262. dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
  15263. 'isPrototypeOf','propertyIsEnumerable','constructor'],
  15264. dontEnumsLength = dontEnums.length;
  15265. return function (obj) {
  15266. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  15267. throw new TypeError();
  15268. }
  15269. var result = [], prop, i;
  15270. for (prop in obj) {
  15271. if (hasOwnProperty.call(obj, prop)) {
  15272. result.push(prop);
  15273. }
  15274. }
  15275. if (hasDontEnumBug) {
  15276. for (i = 0; i < dontEnumsLength; i++) {
  15277. if (hasOwnProperty.call(obj, dontEnums[i])) {
  15278. result.push(dontEnums[i]);
  15279. }
  15280. }
  15281. }
  15282. return result;
  15283. };
  15284. }());
  15285. }
  15286. if (!String.prototype.trim) {
  15287. String.prototype.trim = function () {
  15288. return this.replace(/^\s+|\s+$/g, '');
  15289. };
  15290. }
  15291. if (!String.prototype.trimLeft) {
  15292. String.prototype.trimLeft = function() {
  15293. return this.replace(/^\s+/g, "");
  15294. };
  15295. }
  15296. if (!String.prototype.trimRight) {
  15297. String.prototype.trimRight = function() {
  15298. return this.replace(/\s+$/g, "");
  15299. };
  15300. }
  15301. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  15302. return jsPDF;
  15303. })));