jspdf.debug.js 619 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.jspdf = factory());
  5. }(this, function () { 'use strict';
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  7. return typeof obj;
  8. } : function (obj) {
  9. return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
  10. };
  11. /** @preserve
  12. * jsPDF - PDF Document creation from JavaScript
  13. * Version 1.3.2 Built on 2016-09-30T20:33:17.116Z
  14. * CommitID 7d854cc77d
  15. *
  16. * Copyright (c) 2010-2014 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  17. * 2010 Aaron Spike, https://github.com/acspike
  18. * 2012 Willow Systems Corporation, willow-systems.com
  19. * 2012 Pablo Hess, https://github.com/pablohess
  20. * 2012 Florian Jenett, https://github.com/fjenett
  21. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  22. * 2013 Youssef Beddad, https://github.com/lifof
  23. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  24. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  25. * 2013 Jeremy Morel, https://github.com/jmorel
  26. * 2013 Christoph Hartmann, https://github.com/chris-rock
  27. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  28. * 2014 James Makes, https://github.com/dollaruw
  29. * 2014 Diego Casorran, https://github.com/diegocr
  30. * 2014 Steven Spungin, https://github.com/Flamenco
  31. * 2014 Kenneth Glassey, https://github.com/Gavvers
  32. *
  33. * Licensed under the MIT License
  34. *
  35. * Contributor(s):
  36. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  37. * kim3er, mfo, alnorth, Flamenco
  38. */
  39. /**
  40. * Creates new jsPDF document object instance.
  41. *
  42. * @class
  43. * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
  44. * @param unit Measurement unit to be used when coordinates are specified.
  45. * One of "pt" (points), "mm" (Default), "cm", "in"
  46. * @param format One of 'pageFormats' as shown below, default: a4
  47. * @returns {jsPDF}
  48. * @name jsPDF
  49. */
  50. var jsPDF = function (global) {
  51. 'use strict';
  52. var pdfVersion = '1.3',
  53. pageFormats = { // Size in pt of various paper formats
  54. 'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
  55. 'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
  56. 'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
  57. 'a6': [297.64, 419.53], 'a7': [209.76, 297.64],
  58. 'a8': [147.40, 209.76], 'a9': [104.88, 147.40],
  59. 'a10': [73.70, 104.88], 'b0': [2834.65, 4008.19],
  60. 'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
  61. 'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63],
  62. 'b5': [498.90, 708.66], 'b6': [354.33, 498.90],
  63. 'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
  64. 'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
  65. 'c0': [2599.37, 3676.54], 'c1': [1836.85, 2599.37],
  66. 'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
  67. 'c4': [649.13, 918.43], 'c5': [459.21, 649.13],
  68. 'c6': [323.15, 459.21], 'c7': [229.61, 323.15],
  69. 'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
  70. 'c10': [79.37, 113.39], 'dl': [311.81, 623.62],
  71. 'letter': [612, 792],
  72. 'government-letter': [576, 756],
  73. 'legal': [612, 1008],
  74. 'junior-legal': [576, 360],
  75. 'ledger': [1224, 792],
  76. 'tabloid': [792, 1224],
  77. 'credit-card': [153, 243]
  78. };
  79. /**
  80. * jsPDF's Internal PubSub Implementation.
  81. * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
  82. * Backward compatible rewritten on 2014 by
  83. * Diego Casorran, https://github.com/diegocr
  84. *
  85. * @class
  86. * @name PubSub
  87. */
  88. function PubSub(context) {
  89. var topics = {};
  90. this.subscribe = function (topic, callback, once) {
  91. if (typeof callback !== 'function') {
  92. return false;
  93. }
  94. if (!topics.hasOwnProperty(topic)) {
  95. topics[topic] = {};
  96. }
  97. var id = Math.random().toString(35);
  98. topics[topic][id] = [callback, !!once];
  99. return id;
  100. };
  101. this.unsubscribe = function (token) {
  102. for (var topic in topics) {
  103. if (topics[topic][token]) {
  104. delete topics[topic][token];
  105. return true;
  106. }
  107. }
  108. return false;
  109. };
  110. this.publish = function (topic) {
  111. if (topics.hasOwnProperty(topic)) {
  112. var args = Array.prototype.slice.call(arguments, 1),
  113. idr = [];
  114. for (var id in topics[topic]) {
  115. var sub = topics[topic][id];
  116. try {
  117. sub[0].apply(context, args);
  118. } catch (ex) {
  119. if (global.console) {
  120. console.error('jsPDF PubSub Error', ex.message, ex);
  121. }
  122. }
  123. if (sub[1]) idr.push(id);
  124. }
  125. if (idr.length) idr.forEach(this.unsubscribe);
  126. }
  127. };
  128. }
  129. /**
  130. * @constructor
  131. * @private
  132. */
  133. function jsPDF(orientation, unit, format, compressPdf) {
  134. var options = {};
  135. if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
  136. options = orientation;
  137. orientation = options.orientation;
  138. unit = options.unit || unit;
  139. format = options.format || format;
  140. compressPdf = options.compress || options.compressPdf || compressPdf;
  141. }
  142. // Default options
  143. unit = unit || 'mm';
  144. format = format || 'a4';
  145. orientation = ('' + (orientation || 'P')).toLowerCase();
  146. var format_as_string = ('' + format).toLowerCase(),
  147. compress = !!compressPdf && typeof Uint8Array === 'function',
  148. textColor = options.textColor || '0 g',
  149. drawColor = options.drawColor || '0 G',
  150. activeFontSize = options.fontSize || 16,
  151. lineHeightProportion = options.lineHeight || 1.15,
  152. lineWidth = options.lineWidth || 0.200025,
  153. // 2mm
  154. objectNumber = 2,
  155. // 'n' Current object number
  156. outToPages = !1,
  157. // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  158. offsets = [],
  159. // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  160. fonts = {},
  161. // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  162. fontmap = {},
  163. // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  164. activeFontKey,
  165. // will be string representing the KEY of the font as combination of fontName + fontStyle
  166. k,
  167. // Scale factor
  168. tmp,
  169. page = 0,
  170. currentPage,
  171. pages = [],
  172. pagesContext = [],
  173. // same index as pages and pagedim
  174. pagedim = [],
  175. content = [],
  176. additionalObjects = [],
  177. lineCapID = 0,
  178. lineJoinID = 0,
  179. content_length = 0,
  180. pageWidth,
  181. pageHeight,
  182. pageMode,
  183. zoomMode,
  184. layoutMode,
  185. documentProperties = {
  186. 'title': '',
  187. 'subject': '',
  188. 'author': '',
  189. 'keywords': '',
  190. 'creator': ''
  191. },
  192. API = {},
  193. events = new PubSub(API),
  194. /////////////////////
  195. // Private functions
  196. /////////////////////
  197. f2 = function f2(number) {
  198. return number.toFixed(2); // Ie, %.2f
  199. },
  200. f3 = function f3(number) {
  201. return number.toFixed(3); // Ie, %.3f
  202. },
  203. padd2 = function padd2(number) {
  204. return ('0' + parseInt(number)).slice(-2);
  205. },
  206. out = function out(string) {
  207. if (outToPages) {
  208. /* set by beginPage */
  209. pages[currentPage].push(string);
  210. } else {
  211. // +1 for '\n' that will be used to join 'content'
  212. content_length += string.length + 1;
  213. content.push(string);
  214. }
  215. },
  216. newObject = function newObject() {
  217. // Begin a new object
  218. objectNumber++;
  219. offsets[objectNumber] = content_length;
  220. out(objectNumber + ' 0 obj');
  221. return objectNumber;
  222. },
  223. // Does not output the object until after the pages have been output.
  224. // Returns an object containing the objectId and content.
  225. // All pages have been added so the object ID can be estimated to start right after.
  226. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  227. newAdditionalObject = function newAdditionalObject() {
  228. var objId = pages.length * 2 + 1;
  229. objId += additionalObjects.length;
  230. var obj = { objId: objId, content: '' };
  231. additionalObjects.push(obj);
  232. return obj;
  233. },
  234. // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  235. newObjectDeferred = function newObjectDeferred() {
  236. objectNumber++;
  237. offsets[objectNumber] = function () {
  238. return content_length;
  239. };
  240. return objectNumber;
  241. },
  242. newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
  243. offsets[oid] = content_length;
  244. },
  245. putStream = function putStream(str) {
  246. out('stream');
  247. out(str);
  248. out('endstream');
  249. },
  250. putPages = function putPages() {
  251. var n,
  252. p,
  253. arr,
  254. i,
  255. deflater,
  256. adler32,
  257. adler32cs,
  258. wPt,
  259. hPt,
  260. pageObjectNumbers = [];
  261. adler32cs = global.adler32cs || jsPDF.adler32cs;
  262. if (compress && typeof adler32cs === 'undefined') {
  263. compress = false;
  264. }
  265. // outToPages = false as set in endDocument(). out() writes to content.
  266. for (n = 1; n <= page; n++) {
  267. pageObjectNumbers.push(newObject());
  268. wPt = (pageWidth = pagedim[n].width) * k;
  269. hPt = (pageHeight = pagedim[n].height) * k;
  270. out('<</Type /Page');
  271. out('/Parent 1 0 R');
  272. out('/Resources 2 0 R');
  273. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  274. // Added for annotation plugin
  275. events.publish('putPage', { pageNumber: n, page: pages[n] });
  276. out('/Contents ' + (objectNumber + 1) + ' 0 R');
  277. out('>>');
  278. out('endobj');
  279. // Page content
  280. p = pages[n].join('\n');
  281. newObject();
  282. if (compress) {
  283. arr = [];
  284. i = p.length;
  285. while (i--) {
  286. arr[i] = p.charCodeAt(i);
  287. }
  288. adler32 = adler32cs.from(p);
  289. deflater = new Deflater(6);
  290. deflater.append(new Uint8Array(arr));
  291. p = deflater.flush();
  292. arr = new Uint8Array(p.length + 6);
  293. arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
  294. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
  295. p = String.fromCharCode.apply(null, arr);
  296. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  297. } else {
  298. out('<</Length ' + p.length + '>>');
  299. }
  300. putStream(p);
  301. out('endobj');
  302. }
  303. offsets[1] = content_length;
  304. out('1 0 obj');
  305. out('<</Type /Pages');
  306. var kids = '/Kids [';
  307. for (i = 0; i < page; i++) {
  308. kids += pageObjectNumbers[i] + ' 0 R ';
  309. }
  310. out(kids + ']');
  311. out('/Count ' + page);
  312. out('>>');
  313. out('endobj');
  314. events.publish('postPutPages');
  315. },
  316. putFont = function putFont(font) {
  317. font.objectNumber = newObject();
  318. out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
  319. if (typeof font.encoding === 'string') {
  320. out('/Encoding/' + font.encoding);
  321. }
  322. out('/Subtype/Type1>>');
  323. out('endobj');
  324. },
  325. putFonts = function putFonts() {
  326. for (var fontKey in fonts) {
  327. if (fonts.hasOwnProperty(fontKey)) {
  328. putFont(fonts[fontKey]);
  329. }
  330. }
  331. },
  332. putXobjectDict = function putXobjectDict() {
  333. // Loop through images, or other data objects
  334. events.publish('putXobjectDict');
  335. },
  336. putResourceDictionary = function putResourceDictionary() {
  337. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  338. out('/Font <<');
  339. // Do this for each font, the '1' bit is the index of the font
  340. for (var fontKey in fonts) {
  341. if (fonts.hasOwnProperty(fontKey)) {
  342. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  343. }
  344. }
  345. out('>>');
  346. out('/XObject <<');
  347. putXobjectDict();
  348. out('>>');
  349. },
  350. putResources = function putResources() {
  351. putFonts();
  352. events.publish('putResources');
  353. // Resource dictionary
  354. offsets[2] = content_length;
  355. out('2 0 obj');
  356. out('<<');
  357. putResourceDictionary();
  358. out('>>');
  359. out('endobj');
  360. events.publish('postPutResources');
  361. },
  362. putAdditionalObjects = function putAdditionalObjects() {
  363. events.publish('putAdditionalObjects');
  364. for (var i = 0; i < additionalObjects.length; i++) {
  365. var obj = additionalObjects[i];
  366. offsets[obj.objId] = content_length;
  367. out(obj.objId + ' 0 obj');
  368. out(obj.content);
  369. ;
  370. out('endobj');
  371. }
  372. objectNumber += additionalObjects.length;
  373. events.publish('postPutAdditionalObjects');
  374. },
  375. addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  376. // this is mapping structure for quick font key lookup.
  377. // returns the KEY of the font (ex: "F1") for a given
  378. // pair of font name and type (ex: "Arial". "Italic")
  379. if (!fontmap.hasOwnProperty(fontName)) {
  380. fontmap[fontName] = {};
  381. }
  382. fontmap[fontName][fontStyle] = fontKey;
  383. },
  384. /**
  385. * FontObject describes a particular font as member of an instnace of jsPDF
  386. *
  387. * It's a collection of properties like 'id' (to be used in PDF stream),
  388. * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  389. *
  390. * @class
  391. * @public
  392. * @property id {String} PDF-document-instance-specific label assinged to the font.
  393. * @property PostScriptName {String} PDF specification full name for the font
  394. * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  395. * @name FontObject
  396. */
  397. addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
  398. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  399. // This is FontObject
  400. font = fonts[fontKey] = {
  401. 'id': fontKey,
  402. 'PostScriptName': PostScriptName,
  403. 'fontName': fontName,
  404. 'fontStyle': fontStyle,
  405. 'encoding': encoding,
  406. 'metadata': {}
  407. };
  408. addToFontDictionary(fontKey, fontName, fontStyle);
  409. events.publish('addFont', font);
  410. return fontKey;
  411. },
  412. addFonts = function addFonts() {
  413. var HELVETICA = "helvetica",
  414. TIMES = "times",
  415. COURIER = "courier",
  416. NORMAL = "normal",
  417. BOLD = "bold",
  418. ITALIC = "italic",
  419. BOLD_ITALIC = "bolditalic",
  420. encoding = 'StandardEncoding',
  421. ZAPF = "zapfdingbats",
  422. 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]];
  423. for (var i = 0, l = standardFonts.length; i < l; i++) {
  424. var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
  425. // adding aliases for standard fonts, this time matching the capitalization
  426. var parts = standardFonts[i][0].split('-');
  427. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  428. }
  429. events.publish('addFonts', { fonts: fonts, dictionary: fontmap });
  430. },
  431. SAFE = function __safeCall(fn) {
  432. fn.foo = function __safeCallWrapper() {
  433. try {
  434. return fn.apply(this, arguments);
  435. } catch (e) {
  436. var stack = e.stack || '';
  437. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  438. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  439. if (global.console) {
  440. global.console.error(m, e);
  441. if (global.alert) alert(m);
  442. } else {
  443. throw new Error(m);
  444. }
  445. }
  446. };
  447. fn.foo.bar = fn;
  448. return fn.foo;
  449. },
  450. to8bitStream = function to8bitStream(text, flags) {
  451. /**
  452. * PDF 1.3 spec:
  453. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  454. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  455. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  456. * to be a meaningful beginning of a word or phrase.) The remainder of the
  457. * string consists of Unicode character codes, according to the UTF-16 encoding
  458. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  459. * are represented as 2 bytes per character, with the high-order byte appearing first
  460. * in the string."
  461. *
  462. * In other words, if there are chars in a string with char code above 255, we
  463. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  464. *
  465. * HOWEVER!
  466. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  467. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  468. *
  469. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  470. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  471. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  472. * code page. There, however, all characters in the stream are treated as GIDs,
  473. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  474. * that is tied to a font).
  475. *
  476. * To signal this "special" PDFEscape / to8bitStream handling mode,
  477. * API.text() function sets (unless you overwrite it with manual values
  478. * given to API.text(.., flags) )
  479. * flags.autoencode = true
  480. * flags.noBOM = true
  481. *
  482. * ===================================================================================
  483. * `flags` properties relied upon:
  484. * .sourceEncoding = string with encoding label.
  485. * "Unicode" by default. = encoding of the incoming text.
  486. * pass some non-existing encoding name
  487. * (ex: 'Do not touch my strings! I know what I am doing.')
  488. * to make encoding code skip the encoding step.
  489. * .outputEncoding = Either valid PDF encoding name
  490. * (must be supported by jsPDF font metrics, otherwise no encoding)
  491. * or a JS object, where key = sourceCharCode, value = outputCharCode
  492. * missing keys will be treated as: sourceCharCode === outputCharCode
  493. * .noBOM
  494. * See comment higher above for explanation for why this is important
  495. * .autoencode
  496. * See comment higher above for explanation for why this is important
  497. */
  498. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  499. flags = flags || {};
  500. sourceEncoding = flags.sourceEncoding || 'Unicode';
  501. outputEncoding = flags.outputEncoding;
  502. // This 'encoding' section relies on font metrics format
  503. // attached to font objects by, among others,
  504. // "Willow Systems' standard_font_metrics plugin"
  505. // see jspdf.plugin.standard_font_metrics.js for format
  506. // of the font.metadata.encoding Object.
  507. // It should be something like
  508. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  509. // .widths = {0:width, code:width, ..., 'fof':divisor}
  510. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  511. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  512. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  513. // each font has default encoding. Some have it clearly defined.
  514. if (!outputEncoding && fonts[activeFontKey].encoding) {
  515. outputEncoding = fonts[activeFontKey].encoding;
  516. }
  517. // Hmmm, the above did not work? Let's try again, in different place.
  518. if (!outputEncoding && encodingBlock.codePages) {
  519. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  520. }
  521. if (typeof outputEncoding === 'string') {
  522. outputEncoding = encodingBlock[outputEncoding];
  523. }
  524. // we want output encoding to be a JS Object, where
  525. // key = sourceEncoding's character code and
  526. // value = outputEncoding's character code.
  527. if (outputEncoding) {
  528. isUnicode = false;
  529. newtext = [];
  530. for (i = 0, l = text.length; i < l; i++) {
  531. ch = outputEncoding[text.charCodeAt(i)];
  532. if (ch) {
  533. newtext.push(String.fromCharCode(ch));
  534. } else {
  535. newtext.push(text[i]);
  536. }
  537. // since we are looping over chars anyway, might as well
  538. // check for residual unicodeness
  539. if (newtext[i].charCodeAt(0) >> 8) {
  540. /* more than 255 */
  541. isUnicode = true;
  542. }
  543. }
  544. text = newtext.join('');
  545. }
  546. }
  547. i = text.length;
  548. // isUnicode may be set to false above. Hence the triple-equal to undefined
  549. while (isUnicode === undefined && i !== 0) {
  550. if (text.charCodeAt(i - 1) >> 8) {
  551. /* more than 255 */
  552. isUnicode = true;
  553. }
  554. i--;
  555. }
  556. if (!isUnicode) {
  557. return text;
  558. }
  559. newtext = flags.noBOM ? [] : [254, 255];
  560. for (i = 0, l = text.length; i < l; i++) {
  561. ch = text.charCodeAt(i);
  562. bch = ch >> 8; // divide by 256
  563. if (bch >> 8) {
  564. /* something left after dividing by 256 second time */
  565. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  566. }
  567. newtext.push(bch);
  568. newtext.push(ch - (bch << 8));
  569. }
  570. return String.fromCharCode.apply(undefined, newtext);
  571. },
  572. pdfEscape = function pdfEscape(text, flags) {
  573. /**
  574. * Replace '/', '(', and ')' with pdf-safe versions
  575. *
  576. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  577. * we also need to reference a unicode font and embed it - royal pain in the rear.
  578. *
  579. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  580. * which JavaScript Strings are happy to provide. So, while we still cannot display
  581. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  582. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  583. * is still parseable.
  584. * This will allow immediate support for unicode in document properties strings.
  585. */
  586. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  587. },
  588. putInfo = function putInfo() {
  589. out('/Producer (jsPDF ' + jsPDF.version + ')');
  590. for (var key in documentProperties) {
  591. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  592. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  593. }
  594. }
  595. var created = new Date(),
  596. tzoffset = created.getTimezoneOffset(),
  597. tzsign = tzoffset < 0 ? '+' : '-',
  598. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  599. tzmin = Math.abs(tzoffset % 60),
  600. tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  601. out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
  602. },
  603. putCatalog = function putCatalog() {
  604. out('/Type /Catalog');
  605. out('/Pages 1 0 R');
  606. // PDF13ref Section 7.2.1
  607. if (!zoomMode) zoomMode = 'fullwidth';
  608. switch (zoomMode) {
  609. case 'fullwidth':
  610. out('/OpenAction [3 0 R /FitH null]');
  611. break;
  612. case 'fullheight':
  613. out('/OpenAction [3 0 R /FitV null]');
  614. break;
  615. case 'fullpage':
  616. out('/OpenAction [3 0 R /Fit]');
  617. break;
  618. case 'original':
  619. out('/OpenAction [3 0 R /XYZ null null 1]');
  620. break;
  621. default:
  622. var pcn = '' + zoomMode;
  623. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  624. if (typeof zoomMode === 'number') {
  625. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  626. }
  627. }
  628. if (!layoutMode) layoutMode = 'continuous';
  629. switch (layoutMode) {
  630. case 'continuous':
  631. out('/PageLayout /OneColumn');
  632. break;
  633. case 'single':
  634. out('/PageLayout /SinglePage');
  635. break;
  636. case 'two':
  637. case 'twoleft':
  638. out('/PageLayout /TwoColumnLeft');
  639. break;
  640. case 'tworight':
  641. out('/PageLayout /TwoColumnRight');
  642. break;
  643. }
  644. if (pageMode) {
  645. /**
  646. * A name object specifying how the document should be displayed when opened:
  647. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  648. * UseOutlines : Document outline visible
  649. * UseThumbs : Thumbnail images visible
  650. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  651. */
  652. out('/PageMode /' + pageMode);
  653. }
  654. events.publish('putCatalog');
  655. },
  656. putTrailer = function putTrailer() {
  657. out('/Size ' + (objectNumber + 1));
  658. out('/Root ' + objectNumber + ' 0 R');
  659. out('/Info ' + (objectNumber - 1) + ' 0 R');
  660. },
  661. beginPage = function beginPage(width, height) {
  662. // Dimensions are stored as user units and converted to points on output
  663. var orientation = typeof height === 'string' && height.toLowerCase();
  664. if (typeof width === 'string') {
  665. var format = width.toLowerCase();
  666. if (pageFormats.hasOwnProperty(format)) {
  667. width = pageFormats[format][0] / k;
  668. height = pageFormats[format][1] / k;
  669. }
  670. }
  671. if (Array.isArray(width)) {
  672. height = width[1];
  673. width = width[0];
  674. }
  675. if (orientation) {
  676. switch (orientation.substr(0, 1)) {
  677. case 'l':
  678. if (height > width) orientation = 's';
  679. break;
  680. case 'p':
  681. if (width > height) orientation = 's';
  682. break;
  683. }
  684. if (orientation === 's') {
  685. tmp = width;
  686. width = height;
  687. height = tmp;
  688. }
  689. }
  690. outToPages = true;
  691. pages[++page] = [];
  692. pagedim[page] = {
  693. width: Number(width) || pageWidth,
  694. height: Number(height) || pageHeight
  695. };
  696. pagesContext[page] = {};
  697. _setPage(page);
  698. },
  699. _addPage = function _addPage() {
  700. beginPage.apply(this, arguments);
  701. // Set line width
  702. out(f2(lineWidth * k) + ' w');
  703. // Set draw color
  704. out(drawColor);
  705. // resurrecting non-default line caps, joins
  706. if (lineCapID !== 0) {
  707. out(lineCapID + ' J');
  708. }
  709. if (lineJoinID !== 0) {
  710. out(lineJoinID + ' j');
  711. }
  712. events.publish('addPage', { pageNumber: page });
  713. },
  714. _deletePage = function _deletePage(n) {
  715. if (n > 0 && n <= page) {
  716. pages.splice(n, 1);
  717. pagedim.splice(n, 1);
  718. page--;
  719. if (currentPage > page) {
  720. currentPage = page;
  721. }
  722. this.setPage(currentPage);
  723. }
  724. },
  725. _setPage = function _setPage(n) {
  726. if (n > 0 && n <= page) {
  727. currentPage = n;
  728. pageWidth = pagedim[n].width;
  729. pageHeight = pagedim[n].height;
  730. }
  731. },
  732. /**
  733. * Returns a document-specific font key - a label assigned to a
  734. * font name + font type combination at the time the font was added
  735. * to the font inventory.
  736. *
  737. * Font key is used as label for the desired font for a block of text
  738. * to be added to the PDF document stream.
  739. * @private
  740. * @function
  741. * @param fontName {String} can be undefined on "falthy" to indicate "use current"
  742. * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  743. * @returns {String} Font key.
  744. */
  745. _getFont = function _getFont(fontName, fontStyle) {
  746. var key;
  747. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  748. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  749. if (fontName !== undefined) {
  750. fontName = fontName.toLowerCase();
  751. }
  752. switch (fontName) {
  753. case 'sans-serif':
  754. case 'verdana':
  755. case 'arial':
  756. case 'helvetica':
  757. fontName = 'helvetica';
  758. break;
  759. case 'fixed':
  760. case 'monospace':
  761. case 'terminal':
  762. case 'courier':
  763. fontName = 'courier';
  764. break;
  765. case 'serif':
  766. case 'cursive':
  767. case 'fantasy':
  768. default:
  769. fontName = 'times';
  770. break;
  771. }
  772. try {
  773. // get a string like 'F3' - the KEY corresponding tot he font + type combination.
  774. key = fontmap[fontName][fontStyle];
  775. } catch (e) {}
  776. if (!key) {
  777. //throw new Error("Unable to look up font label for font '" + fontName + "', '"
  778. //+ fontStyle + "'. Refer to getFontList() for available fonts.");
  779. key = fontmap['times'][fontStyle];
  780. if (key == null) {
  781. key = fontmap['times']['normal'];
  782. }
  783. }
  784. return key;
  785. },
  786. buildDocument = function buildDocument() {
  787. outToPages = false; // switches out() to content
  788. objectNumber = 2;
  789. content_length = 0;
  790. content = [];
  791. offsets = [];
  792. additionalObjects = [];
  793. // Added for AcroForm
  794. events.publish('buildDocument');
  795. // putHeader()
  796. out('%PDF-' + pdfVersion);
  797. putPages();
  798. // Must happen after putPages
  799. // Modifies current object Id
  800. putAdditionalObjects();
  801. putResources();
  802. // Info
  803. newObject();
  804. out('<<');
  805. putInfo();
  806. out('>>');
  807. out('endobj');
  808. // Catalog
  809. newObject();
  810. out('<<');
  811. putCatalog();
  812. out('>>');
  813. out('endobj');
  814. // Cross-ref
  815. var o = content_length,
  816. i,
  817. p = "0000000000";
  818. out('xref');
  819. out('0 ' + (objectNumber + 1));
  820. out(p + ' 65535 f ');
  821. for (i = 1; i <= objectNumber; i++) {
  822. var offset = offsets[i];
  823. if (typeof offset === 'function') {
  824. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  825. } else {
  826. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  827. }
  828. }
  829. // Trailer
  830. out('trailer');
  831. out('<<');
  832. putTrailer();
  833. out('>>');
  834. out('startxref');
  835. out('' + o);
  836. out('%%EOF');
  837. outToPages = true;
  838. return content.join('\n');
  839. },
  840. getStyle = function getStyle(style) {
  841. // see path-painting operators in PDF spec
  842. var op = 'S'; // stroke
  843. if (style === 'F') {
  844. op = 'f'; // fill
  845. } else if (style === 'FD' || style === 'DF') {
  846. op = 'B'; // both
  847. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  848. /*
  849. Allow direct use of these PDF path-painting operators:
  850. - f fill using nonzero winding number rule
  851. - f* fill using even-odd rule
  852. - B fill then stroke with fill using non-zero winding number rule
  853. - B* fill then stroke with fill using even-odd rule
  854. */
  855. op = style;
  856. }
  857. return op;
  858. },
  859. getArrayBuffer = function getArrayBuffer() {
  860. var data = buildDocument(),
  861. len = data.length,
  862. ab = new ArrayBuffer(len),
  863. u8 = new Uint8Array(ab);
  864. while (len--) {
  865. u8[len] = data.charCodeAt(len);
  866. }return ab;
  867. },
  868. getBlob = function getBlob() {
  869. return new Blob([getArrayBuffer()], { type: "application/pdf" });
  870. },
  871. /**
  872. * Generates the PDF document.
  873. *
  874. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  875. *
  876. * @param {String} type A string identifying one of the possible output types.
  877. * @param {Object} options An object providing some additional signalling to PDF generator.
  878. * @function
  879. * @returns {jsPDF}
  880. * @methodOf jsPDF#
  881. * @name output
  882. */
  883. _output = SAFE(function (type, options) {
  884. var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
  885. switch (type) {
  886. case undefined:
  887. return buildDocument();
  888. case 'save':
  889. if (navigator.getUserMedia) {
  890. if (global.URL === undefined || global.URL.createObjectURL === undefined) {
  891. return API.output('dataurlnewwindow');
  892. }
  893. }
  894. saveAs(getBlob(), options);
  895. if (typeof saveAs.unload === 'function') {
  896. if (global.setTimeout) {
  897. setTimeout(saveAs.unload, 911);
  898. }
  899. }
  900. break;
  901. case 'arraybuffer':
  902. return getArrayBuffer();
  903. case 'blob':
  904. return getBlob();
  905. case 'bloburi':
  906. case 'bloburl':
  907. // User is responsible of calling revokeObjectURL
  908. return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
  909. case 'datauristring':
  910. case 'dataurlstring':
  911. return datauri;
  912. case 'dataurlnewwindow':
  913. var nW = global.open(datauri);
  914. if (nW || typeof safari === "undefined") return nW;
  915. /* pass through */
  916. case 'datauri':
  917. case 'dataurl':
  918. return global.document.location.href = datauri;
  919. default:
  920. throw new Error('Output type "' + type + '" is not supported.');
  921. }
  922. // @TODO: Add different output options
  923. });
  924. switch (unit) {
  925. case 'pt':
  926. k = 1;
  927. break;
  928. case 'mm':
  929. k = 72 / 25.4000508;
  930. break;
  931. case 'cm':
  932. k = 72 / 2.54000508;
  933. break;
  934. case 'in':
  935. k = 72;
  936. break;
  937. case 'px':
  938. k = 96 / 72;
  939. break;
  940. case 'pc':
  941. k = 12;
  942. break;
  943. case 'em':
  944. k = 12;
  945. break;
  946. case 'ex':
  947. k = 6;
  948. break;
  949. default:
  950. throw 'Invalid unit: ' + unit;
  951. }
  952. //---------------------------------------
  953. // Public API
  954. /**
  955. * Object exposing internal API to plugins
  956. * @public
  957. */
  958. API.internal = {
  959. 'pdfEscape': pdfEscape,
  960. 'getStyle': getStyle,
  961. /**
  962. * Returns {FontObject} describing a particular font.
  963. * @public
  964. * @function
  965. * @param fontName {String} (Optional) Font's family name
  966. * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  967. * @returns {FontObject}
  968. */
  969. 'getFont': function getFont() {
  970. return fonts[_getFont.apply(API, arguments)];
  971. },
  972. 'getFontSize': function getFontSize() {
  973. return activeFontSize;
  974. },
  975. 'getLineHeight': function getLineHeight() {
  976. return activeFontSize * lineHeightProportion;
  977. },
  978. 'write': function write(string1 /*, string2, string3, etc */) {
  979. out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
  980. },
  981. 'getCoordinateString': function getCoordinateString(value) {
  982. return f2(value * k);
  983. },
  984. 'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
  985. return f2((pageHeight - value) * k);
  986. },
  987. 'collections': {},
  988. 'newObject': newObject,
  989. 'newAdditionalObject': newAdditionalObject,
  990. 'newObjectDeferred': newObjectDeferred,
  991. 'newObjectDeferredBegin': newObjectDeferredBegin,
  992. 'putStream': putStream,
  993. 'events': events,
  994. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  995. // units of measurement.
  996. // scaleFactor is set at initialization of the document and calculated against the stated
  997. // default measurement units for the document.
  998. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  999. // through multiplication.
  1000. 'scaleFactor': k,
  1001. 'pageSize': {
  1002. get width() {
  1003. return pageWidth;
  1004. },
  1005. get height() {
  1006. return pageHeight;
  1007. }
  1008. },
  1009. 'output': function output(type, options) {
  1010. return _output(type, options);
  1011. },
  1012. 'getNumberOfPages': function getNumberOfPages() {
  1013. return pages.length - 1;
  1014. },
  1015. 'pages': pages,
  1016. 'out': out,
  1017. 'f2': f2,
  1018. 'getPageInfo': function getPageInfo(pageNumberOneBased) {
  1019. var objId = (pageNumberOneBased - 1) * 2 + 3;
  1020. return { objId: objId, pageNumber: pageNumberOneBased, pageContext: pagesContext[pageNumberOneBased] };
  1021. },
  1022. 'getCurrentPageInfo': function getCurrentPageInfo() {
  1023. var objId = (currentPage - 1) * 2 + 3;
  1024. return { objId: objId, pageNumber: currentPage, pageContext: pagesContext[currentPage] };
  1025. },
  1026. 'getPDFVersion': function getPDFVersion() {
  1027. return pdfVersion;
  1028. }
  1029. };
  1030. /**
  1031. * Adds (and transfers the focus to) new page to the PDF document.
  1032. * @function
  1033. * @returns {jsPDF}
  1034. *
  1035. * @methodOf jsPDF#
  1036. * @name addPage
  1037. */
  1038. API.addPage = function () {
  1039. _addPage.apply(this, arguments);
  1040. return this;
  1041. };
  1042. API.setPage = function () {
  1043. _setPage.apply(this, arguments);
  1044. return this;
  1045. };
  1046. API.insertPage = function (beforePage) {
  1047. this.addPage();
  1048. this.movePage(currentPage, beforePage);
  1049. return this;
  1050. };
  1051. API.movePage = function (targetPage, beforePage) {
  1052. if (targetPage > beforePage) {
  1053. var tmpPages = pages[targetPage];
  1054. var tmpPagedim = pagedim[targetPage];
  1055. var tmpPagesContext = pagesContext[targetPage];
  1056. for (var i = targetPage; i > beforePage; i--) {
  1057. pages[i] = pages[i - 1];
  1058. pagedim[i] = pagedim[i - 1];
  1059. pagesContext[i] = pagesContext[i - 1];
  1060. }
  1061. pages[beforePage] = tmpPages;
  1062. pagedim[beforePage] = tmpPagedim;
  1063. pagesContext[beforePage] = tmpPagesContext;
  1064. this.setPage(beforePage);
  1065. } else if (targetPage < beforePage) {
  1066. var tmpPages = pages[targetPage];
  1067. var tmpPagedim = pagedim[targetPage];
  1068. var tmpPagesContext = pagesContext[targetPage];
  1069. for (var i = targetPage; i < beforePage; i++) {
  1070. pages[i] = pages[i + 1];
  1071. pagedim[i] = pagedim[i + 1];
  1072. pagesContext[i] = pagesContext[i + 1];
  1073. }
  1074. pages[beforePage] = tmpPages;
  1075. pagedim[beforePage] = tmpPagedim;
  1076. pagesContext[beforePage] = tmpPagesContext;
  1077. this.setPage(beforePage);
  1078. }
  1079. return this;
  1080. };
  1081. API.deletePage = function () {
  1082. _deletePage.apply(this, arguments);
  1083. return this;
  1084. };
  1085. API.setDisplayMode = function (zoom, layout, pmode) {
  1086. zoomMode = zoom;
  1087. layoutMode = layout;
  1088. pageMode = pmode;
  1089. return this;
  1090. },
  1091. /**
  1092. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1093. *
  1094. * @function
  1095. * @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.
  1096. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1097. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1098. * @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.
  1099. * @returns {jsPDF}
  1100. * @methodOf jsPDF#
  1101. * @name text
  1102. */
  1103. API.text = function (text, x, y, flags, angle, align) {
  1104. /**
  1105. * Inserts something like this into PDF
  1106. * BT
  1107. * /F1 16 Tf % Font name + size
  1108. * 16 TL % How many units down for next line in multiline text
  1109. * 0 g % color
  1110. * 28.35 813.54 Td % position
  1111. * (line one) Tj
  1112. * T* (line two) Tj
  1113. * T* (line three) Tj
  1114. * ET
  1115. */
  1116. function ESC(s) {
  1117. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1118. return pdfEscape(s, flags);
  1119. }
  1120. // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1121. // in effort to make all calls have similar signature like
  1122. // function(data, coordinates... , miscellaneous)
  1123. // this method had its args flipped.
  1124. // code below allows backward compatibility with old arg order.
  1125. if (typeof text === 'number') {
  1126. tmp = y;
  1127. y = x;
  1128. x = text;
  1129. text = tmp;
  1130. }
  1131. // If there are any newlines in text, we assume
  1132. // the user wanted to print multiple lines, so break the
  1133. // text up into an array. If the text is already an array,
  1134. // we assume the user knows what they are doing.
  1135. // Convert text into an array anyway to simplify
  1136. // later code.
  1137. if (typeof text === 'string') {
  1138. if (text.match(/[\n\r]/)) {
  1139. text = text.split(/\r\n|\r|\n/g);
  1140. } else {
  1141. text = [text];
  1142. }
  1143. }
  1144. if (typeof angle === 'string') {
  1145. align = angle;
  1146. angle = null;
  1147. }
  1148. if (typeof flags === 'string') {
  1149. align = flags;
  1150. flags = null;
  1151. }
  1152. if (typeof flags === 'number') {
  1153. angle = flags;
  1154. flags = null;
  1155. }
  1156. var xtra = '',
  1157. mode = 'Td',
  1158. todo;
  1159. if (angle) {
  1160. angle *= Math.PI / 180;
  1161. var c = Math.cos(angle),
  1162. s = Math.sin(angle);
  1163. xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ");
  1164. mode = 'Tm';
  1165. }
  1166. flags = flags || {};
  1167. if (!('noBOM' in flags)) flags.noBOM = true;
  1168. if (!('autoencode' in flags)) flags.autoencode = true;
  1169. var strokeOption = '';
  1170. var pageContext = this.internal.getCurrentPageInfo().pageContext;
  1171. if (true === flags.stroke) {
  1172. if (pageContext.lastTextWasStroke !== true) {
  1173. strokeOption = '1 Tr\n';
  1174. pageContext.lastTextWasStroke = true;
  1175. }
  1176. } else {
  1177. if (pageContext.lastTextWasStroke) {
  1178. strokeOption = '0 Tr\n';
  1179. }
  1180. pageContext.lastTextWasStroke = false;
  1181. }
  1182. if (typeof this._runningPageHeight === 'undefined') {
  1183. this._runningPageHeight = 0;
  1184. }
  1185. if (typeof text === 'string') {
  1186. text = ESC(text);
  1187. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1188. // we don't want to destroy original text array, so cloning it
  1189. var sa = text.concat(),
  1190. da = [],
  1191. len = sa.length;
  1192. // we do array.join('text that must not be PDFescaped")
  1193. // thus, pdfEscape each component separately
  1194. while (len--) {
  1195. da.push(ESC(sa.shift()));
  1196. }
  1197. var linesLeft = Math.ceil((pageHeight - y - this._runningPageHeight) * k / (activeFontSize * lineHeightProportion));
  1198. if (0 <= linesLeft && linesLeft < da.length + 1) {
  1199. //todo = da.splice(linesLeft-1);
  1200. }
  1201. if (align) {
  1202. var left,
  1203. prevX,
  1204. maxLineLength,
  1205. leading = activeFontSize * lineHeightProportion,
  1206. lineWidths = text.map(function (v) {
  1207. return this.getStringUnitWidth(v) * activeFontSize / k;
  1208. }, this);
  1209. maxLineLength = Math.max.apply(Math, lineWidths);
  1210. // The first line uses the "main" Td setting,
  1211. // and the subsequent lines are offset by the
  1212. // previous line's x coordinate.
  1213. if (align === "center") {
  1214. // The passed in x coordinate defines
  1215. // the center point.
  1216. left = x - maxLineLength / 2;
  1217. x -= lineWidths[0] / 2;
  1218. } else if (align === "right") {
  1219. // The passed in x coordinate defines the
  1220. // rightmost point of the text.
  1221. left = x - maxLineLength;
  1222. x -= lineWidths[0];
  1223. } else {
  1224. throw new Error('Unrecognized alignment option, use "center" or "right".');
  1225. }
  1226. prevX = x;
  1227. text = da[0];
  1228. for (var i = 1, len = da.length; i < len; i++) {
  1229. var delta = maxLineLength - lineWidths[i];
  1230. if (align === "center") delta /= 2;
  1231. // T* = x-offset leading Td ( text )
  1232. text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
  1233. prevX = left + delta;
  1234. }
  1235. } else {
  1236. text = da.join(") Tj\nT* (");
  1237. }
  1238. } else {
  1239. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1240. }
  1241. // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
  1242. // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
  1243. // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
  1244. // Thus, there is NO useful, *reliable* concept of "default" font for a page.
  1245. // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
  1246. // - readers dealing smartly with brokenness of jsPDF's markup.
  1247. var curY;
  1248. if (todo) {
  1249. //this.addPage();
  1250. //this._runningPageHeight += y - (activeFontSize * 1.7 / k);
  1251. //curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1252. } else {
  1253. curY = f2((pageHeight - y) * k);
  1254. }
  1255. //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
  1256. // if (curY < 0){
  1257. // console.log('auto page break');
  1258. // this.addPage();
  1259. // this._runningPageHeight = y - (activeFontSize * 1.7 / k);
  1260. // curY = f2(pageHeight - activeFontSize * 1.7 /k);
  1261. // }
  1262. out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1263. activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
  1264. strokeOption + // stroke option
  1265. textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
  1266. if (todo) {
  1267. //this.text( todo, x, activeFontSize * 1.7 / k);
  1268. //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
  1269. this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
  1270. }
  1271. return this;
  1272. };
  1273. API.lstext = function (text, x, y, spacing) {
  1274. for (var i = 0, len = text.length; i < len; i++, x += spacing) {
  1275. this.text(text[i], x, y);
  1276. }
  1277. };
  1278. API.line = function (x1, y1, x2, y2) {
  1279. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  1280. };
  1281. API.clip = function () {
  1282. // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
  1283. // Call .clip() after calling .rect() with a style argument of null
  1284. out('W'); // clip
  1285. out('S'); // stroke path; necessary for clip to work
  1286. };
  1287. /**
  1288. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  1289. * We introduce the fixed version so as to not break API.
  1290. * @param fillRule
  1291. */
  1292. API.clip_fixed = function (fillRule) {
  1293. // Call .clip() after calling drawing ops with a style argument of null
  1294. // W is the PDF clipping op
  1295. if ('evenodd' === fillRule) {
  1296. out('W*');
  1297. } else {
  1298. out('W');
  1299. }
  1300. // End the path object without filling or stroking it.
  1301. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  1302. // (see Section 4.4.3, “Clipping Path Operators”)
  1303. out('n');
  1304. };
  1305. /**
  1306. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1307. * All data points in `lines` are relative to last line origin.
  1308. * `x`, `y` become x1,y1 for first line / curve in the set.
  1309. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1310. * 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.
  1311. *
  1312. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1313. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1314. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1315. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1316. * @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.
  1317. * @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.
  1318. * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1319. * @function
  1320. * @returns {jsPDF}
  1321. * @methodOf jsPDF#
  1322. * @name lines
  1323. */
  1324. API.lines = function (lines, x, y, scale, style, closed) {
  1325. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1326. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1327. // in effort to make all calls have similar signature like
  1328. // function(content, coordinateX, coordinateY , miscellaneous)
  1329. // this method had its args flipped.
  1330. // code below allows backward compatibility with old arg order.
  1331. if (typeof lines === 'number') {
  1332. tmp = y;
  1333. y = x;
  1334. x = lines;
  1335. lines = tmp;
  1336. }
  1337. scale = scale || [1, 1];
  1338. // starting point
  1339. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1340. scalex = scale[0];
  1341. scaley = scale[1];
  1342. l = lines.length;
  1343. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1344. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1345. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1346. x4 = x; // last / ending point = starting point for first item.
  1347. y4 = y; // last / ending point = starting point for first item.
  1348. for (i = 0; i < l; i++) {
  1349. leg = lines[i];
  1350. if (leg.length === 2) {
  1351. // simple line
  1352. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1353. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1354. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1355. } else {
  1356. // bezier curve
  1357. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1358. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1359. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1360. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1361. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1362. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1363. out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
  1364. }
  1365. }
  1366. if (closed) {
  1367. out(' h');
  1368. }
  1369. // stroking / filling / both the path
  1370. if (style !== null) {
  1371. out(getStyle(style));
  1372. }
  1373. return this;
  1374. };
  1375. /**
  1376. * Adds a rectangle to PDF
  1377. *
  1378. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1379. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1380. * @param {Number} w Width (in units declared at inception of PDF document)
  1381. * @param {Number} h Height (in units declared at inception of PDF document)
  1382. * @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.
  1383. * @function
  1384. * @returns {jsPDF}
  1385. * @methodOf jsPDF#
  1386. * @name rect
  1387. */
  1388. API.rect = function (x, y, w, h, style) {
  1389. var op = getStyle(style);
  1390. out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
  1391. if (style !== null) {
  1392. out(getStyle(style));
  1393. }
  1394. return this;
  1395. };
  1396. /**
  1397. * Adds a triangle to PDF
  1398. *
  1399. * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1400. * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1401. * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1402. * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1403. * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1404. * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1405. * @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.
  1406. * @function
  1407. * @returns {jsPDF}
  1408. * @methodOf jsPDF#
  1409. * @name triangle
  1410. */
  1411. API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  1412. this.lines([[x2 - x1, y2 - y1], // vector to point 2
  1413. [x3 - x2, y3 - y2], // vector to point 3
  1414. [x1 - x3, y1 - y3] // closing vector back to point 1
  1415. ], x1, y1, // start of path
  1416. [1, 1], style, true);
  1417. return this;
  1418. };
  1419. /**
  1420. * Adds a rectangle with rounded corners to PDF
  1421. *
  1422. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1423. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1424. * @param {Number} w Width (in units declared at inception of PDF document)
  1425. * @param {Number} h Height (in units declared at inception of PDF document)
  1426. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1427. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1428. * @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.
  1429. * @function
  1430. * @returns {jsPDF}
  1431. * @methodOf jsPDF#
  1432. * @name roundedRect
  1433. */
  1434. API.roundedRect = function (x, y, w, h, rx, ry, style) {
  1435. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  1436. 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
  1437. [1, 1], style);
  1438. return this;
  1439. };
  1440. /**
  1441. * Adds an ellipse to PDF
  1442. *
  1443. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1444. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1445. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1446. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1447. * @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.
  1448. * @function
  1449. * @returns {jsPDF}
  1450. * @methodOf jsPDF#
  1451. * @name ellipse
  1452. */
  1453. API.ellipse = function (x, y, rx, ry, style) {
  1454. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1455. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1456. 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(' '));
  1457. 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(' '));
  1458. 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(' '));
  1459. 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(' '));
  1460. if (style !== null) {
  1461. out(getStyle(style));
  1462. }
  1463. return this;
  1464. };
  1465. /**
  1466. * Adds an circle to PDF
  1467. *
  1468. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1469. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1470. * @param {Number} r Radius (in units declared at inception of PDF document)
  1471. * @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.
  1472. * @function
  1473. * @returns {jsPDF}
  1474. * @methodOf jsPDF#
  1475. * @name circle
  1476. */
  1477. API.circle = function (x, y, r, style) {
  1478. return this.ellipse(x, y, r, r, style);
  1479. };
  1480. /**
  1481. * Adds a properties to the PDF document
  1482. *
  1483. * @param {Object} A property_name-to-property_value object structure.
  1484. * @function
  1485. * @returns {jsPDF}
  1486. * @methodOf jsPDF#
  1487. * @name setProperties
  1488. */
  1489. API.setProperties = function (properties) {
  1490. // copying only those properties we can render.
  1491. for (var property in documentProperties) {
  1492. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1493. documentProperties[property] = properties[property];
  1494. }
  1495. }
  1496. return this;
  1497. };
  1498. /**
  1499. * Sets font size for upcoming text elements.
  1500. *
  1501. * @param {Number} size Font size in points.
  1502. * @function
  1503. * @returns {jsPDF}
  1504. * @methodOf jsPDF#
  1505. * @name setFontSize
  1506. */
  1507. API.setFontSize = function (size) {
  1508. activeFontSize = size;
  1509. return this;
  1510. };
  1511. /**
  1512. * Sets text font face, variant for upcoming text elements.
  1513. * See output of jsPDF.getFontList() for possible font names, styles.
  1514. *
  1515. * @param {String} fontName Font name or family. Example: "times"
  1516. * @param {String} fontStyle Font style or variant. Example: "italic"
  1517. * @function
  1518. * @returns {jsPDF}
  1519. * @methodOf jsPDF#
  1520. * @name setFont
  1521. */
  1522. API.setFont = function (fontName, fontStyle) {
  1523. activeFontKey = _getFont(fontName, fontStyle);
  1524. // if font is not found, the above line blows up and we never go further
  1525. return this;
  1526. };
  1527. /**
  1528. * Switches font style or variant for upcoming text elements,
  1529. * while keeping the font face or family same.
  1530. * See output of jsPDF.getFontList() for possible font names, styles.
  1531. *
  1532. * @param {String} style Font style or variant. Example: "italic"
  1533. * @function
  1534. * @returns {jsPDF}
  1535. * @methodOf jsPDF#
  1536. * @name setFontStyle
  1537. */
  1538. API.setFontStyle = API.setFontType = function (style) {
  1539. activeFontKey = _getFont(undefined, style);
  1540. // if font is not found, the above line blows up and we never go further
  1541. return this;
  1542. };
  1543. /**
  1544. * Returns an object - a tree of fontName to fontStyle relationships available to
  1545. * active PDF document.
  1546. *
  1547. * @public
  1548. * @function
  1549. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  1550. * @methodOf jsPDF#
  1551. * @name getFontList
  1552. */
  1553. API.getFontList = function () {
  1554. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  1555. var list = {},
  1556. fontName,
  1557. fontStyle,
  1558. tmp;
  1559. for (fontName in fontmap) {
  1560. if (fontmap.hasOwnProperty(fontName)) {
  1561. list[fontName] = tmp = [];
  1562. for (fontStyle in fontmap[fontName]) {
  1563. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  1564. tmp.push(fontStyle);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return list;
  1570. };
  1571. /**
  1572. * Add a custom font.
  1573. *
  1574. * @param {String} Postscript name of the Font. Example: "Menlo-Regular"
  1575. * @param {String} Name of font-family from @font-face definition. Example: "Menlo Regular"
  1576. * @param {String} Font style. Example: "normal"
  1577. * @function
  1578. * @returns the {fontKey} (same as the internal method)
  1579. * @methodOf jsPDF#
  1580. * @name addFont
  1581. */
  1582. API.addFont = function (postScriptName, fontName, fontStyle) {
  1583. addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
  1584. };
  1585. /**
  1586. * Sets line width for upcoming lines.
  1587. *
  1588. * @param {Number} width Line width (in units declared at inception of PDF document)
  1589. * @function
  1590. * @returns {jsPDF}
  1591. * @methodOf jsPDF#
  1592. * @name setLineWidth
  1593. */
  1594. API.setLineWidth = function (width) {
  1595. out((width * k).toFixed(2) + ' w');
  1596. return this;
  1597. };
  1598. /**
  1599. * Sets the stroke color for upcoming elements.
  1600. *
  1601. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1602. * color space is implied.
  1603. *
  1604. * When only ch1 is given, "Gray" color space is implied and it
  1605. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1606. * if values are communicated as String types, or in range from 0 (black)
  1607. * to 255 (white) if communicated as Number type.
  1608. * The RGB-like 0-255 range is provided for backward compatibility.
  1609. *
  1610. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1611. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1612. * (max intensity) if values are communicated as String types, or
  1613. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1614. * as Number types.
  1615. * The RGB-like 0-255 range is provided for backward compatibility.
  1616. *
  1617. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1618. * value must be a in the range from 0.00 (0% concentration) to to
  1619. * 1.00 (100% concentration)
  1620. *
  1621. * Because JavaScript treats fixed point numbers badly (rounds to
  1622. * floating point nearest to binary representation) it is highly advised to
  1623. * communicate the fractional numbers as String types, not JavaScript Number type.
  1624. *
  1625. * @param {Number|String} ch1 Color channel value
  1626. * @param {Number|String} ch2 Color channel value
  1627. * @param {Number|String} ch3 Color channel value
  1628. * @param {Number|String} ch4 Color channel value
  1629. *
  1630. * @function
  1631. * @returns {jsPDF}
  1632. * @methodOf jsPDF#
  1633. * @name setDrawColor
  1634. */
  1635. API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  1636. var color;
  1637. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1638. // Gray color space.
  1639. if (typeof ch1 === 'string') {
  1640. color = ch1 + ' G';
  1641. } else {
  1642. color = f2(ch1 / 255) + ' G';
  1643. }
  1644. } else if (ch4 === undefined) {
  1645. // RGB
  1646. if (typeof ch1 === 'string') {
  1647. color = [ch1, ch2, ch3, 'RG'].join(' ');
  1648. } else {
  1649. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
  1650. }
  1651. } else {
  1652. // CMYK
  1653. if (typeof ch1 === 'string') {
  1654. color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
  1655. } else {
  1656. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
  1657. }
  1658. }
  1659. out(color);
  1660. return this;
  1661. };
  1662. /**
  1663. * Sets the fill color for upcoming elements.
  1664. *
  1665. * Depending on the number of arguments given, Gray, RGB, or CMYK
  1666. * color space is implied.
  1667. *
  1668. * When only ch1 is given, "Gray" color space is implied and it
  1669. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1670. * if values are communicated as String types, or in range from 0 (black)
  1671. * to 255 (white) if communicated as Number type.
  1672. * The RGB-like 0-255 range is provided for backward compatibility.
  1673. *
  1674. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1675. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  1676. * (max intensity) if values are communicated as String types, or
  1677. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1678. * as Number types.
  1679. * The RGB-like 0-255 range is provided for backward compatibility.
  1680. *
  1681. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1682. * value must be a in the range from 0.00 (0% concentration) to to
  1683. * 1.00 (100% concentration)
  1684. *
  1685. * Because JavaScript treats fixed point numbers badly (rounds to
  1686. * floating point nearest to binary representation) it is highly advised to
  1687. * communicate the fractional numbers as String types, not JavaScript Number type.
  1688. *
  1689. * @param {Number|String} ch1 Color channel value
  1690. * @param {Number|String} ch2 Color channel value
  1691. * @param {Number|String} ch3 Color channel value
  1692. * @param {Number|String} ch4 Color channel value
  1693. *
  1694. * @function
  1695. * @returns {jsPDF}
  1696. * @methodOf jsPDF#
  1697. * @name setFillColor
  1698. */
  1699. API.setFillColor = function (ch1, ch2, ch3, ch4) {
  1700. var color;
  1701. if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
  1702. // Gray color space.
  1703. if (typeof ch1 === 'string') {
  1704. color = ch1 + ' g';
  1705. } else {
  1706. color = f2(ch1 / 255) + ' g';
  1707. }
  1708. } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
  1709. // RGB
  1710. if (typeof ch1 === 'string') {
  1711. color = [ch1, ch2, ch3, 'rg'].join(' ');
  1712. } else {
  1713. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
  1714. }
  1715. if (ch4 && ch4.a === 0) {
  1716. //TODO Implement transparency.
  1717. //WORKAROUND use white for now
  1718. color = ['255', '255', '255', 'rg'].join(' ');
  1719. }
  1720. } else {
  1721. // CMYK
  1722. if (typeof ch1 === 'string') {
  1723. color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
  1724. } else {
  1725. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
  1726. }
  1727. }
  1728. out(color);
  1729. return this;
  1730. };
  1731. /**
  1732. * Sets the text color for upcoming elements.
  1733. * If only one, first argument is given,
  1734. * treats the value as gray-scale color value.
  1735. *
  1736. * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
  1737. * @param {Number} g Green channel color value in range 0-255
  1738. * @param {Number} b Blue channel color value in range 0-255
  1739. * @function
  1740. * @returns {jsPDF}
  1741. * @methodOf jsPDF#
  1742. * @name setTextColor
  1743. */
  1744. API.setTextColor = function (r, g, b) {
  1745. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  1746. var hex = parseInt(r.substr(1), 16);
  1747. r = hex >> 16 & 255;
  1748. g = hex >> 8 & 255;
  1749. b = hex & 255;
  1750. }
  1751. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  1752. textColor = f3(r / 255) + ' g';
  1753. } else {
  1754. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  1755. }
  1756. return this;
  1757. };
  1758. /**
  1759. * Is an Object providing a mapping from human-readable to
  1760. * integer flag values designating the varieties of line cap
  1761. * and join styles.
  1762. *
  1763. * @returns {Object}
  1764. * @fieldOf jsPDF#
  1765. * @name CapJoinStyles
  1766. */
  1767. API.CapJoinStyles = {
  1768. 0: 0,
  1769. 'butt': 0,
  1770. 'but': 0,
  1771. 'miter': 0,
  1772. 1: 1,
  1773. 'round': 1,
  1774. 'rounded': 1,
  1775. 'circle': 1,
  1776. 2: 2,
  1777. 'projecting': 2,
  1778. 'project': 2,
  1779. 'square': 2,
  1780. 'bevel': 2
  1781. };
  1782. /**
  1783. * Sets the line cap styles
  1784. * See {jsPDF.CapJoinStyles} for variants
  1785. *
  1786. * @param {String|Number} style A string or number identifying the type of line cap
  1787. * @function
  1788. * @returns {jsPDF}
  1789. * @methodOf jsPDF#
  1790. * @name setLineCap
  1791. */
  1792. API.setLineCap = function (style) {
  1793. var id = this.CapJoinStyles[style];
  1794. if (id === undefined) {
  1795. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  1796. }
  1797. lineCapID = id;
  1798. out(id + ' J');
  1799. return this;
  1800. };
  1801. /**
  1802. * Sets the line join styles
  1803. * See {jsPDF.CapJoinStyles} for variants
  1804. *
  1805. * @param {String|Number} style A string or number identifying the type of line join
  1806. * @function
  1807. * @returns {jsPDF}
  1808. * @methodOf jsPDF#
  1809. * @name setLineJoin
  1810. */
  1811. API.setLineJoin = function (style) {
  1812. var id = this.CapJoinStyles[style];
  1813. if (id === undefined) {
  1814. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  1815. }
  1816. lineJoinID = id;
  1817. out(id + ' j');
  1818. return this;
  1819. };
  1820. // Output is both an internal (for plugins) and external function
  1821. API.output = _output;
  1822. /**
  1823. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  1824. * @param {String} filename The filename including extension.
  1825. *
  1826. * @function
  1827. * @returns {jsPDF}
  1828. * @methodOf jsPDF#
  1829. * @name save
  1830. */
  1831. API.save = function (filename) {
  1832. API.output('save', filename);
  1833. };
  1834. // applying plugins (more methods) ON TOP of built-in API.
  1835. // this is intentional as we allow plugins to override
  1836. // built-ins
  1837. for (var plugin in jsPDF.API) {
  1838. if (jsPDF.API.hasOwnProperty(plugin)) {
  1839. if (plugin === 'events' && jsPDF.API.events.length) {
  1840. (function (events, newEvents) {
  1841. // jsPDF.API.events is a JS Array of Arrays
  1842. // where each Array is a pair of event name, handler
  1843. // Events were added by plugins to the jsPDF instantiator.
  1844. // These are always added to the new instance and some ran
  1845. // during instantiation.
  1846. var eventname, handler_and_args, i;
  1847. for (i = newEvents.length - 1; i !== -1; i--) {
  1848. // subscribe takes 3 args: 'topic', function, runonce_flag
  1849. // if undefined, runonce is false.
  1850. // users can attach callback directly,
  1851. // or they can attach an array with [callback, runonce_flag]
  1852. // that's what the "apply" magic is for below.
  1853. eventname = newEvents[i][0];
  1854. handler_and_args = newEvents[i][1];
  1855. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  1856. }
  1857. })(events, jsPDF.API.events);
  1858. } else {
  1859. API[plugin] = jsPDF.API[plugin];
  1860. }
  1861. }
  1862. }
  1863. //////////////////////////////////////////////////////
  1864. // continuing initialization of jsPDF Document object
  1865. //////////////////////////////////////////////////////
  1866. // Add the first page automatically
  1867. addFonts();
  1868. activeFontKey = 'F1';
  1869. _addPage(format, orientation);
  1870. events.publish('initialized');
  1871. return API;
  1872. }
  1873. /**
  1874. * jsPDF.API is a STATIC property of jsPDF class.
  1875. * jsPDF.API is an object you can add methods and properties to.
  1876. * The methods / properties you add will show up in new jsPDF objects.
  1877. *
  1878. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  1879. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  1880. * Examples:
  1881. * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  1882. * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  1883. *
  1884. * @static
  1885. * @public
  1886. * @memberOf jsPDF
  1887. * @name API
  1888. *
  1889. * @example
  1890. * jsPDF.API.mymethod = function(){
  1891. * // 'this' will be ref to internal API object. see jsPDF source
  1892. * // , so you can refer to built-in methods like so:
  1893. * // this.line(....)
  1894. * // this.text(....)
  1895. * }
  1896. * var pdfdoc = new jsPDF()
  1897. * pdfdoc.mymethod() // <- !!!!!!
  1898. */
  1899. jsPDF.API = { events: [] };
  1900. jsPDF.version = "1.3.2 2016-09-30T20:33:17.116Z:jameshall";
  1901. if (typeof define === 'function' && define.amd) {
  1902. define('jsPDF', function () {
  1903. return jsPDF;
  1904. });
  1905. } else if (typeof module !== 'undefined' && module.exports) {
  1906. module.exports = jsPDF;
  1907. } else {
  1908. global.jsPDF = jsPDF;
  1909. }
  1910. return jsPDF;
  1911. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  1912. /*rollup-keeper-start*/window.tmp = jsPDF;
  1913. /**
  1914. * jsPDF AcroForm Plugin
  1915. * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
  1916. *
  1917. * Licensed under the MIT License.
  1918. * http://opensource.org/licenses/mit-license
  1919. */
  1920. (window.AcroForm = function (jsPDFAPI) {
  1921. 'use strict';
  1922. var AcroForm = window.AcroForm;
  1923. AcroForm.scale = function (x) {
  1924. return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
  1925. };
  1926. AcroForm.antiScale = function (x) {
  1927. return 1 / acroformPlugin.internal.scaleFactor * x;
  1928. };
  1929. var acroformPlugin = {
  1930. fields: [],
  1931. xForms: [],
  1932. /**
  1933. * acroFormDictionaryRoot contains information about the AcroForm Dictionary
  1934. * 0: The Event-Token, the AcroFormDictionaryCallback has
  1935. * 1: The Object ID of the Root
  1936. */
  1937. acroFormDictionaryRoot: null,
  1938. /**
  1939. * After the PDF gets evaluated, the reference to the root has to be reset,
  1940. * this indicates, whether the root has already been printed out
  1941. */
  1942. printedOut: false,
  1943. internal: null
  1944. };
  1945. jsPDF.API.acroformPlugin = acroformPlugin;
  1946. var annotReferenceCallback = function annotReferenceCallback() {
  1947. for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
  1948. var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
  1949. // add Annot Reference!
  1950. if (formObject.hasAnnotation) {
  1951. // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
  1952. createAnnotationReference.call(this, formObject);
  1953. }
  1954. }
  1955. };
  1956. var createAcroForm = function createAcroForm() {
  1957. if (this.acroformPlugin.acroFormDictionaryRoot) {
  1958. //return;
  1959. throw new Error("Exception while creating AcroformDictionary");
  1960. }
  1961. // The Object Number of the AcroForm Dictionary
  1962. this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
  1963. this.acroformPlugin.internal = this.internal;
  1964. // add Callback for creating the AcroForm Dictionary
  1965. this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  1966. this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
  1967. // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
  1968. this.internal.events.subscribe('putCatalog', putCatalogCallback);
  1969. // Register event, that creates all Fields
  1970. this.internal.events.subscribe('postPutPages', createFieldCallback);
  1971. };
  1972. /**
  1973. * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
  1974. * (Requires the Annotation Plugin)
  1975. */
  1976. var createAnnotationReference = function createAnnotationReference(object) {
  1977. var options = {
  1978. type: 'reference',
  1979. object: object
  1980. };
  1981. jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
  1982. };
  1983. var putForm = function putForm(formObject) {
  1984. if (this.acroformPlugin.printedOut) {
  1985. this.acroformPlugin.printedOut = false;
  1986. this.acroformPlugin.acroFormDictionaryRoot = null;
  1987. }
  1988. if (!this.acroformPlugin.acroFormDictionaryRoot) {
  1989. createAcroForm.call(this);
  1990. }
  1991. this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  1992. };
  1993. // Callbacks
  1994. var putCatalogCallback = function putCatalogCallback() {
  1995. //Put reference to AcroForm to DocumentCatalog
  1996. if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  1997. // for safety, shouldn't normally be the case
  1998. this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  1999. } else {
  2000. console.log('Root missing...');
  2001. }
  2002. };
  2003. /**
  2004. * Adds /Acroform X 0 R to Document Catalog,
  2005. * and creates the AcroForm Dictionary
  2006. */
  2007. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  2008. // Remove event
  2009. this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
  2010. delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
  2011. this.acroformPlugin.printedOut = true;
  2012. };
  2013. /**
  2014. * Creates the single Fields and writes them into the Document
  2015. *
  2016. * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
  2017. * (for the FormXObjects...)
  2018. */
  2019. var createFieldCallback = function createFieldCallback(fieldArray) {
  2020. var standardFields = !fieldArray;
  2021. if (!fieldArray) {
  2022. // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
  2023. // Print out Root
  2024. this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
  2025. this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
  2026. }
  2027. var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
  2028. for (var i in fieldArray) {
  2029. var key = i;
  2030. var form = fieldArray[i];
  2031. var oldRect = form.Rect;
  2032. if (form.Rect) {
  2033. form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
  2034. }
  2035. // Start Writing the Object
  2036. this.internal.newObjectDeferredBegin(form.objId);
  2037. var content = "";
  2038. content += form.objId + " 0 obj\n";
  2039. content += "<<\n" + form.getContent();
  2040. form.Rect = oldRect;
  2041. if (form.hasAppearanceStream && !form.appearanceStreamContent) {
  2042. // Calculate Appearance
  2043. var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
  2044. content += "/AP << /N " + appearance + " >>\n";
  2045. this.acroformPlugin.xForms.push(appearance);
  2046. }
  2047. // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
  2048. if (form.appearanceStreamContent) {
  2049. content += "/AP << ";
  2050. // Iterate over N,R and D
  2051. for (var k in form.appearanceStreamContent) {
  2052. var value = form.appearanceStreamContent[k];
  2053. content += "/" + k + " ";
  2054. content += "<< ";
  2055. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  2056. // appearanceStream is an Array or Object!
  2057. for (var i in value) {
  2058. var obj = value[i];
  2059. if (typeof obj === 'function') {
  2060. // if Function is referenced, call it in order to get the FormXObject
  2061. obj = obj.call(this, form);
  2062. }
  2063. content += "/" + i + " " + obj + " ";
  2064. // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
  2065. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2066. }
  2067. } else {
  2068. var obj = value;
  2069. if (typeof obj === 'function') {
  2070. // if Function is referenced, call it in order to get the FormXObject
  2071. obj = obj.call(this, form);
  2072. }
  2073. content += "/" + i + " " + obj + " \n";
  2074. if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
  2075. }
  2076. content += " >>\n";
  2077. }
  2078. // appearance stream is a normal Object..
  2079. content += ">>\n";
  2080. }
  2081. content += ">>\nendobj\n";
  2082. this.internal.out(content);
  2083. }
  2084. if (standardFields) {
  2085. createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
  2086. }
  2087. };
  2088. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  2089. for (var i in fieldArray) {
  2090. var key = i;
  2091. var form = fieldArray[i];
  2092. // Start Writing the Object
  2093. this.internal.newObjectDeferredBegin(form && form.objId);
  2094. var content = "";
  2095. content += form ? form.getString() : '';
  2096. this.internal.out(content);
  2097. delete fieldArray[key];
  2098. }
  2099. };
  2100. // Public:
  2101. jsPDFAPI.addField = function (fieldObject) {
  2102. //var opt = parseOptions(fieldObject);
  2103. if (fieldObject instanceof AcroForm.TextField) {
  2104. addTextField.call(this, fieldObject);
  2105. } else if (fieldObject instanceof AcroForm.ChoiceField) {
  2106. addChoiceField.call(this, fieldObject);
  2107. } else if (fieldObject instanceof AcroForm.Button) {
  2108. addButton.call(this, fieldObject);
  2109. } else if (fieldObject instanceof AcroForm.ChildClass) {
  2110. putForm.call(this, fieldObject);
  2111. } else if (fieldObject) {
  2112. // try to put..
  2113. putForm.call(this, fieldObject);
  2114. }
  2115. fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
  2116. return this;
  2117. };
  2118. // ############### sort in:
  2119. /**
  2120. * Button
  2121. * FT = Btn
  2122. */
  2123. var addButton = function addButton(options) {
  2124. var options = options || new AcroForm.Field();
  2125. options.FT = '/Btn';
  2126. /**
  2127. * Calculating the Ff entry:
  2128. *
  2129. * The Ff entry contains flags, that have to be set bitwise
  2130. * In the Following the number in the Comment is the BitPosition
  2131. */
  2132. var flags = options.Ff || 0;
  2133. // 17, Pushbutton
  2134. if (options.pushbutton) {
  2135. // Options.pushbutton should be 1 or 0
  2136. flags = AcroForm.internal.setBitPosition(flags, 17);
  2137. delete options.pushbutton;
  2138. }
  2139. //16, Radio
  2140. if (options.radio) {
  2141. //flags = options.Ff | options.radio << 15;
  2142. flags = AcroForm.internal.setBitPosition(flags, 16);
  2143. delete options.radio;
  2144. }
  2145. // 15, NoToggleToOff (Radio buttons only
  2146. if (options.noToggleToOff) {
  2147. //flags = options.Ff | options.noToggleToOff << 14;
  2148. flags = AcroForm.internal.setBitPosition(flags, 15);
  2149. //delete options.noToggleToOff;
  2150. }
  2151. // In case, there is no Flag set, it is a check-box
  2152. options.Ff = flags;
  2153. putForm.call(this, options);
  2154. };
  2155. var addTextField = function addTextField(options) {
  2156. var options = options || new AcroForm.Field();
  2157. options.FT = '/Tx';
  2158. /**
  2159. * Calculating the Ff entry:
  2160. *
  2161. * The Ff entry contains flags, that have to be set bitwise
  2162. * In the Following the number in the Comment is the BitPosition
  2163. */
  2164. var flags = options.Ff || 0;
  2165. // 13, multiline
  2166. if (options.multiline) {
  2167. // Set Flag
  2168. flags = flags | 1 << 12;
  2169. // Remove multiline from FieldObject
  2170. //delete options.multiline;
  2171. }
  2172. // 14, Password
  2173. if (options.password) {
  2174. flags = flags | 1 << 13;
  2175. //delete options.password;
  2176. }
  2177. // 21, FileSelect, PDF 1.4...
  2178. if (options.fileSelect) {
  2179. flags = flags | 1 << 20;
  2180. //delete options.fileSelect;
  2181. }
  2182. // 23, DoNotSpellCheck, PDF 1.4...
  2183. if (options.doNotSpellCheck) {
  2184. flags = flags | 1 << 22;
  2185. //delete options.doNotSpellCheck;
  2186. }
  2187. // 24, DoNotScroll, PDF 1.4...
  2188. if (options.doNotScroll) {
  2189. flags = flags | 1 << 23;
  2190. //delete options.doNotScroll;
  2191. }
  2192. options.Ff = options.Ff || flags;
  2193. // Add field
  2194. putForm.call(this, options);
  2195. };
  2196. var addChoiceField = function addChoiceField(opt) {
  2197. var options = opt || new AcroForm.Field();
  2198. options.FT = '/Ch';
  2199. /**
  2200. * Calculating the Ff entry:
  2201. *
  2202. * The Ff entry contains flags, that have to be set bitwise
  2203. * In the Following the number in the Comment is the BitPosition
  2204. */
  2205. var flags = options.Ff || 0;
  2206. // 18, Combo (If not set, the choiceField is a listBox!!)
  2207. if (options.combo) {
  2208. // Set Flag
  2209. flags = AcroForm.internal.setBitPosition(flags, 18);
  2210. // Remove combo from FieldObject
  2211. delete options.combo;
  2212. }
  2213. // 19, Edit
  2214. if (options.edit) {
  2215. flags = AcroForm.internal.setBitPosition(flags, 19);
  2216. delete options.edit;
  2217. }
  2218. // 20, Sort
  2219. if (options.sort) {
  2220. flags = AcroForm.internal.setBitPosition(flags, 20);
  2221. delete options.sort;
  2222. }
  2223. // 22, MultiSelect (PDF 1.4)
  2224. if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
  2225. flags = AcroForm.internal.setBitPosition(flags, 22);
  2226. delete options.multiSelect;
  2227. }
  2228. // 23, DoNotSpellCheck (PDF 1.4)
  2229. if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
  2230. flags = AcroForm.internal.setBitPosition(flags, 23);
  2231. delete options.doNotSpellCheck;
  2232. }
  2233. options.Ff = flags;
  2234. //options.hasAnnotation = true;
  2235. // Add field
  2236. putForm.call(this, options);
  2237. };
  2238. })(jsPDF.API);
  2239. var AcroForm = window.AcroForm;
  2240. AcroForm.internal = {};
  2241. AcroForm.createFormXObject = function (formObject) {
  2242. var xobj = new AcroForm.FormXObject();
  2243. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  2244. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  2245. xobj.BBox = [0, 0, width, height];
  2246. return xobj;
  2247. };
  2248. // Contains Methods for creating standard appearances
  2249. AcroForm.Appearance = {
  2250. CheckBox: {
  2251. createAppearanceStream: function createAppearanceStream() {
  2252. var appearance = {
  2253. N: {
  2254. On: AcroForm.Appearance.CheckBox.YesNormal
  2255. },
  2256. D: {
  2257. On: AcroForm.Appearance.CheckBox.YesPushDown,
  2258. Off: AcroForm.Appearance.CheckBox.OffPushDown
  2259. }
  2260. };
  2261. return appearance;
  2262. },
  2263. /**
  2264. * If any other icons are needed, the number between the brackets can be changed
  2265. * @returns {string}
  2266. */
  2267. createMK: function createMK() {
  2268. // 3-> Hook
  2269. return "<< /CA (3)>>";
  2270. },
  2271. /**
  2272. * Returns the standard On Appearance for a CheckBox
  2273. * @returns {AcroForm.FormXObject}
  2274. */
  2275. YesPushDown: function YesPushDown(formObject) {
  2276. var xobj = AcroForm.createFormXObject(formObject);
  2277. var stream = "";
  2278. // F13 is ZapfDingbats (Symbolic)
  2279. formObject.Q = 1; // set text-alignment as centered
  2280. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
  2281. stream += "0.749023 g\n\
  2282. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2283. f\n\
  2284. BMC\n\
  2285. q\n\
  2286. 0 0 1 rg\n\
  2287. /F13 " + calcRes.fontSize + " Tf 0 g\n\
  2288. BT\n";
  2289. stream += calcRes.text;
  2290. stream += "ET\n\
  2291. Q\n\
  2292. EMC\n";
  2293. xobj.stream = stream;
  2294. return xobj;
  2295. },
  2296. YesNormal: function YesNormal(formObject) {
  2297. var xobj = AcroForm.createFormXObject(formObject);
  2298. var stream = "";
  2299. formObject.Q = 1; // set text-alignment as centered
  2300. var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formObject) * 0.9);
  2301. stream += "1 g\n\
  2302. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2303. f\n\
  2304. q\n\
  2305. 0 0 1 rg\n\
  2306. 0 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
  2307. W\n\
  2308. n\n\
  2309. 0 g\n\
  2310. BT\n\
  2311. /F13 " + calcRes.fontSize + " Tf 0 g\n";
  2312. stream += calcRes.text;
  2313. stream += "ET\n\
  2314. Q\n";
  2315. xobj.stream = stream;
  2316. return xobj;
  2317. },
  2318. /**
  2319. * Returns the standard Off Appearance for a CheckBox
  2320. * @returns {AcroForm.FormXObject}
  2321. */
  2322. OffPushDown: function OffPushDown(formObject) {
  2323. var xobj = AcroForm.createFormXObject(formObject);
  2324. var stream = "";
  2325. stream += "0.749023 g\n\
  2326. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2327. f\n";
  2328. xobj.stream = stream;
  2329. return xobj;
  2330. }
  2331. },
  2332. RadioButton: {
  2333. Circle: {
  2334. createAppearanceStream: function createAppearanceStream(name) {
  2335. var appearanceStreamContent = {
  2336. D: {
  2337. 'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
  2338. },
  2339. N: {}
  2340. };
  2341. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
  2342. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
  2343. return appearanceStreamContent;
  2344. },
  2345. createMK: function createMK() {
  2346. return "<< /CA (l)>>";
  2347. },
  2348. YesNormal: function YesNormal(formObject) {
  2349. var xobj = AcroForm.createFormXObject(formObject);
  2350. var stream = "";
  2351. // Make the Radius of the Circle relative to min(height, width) of formObject
  2352. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2353. // The Borderpadding...
  2354. DotRadius *= 0.9;
  2355. var c = AcroForm.Appearance.internal.Bezier_C;
  2356. /*
  2357. The Following is a Circle created with Bezier-Curves.
  2358. */
  2359. stream += "q\n\
  2360. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2361. " + DotRadius + " 0 m\n\
  2362. " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2363. -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2364. -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2365. " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2366. f\n\
  2367. Q\n";
  2368. xobj.stream = stream;
  2369. return xobj;
  2370. },
  2371. YesPushDown: function YesPushDown(formObject) {
  2372. var xobj = AcroForm.createFormXObject(formObject);
  2373. var stream = "";
  2374. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2375. // The Borderpadding...
  2376. DotRadius *= 0.9;
  2377. // Save results for later use; no need to waste processor ticks on doing math
  2378. var k = DotRadius * 2;
  2379. // var c = AcroForm.Appearance.internal.Bezier_C;
  2380. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2381. var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
  2382. // stream += "0.749023 g\n\
  2383. // q\n\
  2384. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2385. // " + DotRadius * 2 + " 0 m\n\
  2386. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2387. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2388. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2389. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2390. // f\n\
  2391. // Q\n\
  2392. // 0 g\n\
  2393. // q\n\
  2394. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2395. // " + DotRadius + " 0 m\n\
  2396. // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2397. // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
  2398. // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2399. // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
  2400. // f\n\
  2401. // Q\n";
  2402. // FASTER VERSION with less processor ticks spent on math operations
  2403. stream += "0.749023 g\n\
  2404. q\n\
  2405. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2406. " + k + " 0 m\n\
  2407. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2408. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2409. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2410. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2411. f\n\
  2412. Q\n\
  2413. 0 g\n\
  2414. q\n\
  2415. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2416. " + DotRadius + " 0 m\n\
  2417. " + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
  2418. -" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
  2419. -" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
  2420. " + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
  2421. f\n\
  2422. Q\n";
  2423. xobj.stream = stream;
  2424. return xobj;
  2425. },
  2426. OffPushDown: function OffPushDown(formObject) {
  2427. var xobj = AcroForm.createFormXObject(formObject);
  2428. var stream = "";
  2429. var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
  2430. // The Borderpadding...
  2431. DotRadius *= 0.9;
  2432. // Save results for later use; no need to waste processor ticks on doing math
  2433. var k = DotRadius * 2;
  2434. // var c = AcroForm.Appearance.internal.Bezier_C;
  2435. var kc = k * AcroForm.Appearance.internal.Bezier_C;
  2436. // stream += "0.749023 g\n\
  2437. // q\n\
  2438. // 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2439. // " + DotRadius * 2 + " 0 m\n\
  2440. // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
  2441. // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
  2442. // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
  2443. // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
  2444. // f\n\
  2445. // Q\n";
  2446. // FASTER VERSION with less processor ticks spent on math operations
  2447. stream += "0.749023 g\n\
  2448. q\n\
  2449. 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
  2450. " + k + " 0 m\n\
  2451. " + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
  2452. -" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
  2453. -" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
  2454. " + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
  2455. f\n\
  2456. Q\n";
  2457. xobj.stream = stream;
  2458. return xobj;
  2459. }
  2460. },
  2461. Cross: {
  2462. /**
  2463. * Creates the Actual AppearanceDictionary-References
  2464. * @param name
  2465. * @returns
  2466. */
  2467. createAppearanceStream: function createAppearanceStream(name) {
  2468. var appearanceStreamContent = {
  2469. D: {
  2470. 'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
  2471. },
  2472. N: {}
  2473. };
  2474. appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
  2475. appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
  2476. return appearanceStreamContent;
  2477. },
  2478. createMK: function createMK() {
  2479. return "<< /CA (8)>>";
  2480. },
  2481. YesNormal: function YesNormal(formObject) {
  2482. var xobj = AcroForm.createFormXObject(formObject);
  2483. var stream = "";
  2484. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2485. stream += "q\n\
  2486. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2487. W\n\
  2488. n\n\
  2489. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2490. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2491. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2492. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2493. s\n\
  2494. Q\n";
  2495. xobj.stream = stream;
  2496. return xobj;
  2497. },
  2498. YesPushDown: function YesPushDown(formObject) {
  2499. var xobj = AcroForm.createFormXObject(formObject);
  2500. var cross = AcroForm.Appearance.internal.calculateCross(formObject);
  2501. var stream = "";
  2502. stream += "0.749023 g\n\
  2503. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2504. f\n\
  2505. q\n\
  2506. 1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
  2507. W\n\
  2508. n\n\
  2509. " + cross.x1.x + " " + cross.x1.y + " m\n\
  2510. " + cross.x2.x + " " + cross.x2.y + " l\n\
  2511. " + cross.x4.x + " " + cross.x4.y + " m\n\
  2512. " + cross.x3.x + " " + cross.x3.y + " l\n\
  2513. s\n\
  2514. Q\n";
  2515. xobj.stream = stream;
  2516. return xobj;
  2517. },
  2518. OffPushDown: function OffPushDown(formObject) {
  2519. var xobj = AcroForm.createFormXObject(formObject);
  2520. var stream = "";
  2521. stream += "0.749023 g\n\
  2522. 0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
  2523. f\n";
  2524. xobj.stream = stream;
  2525. return xobj;
  2526. }
  2527. }
  2528. },
  2529. /**
  2530. * Returns the standard Appearance
  2531. * @returns {AcroForm.FormXObject}
  2532. */
  2533. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  2534. var stream = "";
  2535. // Set Helvetica to Standard Font (size: auto)
  2536. // Color: Black
  2537. stream += "/Helv 0 Tf 0 g";
  2538. return stream;
  2539. }
  2540. };
  2541. AcroForm.Appearance.internal = {
  2542. Bezier_C: 0.551915024494,
  2543. calculateCross: function calculateCross(formObject) {
  2544. var min = function min(x, y) {
  2545. return x > y ? y : x;
  2546. };
  2547. var width = AcroForm.Appearance.internal.getWidth(formObject);
  2548. var height = AcroForm.Appearance.internal.getHeight(formObject);
  2549. var a = min(width, height);
  2550. var crossSize = a;
  2551. var borderPadding = 2; // The Padding in px
  2552. var cross = {
  2553. x1: { // upperLeft
  2554. x: (width - a) / 2,
  2555. y: (height - a) / 2 + a },
  2556. x2: { // lowerRight
  2557. x: (width - a) / 2 + a,
  2558. y: (height - a) / 2 //borderPadding
  2559. },
  2560. x3: { // lowerLeft
  2561. x: (width - a) / 2,
  2562. y: (height - a) / 2 //borderPadding
  2563. },
  2564. x4: { // upperRight
  2565. x: (width - a) / 2 + a,
  2566. y: (height - a) / 2 + a }
  2567. };
  2568. return cross;
  2569. }
  2570. };
  2571. AcroForm.Appearance.internal.getWidth = function (formObject) {
  2572. return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
  2573. };
  2574. AcroForm.Appearance.internal.getHeight = function (formObject) {
  2575. return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
  2576. };
  2577. // ##########################
  2578. //### For inheritance:
  2579. AcroForm.internal.inherit = function (child, parent) {
  2580. var ObjectCreate = Object.create || function (o) {
  2581. var F = function F() {};
  2582. F.prototype = o;
  2583. return new F();
  2584. };
  2585. child.prototype = Object.create(parent.prototype);
  2586. child.prototype.constructor = child;
  2587. };
  2588. // ### Handy Functions:
  2589. AcroForm.internal.arrayToPdfArray = function (array) {
  2590. if (Array.isArray(array)) {
  2591. var content = ' [';
  2592. for (var i in array) {
  2593. var element = array[i].toString();
  2594. content += element;
  2595. content += i < array.length - 1 ? ' ' : '';
  2596. }
  2597. content += ']';
  2598. return content;
  2599. }
  2600. };
  2601. AcroForm.internal.toPdfString = function (string) {
  2602. string = string || "";
  2603. // put Bracket at the Beginning of the String
  2604. if (string.indexOf('(') !== 0) {
  2605. string = '(' + string;
  2606. }
  2607. if (string.substring(string.length - 1) != ')') {
  2608. string += '(';
  2609. }
  2610. return string;
  2611. };
  2612. // ##########################
  2613. // Classes
  2614. // ##########################
  2615. AcroForm.PDFObject = function () {
  2616. // The Object ID in the PDF Object Model
  2617. // todo
  2618. var _objId;
  2619. Object.defineProperty(this, 'objId', {
  2620. get: function get() {
  2621. if (!_objId) {
  2622. if (this.internal) {
  2623. _objId = this.internal.newObjectDeferred();
  2624. } else if (jsPDF.API.acroformPlugin.internal) {
  2625. // todo - find better option, that doesn't rely on a Global Static var
  2626. _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
  2627. }
  2628. }
  2629. if (!_objId) {
  2630. console.log("Couldn't create Object ID");
  2631. }
  2632. return _objId;
  2633. },
  2634. configurable: false
  2635. });
  2636. };
  2637. AcroForm.PDFObject.prototype.toString = function () {
  2638. return this.objId + " 0 R";
  2639. };
  2640. AcroForm.PDFObject.prototype.getString = function () {
  2641. var res = this.objId + " 0 obj\n<<";
  2642. var content = this.getContent();
  2643. res += content + ">>\n";
  2644. if (this.stream) {
  2645. res += "stream\n";
  2646. res += this.stream;
  2647. res += "endstream\n";
  2648. }
  2649. res += "endobj\n";
  2650. return res;
  2651. };
  2652. AcroForm.PDFObject.prototype.getContent = function () {
  2653. /**
  2654. * Prints out all enumerable Variables from the Object
  2655. * @param fieldObject
  2656. * @returns {string}
  2657. */
  2658. var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
  2659. var content = '';
  2660. var keys = Object.keys(fieldObject).filter(function (key) {
  2661. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  2662. });
  2663. for (var i in keys) {
  2664. var key = keys[i];
  2665. var value = fieldObject[key];
  2666. /*if (key == 'Rect' && value) {
  2667. value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
  2668. }*/
  2669. if (value) {
  2670. if (Array.isArray(value)) {
  2671. content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
  2672. } else if (value instanceof AcroForm.PDFObject) {
  2673. // In case it is a reference to another PDFObject, take the referennce number
  2674. content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
  2675. } else {
  2676. content += '/' + key + ' ' + value + '\n';
  2677. }
  2678. }
  2679. }
  2680. return content;
  2681. };
  2682. var object = "";
  2683. object += createContentFromFieldObject(this);
  2684. return object;
  2685. };
  2686. AcroForm.FormXObject = function () {
  2687. AcroForm.PDFObject.call(this);
  2688. this.Type = "/XObject";
  2689. this.Subtype = "/Form";
  2690. this.FormType = 1;
  2691. this.BBox;
  2692. this.Matrix;
  2693. this.Resources = "2 0 R";
  2694. this.PieceInfo;
  2695. var _stream;
  2696. Object.defineProperty(this, 'Length', {
  2697. enumerable: true,
  2698. get: function get() {
  2699. return _stream !== undefined ? _stream.length : 0;
  2700. }
  2701. });
  2702. Object.defineProperty(this, 'stream', {
  2703. enumerable: false,
  2704. set: function set(val) {
  2705. _stream = val;
  2706. },
  2707. get: function get() {
  2708. if (_stream) {
  2709. return _stream;
  2710. } else {
  2711. return null;
  2712. }
  2713. }
  2714. });
  2715. };
  2716. AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
  2717. AcroForm.AcroFormDictionary = function () {
  2718. AcroForm.PDFObject.call(this);
  2719. var _Kids = [];
  2720. Object.defineProperty(this, 'Kids', {
  2721. enumerable: false,
  2722. configurable: true,
  2723. get: function get() {
  2724. if (_Kids.length > 0) {
  2725. return _Kids;
  2726. } else {
  2727. return;
  2728. }
  2729. }
  2730. });
  2731. Object.defineProperty(this, 'Fields', {
  2732. enumerable: true,
  2733. configurable: true,
  2734. get: function get() {
  2735. return _Kids;
  2736. }
  2737. });
  2738. // Default Appearance
  2739. this.DA;
  2740. };
  2741. AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
  2742. // ##### The Objects, the User can Create:
  2743. // The Field Object contains the Variables, that every Field needs
  2744. // Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
  2745. AcroForm.Field = function () {
  2746. 'use strict';
  2747. AcroForm.PDFObject.call(this);
  2748. var _Rect;
  2749. Object.defineProperty(this, 'Rect', {
  2750. enumerable: true,
  2751. configurable: false,
  2752. get: function get() {
  2753. if (!_Rect) {
  2754. return;
  2755. }
  2756. var tmp = _Rect;
  2757. //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
  2758. return tmp;
  2759. },
  2760. set: function set(val) {
  2761. _Rect = val;
  2762. }
  2763. });
  2764. var _FT = "";
  2765. Object.defineProperty(this, 'FT', {
  2766. enumerable: true,
  2767. set: function set(val) {
  2768. _FT = val;
  2769. },
  2770. get: function get() {
  2771. return _FT;
  2772. }
  2773. });
  2774. /**
  2775. * The Partial name of the Field Object.
  2776. * It has to be unique.
  2777. */
  2778. var _T;
  2779. Object.defineProperty(this, 'T', {
  2780. enumerable: true,
  2781. configurable: false,
  2782. set: function set(val) {
  2783. _T = val;
  2784. },
  2785. get: function get() {
  2786. if (!_T || _T.length < 1) {
  2787. if (this instanceof AcroForm.ChildClass) {
  2788. // In case of a Child from a Radio´Group, you don't need a FieldName!!!
  2789. return;
  2790. }
  2791. return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
  2792. }
  2793. if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
  2794. return _T;
  2795. }
  2796. return "(" + _T + ")";
  2797. }
  2798. });
  2799. var _DA;
  2800. // Defines the default appearance (Needed for variable Text)
  2801. Object.defineProperty(this, 'DA', {
  2802. enumerable: true,
  2803. get: function get() {
  2804. if (!_DA) {
  2805. return;
  2806. }
  2807. return '(' + _DA + ')';
  2808. },
  2809. set: function set(val) {
  2810. _DA = val;
  2811. }
  2812. });
  2813. var _DV;
  2814. // Defines the default value
  2815. Object.defineProperty(this, 'DV', {
  2816. enumerable: true,
  2817. configurable: true,
  2818. get: function get() {
  2819. if (!_DV) {
  2820. return;
  2821. }
  2822. return _DV;
  2823. },
  2824. set: function set(val) {
  2825. _DV = val;
  2826. }
  2827. });
  2828. //this.Type = "/Annot";
  2829. //this.Subtype = "/Widget";
  2830. Object.defineProperty(this, 'Type', {
  2831. enumerable: true,
  2832. get: function get() {
  2833. return this.hasAnnotation ? "/Annot" : null;
  2834. }
  2835. });
  2836. Object.defineProperty(this, 'Subtype', {
  2837. enumerable: true,
  2838. get: function get() {
  2839. return this.hasAnnotation ? "/Widget" : null;
  2840. }
  2841. });
  2842. /**
  2843. *
  2844. * @type {Array}
  2845. */
  2846. this.BG;
  2847. Object.defineProperty(this, 'hasAnnotation', {
  2848. enumerable: false,
  2849. get: function get() {
  2850. if (this.Rect || this.BC || this.BG) {
  2851. return true;
  2852. }
  2853. return false;
  2854. }
  2855. });
  2856. Object.defineProperty(this, 'hasAppearanceStream', {
  2857. enumerable: false,
  2858. configurable: true,
  2859. writable: true
  2860. });
  2861. Object.defineProperty(this, 'page', {
  2862. enumerable: false,
  2863. configurable: true,
  2864. writable: true
  2865. });
  2866. };
  2867. AcroForm.Field.FieldNum = 0;
  2868. AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
  2869. AcroForm.ChoiceField = function () {
  2870. AcroForm.Field.call(this);
  2871. // Field Type = Choice Field
  2872. this.FT = "/Ch";
  2873. // options
  2874. this.Opt = [];
  2875. this.V = '()';
  2876. // Top Index
  2877. this.TI = 0;
  2878. /**
  2879. * Defines, whether the
  2880. * @type {boolean}
  2881. */
  2882. this.combo = false;
  2883. /**
  2884. * Defines, whether the Choice Field is an Edit Field.
  2885. * An Edit Field is automatically an Combo Field.
  2886. */
  2887. Object.defineProperty(this, 'edit', {
  2888. enumerable: true,
  2889. set: function set(val) {
  2890. if (val == true) {
  2891. this._edit = true;
  2892. // ComboBox has to be true
  2893. this.combo = true;
  2894. } else {
  2895. this._edit = false;
  2896. }
  2897. },
  2898. get: function get() {
  2899. if (!this._edit) {
  2900. return false;
  2901. }
  2902. return this._edit;
  2903. },
  2904. configurable: false
  2905. });
  2906. this.hasAppearanceStream = true;
  2907. Object.defineProperty(this, 'V', {
  2908. get: function get() {
  2909. AcroForm.internal.toPdfString();
  2910. }
  2911. });
  2912. };
  2913. AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
  2914. window["ChoiceField"] = AcroForm.ChoiceField;
  2915. AcroForm.ListBox = function () {
  2916. AcroForm.ChoiceField.call(this);
  2917. //var combo = true;
  2918. };
  2919. AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
  2920. window["ListBox"] = AcroForm.ListBox;
  2921. AcroForm.ComboBox = function () {
  2922. AcroForm.ListBox.call(this);
  2923. this.combo = true;
  2924. };
  2925. AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
  2926. window["ComboBox"] = AcroForm.ComboBox;
  2927. AcroForm.EditBox = function () {
  2928. AcroForm.ComboBox.call(this);
  2929. this.edit = true;
  2930. };
  2931. AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
  2932. window["EditBox"] = AcroForm.EditBox;
  2933. AcroForm.Button = function () {
  2934. AcroForm.Field.call(this);
  2935. this.FT = "/Btn";
  2936. //this.hasAnnotation = true;
  2937. };
  2938. AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
  2939. window["Button"] = AcroForm.Button;
  2940. AcroForm.PushButton = function () {
  2941. AcroForm.Button.call(this);
  2942. this.pushbutton = true;
  2943. };
  2944. AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
  2945. window["PushButton"] = AcroForm.PushButton;
  2946. AcroForm.RadioButton = function () {
  2947. AcroForm.Button.call(this);
  2948. this.radio = true;
  2949. var _Kids = [];
  2950. Object.defineProperty(this, 'Kids', {
  2951. enumerable: true,
  2952. get: function get() {
  2953. if (_Kids.length > 0) {
  2954. return _Kids;
  2955. }
  2956. }
  2957. });
  2958. Object.defineProperty(this, '__Kids', {
  2959. get: function get() {
  2960. return _Kids;
  2961. }
  2962. });
  2963. var _noToggleToOff;
  2964. Object.defineProperty(this, 'noToggleToOff', {
  2965. enumerable: false,
  2966. get: function get() {
  2967. return _noToggleToOff;
  2968. },
  2969. set: function set(val) {
  2970. _noToggleToOff = val;
  2971. }
  2972. });
  2973. //this.hasAnnotation = false;
  2974. };
  2975. AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
  2976. window["RadioButton"] = AcroForm.RadioButton;
  2977. /*
  2978. * The Child classs of a RadioButton (the radioGroup)
  2979. * -> The single Buttons
  2980. */
  2981. AcroForm.ChildClass = function (parent, name) {
  2982. AcroForm.Field.call(this);
  2983. this.Parent = parent;
  2984. // todo: set AppearanceType as variable that can be set from the outside...
  2985. this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
  2986. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  2987. // Set Print in the Annot Flag
  2988. this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
  2989. // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
  2990. this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
  2991. // Default Appearance is Off
  2992. this.AS = "/Off"; // + name;
  2993. this._Name = name;
  2994. };
  2995. AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
  2996. AcroForm.RadioButton.prototype.setAppearance = function (appearance) {
  2997. if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
  2998. console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  2999. return;
  3000. }
  3001. for (var i in this.__Kids) {
  3002. var child = this.__Kids[i];
  3003. child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
  3004. child.MK = appearance.createMK();
  3005. }
  3006. };
  3007. AcroForm.RadioButton.prototype.createOption = function (name) {
  3008. var parent = this;
  3009. var kidCount = this.__Kids.length;
  3010. // Create new Child for RadioGroup
  3011. var child = new AcroForm.ChildClass(parent, name);
  3012. // Add to Parent
  3013. this.__Kids.push(child);
  3014. jsPDF.API.addField(child);
  3015. return child;
  3016. };
  3017. AcroForm.CheckBox = function () {
  3018. Button.call(this);
  3019. this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
  3020. this.MK = AcroForm.Appearance.CheckBox.createMK();
  3021. this.AS = "/On";
  3022. this.V = "/On";
  3023. };
  3024. AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
  3025. window["CheckBox"] = AcroForm.CheckBox;
  3026. AcroForm.TextField = function () {
  3027. AcroForm.Field.call(this);
  3028. this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
  3029. this.F = 4;
  3030. var _V;
  3031. Object.defineProperty(this, 'V', {
  3032. get: function get() {
  3033. if (_V) {
  3034. return "(" + _V + ")";
  3035. } else {
  3036. return _V;
  3037. }
  3038. },
  3039. enumerable: true,
  3040. set: function set(val) {
  3041. _V = val;
  3042. }
  3043. });
  3044. var _DV;
  3045. Object.defineProperty(this, 'DV', {
  3046. get: function get() {
  3047. if (_DV) {
  3048. return "(" + _DV + ")";
  3049. } else {
  3050. return _DV;
  3051. }
  3052. },
  3053. enumerable: true,
  3054. set: function set(val) {
  3055. _DV = val;
  3056. }
  3057. });
  3058. var _multiline = false;
  3059. Object.defineProperty(this, 'multiline', {
  3060. enumerable: false,
  3061. get: function get() {
  3062. return _multiline;
  3063. },
  3064. set: function set(val) {
  3065. _multiline = val;
  3066. }
  3067. });
  3068. //this.multiline = false;
  3069. //this.password = false;
  3070. /**
  3071. * For PDF 1.4
  3072. * @type {boolean}
  3073. */
  3074. //this.fileSelect = false;
  3075. /**
  3076. * For PDF 1.4
  3077. * @type {boolean}
  3078. */
  3079. //this.doNotSpellCheck = false;
  3080. /**
  3081. * For PDF 1.4
  3082. * @type {boolean}
  3083. */
  3084. //this.doNotScroll = false;
  3085. var _MaxLen = false;
  3086. Object.defineProperty(this, 'MaxLen', {
  3087. enumerable: true,
  3088. get: function get() {
  3089. return _MaxLen;
  3090. },
  3091. set: function set(val) {
  3092. _MaxLen = val;
  3093. }
  3094. });
  3095. Object.defineProperty(this, 'hasAppearanceStream', {
  3096. enumerable: false,
  3097. get: function get() {
  3098. return this.V || this.DV;
  3099. }
  3100. });
  3101. };
  3102. AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
  3103. window["TextField"] = AcroForm.TextField;
  3104. AcroForm.PasswordField = function () {
  3105. TextField.call(this);
  3106. Object.defineProperty(this, 'password', {
  3107. value: true,
  3108. enumerable: false,
  3109. configurable: false,
  3110. writable: false
  3111. });
  3112. };
  3113. AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
  3114. window["PasswordField"] = AcroForm.PasswordField;
  3115. // ############ internal functions
  3116. /*
  3117. * small workaround for calculating the TextMetric approximately
  3118. * @param text
  3119. * @param fontsize
  3120. * @returns {TextMetrics} (Has Height and Width)
  3121. */
  3122. AcroForm.internal.calculateFontSpace = function (text, fontsize, fonttype) {
  3123. var fonttype = fonttype || "helvetica";
  3124. //re-use canvas object for speed improvements
  3125. var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
  3126. var context = canvas.getContext('2d');
  3127. context.save();
  3128. var newFont = fontsize + " " + fonttype;
  3129. context.font = newFont;
  3130. var res = context.measureText(text);
  3131. context.fontcolor = 'black';
  3132. // Calculate height:
  3133. var context = canvas.getContext('2d');
  3134. res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
  3135. context.restore();
  3136. var width = res.width;
  3137. return res;
  3138. };
  3139. AcroForm.internal.calculateX = function (formObject, text, font, maxFontSize) {
  3140. var maxFontSize = maxFontSize || 12;
  3141. var font = font || "helvetica";
  3142. var returnValue = {
  3143. text: "",
  3144. fontSize: ""
  3145. };
  3146. // Remove Brackets
  3147. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  3148. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
  3149. // split into array of words
  3150. var textSplit = text.split(' ');
  3151. /**
  3152. * the color could be ((alpha)||(r,g,b)||(c,m,y,k))
  3153. * @type {string}
  3154. */
  3155. var color = "0 g\n";
  3156. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3157. var lineSpacing = 2;
  3158. var borderPadding = 2;
  3159. var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
  3160. height = height < 0 ? -height : height;
  3161. var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
  3162. width = width < 0 ? -width : width;
  3163. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3164. if (i + 1 < textSplit.length) {
  3165. var tmp = lastLine + " " + textSplit[i + 1];
  3166. var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
  3167. var FieldWidth = width - 2 * borderPadding;
  3168. return TextWidth <= FieldWidth;
  3169. } else {
  3170. return false;
  3171. }
  3172. };
  3173. fontSize++;
  3174. FontSize: while (true) {
  3175. var text = "";
  3176. fontSize--;
  3177. var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
  3178. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3179. startY += lineSpacing;
  3180. var startX = -borderPadding;
  3181. var lastX = startX,
  3182. lastY = startY;
  3183. var firstWordInLine = 0,
  3184. lastWordInLine = 0;
  3185. var lastLength = 0;
  3186. var y = 0;
  3187. if (fontSize == 0) {
  3188. // In case, the Text doesn't fit at all
  3189. fontSize = 12;
  3190. text = "(...) Tj\n";
  3191. text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
  3192. break;
  3193. }
  3194. lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
  3195. var lastLine = "";
  3196. var lineCount = 0;
  3197. Line: for (var i in textSplit) {
  3198. lastLine += textSplit[i] + " ";
  3199. // Remove last blank
  3200. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3201. var key = parseInt(i);
  3202. lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
  3203. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3204. var isLastWord = i >= textSplit.length - 1;
  3205. if (nextLineIsSmaller && !isLastWord) {
  3206. lastLine += " ";
  3207. continue; // Line
  3208. } else if (!nextLineIsSmaller && !isLastWord) {
  3209. if (!formObject.multiline) {
  3210. continue FontSize;
  3211. } else {
  3212. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3213. // If the Text is higher than the FieldObject
  3214. continue FontSize;
  3215. }
  3216. lastWordInLine = key;
  3217. // go on
  3218. }
  3219. } else if (isLastWord) {
  3220. lastWordInLine = key;
  3221. } else {
  3222. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3223. // If the Text is higher than the FieldObject
  3224. continue FontSize;
  3225. }
  3226. }
  3227. var line = '';
  3228. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3229. line += textSplit[x] + ' ';
  3230. }
  3231. // Remove last blank
  3232. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
  3233. //lastLength -= blankSpace.width;
  3234. lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
  3235. // Calculate startX
  3236. switch (formObject.Q) {
  3237. case 2:
  3238. // Right justified
  3239. startX = width - lastLength - borderPadding;
  3240. break;
  3241. case 1:
  3242. // Q = 1 := Text-Alignment: Center
  3243. startX = (width - lastLength) / 2;
  3244. break;
  3245. case 0:
  3246. default:
  3247. startX = borderPadding;
  3248. break;
  3249. }
  3250. text += startX + ' ' + lastY + ' Td\n';
  3251. text += '(' + line + ') Tj\n';
  3252. // reset X in PDF
  3253. text += -startX + ' 0 Td\n';
  3254. // After a Line, adjust y position
  3255. lastY = -(fontSize + lineSpacing);
  3256. lastX = startX;
  3257. // Reset for next iteration step
  3258. lastLength = 0;
  3259. firstWordInLine = lastWordInLine + 1;
  3260. lineCount++;
  3261. lastLine = "";
  3262. continue Line;
  3263. }
  3264. break;
  3265. }
  3266. returnValue.text = text;
  3267. returnValue.fontSize = fontSize;
  3268. return returnValue;
  3269. };
  3270. AcroForm.internal.calculateAppearanceStream = function (formObject) {
  3271. if (formObject.appearanceStreamContent) {
  3272. // If appearanceStream is already set, use it
  3273. return formObject.appearanceStreamContent;
  3274. }
  3275. if (!formObject.V && !formObject.DV) {
  3276. return;
  3277. }
  3278. // else calculate it
  3279. var stream = '';
  3280. var text = formObject.V || formObject.DV;
  3281. var calcRes = AcroForm.internal.calculateX(formObject, text);
  3282. stream += '/Tx BMC\n' + 'q\n' +
  3283. //color + '\n' +
  3284. '/F1 ' + calcRes.fontSize + ' Tf\n' +
  3285. // Text Matrix
  3286. '1 0 0 1 0 0 Tm\n';
  3287. // Begin Text
  3288. stream += 'BT\n';
  3289. stream += calcRes.text;
  3290. // End Text
  3291. stream += 'ET\n';
  3292. stream += 'Q\n' + 'EMC\n';
  3293. var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
  3294. appearanceStreamContent.stream = stream;
  3295. var appearance = {
  3296. N: {
  3297. 'Normal': appearanceStreamContent
  3298. }
  3299. };
  3300. return appearanceStreamContent;
  3301. };
  3302. /*
  3303. * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
  3304. * @param x
  3305. * @param y
  3306. * @param w
  3307. * @param h
  3308. * @returns {*[]}
  3309. */
  3310. AcroForm.internal.calculateCoordinates = function (x, y, w, h) {
  3311. var coordinates = {};
  3312. if (this.internal) {
  3313. var mmtopx = function mmtopx(x) {
  3314. return x * this.internal.scaleFactor;
  3315. };
  3316. if (Array.isArray(x)) {
  3317. x[0] = AcroForm.scale(x[0]);
  3318. x[1] = AcroForm.scale(x[1]);
  3319. x[2] = AcroForm.scale(x[2]);
  3320. x[3] = AcroForm.scale(x[3]);
  3321. coordinates.lowerLeft_X = x[0] || 0;
  3322. coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
  3323. coordinates.upperRight_X = x[0] + x[2] || 0;
  3324. coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
  3325. } else {
  3326. x = AcroForm.scale(x);
  3327. y = AcroForm.scale(y);
  3328. w = AcroForm.scale(w);
  3329. h = AcroForm.scale(h);
  3330. coordinates.lowerLeft_X = x || 0;
  3331. coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
  3332. coordinates.upperRight_X = x + w || 0;
  3333. coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
  3334. }
  3335. } else {
  3336. // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
  3337. if (Array.isArray(x)) {
  3338. coordinates.lowerLeft_X = x[0] || 0;
  3339. coordinates.lowerLeft_Y = x[1] || 0;
  3340. coordinates.upperRight_X = x[0] + x[2] || 0;
  3341. coordinates.upperRight_Y = x[1] + x[3] || 0;
  3342. } else {
  3343. coordinates.lowerLeft_X = x || 0;
  3344. coordinates.lowerLeft_Y = y || 0;
  3345. coordinates.upperRight_X = x + w || 0;
  3346. coordinates.upperRight_Y = y + h || 0;
  3347. }
  3348. }
  3349. return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
  3350. };
  3351. AcroForm.internal.calculateColor = function (r, g, b) {
  3352. var color = new Array(3);
  3353. color.r = r | 0;
  3354. color.g = g | 0;
  3355. color.b = b | 0;
  3356. return color;
  3357. };
  3358. AcroForm.internal.getBitPosition = function (variable, position) {
  3359. variable = variable || 0;
  3360. var bitMask = 1;
  3361. bitMask = bitMask << position - 1;
  3362. return variable | bitMask;
  3363. };
  3364. AcroForm.internal.setBitPosition = function (variable, position, value) {
  3365. variable = variable || 0;
  3366. value = value || 1;
  3367. var bitMask = 1;
  3368. bitMask = bitMask << position - 1;
  3369. if (value == 1) {
  3370. // Set the Bit to 1
  3371. var variable = variable | bitMask;
  3372. } else {
  3373. // Set the Bit to 0
  3374. var variable = variable & ~bitMask;
  3375. }
  3376. return variable;
  3377. };
  3378. /**
  3379. * jsPDF addHTML PlugIn
  3380. * Copyright (c) 2014 Diego Casorran
  3381. *
  3382. * Licensed under the MIT License.
  3383. * http://opensource.org/licenses/mit-license
  3384. */
  3385. (function (jsPDFAPI) {
  3386. 'use strict';
  3387. /**
  3388. * Renders an HTML element to canvas object which added to the PDF
  3389. *
  3390. * This PlugIn requires html2canvas: https://github.com/niklasvh/html2canvas
  3391. * OR rasterizeHTML: https://github.com/cburgmer/rasterizeHTML.js
  3392. *
  3393. * @public
  3394. * @function
  3395. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  3396. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  3397. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  3398. * @param options {Object} Additional options, check the code below.
  3399. * @param callback {Function} to call when the rendering has finished.
  3400. *
  3401. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  3402. * case the image is positioned at 0x0 covering the whole PDF document
  3403. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  3404. */
  3405. jsPDFAPI.addHTML = function (element, x, y, options, callback) {
  3406. 'use strict';
  3407. 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');
  3408. if (typeof x !== 'number') {
  3409. options = x;
  3410. callback = y;
  3411. }
  3412. if (typeof options === 'function') {
  3413. callback = options;
  3414. options = null;
  3415. }
  3416. var I = this.internal,
  3417. K = I.scaleFactor,
  3418. W = I.pageSize.width,
  3419. H = I.pageSize.height;
  3420. options = options || {};
  3421. options.onrendered = function (obj) {
  3422. x = parseInt(x) || 0;
  3423. y = parseInt(y) || 0;
  3424. var dim = options.dim || {};
  3425. var h = dim.h || 0;
  3426. var w = dim.w || Math.min(W, obj.width / K) - x;
  3427. var format = 'JPEG';
  3428. if (options.format) format = options.format;
  3429. if (obj.height > H && options.pagesplit) {
  3430. var crop = function () {
  3431. var cy = 0;
  3432. while (1) {
  3433. var canvas = document.createElement('canvas');
  3434. canvas.width = Math.min(W * K, obj.width);
  3435. canvas.height = Math.min(H * K, obj.height - cy);
  3436. var ctx = canvas.getContext('2d');
  3437. ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
  3438. var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
  3439. this.addImage.apply(this, args);
  3440. cy += canvas.height;
  3441. if (cy >= obj.height) break;
  3442. this.addPage();
  3443. }
  3444. callback(w, cy, null, args);
  3445. }.bind(this);
  3446. if (obj.nodeName === 'CANVAS') {
  3447. var img = new Image();
  3448. img.onload = crop;
  3449. img.src = obj.toDataURL("image/png");
  3450. obj = img;
  3451. } else {
  3452. crop();
  3453. }
  3454. } else {
  3455. var alias = Math.random().toString(35);
  3456. var args = [obj, x, y, w, h, format, alias, 'SLOW'];
  3457. this.addImage.apply(this, args);
  3458. callback(w, h, alias, args);
  3459. }
  3460. }.bind(this);
  3461. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  3462. return html2canvas(element, options);
  3463. }
  3464. if (typeof rasterizeHTML !== 'undefined') {
  3465. var meth = 'drawDocument';
  3466. if (typeof element === 'string') {
  3467. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  3468. }
  3469. options.width = options.width || W * K;
  3470. return rasterizeHTML[meth](element, void 0, options).then(function (r) {
  3471. options.onrendered(r.image);
  3472. }, function (e) {
  3473. callback(null, e);
  3474. });
  3475. }
  3476. return null;
  3477. };
  3478. })(jsPDF.API);
  3479. /** @preserve
  3480. * jsPDF addImage plugin
  3481. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  3482. * 2013 Chris Dowling, https://github.com/gingerchris
  3483. * 2013 Trinh Ho, https://github.com/ineedfat
  3484. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  3485. * 2013 Norah Smith, https://github.com/burnburnrocket
  3486. * 2014 Diego Casorran, https://github.com/diegocr
  3487. * 2014 James Robb, https://github.com/jamesbrobb
  3488. *
  3489. *
  3490. */
  3491. ;(function (jsPDFAPI) {
  3492. 'use strict';
  3493. var namespace = 'addImage_',
  3494. supported_image_types = ['jpeg', 'jpg', 'png'];
  3495. // Image functionality ported from pdf.js
  3496. var putImage = function putImage(img) {
  3497. var objectNumber = this.internal.newObject(),
  3498. out = this.internal.write,
  3499. putStream = this.internal.putStream;
  3500. img['n'] = objectNumber;
  3501. out('<</Type /XObject');
  3502. out('/Subtype /Image');
  3503. out('/Width ' + img['w']);
  3504. out('/Height ' + img['h']);
  3505. if (img['cs'] === this.color_spaces.INDEXED) {
  3506. out('/ColorSpace [/Indexed /DeviceRGB '
  3507. // if an indexed png defines more than one colour with transparency, we've created a smask
  3508. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
  3509. } else {
  3510. out('/ColorSpace /' + img['cs']);
  3511. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  3512. out('/Decode [1 0 1 0 1 0 1 0]');
  3513. }
  3514. }
  3515. out('/BitsPerComponent ' + img['bpc']);
  3516. if ('f' in img) {
  3517. out('/Filter /' + img['f']);
  3518. }
  3519. if ('dp' in img) {
  3520. out('/DecodeParms <<' + img['dp'] + '>>');
  3521. }
  3522. if ('trns' in img && img['trns'].constructor == Array) {
  3523. var trns = '',
  3524. i = 0,
  3525. len = img['trns'].length;
  3526. for (; i < len; i++) {
  3527. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  3528. }out('/Mask [' + trns + ']');
  3529. }
  3530. if ('smask' in img) {
  3531. out('/SMask ' + (objectNumber + 1) + ' 0 R');
  3532. }
  3533. out('/Length ' + img['data'].length + '>>');
  3534. putStream(img['data']);
  3535. out('endobj');
  3536. // Soft mask
  3537. if ('smask' in img) {
  3538. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  3539. var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
  3540. if ('f' in img) smask.f = img['f'];
  3541. putImage.call(this, smask);
  3542. }
  3543. //Palette
  3544. if (img['cs'] === this.color_spaces.INDEXED) {
  3545. this.internal.newObject();
  3546. //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  3547. //putStream(zlib.compress(img['pal']));
  3548. out('<< /Length ' + img['pal'].length + '>>');
  3549. putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
  3550. out('endobj');
  3551. }
  3552. },
  3553. putResourcesCallback = function putResourcesCallback() {
  3554. var images = this.internal.collections[namespace + 'images'];
  3555. for (var i in images) {
  3556. putImage.call(this, images[i]);
  3557. }
  3558. },
  3559. putXObjectsDictCallback = function putXObjectsDictCallback() {
  3560. var images = this.internal.collections[namespace + 'images'],
  3561. out = this.internal.write,
  3562. image;
  3563. for (var i in images) {
  3564. image = images[i];
  3565. out('/I' + image['i'], image['n'], '0', 'R');
  3566. }
  3567. },
  3568. checkCompressValue = function checkCompressValue(value) {
  3569. if (value && typeof value === 'string') value = value.toUpperCase();
  3570. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  3571. },
  3572. getImages = function getImages() {
  3573. var images = this.internal.collections[namespace + 'images'];
  3574. //first run, so initialise stuff
  3575. if (!images) {
  3576. this.internal.collections[namespace + 'images'] = images = {};
  3577. this.internal.events.subscribe('putResources', putResourcesCallback);
  3578. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  3579. }
  3580. return images;
  3581. },
  3582. getImageIndex = function getImageIndex(images) {
  3583. var imageIndex = 0;
  3584. if (images) {
  3585. // this is NOT the first time this method is ran on this instance of jsPDF object.
  3586. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  3587. var i = 0;
  3588. for (var e in o) {
  3589. if (o.hasOwnProperty(e)) {
  3590. i++;
  3591. }
  3592. }
  3593. return i;
  3594. }(images);
  3595. }
  3596. return imageIndex;
  3597. },
  3598. notDefined = function notDefined(value) {
  3599. return typeof value === 'undefined' || value === null;
  3600. },
  3601. generateAliasFromData = function generateAliasFromData(data) {
  3602. return typeof data === 'string' && jsPDFAPI.sHashCode(data);
  3603. },
  3604. doesNotSupportImageType = function doesNotSupportImageType(type) {
  3605. return supported_image_types.indexOf(type) === -1;
  3606. },
  3607. processMethodNotEnabled = function processMethodNotEnabled(type) {
  3608. return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
  3609. },
  3610. isDOMElement = function isDOMElement(object) {
  3611. return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
  3612. },
  3613. createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
  3614. //if element is an image which uses data url definition, just return the dataurl
  3615. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  3616. var src = '' + element.getAttribute('src');
  3617. if (!angle && src.indexOf('data:image/') === 0) return src;
  3618. // only if the user doesn't care about a format
  3619. if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
  3620. }
  3621. if (element.nodeName === 'CANVAS') {
  3622. var canvas = element;
  3623. } else {
  3624. var canvas = document.createElement('canvas');
  3625. canvas.width = element.clientWidth || element.width;
  3626. canvas.height = element.clientHeight || element.height;
  3627. var ctx = canvas.getContext('2d');
  3628. if (!ctx) {
  3629. throw 'addImage requires canvas to be supported by browser.';
  3630. }
  3631. if (angle) {
  3632. var x,
  3633. y,
  3634. b,
  3635. c,
  3636. s,
  3637. w,
  3638. h,
  3639. to_radians = Math.PI / 180,
  3640. angleInRadians;
  3641. if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
  3642. x = angle.x;
  3643. y = angle.y;
  3644. b = angle.bg;
  3645. angle = angle.angle;
  3646. }
  3647. angleInRadians = angle * to_radians;
  3648. c = Math.abs(Math.cos(angleInRadians));
  3649. s = Math.abs(Math.sin(angleInRadians));
  3650. w = canvas.width;
  3651. h = canvas.height;
  3652. canvas.width = h * s + w * c;
  3653. canvas.height = h * c + w * s;
  3654. if (isNaN(x)) x = canvas.width / 2;
  3655. if (isNaN(y)) y = canvas.height / 2;
  3656. ctx.clearRect(0, 0, canvas.width, canvas.height);
  3657. ctx.fillStyle = b || 'white';
  3658. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3659. ctx.save();
  3660. ctx.translate(x, y);
  3661. ctx.rotate(angleInRadians);
  3662. ctx.drawImage(element, -(w / 2), -(h / 2));
  3663. ctx.rotate(-angleInRadians);
  3664. ctx.translate(-x, -y);
  3665. ctx.restore();
  3666. } else {
  3667. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  3668. }
  3669. }
  3670. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  3671. },
  3672. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  3673. var cached_info;
  3674. if (images) {
  3675. for (var e in images) {
  3676. if (alias === images[e].alias) {
  3677. cached_info = images[e];
  3678. break;
  3679. }
  3680. }
  3681. }
  3682. return cached_info;
  3683. },
  3684. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  3685. if (!w && !h) {
  3686. w = -96;
  3687. h = -96;
  3688. }
  3689. if (w < 0) {
  3690. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  3691. }
  3692. if (h < 0) {
  3693. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  3694. }
  3695. if (w === 0) {
  3696. w = h * info['w'] / info['h'];
  3697. }
  3698. if (h === 0) {
  3699. h = w * info['h'] / info['w'];
  3700. }
  3701. return [w, h];
  3702. },
  3703. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
  3704. var dims = determineWidthAndHeight.call(this, w, h, info),
  3705. coord = this.internal.getCoordinateString,
  3706. vcoord = this.internal.getVerticalCoordinateString;
  3707. w = dims[0];
  3708. h = dims[1];
  3709. images[index] = info;
  3710. this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
  3711. , coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
  3712. };
  3713. /**
  3714. * COLOR SPACES
  3715. */
  3716. jsPDFAPI.color_spaces = {
  3717. DEVICE_RGB: 'DeviceRGB',
  3718. DEVICE_GRAY: 'DeviceGray',
  3719. DEVICE_CMYK: 'DeviceCMYK',
  3720. CAL_GREY: 'CalGray',
  3721. CAL_RGB: 'CalRGB',
  3722. LAB: 'Lab',
  3723. ICC_BASED: 'ICCBased',
  3724. INDEXED: 'Indexed',
  3725. PATTERN: 'Pattern',
  3726. SEPARATION: 'Separation',
  3727. DEVICE_N: 'DeviceN'
  3728. };
  3729. /**
  3730. * DECODE METHODS
  3731. */
  3732. jsPDFAPI.decode = {
  3733. DCT_DECODE: 'DCTDecode',
  3734. FLATE_DECODE: 'FlateDecode',
  3735. LZW_DECODE: 'LZWDecode',
  3736. JPX_DECODE: 'JPXDecode',
  3737. JBIG2_DECODE: 'JBIG2Decode',
  3738. ASCII85_DECODE: 'ASCII85Decode',
  3739. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  3740. RUN_LENGTH_DECODE: 'RunLengthDecode',
  3741. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  3742. };
  3743. /**
  3744. * IMAGE COMPRESSION TYPES
  3745. */
  3746. jsPDFAPI.image_compression = {
  3747. NONE: 'NONE',
  3748. FAST: 'FAST',
  3749. MEDIUM: 'MEDIUM',
  3750. SLOW: 'SLOW'
  3751. };
  3752. jsPDFAPI.sHashCode = function (str) {
  3753. return Array.prototype.reduce && str.split("").reduce(function (a, b) {
  3754. a = (a << 5) - a + b.charCodeAt(0);return a & a;
  3755. }, 0);
  3756. };
  3757. jsPDFAPI.isString = function (object) {
  3758. return typeof object === 'string';
  3759. };
  3760. /**
  3761. * Strips out and returns info from a valid base64 data URI
  3762. * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  3763. * @returns an Array containing the following
  3764. * [0] the complete data URI
  3765. * [1] <MIME-type>
  3766. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  3767. * [4] <data>
  3768. */
  3769. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  3770. return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI)
  3771. );
  3772. };
  3773. /**
  3774. * Check to see if ArrayBuffer is supported
  3775. */
  3776. jsPDFAPI.supportsArrayBuffer = function () {
  3777. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  3778. };
  3779. /**
  3780. * Tests supplied object to determine if ArrayBuffer
  3781. * @param {Object[object]}
  3782. */
  3783. jsPDFAPI.isArrayBuffer = function (object) {
  3784. if (!this.supportsArrayBuffer()) return false;
  3785. return object instanceof ArrayBuffer;
  3786. };
  3787. /**
  3788. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  3789. * @param {Object[object]}
  3790. */
  3791. jsPDFAPI.isArrayBufferView = function (object) {
  3792. if (!this.supportsArrayBuffer()) return false;
  3793. if (typeof Uint32Array === 'undefined') return false;
  3794. 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;
  3795. };
  3796. /**
  3797. * Exactly what it says on the tin
  3798. */
  3799. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  3800. /*
  3801. * not sure how efficient this will be will bigger files. Is there a native method?
  3802. */
  3803. var len = binary_string.length;
  3804. var bytes = new Uint8Array(len);
  3805. for (var i = 0; i < len; i++) {
  3806. bytes[i] = binary_string.charCodeAt(i);
  3807. }
  3808. return bytes;
  3809. };
  3810. /**
  3811. * @see this discussion
  3812. * http://stackoverflow.com/questions/6965107/converting-between-strings-and-arraybuffers
  3813. *
  3814. * As stated, i imagine the method below is highly inefficent for large files.
  3815. *
  3816. * Also of note from Mozilla,
  3817. *
  3818. * "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)."
  3819. *
  3820. * https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView
  3821. *
  3822. * Although i'm strugglig to see how StringView solves this issue? Doesn't appear to be a direct method for conversion?
  3823. *
  3824. * Async method using Blob and FileReader could be best, but i'm not sure how to fit it into the flow?
  3825. */
  3826. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  3827. /*if('TextDecoder' in window){
  3828. var decoder = new TextDecoder('ascii');
  3829. return decoder.decode(buffer);
  3830. }*/
  3831. if (this.isArrayBuffer(buffer)) buffer = new Uint8Array(buffer);
  3832. var binary_string = '';
  3833. var len = buffer.byteLength;
  3834. for (var i = 0; i < len; i++) {
  3835. binary_string += String.fromCharCode(buffer[i]);
  3836. }
  3837. return binary_string;
  3838. /*
  3839. * Another solution is the method below - convert array buffer straight to base64 and then use atob
  3840. */
  3841. //return atob(this.arrayBufferToBase64(buffer));
  3842. };
  3843. /**
  3844. * Converts an ArrayBuffer directly to base64
  3845. *
  3846. * Taken from here
  3847. *
  3848. * http://jsperf.com/encoding-xhr-image-data/31
  3849. *
  3850. * Need to test if this is a better solution for larger files
  3851. *
  3852. */
  3853. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  3854. var base64 = '';
  3855. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3856. var bytes = new Uint8Array(arrayBuffer);
  3857. var byteLength = bytes.byteLength;
  3858. var byteRemainder = byteLength % 3;
  3859. var mainLength = byteLength - byteRemainder;
  3860. var a, b, c, d;
  3861. var chunk;
  3862. // Main loop deals with bytes in chunks of 3
  3863. for (var i = 0; i < mainLength; i = i + 3) {
  3864. // Combine the three bytes into a single integer
  3865. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
  3866. // Use bitmasks to extract 6-bit segments from the triplet
  3867. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  3868. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  3869. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  3870. d = chunk & 63; // 63 = 2^6 - 1
  3871. // Convert the raw binary segments to the appropriate ASCII encoding
  3872. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  3873. }
  3874. // Deal with the remaining bytes and padding
  3875. if (byteRemainder == 1) {
  3876. chunk = bytes[mainLength];
  3877. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  3878. // Set the 4 least significant bits to zero
  3879. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  3880. base64 += encodings[a] + encodings[b] + '==';
  3881. } else if (byteRemainder == 2) {
  3882. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  3883. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  3884. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  3885. // Set the 2 least significant bits to zero
  3886. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  3887. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  3888. }
  3889. return base64;
  3890. };
  3891. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  3892. var info = {
  3893. alias: alias,
  3894. w: wd,
  3895. h: ht,
  3896. cs: cs,
  3897. bpc: bpc,
  3898. i: imageIndex,
  3899. data: data
  3900. // n: objectNumber will be added by putImage code
  3901. };
  3902. if (f) info.f = f;
  3903. if (dp) info.dp = dp;
  3904. if (trns) info.trns = trns;
  3905. if (pal) info.pal = pal;
  3906. if (smask) info.smask = smask;
  3907. if (p) info.p = p; // predictor parameter for PNG compression
  3908. return info;
  3909. };
  3910. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  3911. 'use strict';
  3912. if (typeof format !== 'string') {
  3913. var tmp = h;
  3914. h = w;
  3915. w = y;
  3916. y = x;
  3917. x = format;
  3918. format = tmp;
  3919. }
  3920. if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  3921. var options = imageData;
  3922. imageData = options.imageData;
  3923. format = options.format || format;
  3924. x = options.x || x || 0;
  3925. y = options.y || y || 0;
  3926. w = options.w || w;
  3927. h = options.h || h;
  3928. alias = options.alias || alias;
  3929. compression = options.compression || compression;
  3930. rotation = options.rotation || options.angle || rotation;
  3931. }
  3932. if (isNaN(x) || isNaN(y)) {
  3933. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  3934. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  3935. }
  3936. var images = getImages.call(this),
  3937. info;
  3938. if (!(info = checkImagesForAlias(imageData, images))) {
  3939. var dataAsBinaryString;
  3940. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
  3941. if (notDefined(alias)) alias = generateAliasFromData(imageData);
  3942. if (!(info = checkImagesForAlias(alias, images))) {
  3943. if (this.isString(imageData)) {
  3944. var base64Info = this.extractInfoFromBase64DataURI(imageData);
  3945. if (base64Info) {
  3946. format = base64Info[2];
  3947. imageData = atob(base64Info[3]); //convert to binary string
  3948. } else {
  3949. if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
  3950. }
  3951. }
  3952. format = (format || 'JPEG').toLowerCase();
  3953. if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
  3954. if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
  3955. /**
  3956. * need to test if it's more efficient to convert all binary strings
  3957. * to TypedArray - or should we just leave and process as string?
  3958. */
  3959. if (this.supportsArrayBuffer()) {
  3960. // no need to convert if imageData is already uint8array
  3961. if (!(imageData instanceof Uint8Array)) {
  3962. dataAsBinaryString = imageData;
  3963. imageData = this.binaryStringToUint8Array(imageData);
  3964. }
  3965. }
  3966. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  3967. if (!info) throw new Error('An unkwown error occurred whilst processing the image');
  3968. }
  3969. }
  3970. writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
  3971. return this;
  3972. };
  3973. /**
  3974. * JPEG SUPPORT
  3975. **/
  3976. //takes a string imgData containing the raw bytes of
  3977. //a jpeg image and returns [width, height]
  3978. //Algorithm from: http://www.64lines.com/jpeg-width-height
  3979. var getJpegSize = function getJpegSize(imgData) {
  3980. 'use strict';
  3981. var width, height, numcomponents;
  3982. // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  3983. 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) {
  3984. throw new Error('getJpegSize requires a binary string jpeg file');
  3985. }
  3986. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  3987. var i = 4,
  3988. len = imgData.length;
  3989. while (i < len) {
  3990. i += blockLength;
  3991. if (imgData.charCodeAt(i) !== 0xff) {
  3992. throw new Error('getJpegSize could not find the size of the image');
  3993. }
  3994. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  3995. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  3996. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  3997. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  3998. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  3999. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  4000. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  4001. imgData.charCodeAt(i + 1) === 0xc7) {
  4002. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  4003. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  4004. numcomponents = imgData.charCodeAt(i + 9);
  4005. return [width, height, numcomponents];
  4006. } else {
  4007. i += 2;
  4008. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  4009. }
  4010. }
  4011. },
  4012. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  4013. var hdr = data[0] << 8 | data[1];
  4014. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  4015. var len = data.length,
  4016. block = (data[4] << 8) + data[5],
  4017. pos = 4,
  4018. bytes,
  4019. width,
  4020. height,
  4021. numcomponents;
  4022. while (pos < len) {
  4023. pos += block;
  4024. bytes = readBytes(data, pos);
  4025. block = (bytes[2] << 8) + bytes[3];
  4026. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  4027. bytes = readBytes(data, pos + 5);
  4028. width = (bytes[2] << 8) + bytes[3];
  4029. height = (bytes[0] << 8) + bytes[1];
  4030. numcomponents = bytes[4];
  4031. return { width: width, height: height, numcomponents: numcomponents };
  4032. }
  4033. pos += 2;
  4034. }
  4035. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  4036. },
  4037. readBytes = function readBytes(data, offset) {
  4038. return data.subarray(offset, offset + 5);
  4039. };
  4040. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString) {
  4041. 'use strict';
  4042. var colorSpace = this.color_spaces.DEVICE_RGB,
  4043. filter = this.decode.DCT_DECODE,
  4044. bpc = 8,
  4045. dims;
  4046. if (this.isString(data)) {
  4047. dims = getJpegSize(data);
  4048. return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4049. }
  4050. if (this.isArrayBuffer(data)) data = new Uint8Array(data);
  4051. if (this.isArrayBufferView(data)) {
  4052. dims = getJpegSizeFromBytes(data);
  4053. // if we already have a stored binary string rep use that
  4054. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  4055. return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
  4056. }
  4057. return null;
  4058. };
  4059. jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
  4060. return this.processJPEG.apply(this, arguments);
  4061. };
  4062. })(jsPDF.API);
  4063. /**
  4064. * jsPDF Annotations PlugIn
  4065. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4066. *
  4067. * Licensed under the MIT License.
  4068. * http://opensource.org/licenses/mit-license
  4069. */
  4070. /**
  4071. * There are many types of annotations in a PDF document. Annotations are placed
  4072. * on a page at a particular location. They are not 'attached' to an object.
  4073. * <br />
  4074. * This plugin current supports <br />
  4075. * <li> Goto Page (set pageNumber and top in options)
  4076. * <li> Goto Name (set name and top in options)
  4077. * <li> Goto URL (set url in options)
  4078. * <p>
  4079. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  4080. * (set magFactor in options). XYZ is the default.
  4081. * </p>
  4082. * <p>
  4083. * Links, Text, Popup, and FreeText are supported.
  4084. * </p>
  4085. * <p>
  4086. * Options In PDF spec Not Implemented Yet
  4087. * <li> link border
  4088. * <li> named target
  4089. * <li> page coordinates
  4090. * <li> destination page scaling and layout
  4091. * <li> actions other than URL and GotoPage
  4092. * <li> background / hover actions
  4093. * </p>
  4094. */
  4095. /*
  4096. Destination Magnification Factors
  4097. See PDF 1.3 Page 386 for meanings and options
  4098. [supported]
  4099. XYZ (options; left top zoom)
  4100. Fit (no options)
  4101. FitH (options: top)
  4102. FitV (options: left)
  4103. [not supported]
  4104. FitR
  4105. FitB
  4106. FitBH
  4107. FitBV
  4108. */
  4109. (function (jsPDFAPI) {
  4110. 'use strict';
  4111. var annotationPlugin = {
  4112. /**
  4113. * An array of arrays, indexed by <em>pageNumber</em>.
  4114. */
  4115. annotations: [],
  4116. f2: function f2(number) {
  4117. return number.toFixed(2);
  4118. },
  4119. notEmpty: function notEmpty(obj) {
  4120. if (typeof obj != 'undefined') {
  4121. if (obj != '') {
  4122. return true;
  4123. }
  4124. }
  4125. }
  4126. };
  4127. jsPDF.API.annotationPlugin = annotationPlugin;
  4128. jsPDF.API.events.push(['addPage', function (info) {
  4129. this.annotationPlugin.annotations[info.pageNumber] = [];
  4130. }]);
  4131. jsPDFAPI.events.push(['putPage', function (info) {
  4132. //TODO store annotations in pageContext so reorder/remove will not affect them.
  4133. var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
  4134. var found = false;
  4135. for (var a = 0; a < pageAnnos.length && !found; a++) {
  4136. var anno = pageAnnos[a];
  4137. switch (anno.type) {
  4138. case 'link':
  4139. if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
  4140. found = true;
  4141. break;
  4142. }
  4143. case 'reference':
  4144. case 'text':
  4145. case 'freetext':
  4146. found = true;
  4147. break;
  4148. }
  4149. }
  4150. if (found == false) {
  4151. return;
  4152. }
  4153. this.internal.write("/Annots [");
  4154. var f2 = this.annotationPlugin.f2;
  4155. var k = this.internal.scaleFactor;
  4156. var pageHeight = this.internal.pageSize.height;
  4157. var pageInfo = this.internal.getPageInfo(info.pageNumber);
  4158. for (var a = 0; a < pageAnnos.length; a++) {
  4159. var anno = pageAnnos[a];
  4160. switch (anno.type) {
  4161. case 'reference':
  4162. // References to Widget Anotations (for AcroForm Fields)
  4163. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  4164. break;
  4165. case 'text':
  4166. // Create a an object for both the text and the popup
  4167. var objText = this.internal.newAdditionalObject();
  4168. var objPopup = this.internal.newAdditionalObject();
  4169. var title = anno.title || 'Note';
  4170. 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) + "] ";
  4171. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4172. line += ' /Popup ' + objPopup.objId + " 0 R";
  4173. line += ' /P ' + pageInfo.objId + " 0 R";
  4174. line += ' /T (' + title + ') >>';
  4175. objText.content = line;
  4176. var parent = objText.objId + ' 0 R';
  4177. var popoff = 30;
  4178. 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) + "] ";
  4179. //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) + "] ";
  4180. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  4181. if (anno.open) {
  4182. line += ' /Open true';
  4183. }
  4184. line += ' >>';
  4185. objPopup.content = line;
  4186. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  4187. break;
  4188. case 'freetext':
  4189. 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) + "] ";
  4190. var color = anno.color || '#000000';
  4191. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  4192. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  4193. line += ' /Border [0 0 0]';
  4194. line += ' >>';
  4195. this.internal.write(line);
  4196. break;
  4197. case 'link':
  4198. if (anno.options.name) {
  4199. var loc = this.annotations._nameMap[anno.options.name];
  4200. anno.options.pageNumber = loc.page;
  4201. anno.options.top = loc.y;
  4202. } else {
  4203. if (!anno.options.top) {
  4204. anno.options.top = 0;
  4205. }
  4206. }
  4207. //var pageHeight = this.internal.pageSize.height * this.internal.scaleFactor;
  4208. 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) + "] ";
  4209. var line = '';
  4210. if (anno.options.url) {
  4211. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  4212. } else if (anno.options.pageNumber) {
  4213. // first page is 0
  4214. var info = this.internal.getPageInfo(anno.options.pageNumber);
  4215. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  4216. anno.options.magFactor = anno.options.magFactor || "XYZ";
  4217. switch (anno.options.magFactor) {
  4218. case 'Fit':
  4219. line += ' /Fit]';
  4220. break;
  4221. case 'FitH':
  4222. //anno.options.top = anno.options.top || f2(pageHeight * k);
  4223. line += ' /FitH ' + anno.options.top + ']';
  4224. break;
  4225. case 'FitV':
  4226. anno.options.left = anno.options.left || 0;
  4227. line += ' /FitV ' + anno.options.left + ']';
  4228. break;
  4229. case 'XYZ':
  4230. default:
  4231. var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
  4232. anno.options.left = anno.options.left || 0;
  4233. // 0 or null zoom will not change zoom factor
  4234. if (typeof anno.options.zoom === 'undefined') {
  4235. anno.options.zoom = 0;
  4236. }
  4237. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  4238. break;
  4239. }
  4240. } else {
  4241. // TODO error - should not be here
  4242. }
  4243. if (line != '') {
  4244. line += " >>";
  4245. this.internal.write(line);
  4246. }
  4247. break;
  4248. }
  4249. }
  4250. this.internal.write("]");
  4251. }]);
  4252. jsPDFAPI.createAnnotation = function (options) {
  4253. switch (options.type) {
  4254. case 'link':
  4255. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  4256. break;
  4257. case 'text':
  4258. case 'freetext':
  4259. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
  4260. break;
  4261. }
  4262. };
  4263. /**
  4264. * valid options
  4265. * <li> pageNumber or url [required]
  4266. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4267. */
  4268. jsPDFAPI.link = function (x, y, w, h, options) {
  4269. 'use strict';
  4270. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4271. x: x,
  4272. y: y,
  4273. w: w,
  4274. h: h,
  4275. options: options,
  4276. type: 'link'
  4277. });
  4278. };
  4279. /**
  4280. * valid options
  4281. * <li> pageNumber or url [required]
  4282. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  4283. */
  4284. jsPDFAPI.link = function (x, y, w, h, options) {
  4285. 'use strict';
  4286. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  4287. x: x,
  4288. y: y,
  4289. w: w,
  4290. h: h,
  4291. options: options,
  4292. type: 'link'
  4293. });
  4294. };
  4295. /**
  4296. * Currently only supports single line text.
  4297. * Returns the width of the text/link
  4298. */
  4299. jsPDFAPI.textWithLink = function (text, x, y, options) {
  4300. 'use strict';
  4301. var width = this.getTextWidth(text);
  4302. var height = this.internal.getLineHeight();
  4303. this.text(text, x, y);
  4304. //TODO We really need the text baseline height to do this correctly.
  4305. // Or ability to draw text on top, bottom, center, or baseline.
  4306. y += height * .2;
  4307. this.link(x, y - height, width, height, options);
  4308. return width;
  4309. };
  4310. //TODO move into external library
  4311. jsPDFAPI.getTextWidth = function (text) {
  4312. 'use strict';
  4313. var fontSize = this.internal.getFontSize();
  4314. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  4315. return txtWidth;
  4316. };
  4317. //TODO move into external library
  4318. jsPDFAPI.getLineHeight = function () {
  4319. return this.internal.getLineHeight();
  4320. };
  4321. return this;
  4322. })(jsPDF.API);
  4323. /**
  4324. * jsPDF Autoprint Plugin
  4325. *
  4326. * Licensed under the MIT License.
  4327. * http://opensource.org/licenses/mit-license
  4328. */
  4329. (function (jsPDFAPI) {
  4330. 'use strict';
  4331. jsPDFAPI.autoPrint = function () {
  4332. 'use strict';
  4333. var refAutoPrintTag;
  4334. this.internal.events.subscribe('postPutResources', function () {
  4335. refAutoPrintTag = this.internal.newObject();
  4336. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  4337. });
  4338. this.internal.events.subscribe("putCatalog", function () {
  4339. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  4340. });
  4341. return this;
  4342. };
  4343. })(jsPDF.API);
  4344. /**
  4345. * jsPDF Canvas PlugIn
  4346. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4347. *
  4348. * Licensed under the MIT License.
  4349. * http://opensource.org/licenses/mit-license
  4350. */
  4351. /**
  4352. * This plugin mimics the HTML5 Canvas
  4353. *
  4354. * The goal is to provide a way for current canvas users to print directly to a PDF.
  4355. */
  4356. (function (jsPDFAPI) {
  4357. 'use strict';
  4358. jsPDFAPI.events.push(['initialized', function () {
  4359. this.canvas.pdf = this;
  4360. }]);
  4361. jsPDFAPI.canvas = {
  4362. getContext: function getContext(name) {
  4363. this.pdf.context2d._canvas = this;
  4364. return this.pdf.context2d;
  4365. },
  4366. style: {}
  4367. };
  4368. Object.defineProperty(jsPDFAPI.canvas, 'width', {
  4369. get: function get() {
  4370. return this._width;
  4371. },
  4372. set: function set(value) {
  4373. this._width = value;
  4374. this.getContext('2d').pageWrapX = value + 1;
  4375. }
  4376. });
  4377. Object.defineProperty(jsPDFAPI.canvas, 'height', {
  4378. get: function get() {
  4379. return this._height;
  4380. },
  4381. set: function set(value) {
  4382. this._height = value;
  4383. this.getContext('2d').pageWrapY = value + 1;
  4384. }
  4385. });
  4386. return this;
  4387. })(jsPDF.API);
  4388. /** ====================================================================
  4389. * jsPDF Cell plugin
  4390. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  4391. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  4392. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  4393. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  4394. * 2014 James Hall, james@parall.ax
  4395. * 2014 Diego Casorran, https://github.com/diegocr
  4396. *
  4397. *
  4398. * ====================================================================
  4399. */
  4400. (function (jsPDFAPI) {
  4401. 'use strict';
  4402. /*jslint browser:true */
  4403. /*global document: false, jsPDF */
  4404. var fontName,
  4405. fontSize,
  4406. fontStyle,
  4407. padding = 3,
  4408. margin = 13,
  4409. headerFunction,
  4410. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
  4411. pages = 1,
  4412. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  4413. lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
  4414. },
  4415. getLastCellPosition = function getLastCellPosition() {
  4416. return lastCellPos;
  4417. },
  4418. NO_MARGINS = { left: 0, top: 0, bottom: 0 };
  4419. jsPDFAPI.setHeaderFunction = function (func) {
  4420. headerFunction = func;
  4421. };
  4422. jsPDFAPI.getTextDimensions = function (txt) {
  4423. fontName = this.internal.getFont().fontName;
  4424. fontSize = this.table_font_size || this.internal.getFontSize();
  4425. fontStyle = this.internal.getFont().fontStyle;
  4426. // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
  4427. var px2pt = 0.264583 * 72 / 25.4,
  4428. dimensions,
  4429. text;
  4430. text = document.createElement('font');
  4431. text.id = "jsPDFCell";
  4432. try {
  4433. text.style.fontStyle = fontStyle;
  4434. } catch (e) {
  4435. text.style.fontWeight = fontStyle;
  4436. }
  4437. text.style.fontName = fontName;
  4438. text.style.fontSize = fontSize + 'pt';
  4439. try {
  4440. text.textContent = txt;
  4441. } catch (e) {
  4442. text.innerText = txt;
  4443. }
  4444. document.body.appendChild(text);
  4445. dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
  4446. document.body.removeChild(text);
  4447. return dimensions;
  4448. };
  4449. jsPDFAPI.cellAddPage = function () {
  4450. var margins = this.margins || NO_MARGINS;
  4451. this.addPage();
  4452. setLastCellPosition(margins.left, margins.top, undefined, undefined);
  4453. //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  4454. pages += 1;
  4455. };
  4456. jsPDFAPI.cellInitialize = function () {
  4457. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
  4458. pages = 1;
  4459. };
  4460. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  4461. var curCell = getLastCellPosition();
  4462. var pgAdded = false;
  4463. // If this is not the first cell, we must change its position
  4464. if (curCell.ln !== undefined) {
  4465. if (curCell.ln === ln) {
  4466. //Same line
  4467. x = curCell.x + curCell.w;
  4468. y = curCell.y;
  4469. } else {
  4470. //New line
  4471. var margins = this.margins || NO_MARGINS;
  4472. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
  4473. this.cellAddPage();
  4474. pgAdded = true;
  4475. if (this.printHeaders && this.tableHeaderRow) {
  4476. this.printHeaderRow(ln, true);
  4477. }
  4478. }
  4479. //We ignore the passed y: the lines may have different heights
  4480. y = getLastCellPosition().y + getLastCellPosition().h;
  4481. if (pgAdded) y = margin + 10;
  4482. }
  4483. }
  4484. if (txt[0] !== undefined) {
  4485. if (this.printingHeaderRow) {
  4486. this.rect(x, y, w, h, 'FD');
  4487. } else {
  4488. this.rect(x, y, w, h);
  4489. }
  4490. if (align === 'right') {
  4491. if (!(txt instanceof Array)) {
  4492. txt = [txt];
  4493. }
  4494. for (var i = 0; i < txt.length; i++) {
  4495. var currentLine = txt[i];
  4496. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
  4497. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  4498. }
  4499. } else {
  4500. this.text(txt, x + padding, y + this.internal.getLineHeight());
  4501. }
  4502. }
  4503. setLastCellPosition(x, y, w, h, ln);
  4504. return this;
  4505. };
  4506. /**
  4507. * Return the maximum value from an array
  4508. * @param array
  4509. * @param comparisonFn
  4510. * @returns {*}
  4511. */
  4512. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  4513. var max = array[0],
  4514. i,
  4515. ln,
  4516. item;
  4517. for (i = 0, ln = array.length; i < ln; i += 1) {
  4518. item = array[i];
  4519. if (comparisonFn) {
  4520. if (comparisonFn(max, item) === -1) {
  4521. max = item;
  4522. }
  4523. } else {
  4524. if (item > max) {
  4525. max = item;
  4526. }
  4527. }
  4528. }
  4529. return max;
  4530. };
  4531. /**
  4532. * Create a table from a set of data.
  4533. * @param {Integer} [x] : left-position for top-left corner of table
  4534. * @param {Integer} [y] top-position for top-left corner of table
  4535. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  4536. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  4537. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  4538. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  4539. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  4540. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  4541. */
  4542. jsPDFAPI.table = function (x, y, data, headers, config) {
  4543. if (!data) {
  4544. throw 'No data for PDF table';
  4545. }
  4546. var headerNames = [],
  4547. headerPrompts = [],
  4548. header,
  4549. i,
  4550. ln,
  4551. cln,
  4552. columnMatrix = {},
  4553. columnWidths = {},
  4554. columnData,
  4555. column,
  4556. columnMinWidths = [],
  4557. j,
  4558. tableHeaderConfigs = [],
  4559. model,
  4560. jln,
  4561. func,
  4562. //set up defaults. If a value is provided in config, defaults will be overwritten:
  4563. autoSize = false,
  4564. printHeaders = true,
  4565. fontSize = 12,
  4566. margins = NO_MARGINS;
  4567. margins.width = this.internal.pageSize.width;
  4568. if (config) {
  4569. //override config defaults if the user has specified non-default behavior:
  4570. if (config.autoSize === true) {
  4571. autoSize = true;
  4572. }
  4573. if (config.printHeaders === false) {
  4574. printHeaders = false;
  4575. }
  4576. if (config.fontSize) {
  4577. fontSize = config.fontSize;
  4578. }
  4579. if (config.css && typeof config.css['font-size'] !== "undefined") {
  4580. fontSize = config.css['font-size'] * 16;
  4581. }
  4582. if (config.margins) {
  4583. margins = config.margins;
  4584. }
  4585. }
  4586. /**
  4587. * @property {Number} lnMod
  4588. * Keep track of the current line number modifier used when creating cells
  4589. */
  4590. this.lnMod = 0;
  4591. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
  4592. this.printHeaders = printHeaders;
  4593. this.margins = margins;
  4594. this.setFontSize(fontSize);
  4595. this.table_font_size = fontSize;
  4596. // Set header values
  4597. if (headers === undefined || headers === null) {
  4598. // No headers defined so we derive from data
  4599. headerNames = Object.keys(data[0]);
  4600. } else if (headers[0] && typeof headers[0] !== 'string') {
  4601. var px2pt = 0.264583 * 72 / 25.4;
  4602. // Split header configs into names and prompts
  4603. for (i = 0, ln = headers.length; i < ln; i += 1) {
  4604. header = headers[i];
  4605. headerNames.push(header.name);
  4606. headerPrompts.push(header.prompt);
  4607. columnWidths[header.name] = header.width * px2pt;
  4608. }
  4609. } else {
  4610. headerNames = headers;
  4611. }
  4612. if (autoSize) {
  4613. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  4614. func = function func(rec) {
  4615. return rec[header];
  4616. };
  4617. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4618. header = headerNames[i];
  4619. columnMatrix[header] = data.map(func);
  4620. // get header width
  4621. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
  4622. column = columnMatrix[header];
  4623. // get cell widths
  4624. for (j = 0, cln = column.length; j < cln; j += 1) {
  4625. columnData = column[j];
  4626. columnMinWidths.push(this.getTextDimensions(columnData).w);
  4627. }
  4628. // get final column width
  4629. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
  4630. //have to reset
  4631. columnMinWidths = [];
  4632. }
  4633. }
  4634. // -- Construct the table
  4635. if (printHeaders) {
  4636. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
  4637. // Construct the header row
  4638. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  4639. header = headerNames[i];
  4640. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  4641. }
  4642. // Store the table header config
  4643. this.setTableHeaderRow(tableHeaderConfigs);
  4644. // Print the header for the start of the table
  4645. this.printHeaderRow(1, false);
  4646. }
  4647. // Construct the data rows
  4648. for (i = 0, ln = data.length; i < ln; i += 1) {
  4649. var lineHeight;
  4650. model = data[i];
  4651. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  4652. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  4653. header = headerNames[j];
  4654. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  4655. }
  4656. }
  4657. this.lastCellPos = lastCellPos;
  4658. this.table_x = x;
  4659. this.table_y = y;
  4660. return this;
  4661. };
  4662. /**
  4663. * Calculate the height for containing the highest column
  4664. * @param {String[]} headerNames is the header, used as keys to the data
  4665. * @param {Integer[]} columnWidths is size of each column
  4666. * @param {Object[]} model is the line of data we want to calculate the height of
  4667. */
  4668. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  4669. var header,
  4670. lineHeight = 0;
  4671. for (var j = 0; j < headerNames.length; j++) {
  4672. header = headerNames[j];
  4673. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  4674. var h = this.internal.getLineHeight() * model[header].length + padding;
  4675. if (h > lineHeight) lineHeight = h;
  4676. }
  4677. return lineHeight;
  4678. };
  4679. /**
  4680. * Store the config for outputting a table header
  4681. * @param {Object[]} config
  4682. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  4683. * except the ln parameter is excluded
  4684. */
  4685. jsPDFAPI.setTableHeaderRow = function (config) {
  4686. this.tableHeaderRow = config;
  4687. };
  4688. /**
  4689. * Output the store header row
  4690. * @param lineNumber The line number to output the header at
  4691. */
  4692. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  4693. if (!this.tableHeaderRow) {
  4694. throw 'Property tableHeaderRow does not exist.';
  4695. }
  4696. var tableHeaderCell, tmpArray, i, ln;
  4697. this.printingHeaderRow = true;
  4698. if (headerFunction !== undefined) {
  4699. var position = headerFunction(this, pages);
  4700. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  4701. }
  4702. this.setFontStyle('bold');
  4703. var tempHeaderConf = [];
  4704. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  4705. this.setFillColor(200, 200, 200);
  4706. tableHeaderCell = this.tableHeaderRow[i];
  4707. if (new_page) {
  4708. this.margins.top = margin;
  4709. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  4710. tempHeaderConf.push(tableHeaderCell);
  4711. }
  4712. tmpArray = [].concat(tableHeaderCell);
  4713. this.cell.apply(this, tmpArray.concat(lineNumber));
  4714. }
  4715. if (tempHeaderConf.length > 0) {
  4716. this.setTableHeaderRow(tempHeaderConf);
  4717. }
  4718. this.setFontStyle('normal');
  4719. this.printingHeaderRow = false;
  4720. };
  4721. })(jsPDF.API);
  4722. /**
  4723. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4724. *
  4725. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  4726. */
  4727. /**
  4728. * This plugin mimics the HTML5 Canvas's context2d.
  4729. *
  4730. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  4731. */
  4732. /**
  4733. * TODO implement stroke opacity (refactor from fill() method )
  4734. * TODO transform angle and radii parameters
  4735. */
  4736. /**
  4737. * require('jspdf.js'); require('lib/css_colors.js');
  4738. */
  4739. (function (jsPDFAPI) {
  4740. 'use strict';
  4741. jsPDFAPI.events.push(['initialized', function () {
  4742. this.context2d.pdf = this;
  4743. this.context2d.internal.pdf = this;
  4744. this.context2d.ctx = new context();
  4745. this.context2d.ctxStack = [];
  4746. this.context2d.path = [];
  4747. }]);
  4748. jsPDFAPI.context2d = {
  4749. pageWrapXEnabled: false,
  4750. pageWrapYEnabled: false,
  4751. pageWrapX: 9999999,
  4752. pageWrapY: 9999999,
  4753. ctx: new context(),
  4754. f2: function f2(number) {
  4755. return number.toFixed(2);
  4756. },
  4757. fillRect: function fillRect(x, y, w, h) {
  4758. if (this._isFillTransparent()) {
  4759. return;
  4760. }
  4761. x = this._wrapX(x);
  4762. y = this._wrapY(y);
  4763. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4764. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  4765. },
  4766. strokeRect: function strokeRect(x, y, w, h) {
  4767. if (this._isStrokeTransparent()) {
  4768. return;
  4769. }
  4770. x = this._wrapX(x);
  4771. y = this._wrapY(y);
  4772. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4773. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
  4774. },
  4775. /**
  4776. * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  4777. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  4778. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  4779. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  4780. * @param x
  4781. * @param y
  4782. * @param w
  4783. * @param h
  4784. */
  4785. clearRect: function clearRect(x, y, w, h) {
  4786. if (this.ctx.ignoreClearRect) {
  4787. return;
  4788. }
  4789. x = this._wrapX(x);
  4790. y = this._wrapY(y);
  4791. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  4792. this.save();
  4793. this.setFillStyle('#ffffff');
  4794. //TODO This is hack to fill with white.
  4795. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  4796. this.restore();
  4797. },
  4798. save: function save() {
  4799. this.ctx._fontSize = this.pdf.internal.getFontSize();
  4800. var ctx = new context();
  4801. ctx.copy(this.ctx);
  4802. this.ctxStack.push(this.ctx);
  4803. this.ctx = ctx;
  4804. },
  4805. restore: function restore() {
  4806. this.ctx = this.ctxStack.pop();
  4807. this.setFillStyle(this.ctx.fillStyle);
  4808. this.setStrokeStyle(this.ctx.strokeStyle);
  4809. this.setFont(this.ctx.font);
  4810. this.pdf.setFontSize(this.ctx._fontSize);
  4811. this.setLineCap(this.ctx.lineCap);
  4812. this.setLineWidth(this.ctx.lineWidth);
  4813. this.setLineJoin(this.ctx.lineJoin);
  4814. },
  4815. rect: function rect(x, y, w, h) {
  4816. this.moveTo(x, y);
  4817. this.lineTo(x + w, y);
  4818. this.lineTo(x + w, y + h);
  4819. this.lineTo(x, y + h);
  4820. this.lineTo(x, y); //TODO not needed
  4821. this.closePath();
  4822. },
  4823. beginPath: function beginPath() {
  4824. this.path = [];
  4825. },
  4826. closePath: function closePath() {
  4827. this.path.push({
  4828. type: 'close'
  4829. });
  4830. },
  4831. _getRgba: function _getRgba(style) {
  4832. // get the decimal values of r, g, and b;
  4833. var rgba = {};
  4834. if (this.internal.rxTransparent.test(style)) {
  4835. rgba.r = 0;
  4836. rgba.g = 0;
  4837. rgba.b = 0;
  4838. rgba.a = 0;
  4839. } else {
  4840. var m = this.internal.rxRgb.exec(style);
  4841. if (m != null) {
  4842. rgba.r = parseInt(m[1]);
  4843. rgba.g = parseInt(m[2]);
  4844. rgba.b = parseInt(m[3]);
  4845. rgba.a = 1;
  4846. } else {
  4847. m = this.internal.rxRgba.exec(style);
  4848. if (m != null) {
  4849. rgba.r = parseInt(m[1]);
  4850. rgba.g = parseInt(m[2]);
  4851. rgba.b = parseInt(m[3]);
  4852. rgba.a = parseFloat(m[4]);
  4853. } else {
  4854. rgba.a = 1;
  4855. if (style.charAt(0) != '#') {
  4856. style = CssColors.colorNameToHex(style);
  4857. if (!style) {
  4858. style = '#000000';
  4859. }
  4860. } else {}
  4861. if (style.length === 4) {
  4862. rgba.r = style.substring(1, 2);
  4863. rgba.r += r;
  4864. rgba.g = style.substring(2, 3);
  4865. rgba.g += g;
  4866. rgba.b = style.substring(3, 4);
  4867. rgba.b += b;
  4868. } else {
  4869. rgba.r = style.substring(1, 3);
  4870. rgba.g = style.substring(3, 5);
  4871. rgba.b = style.substring(5, 7);
  4872. }
  4873. rgba.r = parseInt(rgba.r, 16);
  4874. rgba.g = parseInt(rgba.g, 16);
  4875. rgba.b = parseInt(rgba.b, 16);
  4876. }
  4877. }
  4878. }
  4879. rgba.style = style;
  4880. return rgba;
  4881. },
  4882. setFillStyle: function setFillStyle(style) {
  4883. // get the decimal values of r, g, and b;
  4884. var r, g, b, a;
  4885. if (this.internal.rxTransparent.test(style)) {
  4886. r = 0;
  4887. g = 0;
  4888. b = 0;
  4889. a = 0;
  4890. } else {
  4891. var m = this.internal.rxRgb.exec(style);
  4892. if (m != null) {
  4893. r = parseInt(m[1]);
  4894. g = parseInt(m[2]);
  4895. b = parseInt(m[3]);
  4896. a = 1;
  4897. } else {
  4898. m = this.internal.rxRgba.exec(style);
  4899. if (m != null) {
  4900. r = parseInt(m[1]);
  4901. g = parseInt(m[2]);
  4902. b = parseInt(m[3]);
  4903. a = parseFloat(m[4]);
  4904. } else {
  4905. a = 1;
  4906. if (style.charAt(0) != '#') {
  4907. style = CssColors.colorNameToHex(style);
  4908. if (!style) {
  4909. style = '#000000';
  4910. }
  4911. } else {}
  4912. if (style.length === 4) {
  4913. r = style.substring(1, 2);
  4914. r += r;
  4915. g = style.substring(2, 3);
  4916. g += g;
  4917. b = style.substring(3, 4);
  4918. b += b;
  4919. } else {
  4920. r = style.substring(1, 3);
  4921. g = style.substring(3, 5);
  4922. b = style.substring(5, 7);
  4923. }
  4924. r = parseInt(r, 16);
  4925. g = parseInt(g, 16);
  4926. b = parseInt(b, 16);
  4927. }
  4928. }
  4929. }
  4930. this.ctx.fillStyle = style;
  4931. this.ctx._isFillTransparent = a == 0;
  4932. this.ctx._fillOpacity = a;
  4933. this.pdf.setFillColor(r, g, b, {
  4934. a: a
  4935. });
  4936. this.pdf.setTextColor(r, g, b, {
  4937. a: a
  4938. });
  4939. },
  4940. setStrokeStyle: function setStrokeStyle(style) {
  4941. var rgba = this._getRgba(style);
  4942. this.ctx.strokeStyle = rgba.style;
  4943. this.ctx._isStrokeTransparent = rgba.a == 0;
  4944. this.ctx._strokeOpacity = rgba.a;
  4945. //TODO jsPDF to handle rgba
  4946. if (rgba.a === 0) {
  4947. this.pdf.setDrawColor(255, 255, 255);
  4948. } else if (rgba.a === 1) {
  4949. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  4950. } else {
  4951. //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
  4952. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  4953. }
  4954. },
  4955. fillText: function fillText(text, x, y, maxWidth) {
  4956. if (this._isFillTransparent()) {
  4957. return;
  4958. }
  4959. x = this._wrapX(x);
  4960. y = this._wrapY(y);
  4961. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  4962. x = xpt[0];
  4963. y = xpt[1];
  4964. var rads = this._matrix_rotation(this.ctx._transform);
  4965. var degs = rads * 57.2958;
  4966. //TODO only push the clip if it has not been applied to the current PDF context
  4967. if (this.ctx._clip_path.length > 0) {
  4968. var lines;
  4969. if (window.outIntercept) {
  4970. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  4971. } else {
  4972. lines = this.pdf.internal.pages[1];
  4973. }
  4974. lines.push("q");
  4975. var origPath = this.path;
  4976. this.path = this.ctx._clip_path;
  4977. this.ctx._clip_path = [];
  4978. this._fill(null, true);
  4979. this.ctx._clip_path = this.path;
  4980. this.path = origPath;
  4981. }
  4982. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  4983. if (this.ctx._clip_path.length > 0) {
  4984. lines.push('Q');
  4985. }
  4986. },
  4987. strokeText: function strokeText(text, x, y, maxWidth) {
  4988. if (this._isStrokeTransparent()) {
  4989. return;
  4990. }
  4991. x = this._wrapX(x);
  4992. y = this._wrapY(y);
  4993. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  4994. x = xpt[0];
  4995. y = xpt[1];
  4996. var rads = this._matrix_rotation(this.ctx._transform);
  4997. var degs = rads * 57.2958;
  4998. //TODO only push the clip if it has not been applied to the current PDF context
  4999. if (this.ctx._clip_path.length > 0) {
  5000. var lines;
  5001. if (window.outIntercept) {
  5002. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5003. } else {
  5004. lines = this.pdf.internal.pages[1];
  5005. }
  5006. lines.push("q");
  5007. var origPath = this.path;
  5008. this.path = this.ctx._clip_path;
  5009. this.ctx._clip_path = [];
  5010. this._fill(null, true);
  5011. this.ctx._clip_path = this.path;
  5012. this.path = origPath;
  5013. }
  5014. this.pdf.text(text, x, this._getBaseline(y), {
  5015. stroke: true
  5016. }, degs);
  5017. if (this.ctx._clip_path.length > 0) {
  5018. lines.push('Q');
  5019. }
  5020. },
  5021. setFont: function setFont(font) {
  5022. this.ctx.font = font;
  5023. //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
  5024. var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
  5025. m = rx.exec(font);
  5026. if (m != null) {
  5027. var fontStyle = m[1];
  5028. var fontVariant = m[2];
  5029. var fontWeight = m[3];
  5030. var fontSize = m[4];
  5031. var fontSizeUnit = m[5];
  5032. var fontFamily = m[6];
  5033. if ('px' === fontSizeUnit) {
  5034. fontSize = Math.floor(parseFloat(fontSize));
  5035. // fontSize = fontSize * 1.25;
  5036. } else if ('em' === fontSizeUnit) {
  5037. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5038. } else {
  5039. fontSize = Math.floor(parseFloat(fontSize));
  5040. }
  5041. this.pdf.setFontSize(fontSize);
  5042. if (fontWeight === 'bold' || fontWeight === '700') {
  5043. this.pdf.setFontStyle('bold');
  5044. } else {
  5045. if (fontStyle === 'italic') {
  5046. this.pdf.setFontStyle('italic');
  5047. } else {
  5048. this.pdf.setFontStyle('normal');
  5049. }
  5050. }
  5051. var name = fontFamily;
  5052. var parts = name.toLowerCase().split(/\s*,\s*/);
  5053. var jsPdfFontName;
  5054. if (parts.indexOf('arial') != -1) {
  5055. jsPdfFontName = 'Arial';
  5056. } else if (parts.indexOf('verdana') != -1) {
  5057. jsPdfFontName = 'Verdana';
  5058. } else if (parts.indexOf('helvetica') != -1) {
  5059. jsPdfFontName = 'Helvetica';
  5060. } else if (parts.indexOf('sans-serif') != -1) {
  5061. jsPdfFontName = 'sans-serif';
  5062. } else if (parts.indexOf('fixed') != -1) {
  5063. jsPdfFontName = 'Fixed';
  5064. } else if (parts.indexOf('monospace') != -1) {
  5065. jsPdfFontName = 'Monospace';
  5066. } else if (parts.indexOf('terminal') != -1) {
  5067. jsPdfFontName = 'Terminal';
  5068. } else if (parts.indexOf('courier') != -1) {
  5069. jsPdfFontName = 'Courier';
  5070. } else if (parts.indexOf('times') != -1) {
  5071. jsPdfFontName = 'Times';
  5072. } else if (parts.indexOf('cursive') != -1) {
  5073. jsPdfFontName = 'Cursive';
  5074. } else if (parts.indexOf('fantasy') != -1) {
  5075. jsPdfFontName = 'Fantasy';
  5076. } else if (parts.indexOf('serif') != -1) {
  5077. jsPdfFontName = 'Serif';
  5078. } else {
  5079. jsPdfFontName = 'Serif';
  5080. }
  5081. //TODO check more cases
  5082. var style;
  5083. if ('bold' === fontWeight) {
  5084. style = 'bold';
  5085. } else {
  5086. style = 'normal';
  5087. }
  5088. this.pdf.setFont(jsPdfFontName, style);
  5089. } else {
  5090. var rx = /(\d+)(pt|px|em)\s+(\w+)\s*(\w+)?/;
  5091. var m = rx.exec(font);
  5092. if (m != null) {
  5093. var size = m[1];
  5094. var unit = m[2];
  5095. var name = m[3];
  5096. var style = m[4];
  5097. if (!style) {
  5098. style = 'normal';
  5099. }
  5100. if ('em' === fontSizeUnit) {
  5101. size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  5102. } else {
  5103. size = Math.floor(parseFloat(size));
  5104. }
  5105. this.pdf.setFontSize(size);
  5106. this.pdf.setFont(name, style);
  5107. }
  5108. }
  5109. },
  5110. setTextBaseline: function setTextBaseline(baseline) {
  5111. this.ctx.textBaseline = baseline;
  5112. },
  5113. getTextBaseline: function getTextBaseline() {
  5114. return this.ctx.textBaseline;
  5115. },
  5116. //TODO implement textAlign
  5117. setTextAlign: function setTextAlign(align) {
  5118. this.ctx.textAlign = align;
  5119. },
  5120. getTextAlign: function getTextAlign() {
  5121. return this.ctx.textAlign;
  5122. },
  5123. setLineWidth: function setLineWidth(width) {
  5124. this.ctx.lineWidth = width;
  5125. this.pdf.setLineWidth(width);
  5126. },
  5127. setLineCap: function setLineCap(style) {
  5128. this.ctx.lineCap = style;
  5129. this.pdf.setLineCap(style);
  5130. },
  5131. setLineJoin: function setLineJoin(style) {
  5132. this.ctx.lineJoin = style;
  5133. this.pdf.setLineJoin(style);
  5134. },
  5135. moveTo: function moveTo(x, y) {
  5136. x = this._wrapX(x);
  5137. y = this._wrapY(y);
  5138. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5139. x = xpt[0];
  5140. y = xpt[1];
  5141. var obj = {
  5142. type: 'mt',
  5143. x: x,
  5144. y: y
  5145. };
  5146. this.path.push(obj);
  5147. },
  5148. _wrapX: function _wrapX(x) {
  5149. if (this.pageWrapXEnabled) {
  5150. return x % this.pageWrapX;
  5151. } else {
  5152. return x;
  5153. }
  5154. },
  5155. _wrapY: function _wrapY(y) {
  5156. if (this.pageWrapYEnabled) {
  5157. this._gotoPage(this._page(y));
  5158. return (y - this.lastBreak) % this.pageWrapY;
  5159. } else {
  5160. return y;
  5161. }
  5162. },
  5163. transform: function transform(a, b, c, d, e, f) {
  5164. //TODO apply to current transformation instead of replacing
  5165. this.ctx._transform = [a, b, c, d, e, f];
  5166. },
  5167. setTransform: function setTransform(a, b, c, d, e, f) {
  5168. this.ctx._transform = [a, b, c, d, e, f];
  5169. },
  5170. _getTransform: function _getTransform() {
  5171. return this.ctx._transform;
  5172. },
  5173. lastBreak: 0,
  5174. // Y Position of page breaks.
  5175. pageBreaks: [],
  5176. // returns: One-based Page Number
  5177. // Should only be used if pageWrapYEnabled is true
  5178. _page: function _page(y) {
  5179. if (this.pageWrapYEnabled) {
  5180. this.lastBreak = 0;
  5181. var manualBreaks = 0;
  5182. var autoBreaks = 0;
  5183. for (var i = 0; i < this.pageBreaks.length; i++) {
  5184. if (y >= this.pageBreaks[i]) {
  5185. manualBreaks++;
  5186. if (this.lastBreak === 0) {
  5187. autoBreaks++;
  5188. }
  5189. var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
  5190. this.lastBreak = this.pageBreaks[i];
  5191. var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
  5192. autoBreaks += pagesSinceLastBreak;
  5193. }
  5194. }
  5195. if (this.lastBreak === 0) {
  5196. var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
  5197. autoBreaks += pagesSinceLastBreak;
  5198. }
  5199. return autoBreaks + manualBreaks;
  5200. } else {
  5201. return this.pdf.internal.getCurrentPageInfo().pageNumber;
  5202. }
  5203. },
  5204. _gotoPage: function _gotoPage(pageOneBased) {
  5205. // This is a stub to be overriden if needed
  5206. },
  5207. lineTo: function lineTo(x, y) {
  5208. x = this._wrapX(x);
  5209. y = this._wrapY(y);
  5210. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5211. x = xpt[0];
  5212. y = xpt[1];
  5213. var obj = {
  5214. type: 'lt',
  5215. x: x,
  5216. y: y
  5217. };
  5218. this.path.push(obj);
  5219. },
  5220. bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
  5221. x1 = this._wrapX(x1);
  5222. y1 = this._wrapY(y1);
  5223. x2 = this._wrapX(x2);
  5224. y2 = this._wrapY(y2);
  5225. x = this._wrapX(x);
  5226. y = this._wrapY(y);
  5227. var xpt;
  5228. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5229. x = xpt[0];
  5230. y = xpt[1];
  5231. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5232. x1 = xpt[0];
  5233. y1 = xpt[1];
  5234. xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
  5235. x2 = xpt[0];
  5236. y2 = xpt[1];
  5237. var obj = {
  5238. type: 'bct',
  5239. x1: x1,
  5240. y1: y1,
  5241. x2: x2,
  5242. y2: y2,
  5243. x: x,
  5244. y: y
  5245. };
  5246. this.path.push(obj);
  5247. },
  5248. quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
  5249. x1 = this._wrapX(x1);
  5250. y1 = this._wrapY(y1);
  5251. x = this._wrapX(x);
  5252. y = this._wrapY(y);
  5253. var xpt;
  5254. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5255. x = xpt[0];
  5256. y = xpt[1];
  5257. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  5258. x1 = xpt[0];
  5259. y1 = xpt[1];
  5260. var obj = {
  5261. type: 'qct',
  5262. x1: x1,
  5263. y1: y1,
  5264. x: x,
  5265. y: y
  5266. };
  5267. this.path.push(obj);
  5268. },
  5269. arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
  5270. x = this._wrapX(x);
  5271. y = this._wrapY(y);
  5272. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  5273. x = xpt[0];
  5274. y = xpt[1];
  5275. var obj = {
  5276. type: 'arc',
  5277. x: x,
  5278. y: y,
  5279. radius: radius,
  5280. startAngle: startAngle,
  5281. endAngle: endAngle,
  5282. anticlockwise: anticlockwise
  5283. };
  5284. this.path.push(obj);
  5285. },
  5286. drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
  5287. if (x2 !== undefined) {
  5288. x = x2;
  5289. y = y2;
  5290. w = w2;
  5291. h = h2;
  5292. }
  5293. x = this._wrapX(x);
  5294. y = this._wrapY(y);
  5295. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5296. var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
  5297. // TODO implement source clipping and image scaling
  5298. var format;
  5299. var rx = /data:image\/(\w+).*/i;
  5300. var m = rx.exec(img);
  5301. if (m != null) {
  5302. format = m[1];
  5303. } else {
  5304. // format = "jpeg";
  5305. format = "png";
  5306. }
  5307. this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
  5308. },
  5309. /**
  5310. * Multiply the first matrix by the second
  5311. * @param m1
  5312. * @param m2
  5313. * @returns {*[]}
  5314. * @private
  5315. */
  5316. _matrix_multiply: function _matrix_multiply(m2, m1) {
  5317. var sx = m1[0];
  5318. var shy = m1[1];
  5319. var shx = m1[2];
  5320. var sy = m1[3];
  5321. var tx = m1[4];
  5322. var ty = m1[5];
  5323. var t0 = sx * m2[0] + shy * m2[2];
  5324. var t2 = shx * m2[0] + sy * m2[2];
  5325. var t4 = tx * m2[0] + ty * m2[2] + m2[4];
  5326. shy = sx * m2[1] + shy * m2[3];
  5327. sy = shx * m2[1] + sy * m2[3];
  5328. ty = tx * m2[1] + ty * m2[3] + m2[5];
  5329. sx = t0;
  5330. shx = t2;
  5331. tx = t4;
  5332. return [sx, shy, shx, sy, tx, ty];
  5333. },
  5334. _matrix_rotation: function _matrix_rotation(m) {
  5335. return Math.atan2(m[2], m[0]);
  5336. },
  5337. _matrix_decompose: function _matrix_decompose(matrix) {
  5338. var a = matrix[0];
  5339. var b = matrix[1];
  5340. var c = matrix[2];
  5341. var d = matrix[3];
  5342. var scaleX = Math.sqrt(a * a + b * b);
  5343. a /= scaleX;
  5344. b /= scaleX;
  5345. var shear = a * c + b * d;
  5346. c -= a * shear;
  5347. d -= b * shear;
  5348. var scaleY = Math.sqrt(c * c + d * d);
  5349. c /= scaleY;
  5350. d /= scaleY;
  5351. shear /= scaleY;
  5352. if (a * d < b * c) {
  5353. a = -a;
  5354. b = -b;
  5355. shear = -shear;
  5356. scaleX = -scaleX;
  5357. }
  5358. return {
  5359. scale: [scaleX, 0, 0, scaleY, 0, 0],
  5360. translate: [1, 0, 0, 1, matrix[4], matrix[5]],
  5361. rotate: [a, b, -b, a, 0, 0],
  5362. skew: [1, 0, shear, 1, 0, 0]
  5363. };
  5364. },
  5365. _matrix_map_point: function _matrix_map_point(m1, pt) {
  5366. var sx = m1[0];
  5367. var shy = m1[1];
  5368. var shx = m1[2];
  5369. var sy = m1[3];
  5370. var tx = m1[4];
  5371. var ty = m1[5];
  5372. var px = pt[0];
  5373. var py = pt[1];
  5374. var x = px * sx + py * shx + tx;
  5375. var y = px * shy + py * sy + ty;
  5376. return [x, y];
  5377. },
  5378. _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
  5379. var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
  5380. return { x: xpt[0], y: xpt[1] };
  5381. },
  5382. _matrix_map_rect: function _matrix_map_rect(m1, rect) {
  5383. var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
  5384. var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
  5385. return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
  5386. },
  5387. _matrix_is_identity: function _matrix_is_identity(m1) {
  5388. if (m1[0] != 1) {
  5389. return false;
  5390. }
  5391. if (m1[1] != 0) {
  5392. return false;
  5393. }
  5394. if (m1[2] != 0) {
  5395. return false;
  5396. }
  5397. if (m1[3] != 1) {
  5398. return false;
  5399. }
  5400. if (m1[4] != 0) {
  5401. return false;
  5402. }
  5403. if (m1[5] != 0) {
  5404. return false;
  5405. }
  5406. return true;
  5407. },
  5408. rotate: function rotate(angle) {
  5409. var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
  5410. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5411. },
  5412. scale: function scale(sx, sy) {
  5413. var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
  5414. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5415. },
  5416. translate: function translate(x, y) {
  5417. var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
  5418. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  5419. },
  5420. stroke: function stroke() {
  5421. if (this.ctx._clip_path.length > 0) {
  5422. var lines;
  5423. if (window.outIntercept) {
  5424. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5425. } else {
  5426. lines = this.pdf.internal.pages[1];
  5427. }
  5428. lines.push("q");
  5429. var origPath = this.path;
  5430. this.path = this.ctx._clip_path;
  5431. this.ctx._clip_path = [];
  5432. this._stroke(true);
  5433. this.ctx._clip_path = this.path;
  5434. this.path = origPath;
  5435. this._stroke(false);
  5436. lines.push("Q");
  5437. } else {
  5438. this._stroke(false);
  5439. }
  5440. },
  5441. _stroke: function _stroke(isClip) {
  5442. if (!isClip && this._isStrokeTransparent()) {
  5443. return;
  5444. }
  5445. //TODO opacity
  5446. var moves = [];
  5447. var closed = false;
  5448. var xPath = this.path;
  5449. for (var i = 0; i < xPath.length; i++) {
  5450. var pt = xPath[i];
  5451. switch (pt.type) {
  5452. case 'mt':
  5453. moves.push({ start: pt, deltas: [], abs: [] });
  5454. break;
  5455. case 'lt':
  5456. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5457. moves[moves.length - 1].deltas.push(delta);
  5458. moves[moves.length - 1].abs.push(pt);
  5459. break;
  5460. case 'bct':
  5461. 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];
  5462. moves[moves.length - 1].deltas.push(delta);
  5463. break;
  5464. case 'qct':
  5465. // convert to bezier
  5466. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5467. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5468. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5469. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5470. var x3 = pt.x;
  5471. var y3 = pt.y;
  5472. 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];
  5473. moves[moves.length - 1].deltas.push(delta);
  5474. break;
  5475. case 'arc':
  5476. moves[moves.length - 1].arc = true;
  5477. moves[moves.length - 1].abs.push(pt);
  5478. break;
  5479. case 'close':
  5480. closed = true;
  5481. break;
  5482. }
  5483. }
  5484. for (var i = 0; i < moves.length; i++) {
  5485. var style;
  5486. if (i == moves.length - 1) {
  5487. style = 's';
  5488. } else {
  5489. style = null;
  5490. }
  5491. if (moves[i].arc) {
  5492. var arcs = moves[i].abs;
  5493. for (var ii = 0; ii < arcs.length; ii++) {
  5494. var arc = arcs[ii];
  5495. var start = arc.startAngle * 360 / (2 * Math.PI);
  5496. var end = arc.endAngle * 360 / (2 * Math.PI);
  5497. var x = arc.x;
  5498. var y = arc.y;
  5499. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
  5500. }
  5501. } else {
  5502. var x = moves[i].start.x;
  5503. var y = moves[i].start.y;
  5504. if (!isClip) {
  5505. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5506. } else {
  5507. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5508. this.pdf.clip_fixed();
  5509. }
  5510. }
  5511. }
  5512. },
  5513. _isFillTransparent: function _isFillTransparent() {
  5514. return this.ctx._isFillTransparent || this.globalAlpha == 0;
  5515. },
  5516. _isStrokeTransparent: function _isStrokeTransparent() {
  5517. return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
  5518. },
  5519. fill: function fill(fillRule) {
  5520. //evenodd or nonzero (default)
  5521. if (this.ctx._clip_path.length > 0) {
  5522. var lines;
  5523. if (window.outIntercept) {
  5524. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5525. } else {
  5526. lines = this.pdf.internal.pages[1];
  5527. }
  5528. lines.push("q");
  5529. var origPath = this.path;
  5530. this.path = this.ctx._clip_path;
  5531. this.ctx._clip_path = [];
  5532. this._fill(fillRule, true);
  5533. this.ctx._clip_path = this.path;
  5534. this.path = origPath;
  5535. this._fill(fillRule, false);
  5536. lines.push('Q');
  5537. } else {
  5538. this._fill(fillRule, false);
  5539. }
  5540. },
  5541. _fill: function _fill(fillRule, isClip) {
  5542. if (this._isFillTransparent()) {
  5543. return;
  5544. }
  5545. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5546. var lines;
  5547. if (window.outIntercept) {
  5548. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  5549. } else {
  5550. lines = this.pdf.internal.pages[1];
  5551. }
  5552. // if (this.ctx._clip_path.length > 0) {
  5553. // lines.push('q');
  5554. // var oldPath = this.path;
  5555. // this.path = this.ctx._clip_path;
  5556. // this.ctx._clip_path = [];
  5557. // this._fill(fillRule, true);
  5558. // this.ctx._clip_path = this.path;
  5559. // this.path = oldPath;
  5560. // }
  5561. var moves = [];
  5562. var outInterceptOld = window.outIntercept;
  5563. if (v2Support) {
  5564. // Blend and Mask
  5565. switch (this.ctx.globalCompositeOperation) {
  5566. case 'normal':
  5567. case 'source-over':
  5568. break;
  5569. case 'destination-in':
  5570. case 'destination-out':
  5571. //TODO this need to be added to the current group or page
  5572. // define a mask stream
  5573. var obj = this.pdf.internal.newStreamObject();
  5574. // define a mask state
  5575. var obj2 = this.pdf.internal.newObject2();
  5576. obj2.push('<</Type /ExtGState');
  5577. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5578. obj2.push('>>');
  5579. // add mask to page resources
  5580. var gsName = 'MASK' + obj2.objId;
  5581. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5582. var instruction = '/' + gsName + ' gs';
  5583. // add mask to page, group, or stream
  5584. lines.splice(0, 0, 'q');
  5585. lines.splice(1, 0, instruction);
  5586. lines.push('Q');
  5587. window.outIntercept = obj;
  5588. break;
  5589. default:
  5590. var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
  5591. if (dictionaryEntry) {
  5592. this.pdf.internal.out(dictionaryEntry + ' gs');
  5593. }
  5594. break;
  5595. }
  5596. }
  5597. var alpha = this.ctx.globalAlpha;
  5598. if (this.ctx._fillOpacity < 1) {
  5599. // TODO combine this with global opacity
  5600. alpha = this.ctx._fillOpacity;
  5601. }
  5602. //TODO check for an opacity graphics state that was already created
  5603. //TODO do not set opacity if current value is already active
  5604. if (v2Support) {
  5605. var objOpac = this.pdf.internal.newObject2();
  5606. objOpac.push('<</Type /ExtGState');
  5607. //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
  5608. //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
  5609. objOpac.push('/CA ' + alpha); // Stroke
  5610. objOpac.push('/ca ' + alpha); // Not Stroke
  5611. objOpac.push('>>');
  5612. var gsName = 'GS_O_' + objOpac.objId;
  5613. this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
  5614. this.pdf.internal.out('/' + gsName + ' gs');
  5615. }
  5616. var xPath = this.path;
  5617. for (var i = 0; i < xPath.length; i++) {
  5618. var pt = xPath[i];
  5619. switch (pt.type) {
  5620. case 'mt':
  5621. moves.push({ start: pt, deltas: [], abs: [] });
  5622. break;
  5623. case 'lt':
  5624. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  5625. moves[moves.length - 1].deltas.push(delta);
  5626. moves[moves.length - 1].abs.push(pt);
  5627. break;
  5628. case 'bct':
  5629. 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];
  5630. moves[moves.length - 1].deltas.push(delta);
  5631. break;
  5632. case 'qct':
  5633. // convert to bezier
  5634. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  5635. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  5636. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  5637. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  5638. var x3 = pt.x;
  5639. var y3 = pt.y;
  5640. 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];
  5641. moves[moves.length - 1].deltas.push(delta);
  5642. break;
  5643. case 'arc':
  5644. //TODO this was hack to avoid out of bounds issue
  5645. if (moves.length == 0) {
  5646. moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
  5647. }
  5648. moves[moves.length - 1].arc = true;
  5649. moves[moves.length - 1].abs.push(pt);
  5650. break;
  5651. case 'close':
  5652. //moves[moves.length - 1].deltas.push('close');
  5653. break;
  5654. }
  5655. }
  5656. for (var i = 0; i < moves.length; i++) {
  5657. var style;
  5658. if (i == moves.length - 1) {
  5659. style = 'f';
  5660. if (fillRule === 'evenodd') {
  5661. style += '*';
  5662. }
  5663. } else {
  5664. style = null;
  5665. }
  5666. if (moves[i].arc) {
  5667. var arcs = moves[i].abs;
  5668. for (var ii = 0; ii < arcs.length; ii++) {
  5669. var arc = arcs[ii];
  5670. //TODO lines deltas were getting in here
  5671. if (typeof arc.startAngle !== 'undefined') {
  5672. var start = arc.startAngle * 360 / (2 * Math.PI);
  5673. var end = arc.endAngle * 360 / (2 * Math.PI);
  5674. // Add the current position (last move to)
  5675. //var x = moves[i].start.x + arc.x;
  5676. //var y = moves[i].start.y + arc.y;
  5677. var x = arc.x;
  5678. var y = arc.y;
  5679. if (ii == 0) {
  5680. this.internal.move2(this, x, y);
  5681. }
  5682. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
  5683. } else {
  5684. this.internal.line2(c2d, arc.x, arc.y);
  5685. }
  5686. }
  5687. // extra move bug causing close to resolve to wrong point
  5688. var x = moves[i].start.x;
  5689. var y = moves[i].start.y;
  5690. this.internal.line2(c2d, x, y);
  5691. this.pdf.internal.out('h');
  5692. this.pdf.internal.out('f');
  5693. } else {
  5694. var x = moves[i].start.x;
  5695. var y = moves[i].start.y;
  5696. if (!isClip) {
  5697. this.pdf.lines(moves[i].deltas, x, y, null, style);
  5698. } else {
  5699. this.pdf.lines(moves[i].deltas, x, y, null, null);
  5700. this.pdf.clip_fixed();
  5701. }
  5702. }
  5703. }
  5704. window.outIntercept = outInterceptOld;
  5705. // if (this.ctx._clip_path.length > 0) {
  5706. // lines.push('Q');
  5707. // }
  5708. },
  5709. pushMask: function pushMask() {
  5710. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  5711. if (!v2Support) {
  5712. console.log('jsPDF v2 not enabled');
  5713. return;
  5714. }
  5715. // define a mask stream
  5716. var obj = this.pdf.internal.newStreamObject();
  5717. // define a mask state
  5718. var obj2 = this.pdf.internal.newObject2();
  5719. obj2.push('<</Type /ExtGState');
  5720. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  5721. obj2.push('>>');
  5722. // add mask to page resources
  5723. var gsName = 'MASK' + obj2.objId;
  5724. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  5725. var instruction = '/' + gsName + ' gs';
  5726. this.pdf.internal.out(instruction);
  5727. },
  5728. clip: function clip() {
  5729. //TODO do we reset the path, or just copy it?
  5730. if (this.ctx._clip_path.length > 0) {
  5731. for (var i = 0; i < this.path.length; i++) {
  5732. this.ctx._clip_path.push(this.path[i]);
  5733. }
  5734. } else {
  5735. this.ctx._clip_path = this.path;
  5736. }
  5737. this.path = [];
  5738. },
  5739. measureText: function measureText(text) {
  5740. var pdf = this.pdf;
  5741. return {
  5742. getWidth: function getWidth() {
  5743. var fontSize = pdf.internal.getFontSize();
  5744. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  5745. return txtWidth;
  5746. },
  5747. get width() {
  5748. return this.getWidth(text);
  5749. }
  5750. };
  5751. },
  5752. _getBaseline: function _getBaseline(y) {
  5753. var height = parseInt(this.pdf.internal.getFontSize());
  5754. // TODO Get descent from font descriptor
  5755. var descent = height * .25;
  5756. switch (this.ctx.textBaseline) {
  5757. case 'bottom':
  5758. return y - descent;
  5759. case 'top':
  5760. return y + height;
  5761. case 'hanging':
  5762. return y + height - descent;
  5763. case 'middle':
  5764. return y + height / 2 - descent;
  5765. case 'ideographic':
  5766. // TODO not implemented
  5767. return y;
  5768. case 'alphabetic':
  5769. default:
  5770. return y;
  5771. }
  5772. }
  5773. };
  5774. var c2d = jsPDFAPI.context2d;
  5775. // accessor methods
  5776. Object.defineProperty(c2d, 'fillStyle', {
  5777. set: function set(value) {
  5778. this.setFillStyle(value);
  5779. },
  5780. get: function get() {
  5781. return this.ctx.fillStyle;
  5782. }
  5783. });
  5784. Object.defineProperty(c2d, 'strokeStyle', {
  5785. set: function set(value) {
  5786. this.setStrokeStyle(value);
  5787. },
  5788. get: function get() {
  5789. return this.ctx.strokeStyle;
  5790. }
  5791. });
  5792. Object.defineProperty(c2d, 'lineWidth', {
  5793. set: function set(value) {
  5794. this.setLineWidth(value);
  5795. },
  5796. get: function get() {
  5797. return this.ctx.lineWidth;
  5798. }
  5799. });
  5800. Object.defineProperty(c2d, 'lineCap', {
  5801. set: function set(val) {
  5802. this.setLineCap(val);
  5803. },
  5804. get: function get() {
  5805. return this.ctx.lineCap;
  5806. }
  5807. });
  5808. Object.defineProperty(c2d, 'lineJoin', {
  5809. set: function set(val) {
  5810. this.setLineJoin(val);
  5811. },
  5812. get: function get() {
  5813. return this.ctx.lineJoin;
  5814. }
  5815. });
  5816. Object.defineProperty(c2d, 'miterLimit', {
  5817. set: function set(val) {
  5818. this.ctx.miterLimit = val;
  5819. },
  5820. get: function get() {
  5821. return this.ctx.miterLimit;
  5822. }
  5823. });
  5824. Object.defineProperty(c2d, 'textBaseline', {
  5825. set: function set(value) {
  5826. this.setTextBaseline(value);
  5827. },
  5828. get: function get() {
  5829. return this.getTextBaseline();
  5830. }
  5831. });
  5832. Object.defineProperty(c2d, 'textAlign', {
  5833. set: function set(value) {
  5834. this.setTextAlign(value);
  5835. },
  5836. get: function get() {
  5837. return this.getTextAlign();
  5838. }
  5839. });
  5840. Object.defineProperty(c2d, 'font', {
  5841. set: function set(value) {
  5842. this.setFont(value);
  5843. },
  5844. get: function get() {
  5845. return this.ctx.font;
  5846. }
  5847. });
  5848. Object.defineProperty(c2d, 'globalCompositeOperation', {
  5849. set: function set(value) {
  5850. this.ctx.globalCompositeOperation = value;
  5851. },
  5852. get: function get() {
  5853. return this.ctx.globalCompositeOperation;
  5854. }
  5855. });
  5856. Object.defineProperty(c2d, 'globalAlpha', {
  5857. set: function set(value) {
  5858. this.ctx.globalAlpha = value;
  5859. },
  5860. get: function get() {
  5861. return this.ctx.globalAlpha;
  5862. }
  5863. });
  5864. // Not HTML API
  5865. Object.defineProperty(c2d, 'ignoreClearRect', {
  5866. set: function set(value) {
  5867. this.ctx.ignoreClearRect = value;
  5868. },
  5869. get: function get() {
  5870. return this.ctx.ignoreClearRect;
  5871. }
  5872. });
  5873. // End Not HTML API
  5874. c2d.internal = {};
  5875. c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  5876. c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  5877. c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  5878. // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
  5879. c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
  5880. var includeMove = true;
  5881. var k = this.pdf.internal.scaleFactor;
  5882. var pageHeight = this.pdf.internal.pageSize.height;
  5883. var f2 = this.pdf.internal.f2;
  5884. var a1r = a1 * (Math.PI / 180);
  5885. var a2r = a2 * (Math.PI / 180);
  5886. var curves = this.createArc(r, a1r, a2r, anticlockwise);
  5887. var pathData = null;
  5888. for (var i = 0; i < curves.length; i++) {
  5889. var curve = curves[i];
  5890. if (includeMove && i == 0) {
  5891. 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(' '));
  5892. } else {
  5893. 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(' '));
  5894. }
  5895. //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
  5896. c2d._lastPoint = { x: xc, y: yc };
  5897. // 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'
  5898. }
  5899. if (style !== null) {
  5900. this.pdf.internal.out(this.pdf.internal.getStyle(style));
  5901. }
  5902. };
  5903. /**
  5904. *
  5905. * @param x Edge point X
  5906. * @param y Edge point Y
  5907. * @param r Radius
  5908. * @param a1 start angle
  5909. * @param a2 end angle
  5910. * @param anticlockwise
  5911. * @param style
  5912. * @param isClip
  5913. */
  5914. c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
  5915. // we need to convert from cartesian to polar here methinks.
  5916. var centerX = x; // + r;
  5917. var centerY = y;
  5918. if (false) {}
  5919. if (!isClip) {
  5920. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
  5921. } else {
  5922. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
  5923. this.pdf.clip_fixed();
  5924. }
  5925. };
  5926. c2d.internal.move2 = function (c2d, x, y) {
  5927. var k = this.pdf.internal.scaleFactor;
  5928. var pageHeight = this.pdf.internal.pageSize.height;
  5929. var f2 = this.pdf.internal.f2;
  5930. this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
  5931. c2d._lastPoint = { x: x, y: y };
  5932. };
  5933. c2d.internal.line2 = function (c2d, dx, dy) {
  5934. var k = this.pdf.internal.scaleFactor;
  5935. var pageHeight = this.pdf.internal.pageSize.height;
  5936. var f2 = this.pdf.internal.f2;
  5937. //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
  5938. var pt = { x: dx, y: dy };
  5939. this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
  5940. //this.pdf.internal.out('f');
  5941. c2d._lastPoint = pt;
  5942. };
  5943. /**
  5944. * 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.
  5945. *
  5946. * 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.
  5947. */
  5948. c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
  5949. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
  5950. // normalize startAngle, endAngle to [-2PI, 2PI]
  5951. var twoPI = Math.PI * 2;
  5952. var startAngleN = startAngle;
  5953. if (startAngleN < twoPI || startAngleN > twoPI) {
  5954. startAngleN = startAngleN % twoPI;
  5955. }
  5956. var endAngleN = endAngle;
  5957. if (endAngleN < twoPI || endAngleN > twoPI) {
  5958. endAngleN = endAngleN % twoPI;
  5959. }
  5960. // Compute the sequence of arc curves, up to PI/2 at a time.
  5961. // Total arc angle is less than 2PI.
  5962. var curves = [];
  5963. var piOverTwo = Math.PI / 2.0;
  5964. // var sgn = (startAngle < endAngle) ? +1 : -1; // clockwise or counterclockwise
  5965. var sgn = anticlockwise ? -1 : +1;
  5966. var a1 = startAngle;
  5967. for (var totalAngle = Math.min(twoPI, Math.abs(endAngleN - startAngleN)); totalAngle > EPSILON;) {
  5968. var a2 = a1 + sgn * Math.min(totalAngle, piOverTwo);
  5969. curves.push(this.createSmallArc(radius, a1, a2));
  5970. totalAngle -= Math.abs(a2 - a1);
  5971. a1 = a2;
  5972. }
  5973. return curves;
  5974. };
  5975. /**
  5976. * 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.
  5977. *
  5978. * 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.
  5979. *
  5980. * 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.
  5981. */
  5982. c2d.internal.createSmallArc = function (r, a1, a2) {
  5983. // Compute all four points for an arc that subtends the same total angle
  5984. // but is centered on the X-axis
  5985. var a = (a2 - a1) / 2.0;
  5986. var x4 = r * Math.cos(a);
  5987. var y4 = r * Math.sin(a);
  5988. var x1 = x4;
  5989. var y1 = -y4;
  5990. var q1 = x1 * x1 + y1 * y1;
  5991. var q2 = q1 + x1 * x4 + y1 * y4;
  5992. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  5993. var x2 = x1 - k2 * y1;
  5994. var y2 = y1 + k2 * x1;
  5995. var x3 = x2;
  5996. var y3 = -y2;
  5997. // Find the arc points' actual locations by computing x1,y1 and x4,y4
  5998. // and rotating the control points by a + a1
  5999. var ar = a + a1;
  6000. var cos_ar = Math.cos(ar);
  6001. var sin_ar = Math.sin(ar);
  6002. return {
  6003. x1: r * Math.cos(a1),
  6004. y1: r * Math.sin(a1),
  6005. x2: x2 * cos_ar - y2 * sin_ar,
  6006. y2: x2 * sin_ar + y2 * cos_ar,
  6007. x3: x3 * cos_ar - y3 * sin_ar,
  6008. y3: x3 * sin_ar + y3 * cos_ar,
  6009. x4: r * Math.cos(a2),
  6010. y4: r * Math.sin(a2)
  6011. };
  6012. };
  6013. function context() {
  6014. this._isStrokeTransparent = false;
  6015. this._strokeOpacity = 1;
  6016. this.strokeStyle = '#000000';
  6017. this.fillStyle = '#000000';
  6018. this._isFillTransparent = false;
  6019. this._fillOpacity = 1;
  6020. this.font = "12pt times";
  6021. this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
  6022. this.textAlign = 'start';
  6023. this.lineWidth = 1;
  6024. this.lineJoin = 'miter'; // round, bevel, miter
  6025. this.lineCap = 'butt'; // butt, round, square
  6026. this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
  6027. this.globalCompositeOperation = 'normal';
  6028. this.globalAlpha = 1.0;
  6029. this._clip_path = [];
  6030. // TODO miter limit //default 10
  6031. // Not HTML API
  6032. this.ignoreClearRect = false;
  6033. this.copy = function (ctx) {
  6034. this._isStrokeTransparent = ctx._isStrokeTransparent;
  6035. this._strokeOpacity = ctx._strokeOpacity;
  6036. this.strokeStyle = ctx.strokeStyle;
  6037. this._isFillTransparent = ctx._isFillTransparent;
  6038. this._fillOpacity = ctx._fillOpacity;
  6039. this.fillStyle = ctx.fillStyle;
  6040. this.font = ctx.font;
  6041. this.lineWidth = ctx.lineWidth;
  6042. this.lineJoin = ctx.lineJoin;
  6043. this.lineCap = ctx.lineCap;
  6044. this.textBaseline = ctx.textBaseline;
  6045. this.textAlign = ctx.textAlign;
  6046. this._fontSize = ctx._fontSize;
  6047. this._transform = ctx._transform.slice(0);
  6048. this.globalCompositeOperation = ctx.globalCompositeOperation;
  6049. this.globalAlpha = ctx.globalAlpha;
  6050. this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
  6051. // Not HTML API
  6052. this.ignoreClearRect = ctx.ignoreClearRect;
  6053. };
  6054. }
  6055. return this;
  6056. })(jsPDF.API);
  6057. /** @preserve
  6058. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  6059. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  6060. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  6061. * 2014 Diego Casorran, https://github.com/diegocr
  6062. * 2014 Daniel Husar, https://github.com/danielhusar
  6063. * 2014 Wolfgang Gassler, https://github.com/woolfg
  6064. * 2014 Steven Spungin, https://github.com/flamenco
  6065. *
  6066. *
  6067. * ====================================================================
  6068. */
  6069. (function (jsPDFAPI) {
  6070. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  6071. clone = function () {
  6072. return function (obj) {
  6073. Clone.prototype = obj;
  6074. return new Clone();
  6075. };
  6076. function Clone() {}
  6077. }();
  6078. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  6079. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  6080. i = 0;
  6081. l = array.length;
  6082. fragment = void 0;
  6083. lTrimmed = false;
  6084. rTrimmed = false;
  6085. while (!lTrimmed && i !== l) {
  6086. fragment = array[i] = array[i].trimLeft();
  6087. if (fragment) {
  6088. lTrimmed = true;
  6089. }
  6090. i++;
  6091. }
  6092. i = l - 1;
  6093. while (l && !rTrimmed && i !== -1) {
  6094. fragment = array[i] = array[i].trimRight();
  6095. if (fragment) {
  6096. rTrimmed = true;
  6097. }
  6098. i--;
  6099. }
  6100. r = /\s+$/g;
  6101. trailingSpace = true;
  6102. i = 0;
  6103. while (i !== l) {
  6104. // Leave the line breaks intact
  6105. if (array[i] != "\u2028") {
  6106. fragment = array[i].replace(/\s+/g, " ");
  6107. if (trailingSpace) {
  6108. fragment = fragment.trimLeft();
  6109. }
  6110. if (fragment) {
  6111. trailingSpace = r.test(fragment);
  6112. }
  6113. array[i] = fragment;
  6114. }
  6115. i++;
  6116. }
  6117. return array;
  6118. };
  6119. Renderer = function Renderer(pdf, x, y, settings) {
  6120. this.pdf = pdf;
  6121. this.x = x;
  6122. this.y = y;
  6123. this.settings = settings;
  6124. //list of functions which are called after each element-rendering process
  6125. this.watchFunctions = [];
  6126. this.init();
  6127. return this;
  6128. };
  6129. ResolveFont = function ResolveFont(css_font_family_string) {
  6130. var name, part, parts;
  6131. name = void 0;
  6132. parts = css_font_family_string.split(",");
  6133. part = parts.shift();
  6134. while (!name && part) {
  6135. name = FontNameDB[part.trim().toLowerCase()];
  6136. part = parts.shift();
  6137. }
  6138. return name;
  6139. };
  6140. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  6141. //IE8 issues
  6142. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  6143. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  6144. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  6145. }
  6146. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  6147. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  6148. }
  6149. var normal, undef, value;
  6150. undef = void 0;
  6151. normal = 16.00;
  6152. value = UnitedNumberMap[css_line_height_string];
  6153. if (value) {
  6154. return value;
  6155. }
  6156. value = {
  6157. "xx-small": 9,
  6158. "x-small": 11,
  6159. small: 13,
  6160. medium: 16,
  6161. large: 19,
  6162. "x-large": 23,
  6163. "xx-large": 28,
  6164. auto: 0
  6165. }[{ css_line_height_string: css_line_height_string }];
  6166. if (value !== undef) {
  6167. return UnitedNumberMap[css_line_height_string] = value / normal;
  6168. }
  6169. if (value = parseFloat(css_line_height_string)) {
  6170. return UnitedNumberMap[css_line_height_string] = value / normal;
  6171. }
  6172. value = css_line_height_string.match(/([\d\.]+)(px)/);
  6173. if (value.length === 3) {
  6174. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  6175. }
  6176. return UnitedNumberMap[css_line_height_string] = 1;
  6177. };
  6178. GetCSS = function GetCSS(element) {
  6179. var css, tmp, computedCSSElement;
  6180. computedCSSElement = function (el) {
  6181. var compCSS;
  6182. compCSS = function (el) {
  6183. if (document.defaultView && document.defaultView.getComputedStyle) {
  6184. return document.defaultView.getComputedStyle(el, null);
  6185. } else if (el.currentStyle) {
  6186. return el.currentStyle;
  6187. } else {
  6188. return el.style;
  6189. }
  6190. }(el);
  6191. return function (prop) {
  6192. prop = prop.replace(/-\D/g, function (match) {
  6193. return match.charAt(1).toUpperCase();
  6194. });
  6195. return compCSS[prop];
  6196. };
  6197. }(element);
  6198. css = {};
  6199. tmp = void 0;
  6200. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  6201. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  6202. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  6203. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  6204. if (tmp === "bold") {
  6205. if (css["font-style"] === "normal") {
  6206. css["font-style"] = tmp;
  6207. } else {
  6208. css["font-style"] = tmp + css["font-style"];
  6209. }
  6210. }
  6211. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  6212. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  6213. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  6214. tmp = css["display"] === "block";
  6215. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  6216. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  6217. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  6218. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  6219. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  6220. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  6221. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  6222. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  6223. css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
  6224. //float and clearing of floats
  6225. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  6226. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  6227. css["color"] = computedCSSElement("color");
  6228. return css;
  6229. };
  6230. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  6231. var handlers, i, isHandledElsewhere, l, t;
  6232. isHandledElsewhere = false;
  6233. i = void 0;
  6234. l = void 0;
  6235. t = void 0;
  6236. handlers = elementHandlers["#" + element.id];
  6237. if (handlers) {
  6238. if (typeof handlers === "function") {
  6239. isHandledElsewhere = handlers(element, renderer);
  6240. } else {
  6241. i = 0;
  6242. l = handlers.length;
  6243. while (!isHandledElsewhere && i !== l) {
  6244. isHandledElsewhere = handlers[i](element, renderer);
  6245. i++;
  6246. }
  6247. }
  6248. }
  6249. handlers = elementHandlers[element.nodeName];
  6250. if (!isHandledElsewhere && handlers) {
  6251. if (typeof handlers === "function") {
  6252. isHandledElsewhere = handlers(element, renderer);
  6253. } else {
  6254. i = 0;
  6255. l = handlers.length;
  6256. while (!isHandledElsewhere && i !== l) {
  6257. isHandledElsewhere = handlers[i](element, renderer);
  6258. i++;
  6259. }
  6260. }
  6261. }
  6262. return isHandledElsewhere;
  6263. };
  6264. tableToJson = function tableToJson(table, renderer) {
  6265. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  6266. data = [];
  6267. headers = [];
  6268. i = 0;
  6269. l = table.rows[0].cells.length;
  6270. table_with = table.clientWidth;
  6271. while (i < l) {
  6272. cell = table.rows[0].cells[i];
  6273. headers[i] = {
  6274. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  6275. prompt: cell.textContent.replace(/\r?\n/g, ''),
  6276. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
  6277. };
  6278. i++;
  6279. }
  6280. i = 1;
  6281. while (i < table.rows.length) {
  6282. tableRow = table.rows[i];
  6283. rowData = {};
  6284. j = 0;
  6285. while (j < tableRow.cells.length) {
  6286. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  6287. j++;
  6288. }
  6289. data.push(rowData);
  6290. i++;
  6291. }
  6292. return table_obj = {
  6293. rows: data,
  6294. headers: headers
  6295. };
  6296. };
  6297. var SkipNode = {
  6298. SCRIPT: 1,
  6299. STYLE: 1,
  6300. NOSCRIPT: 1,
  6301. OBJECT: 1,
  6302. EMBED: 1,
  6303. SELECT: 1
  6304. };
  6305. var listCount = 1;
  6306. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  6307. var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
  6308. cns = element.childNodes;
  6309. cn = void 0;
  6310. fragmentCSS = GetCSS(element);
  6311. isBlock = fragmentCSS.display === "block";
  6312. if (isBlock) {
  6313. renderer.setBlockBoundary();
  6314. renderer.setBlockStyle(fragmentCSS);
  6315. }
  6316. px2pt = 0.264583 * 72 / 25.4;
  6317. i = 0;
  6318. l = cns.length;
  6319. while (i < l) {
  6320. cn = cns[i];
  6321. if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
  6322. //execute all watcher functions to e.g. reset floating
  6323. renderer.executeWatchFunctions(cn);
  6324. /*** HEADER rendering **/
  6325. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  6326. var header = cn;
  6327. //store old top margin
  6328. var oldMarginTop = renderer.pdf.margins_doc.top;
  6329. //subscribe for new page event and render header first on every page
  6330. renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
  6331. //set current y position to old margin
  6332. renderer.y = oldMarginTop;
  6333. //render all child nodes of the header element
  6334. _DrillForContent(header, renderer, elementHandlers);
  6335. //set margin to old margin + rendered header + 10 space to prevent overlapping
  6336. //important for other plugins (e.g. table) to start rendering at correct position after header
  6337. renderer.pdf.margins_doc.top = renderer.y + 10;
  6338. renderer.y += 10;
  6339. }, false);
  6340. }
  6341. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  6342. if (~cn.textContent.indexOf("ADD_PAGE")) {
  6343. renderer.pdf.addPage();
  6344. renderer.y = renderer.pdf.margins_doc.top;
  6345. }
  6346. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  6347. /*** IMAGE RENDERING ***/
  6348. var cached_image;
  6349. if (cn.nodeName === "IMG") {
  6350. var url = cn.getAttribute("src");
  6351. cached_image = images[renderer.pdf.sHashCode(url) || url];
  6352. }
  6353. if (cached_image) {
  6354. if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  6355. renderer.pdf.addPage();
  6356. renderer.y = renderer.pdf.margins_doc.top;
  6357. //check if we have to set back some values due to e.g. header rendering for new page
  6358. renderer.executeWatchFunctions(cn);
  6359. }
  6360. var imagesCSS = GetCSS(cn);
  6361. var imageX = renderer.x;
  6362. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
  6363. //define additional paddings, margins which have to be taken into account for margin calculations
  6364. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  6365. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  6366. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  6367. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
  6368. //if float is set to right, move the image to the right border
  6369. //add space if margin is set
  6370. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  6371. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  6372. } else {
  6373. imageX += additionalSpaceLeft;
  6374. }
  6375. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  6376. cached_image = undefined;
  6377. //if the float prop is specified we have to float the text around the image
  6378. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  6379. //add functiont to set back coordinates after image rendering
  6380. renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
  6381. //undo drawing box adaptions which were set by floating
  6382. if (renderer.y >= thresholdY) {
  6383. renderer.x += diffX;
  6384. renderer.settings.width += diffWidth;
  6385. return true;
  6386. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  6387. renderer.x += diffX;
  6388. renderer.y = thresholdY;
  6389. renderer.settings.width += diffWidth;
  6390. return true;
  6391. } else {
  6392. return false;
  6393. }
  6394. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
  6395. //reset floating by clear:both divs
  6396. //just set cursorY after the floating element
  6397. renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
  6398. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  6399. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  6400. renderer.y = yPositionAfterFloating;
  6401. return true;
  6402. } else {
  6403. return false;
  6404. }
  6405. } else {
  6406. return true;
  6407. }
  6408. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
  6409. //if floating is set we decrease the available width by the image width
  6410. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
  6411. //if left just add the image width to the X coordinate
  6412. if (imagesCSS['float'] === 'left') {
  6413. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  6414. }
  6415. } else {
  6416. //if no floating is set, move the rendering cursor after the image height
  6417. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  6418. }
  6419. /*** TABLE RENDERING ***/
  6420. } else if (cn.nodeName === "TABLE") {
  6421. table2json = tableToJson(cn, renderer);
  6422. renderer.y += 10;
  6423. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  6424. autoSize: false,
  6425. printHeaders: elementHandlers.printHeaders,
  6426. margins: renderer.pdf.margins_doc,
  6427. css: GetCSS(cn)
  6428. });
  6429. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  6430. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  6431. listCount = 1;
  6432. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6433. _DrillForContent(cn, renderer, elementHandlers);
  6434. }
  6435. renderer.y += 10;
  6436. } else if (cn.nodeName === "LI") {
  6437. var temp = renderer.x;
  6438. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  6439. renderer.y += 3;
  6440. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6441. _DrillForContent(cn, renderer, elementHandlers);
  6442. }
  6443. renderer.x = temp;
  6444. } else if (cn.nodeName === "BR") {
  6445. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  6446. renderer.addText("\u2028", clone(fragmentCSS));
  6447. } else {
  6448. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  6449. _DrillForContent(cn, renderer, elementHandlers);
  6450. }
  6451. }
  6452. } else if (cn.nodeType === 3) {
  6453. var value = cn.nodeValue;
  6454. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  6455. if (cn.parentNode.parentNode.nodeName === "OL") {
  6456. value = listCount++ + '. ' + value;
  6457. } else {
  6458. var fontSize = fragmentCSS["font-size"];
  6459. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  6460. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  6461. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  6462. cb = function cb(x, y) {
  6463. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  6464. };
  6465. }
  6466. }
  6467. // Only add the text if the text node is in the body element
  6468. // Add compatibility with IE11
  6469. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  6470. renderer.addText(value, fragmentCSS);
  6471. }
  6472. } else if (typeof cn === "string") {
  6473. renderer.addText(cn, fragmentCSS);
  6474. }
  6475. }
  6476. i++;
  6477. }
  6478. elementHandlers.outY = renderer.y;
  6479. if (isBlock) {
  6480. return renderer.setBlockBoundary(cb);
  6481. }
  6482. };
  6483. images = {};
  6484. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  6485. var imgs = element.getElementsByTagName('img'),
  6486. l = imgs.length,
  6487. found_images,
  6488. x = 0;
  6489. function done() {
  6490. renderer.pdf.internal.events.publish('imagesLoaded');
  6491. cb(found_images);
  6492. }
  6493. function loadImage(url, width, height) {
  6494. if (!url) return;
  6495. var img = new Image();
  6496. found_images = ++x;
  6497. img.crossOrigin = '';
  6498. img.onerror = img.onload = function () {
  6499. if (img.complete) {
  6500. //to support data urls in images, set width and height
  6501. //as those values are not recognized automatically
  6502. if (img.src.indexOf('data:image/') === 0) {
  6503. img.width = width || img.width || 0;
  6504. img.height = height || img.height || 0;
  6505. }
  6506. //if valid image add to known images array
  6507. if (img.width + img.height) {
  6508. var hash = renderer.pdf.sHashCode(url) || url;
  6509. images[hash] = images[hash] || img;
  6510. }
  6511. }
  6512. if (! --x) {
  6513. done();
  6514. }
  6515. };
  6516. img.src = url;
  6517. }
  6518. while (l--) {
  6519. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  6520. }return x || done();
  6521. };
  6522. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  6523. //check if we can found a <footer> element
  6524. var footer = elem.getElementsByTagName("footer");
  6525. if (footer.length > 0) {
  6526. footer = footer[0];
  6527. //bad hack to get height of footer
  6528. //creat dummy out and check new y after fake rendering
  6529. var oldOut = renderer.pdf.internal.write;
  6530. var oldY = renderer.y;
  6531. renderer.pdf.internal.write = function () {};
  6532. _DrillForContent(footer, renderer, elementHandlers);
  6533. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  6534. renderer.y = oldY;
  6535. renderer.pdf.internal.write = oldOut;
  6536. //add 20% to prevent overlapping
  6537. renderer.pdf.margins_doc.bottom += footerHeight;
  6538. //Create function render header on every page
  6539. var renderFooter = function renderFooter(pageInfo) {
  6540. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
  6541. //set current y position to old margin
  6542. var oldPosition = renderer.y;
  6543. //render all child nodes of the header element
  6544. renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
  6545. renderer.pdf.margins_doc.bottom -= footerHeight;
  6546. //check if we have to add page numbers
  6547. var spans = footer.getElementsByTagName('span');
  6548. for (var i = 0; i < spans.length; ++i) {
  6549. //if we find some span element with class pageCounter, set the page
  6550. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  6551. spans[i].innerHTML = pageNumber;
  6552. }
  6553. //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  6554. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6555. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  6556. }
  6557. }
  6558. //render footer content
  6559. _DrillForContent(footer, renderer, elementHandlers);
  6560. //set bottom margin to previous height including the footer height
  6561. renderer.pdf.margins_doc.bottom += footerHeight;
  6562. //important for other plugins (e.g. table) to start rendering at correct position after header
  6563. renderer.y = oldPosition;
  6564. };
  6565. //check if footer contains totalPages which should be replace at the disoposal of the document
  6566. var spans = footer.getElementsByTagName('span');
  6567. for (var i = 0; i < spans.length; ++i) {
  6568. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  6569. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  6570. }
  6571. }
  6572. //register event to render footer on every new page
  6573. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
  6574. //render footer on first page
  6575. renderFooter();
  6576. //prevent footer rendering
  6577. SkipNode['FOOTER'] = 1;
  6578. }
  6579. };
  6580. process = function process(pdf, element, x, y, settings, callback) {
  6581. if (!element) return false;
  6582. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  6583. if (typeof element === "string") {
  6584. element = function (element) {
  6585. var $frame, $hiddendiv, framename, visuallyhidden;
  6586. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  6587. 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;";
  6588. $hiddendiv = document.createElement('div');
  6589. $hiddendiv.style.cssText = visuallyhidden;
  6590. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  6591. document.body.appendChild($hiddendiv);
  6592. $frame = window.frames[framename];
  6593. $frame.document.open();
  6594. $frame.document.writeln(element);
  6595. $frame.document.close();
  6596. return $frame.document.body;
  6597. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  6598. }
  6599. var r = new Renderer(pdf, x, y, settings),
  6600. out;
  6601. // 1. load images
  6602. // 2. prepare optional footer elements
  6603. // 3. render content
  6604. loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
  6605. checkForFooter(element, r, settings.elementHandlers);
  6606. _DrillForContent(element, r, settings.elementHandlers);
  6607. //send event dispose for final taks (e.g. footer totalpage replacement)
  6608. r.pdf.internal.events.publish('htmlRenderingFinished');
  6609. out = r.dispose();
  6610. if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  6611. });
  6612. return out || { x: r.x, y: r.y };
  6613. };
  6614. Renderer.prototype.init = function () {
  6615. this.paragraph = {
  6616. text: [],
  6617. style: []
  6618. };
  6619. return this.pdf.internal.write("q");
  6620. };
  6621. Renderer.prototype.dispose = function () {
  6622. this.pdf.internal.write("Q");
  6623. return {
  6624. x: this.x,
  6625. y: this.y,
  6626. ready: true
  6627. };
  6628. };
  6629. //Checks if we have to execute some watcher functions
  6630. //e.g. to end text floating around an image
  6631. Renderer.prototype.executeWatchFunctions = function (el) {
  6632. var ret = false;
  6633. var narray = [];
  6634. if (this.watchFunctions.length > 0) {
  6635. for (var i = 0; i < this.watchFunctions.length; ++i) {
  6636. if (this.watchFunctions[i](el) === true) {
  6637. ret = true;
  6638. } else {
  6639. narray.push(this.watchFunctions[i]);
  6640. }
  6641. }
  6642. this.watchFunctions = narray;
  6643. }
  6644. return ret;
  6645. };
  6646. Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
  6647. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  6648. defaultFontSize = 12;
  6649. k = this.pdf.internal.scaleFactor;
  6650. fontMetricsCache = {};
  6651. ff = void 0;
  6652. fs = void 0;
  6653. fontMetrics = void 0;
  6654. fragment = void 0;
  6655. style = void 0;
  6656. fragmentSpecificMetrics = void 0;
  6657. fragmentLength = void 0;
  6658. fragmentChopped = void 0;
  6659. line = [];
  6660. lines = [line];
  6661. currentLineLength = 0;
  6662. maxLineLength = this.settings.width;
  6663. while (fragments.length) {
  6664. fragment = fragments.shift();
  6665. style = styles.shift();
  6666. if (fragment) {
  6667. ff = style["font-family"];
  6668. fs = style["font-style"];
  6669. fontMetrics = fontMetricsCache[ff + fs];
  6670. if (!fontMetrics) {
  6671. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  6672. fontMetricsCache[ff + fs] = fontMetrics;
  6673. }
  6674. fragmentSpecificMetrics = {
  6675. widths: fontMetrics.widths,
  6676. kerning: fontMetrics.kerning,
  6677. fontSize: style["font-size"] * defaultFontSize,
  6678. textIndent: currentLineLength
  6679. };
  6680. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6681. if (fragment == "\u2028") {
  6682. line = [];
  6683. lines.push(line);
  6684. } else if (currentLineLength + fragmentLength > maxLineLength) {
  6685. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  6686. line.push([fragmentChopped.shift(), style]);
  6687. while (fragmentChopped.length) {
  6688. line = [[fragmentChopped.shift(), style]];
  6689. lines.push(line);
  6690. }
  6691. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6692. } else {
  6693. line.push([fragment, style]);
  6694. currentLineLength += fragmentLength;
  6695. }
  6696. }
  6697. }
  6698. //if text alignment was set, set margin/indent of each line
  6699. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  6700. for (var i = 0; i < lines.length; ++i) {
  6701. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  6702. //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  6703. if (i > 0) {
  6704. lines[i][0][1] = clone(lines[i][0][1]);
  6705. }
  6706. var space = maxLineLength - length;
  6707. if (style['text-align'] === 'right') {
  6708. lines[i][0][1]['margin-left'] = space;
  6709. //if alignment is not right, it has to be center so split the space to the left and the right
  6710. } else if (style['text-align'] === 'center') {
  6711. lines[i][0][1]['margin-left'] = space / 2;
  6712. //if justify was set, calculate the word spacing and define in by using the css property
  6713. } else if (style['text-align'] === 'justify') {
  6714. var countSpaces = lines[i][0][0].split(' ').length - 1;
  6715. lines[i][0][1]['word-spacing'] = space / countSpaces;
  6716. //ignore the last line in justify mode
  6717. if (i === lines.length - 1) {
  6718. lines[i][0][1]['word-spacing'] = 0;
  6719. }
  6720. }
  6721. }
  6722. }
  6723. return lines;
  6724. };
  6725. Renderer.prototype.RenderTextFragment = function (text, style) {
  6726. var defaultFontSize, font, maxLineHeight;
  6727. maxLineHeight = 0;
  6728. defaultFontSize = 12;
  6729. if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  6730. this.pdf.internal.write("ET", "Q");
  6731. this.pdf.addPage();
  6732. this.y = this.pdf.margins_doc.top;
  6733. this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
  6734. //move cursor by one line on new page
  6735. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  6736. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  6737. }
  6738. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  6739. // text color
  6740. var pdfTextColor = this.getPdfColor(style["color"]);
  6741. if (pdfTextColor !== this.lastTextColor) {
  6742. this.pdf.internal.write(pdfTextColor);
  6743. this.lastTextColor = pdfTextColor;
  6744. }
  6745. //set the word spacing for e.g. justify style
  6746. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  6747. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  6748. }
  6749. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  6750. //set the word spacing back to neutral => 0
  6751. if (style['word-spacing'] !== undefined) {
  6752. this.pdf.internal.write(0, "Tw");
  6753. }
  6754. };
  6755. // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  6756. Renderer.prototype.getPdfColor = function (style) {
  6757. var textColor;
  6758. var r, g, b;
  6759. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  6760. var m = rx.exec(style);
  6761. if (m != null) {
  6762. r = parseInt(m[1]);
  6763. g = parseInt(m[2]);
  6764. b = parseInt(m[3]);
  6765. } else {
  6766. if (style.charAt(0) != '#') {
  6767. style = CssColors.colorNameToHex(style);
  6768. if (!style) {
  6769. style = '#000000';
  6770. }
  6771. }
  6772. r = style.substring(1, 3);
  6773. r = parseInt(r, 16);
  6774. g = style.substring(3, 5);
  6775. g = parseInt(g, 16);
  6776. b = style.substring(5, 7);
  6777. b = parseInt(b, 16);
  6778. }
  6779. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  6780. var hex = parseInt(r.substr(1), 16);
  6781. r = hex >> 16 & 255;
  6782. g = hex >> 8 & 255;
  6783. b = hex & 255;
  6784. }
  6785. var f3 = this.f3;
  6786. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  6787. textColor = f3(r / 255) + ' g';
  6788. } else {
  6789. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  6790. }
  6791. return textColor;
  6792. };
  6793. Renderer.prototype.f3 = function (number) {
  6794. return number.toFixed(3); // Ie, %.3f
  6795. }, Renderer.prototype.renderParagraph = function (cb) {
  6796. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  6797. fragments = PurgeWhiteSpace(this.paragraph.text);
  6798. styles = this.paragraph.style;
  6799. blockstyle = this.paragraph.blockstyle;
  6800. priorblockstyle = this.paragraph.priorblockstyle || {};
  6801. this.paragraph = {
  6802. text: [],
  6803. style: [],
  6804. blockstyle: {},
  6805. priorblockstyle: blockstyle
  6806. };
  6807. if (!fragments.join("").trim()) {
  6808. return;
  6809. }
  6810. lines = this.splitFragmentsIntoLines(fragments, styles);
  6811. line = void 0;
  6812. maxLineHeight = void 0;
  6813. defaultFontSize = 12;
  6814. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  6815. this.priorMarginBottom = this.priorMarginBottom || 0;
  6816. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  6817. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  6818. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  6819. if (blockstyle['page-break-before'] === 'always') {
  6820. this.pdf.addPage();
  6821. this.y = 0;
  6822. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  6823. }
  6824. out = this.pdf.internal.write;
  6825. i = void 0;
  6826. l = void 0;
  6827. this.y += paragraphspacing_before;
  6828. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  6829. //stores the current indent of cursor position
  6830. var currentIndent = 0;
  6831. while (lines.length) {
  6832. line = lines.shift();
  6833. maxLineHeight = 0;
  6834. i = 0;
  6835. l = line.length;
  6836. while (i !== l) {
  6837. if (line[i][0].trim()) {
  6838. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  6839. fontSize = line[i][1]["font-size"] * 7;
  6840. }
  6841. i++;
  6842. }
  6843. //if we have to move the cursor to adapt the indent
  6844. var indentMove = 0;
  6845. var wantedIndent = 0;
  6846. //if a margin was added (by e.g. a text-alignment), move the cursor
  6847. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  6848. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  6849. indentMove = wantedIndent - currentIndent;
  6850. currentIndent = wantedIndent;
  6851. }
  6852. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
  6853. //move the cursor
  6854. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  6855. i = 0;
  6856. l = line.length;
  6857. while (i !== l) {
  6858. if (line[i][0]) {
  6859. this.RenderTextFragment(line[i][0], line[i][1]);
  6860. }
  6861. i++;
  6862. }
  6863. this.y += maxLineHeight * fontToUnitRatio;
  6864. //if some watcher function was executed successful, so e.g. margin and widths were changed,
  6865. //reset line drawing and calculate position and lines again
  6866. //e.g. to stop text floating around an image
  6867. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  6868. var localFragments = [];
  6869. var localStyles = [];
  6870. //create fragment array of
  6871. lines.forEach(function (localLine) {
  6872. var i = 0;
  6873. var l = localLine.length;
  6874. while (i !== l) {
  6875. if (localLine[i][0]) {
  6876. localFragments.push(localLine[i][0] + ' ');
  6877. localStyles.push(localLine[i][1]);
  6878. }
  6879. ++i;
  6880. }
  6881. });
  6882. //split lines again due to possible coordinate changes
  6883. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
  6884. //reposition the current cursor
  6885. out("ET", "Q");
  6886. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  6887. }
  6888. }
  6889. if (cb && typeof cb === "function") {
  6890. cb.call(this, this.x - 9, this.y - fontSize / 2);
  6891. }
  6892. out("ET", "Q");
  6893. return this.y += paragraphspacing_after;
  6894. };
  6895. Renderer.prototype.setBlockBoundary = function (cb) {
  6896. return this.renderParagraph(cb);
  6897. };
  6898. Renderer.prototype.setBlockStyle = function (css) {
  6899. return this.paragraph.blockstyle = css;
  6900. };
  6901. Renderer.prototype.addText = function (text, css) {
  6902. this.paragraph.text.push(text);
  6903. return this.paragraph.style.push(css);
  6904. };
  6905. FontNameDB = {
  6906. helvetica: "helvetica",
  6907. "sans-serif": "helvetica",
  6908. "times new roman": "times",
  6909. serif: "times",
  6910. times: "times",
  6911. monospace: "courier",
  6912. courier: "courier"
  6913. };
  6914. FontWeightMap = {
  6915. 100: "normal",
  6916. 200: "normal",
  6917. 300: "normal",
  6918. 400: "normal",
  6919. 500: "bold",
  6920. 600: "bold",
  6921. 700: "bold",
  6922. 800: "bold",
  6923. 900: "bold",
  6924. normal: "normal",
  6925. bold: "bold",
  6926. bolder: "bold",
  6927. lighter: "normal"
  6928. };
  6929. FontStyleMap = {
  6930. normal: "normal",
  6931. italic: "italic",
  6932. oblique: "italic"
  6933. };
  6934. TextAlignMap = {
  6935. left: "left",
  6936. right: "right",
  6937. center: "center",
  6938. justify: "justify"
  6939. };
  6940. FloatMap = {
  6941. none: 'none',
  6942. right: 'right',
  6943. left: 'left'
  6944. };
  6945. ClearMap = {
  6946. none: 'none',
  6947. both: 'both'
  6948. };
  6949. UnitedNumberMap = {
  6950. normal: 1
  6951. };
  6952. /**
  6953. * Converts HTML-formatted text into formatted PDF text.
  6954. *
  6955. * Notes:
  6956. * 2012-07-18
  6957. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  6958. * Plugin relies on jQuery for CSS extraction.
  6959. * Targeting HTML output from Markdown templating, which is a very simple
  6960. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  6961. * Images, tables are NOT supported.
  6962. *
  6963. * @public
  6964. * @function
  6965. * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  6966. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  6967. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  6968. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  6969. * @returns {Object} jsPDF instance
  6970. */
  6971. jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
  6972. "use strict";
  6973. this.margins_doc = margins || {
  6974. top: 0,
  6975. bottom: 0
  6976. };
  6977. if (!settings) settings = {};
  6978. if (!settings.elementHandlers) settings.elementHandlers = {};
  6979. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  6980. };
  6981. })(jsPDF.API);
  6982. /** ====================================================================
  6983. * jsPDF JavaScript plugin
  6984. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  6985. *
  6986. *
  6987. * ====================================================================
  6988. */
  6989. /*global jsPDF */
  6990. (function (jsPDFAPI) {
  6991. 'use strict';
  6992. var jsNamesObj, jsJsObj, text;
  6993. jsPDFAPI.addJS = function (txt) {
  6994. text = txt;
  6995. this.internal.events.subscribe('postPutResources', function (txt) {
  6996. jsNamesObj = this.internal.newObject();
  6997. this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
  6998. jsJsObj = this.internal.newObject();
  6999. this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
  7000. });
  7001. this.internal.events.subscribe('putCatalog', function () {
  7002. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  7003. this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  7004. }
  7005. });
  7006. return this;
  7007. };
  7008. })(jsPDF.API);
  7009. /**
  7010. * jsPDF Outline PlugIn
  7011. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7012. *
  7013. * Licensed under the MIT License.
  7014. * http://opensource.org/licenses/mit-license
  7015. */
  7016. /**
  7017. * Generates a PDF Outline
  7018. */
  7019. ;
  7020. (function (jsPDFAPI) {
  7021. 'use strict';
  7022. jsPDFAPI.events.push(['postPutResources', function () {
  7023. var pdf = this;
  7024. var rx = /^(\d+) 0 obj$/;
  7025. // Write action goto objects for each page
  7026. // this.outline.destsGoto = [];
  7027. // for (var i = 0; i < totalPages; i++) {
  7028. // var id = pdf.internal.newObject();
  7029. // this.outline.destsGoto.push(id);
  7030. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  7031. // null null]/S/GoTo>> endobj");
  7032. // }
  7033. //
  7034. // for (var i = 0; i < dests.length; i++) {
  7035. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  7036. // R");
  7037. // }
  7038. //
  7039. if (this.outline.root.children.length > 0) {
  7040. var lines = pdf.outline.render().split(/\r\n/);
  7041. for (var i = 0; i < lines.length; i++) {
  7042. var line = lines[i];
  7043. var m = rx.exec(line);
  7044. if (m != null) {
  7045. var oid = m[1];
  7046. pdf.internal.newObjectDeferredBegin(oid);
  7047. }
  7048. pdf.internal.write(line);
  7049. }
  7050. }
  7051. // This code will write named destination for each page reference
  7052. // (page_1, etc)
  7053. if (this.outline.createNamedDestinations) {
  7054. var totalPages = this.internal.pages.length;
  7055. // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  7056. // follow 5, 7, 9, etc
  7057. // Write destination objects for each page
  7058. var dests = [];
  7059. for (var i = 0; i < totalPages; i++) {
  7060. var id = pdf.internal.newObject();
  7061. dests.push(id);
  7062. var info = pdf.internal.getPageInfo(i + 1);
  7063. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  7064. }
  7065. // assign a name for each destination
  7066. var names2Oid = pdf.internal.newObject();
  7067. pdf.internal.write('<< /Names [ ');
  7068. for (var i = 0; i < dests.length; i++) {
  7069. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  7070. }
  7071. pdf.internal.write(' ] >>', 'endobj');
  7072. // var kids = pdf.internal.newObject();
  7073. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  7074. // pdf.internal.write(' ] >>', 'endobj');
  7075. var namesOid = pdf.internal.newObject();
  7076. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  7077. pdf.internal.write('>>', 'endobj');
  7078. }
  7079. }]);
  7080. jsPDFAPI.events.push(['putCatalog', function () {
  7081. var pdf = this;
  7082. if (pdf.outline.root.children.length > 0) {
  7083. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  7084. if (this.outline.createNamedDestinations) {
  7085. pdf.internal.write("/Names " + namesOid + " 0 R");
  7086. }
  7087. // Open with Bookmarks showing
  7088. // pdf.internal.write("/PageMode /UseOutlines");
  7089. }
  7090. }]);
  7091. jsPDFAPI.events.push(['initialized', function () {
  7092. var pdf = this;
  7093. pdf.outline = {
  7094. createNamedDestinations: false,
  7095. root: {
  7096. children: []
  7097. }
  7098. };
  7099. var namesOid;
  7100. var destsGoto = [];
  7101. /**
  7102. * Options: pageNumber
  7103. */
  7104. pdf.outline.add = function (parent, title, options) {
  7105. var item = {
  7106. title: title,
  7107. options: options,
  7108. children: []
  7109. };
  7110. if (parent == null) {
  7111. parent = this.root;
  7112. }
  7113. parent.children.push(item);
  7114. return item;
  7115. };
  7116. pdf.outline.render = function () {
  7117. this.ctx = {};
  7118. this.ctx.val = '';
  7119. this.ctx.pdf = pdf;
  7120. this.genIds_r(this.root);
  7121. this.renderRoot(this.root);
  7122. this.renderItems(this.root);
  7123. return this.ctx.val;
  7124. };
  7125. pdf.outline.genIds_r = function (node) {
  7126. node.id = pdf.internal.newObjectDeferred();
  7127. for (var i = 0; i < node.children.length; i++) {
  7128. this.genIds_r(node.children[i]);
  7129. }
  7130. };
  7131. pdf.outline.renderRoot = function (node) {
  7132. this.objStart(node);
  7133. this.line('/Type /Outlines');
  7134. if (node.children.length > 0) {
  7135. this.line('/First ' + this.makeRef(node.children[0]));
  7136. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  7137. }
  7138. this.line('/Count ' + this.count_r({
  7139. count: 0
  7140. }, node));
  7141. this.objEnd();
  7142. };
  7143. pdf.outline.renderItems = function (node) {
  7144. for (var i = 0; i < node.children.length; i++) {
  7145. var item = node.children[i];
  7146. this.objStart(item);
  7147. this.line('/Title ' + this.makeString(item.title));
  7148. this.line('/Parent ' + this.makeRef(node));
  7149. if (i > 0) {
  7150. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  7151. }
  7152. if (i < node.children.length - 1) {
  7153. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  7154. }
  7155. if (item.children.length > 0) {
  7156. this.line('/First ' + this.makeRef(item.children[0]));
  7157. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  7158. }
  7159. var count = this.count = this.count_r({
  7160. count: 0
  7161. }, item);
  7162. if (count > 0) {
  7163. this.line('/Count ' + count);
  7164. }
  7165. if (item.options) {
  7166. if (item.options.pageNumber) {
  7167. // Explicit Destination
  7168. //WARNING this assumes page ids are 3,5,7, etc.
  7169. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  7170. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7171. // this line does not work on all clients (pageNumber instead of page ref)
  7172. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
  7173. // Named Destination
  7174. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  7175. // Action Destination
  7176. // var id = pdf.internal.newObject();
  7177. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  7178. // this.line('/A ' + id + ' 0 R' );
  7179. }
  7180. }
  7181. this.objEnd();
  7182. }
  7183. for (var i = 0; i < node.children.length; i++) {
  7184. var item = node.children[i];
  7185. this.renderItems(item);
  7186. }
  7187. };
  7188. pdf.outline.line = function (text) {
  7189. this.ctx.val += text + '\r\n';
  7190. };
  7191. pdf.outline.makeRef = function (node) {
  7192. return node.id + ' 0 R';
  7193. };
  7194. pdf.outline.makeString = function (val) {
  7195. return '(' + pdf.internal.pdfEscape(val) + ')';
  7196. };
  7197. pdf.outline.objStart = function (node) {
  7198. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  7199. };
  7200. pdf.outline.objEnd = function (node) {
  7201. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  7202. };
  7203. pdf.outline.count_r = function (ctx, node) {
  7204. for (var i = 0; i < node.children.length; i++) {
  7205. ctx.count++;
  7206. this.count_r(ctx, node.children[i]);
  7207. }
  7208. return ctx.count;
  7209. };
  7210. }]);
  7211. return this;
  7212. })(jsPDF.API);
  7213. /**@preserve
  7214. * ====================================================================
  7215. * jsPDF PNG PlugIn
  7216. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  7217. *
  7218. *
  7219. * ====================================================================
  7220. */
  7221. (function (jsPDFAPI) {
  7222. 'use strict';
  7223. /*
  7224. * @see http://www.w3.org/TR/PNG-Chunks.html
  7225. *
  7226. Color Allowed Interpretation
  7227. Type Bit Depths
  7228. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  7229. 2 8,16 Each pixel is an R,G,B triple.
  7230. 3 1,2,4,8 Each pixel is a palette index;
  7231. a PLTE chunk must appear.
  7232. 4 8,16 Each pixel is a grayscale sample,
  7233. followed by an alpha sample.
  7234. 6 8,16 Each pixel is an R,G,B triple,
  7235. followed by an alpha sample.
  7236. */
  7237. /*
  7238. * PNG filter method types
  7239. *
  7240. * @see http://www.w3.org/TR/PNG-Filters.html
  7241. * @see http://www.libpng.org/pub/png/book/chapter09.html
  7242. *
  7243. * This is what the value 'Predictor' in decode params relates to
  7244. *
  7245. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  7246. * 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.
  7247. *
  7248. 0 None
  7249. 1 Sub
  7250. 2 Up
  7251. 3 Average
  7252. 4 Paeth
  7253. */
  7254. var doesNotHavePngJS = function doesNotHavePngJS() {
  7255. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  7256. },
  7257. canCompress = function canCompress(value) {
  7258. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  7259. },
  7260. hasCompressionJS = function hasCompressionJS() {
  7261. var inst = typeof Deflater === 'function';
  7262. if (!inst) throw new Error("requires deflate.js for compression");
  7263. return inst;
  7264. },
  7265. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  7266. var level = 5,
  7267. filter_method = filterUp;
  7268. switch (compression) {
  7269. case jsPDFAPI.image_compression.FAST:
  7270. level = 3;
  7271. filter_method = filterSub;
  7272. break;
  7273. case jsPDFAPI.image_compression.MEDIUM:
  7274. level = 6;
  7275. filter_method = filterAverage;
  7276. break;
  7277. case jsPDFAPI.image_compression.SLOW:
  7278. level = 9;
  7279. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  7280. break;
  7281. }
  7282. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  7283. var header = new Uint8Array(createZlibHeader(level));
  7284. var checksum = adler32(bytes);
  7285. var deflate = new Deflater(level);
  7286. var a = deflate.append(bytes);
  7287. var cBytes = deflate.flush();
  7288. var len = header.length + a.length + cBytes.length;
  7289. var cmpd = new Uint8Array(len + 4);
  7290. cmpd.set(header);
  7291. cmpd.set(a, header.length);
  7292. cmpd.set(cBytes, header.length + a.length);
  7293. cmpd[len++] = checksum >>> 24 & 0xff;
  7294. cmpd[len++] = checksum >>> 16 & 0xff;
  7295. cmpd[len++] = checksum >>> 8 & 0xff;
  7296. cmpd[len++] = checksum & 0xff;
  7297. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  7298. },
  7299. createZlibHeader = function createZlibHeader(bytes, level) {
  7300. /*
  7301. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  7302. */
  7303. var cm = 8;
  7304. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  7305. var cmf = cinfo << 4 | cm;
  7306. var hdr = cmf << 8;
  7307. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  7308. hdr |= flevel << 6;
  7309. hdr |= 0; //FDICT
  7310. hdr += 31 - hdr % 31;
  7311. return [cmf, hdr & 0xff & 0xff];
  7312. },
  7313. adler32 = function adler32(array, param) {
  7314. var adler = 1;
  7315. var s1 = adler & 0xffff,
  7316. s2 = adler >>> 16 & 0xffff;
  7317. var len = array.length;
  7318. var tlen;
  7319. var i = 0;
  7320. while (len > 0) {
  7321. tlen = len > param ? param : len;
  7322. len -= tlen;
  7323. do {
  7324. s1 += array[i++];
  7325. s2 += s1;
  7326. } while (--tlen);
  7327. s1 %= 65521;
  7328. s2 %= 65521;
  7329. }
  7330. return (s2 << 16 | s1) >>> 0;
  7331. },
  7332. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  7333. var lines = bytes.length / lineLength,
  7334. result = new Uint8Array(bytes.length + lines),
  7335. filter_methods = getFilterMethods(),
  7336. i = 0,
  7337. line,
  7338. prevLine,
  7339. offset;
  7340. for (; i < lines; i++) {
  7341. offset = i * lineLength;
  7342. line = bytes.subarray(offset, offset + lineLength);
  7343. if (filter_method) {
  7344. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  7345. } else {
  7346. var j = 0,
  7347. len = filter_methods.length,
  7348. results = [];
  7349. for (; j < len; j++) {
  7350. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  7351. }var ind = getIndexOfSmallestSum(results.concat());
  7352. result.set(results[ind], offset + i);
  7353. }
  7354. prevLine = line;
  7355. }
  7356. return result;
  7357. },
  7358. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  7359. /*var result = new Uint8Array(line.length + 1);
  7360. result[0] = 0;
  7361. result.set(line, 1);*/
  7362. var result = Array.apply([], line);
  7363. result.unshift(0);
  7364. return result;
  7365. },
  7366. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  7367. var result = [],
  7368. i = 0,
  7369. len = line.length,
  7370. left;
  7371. result[0] = 1;
  7372. for (; i < len; i++) {
  7373. left = line[i - colorsPerPixel] || 0;
  7374. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  7375. }
  7376. return result;
  7377. },
  7378. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  7379. var result = [],
  7380. i = 0,
  7381. len = line.length,
  7382. up;
  7383. result[0] = 2;
  7384. for (; i < len; i++) {
  7385. up = prevLine && prevLine[i] || 0;
  7386. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  7387. }
  7388. return result;
  7389. },
  7390. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  7391. var result = [],
  7392. i = 0,
  7393. len = line.length,
  7394. left,
  7395. up;
  7396. result[0] = 3;
  7397. for (; i < len; i++) {
  7398. left = line[i - colorsPerPixel] || 0;
  7399. up = prevLine && prevLine[i] || 0;
  7400. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  7401. }
  7402. return result;
  7403. },
  7404. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  7405. var result = [],
  7406. i = 0,
  7407. len = line.length,
  7408. left,
  7409. up,
  7410. upLeft,
  7411. paeth;
  7412. result[0] = 4;
  7413. for (; i < len; i++) {
  7414. left = line[i - colorsPerPixel] || 0;
  7415. up = prevLine && prevLine[i] || 0;
  7416. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  7417. paeth = paethPredictor(left, up, upLeft);
  7418. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  7419. }
  7420. return result;
  7421. },
  7422. paethPredictor = function paethPredictor(left, up, upLeft) {
  7423. var p = left + up - upLeft,
  7424. pLeft = Math.abs(p - left),
  7425. pUp = Math.abs(p - up),
  7426. pUpLeft = Math.abs(p - upLeft);
  7427. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  7428. },
  7429. getFilterMethods = function getFilterMethods() {
  7430. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  7431. },
  7432. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  7433. var i = 0,
  7434. len = arrays.length,
  7435. sum,
  7436. min,
  7437. ind;
  7438. while (i < len) {
  7439. sum = absSum(arrays[i].slice(1));
  7440. if (sum < min || !min) {
  7441. min = sum;
  7442. ind = i;
  7443. }
  7444. i++;
  7445. }
  7446. return ind;
  7447. },
  7448. absSum = function absSum(array) {
  7449. var i = 0,
  7450. len = array.length,
  7451. sum = 0;
  7452. while (i < len) {
  7453. sum += Math.abs(array[i++]);
  7454. }return sum;
  7455. },
  7456. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  7457. var predictor;
  7458. switch (compression) {
  7459. case jsPDFAPI.image_compression.FAST:
  7460. predictor = 11;
  7461. break;
  7462. case jsPDFAPI.image_compression.MEDIUM:
  7463. predictor = 13;
  7464. break;
  7465. case jsPDFAPI.image_compression.SLOW:
  7466. predictor = 14;
  7467. break;
  7468. }
  7469. return predictor;
  7470. },
  7471. logImg = function logImg(img) {
  7472. console.log("width: " + img.width);
  7473. console.log("height: " + img.height);
  7474. console.log("bits: " + img.bits);
  7475. console.log("colorType: " + img.colorType);
  7476. console.log("transparency:");
  7477. console.log(img.transparency);
  7478. console.log("text:");
  7479. console.log(img.text);
  7480. console.log("compressionMethod: " + img.compressionMethod);
  7481. console.log("filterMethod: " + img.filterMethod);
  7482. console.log("interlaceMethod: " + img.interlaceMethod);
  7483. console.log("imgData:");
  7484. console.log(img.imgData);
  7485. console.log("palette:");
  7486. console.log(img.palette);
  7487. console.log("colors: " + img.colors);
  7488. console.log("colorSpace: " + img.colorSpace);
  7489. console.log("pixelBitlength: " + img.pixelBitlength);
  7490. console.log("hasAlphaChannel: " + img.hasAlphaChannel);
  7491. };
  7492. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  7493. 'use strict';
  7494. var colorSpace = this.color_spaces.DEVICE_RGB,
  7495. decode = this.decode.FLATE_DECODE,
  7496. bpc = 8,
  7497. img,
  7498. dp,
  7499. trns,
  7500. colors,
  7501. pal,
  7502. smask;
  7503. /* if(this.isString(imageData)) {
  7504. }*/
  7505. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  7506. if (this.isArrayBufferView(imageData)) {
  7507. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  7508. img = new PNG(imageData);
  7509. imageData = img.imgData;
  7510. bpc = img.bits;
  7511. colorSpace = img.colorSpace;
  7512. colors = img.colors;
  7513. //logImg(img);
  7514. /*
  7515. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  7516. *
  7517. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  7518. *
  7519. * Extract alpha to create two separate images, using the alpha as a sMask
  7520. */
  7521. if ([4, 6].indexOf(img.colorType) !== -1) {
  7522. /*
  7523. * processes 8 bit RGBA and grayscale + alpha images
  7524. */
  7525. if (img.bits === 8) {
  7526. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  7527. len = pixels.length,
  7528. imgData = new Uint8Array(len * img.colors),
  7529. alphaData = new Uint8Array(len),
  7530. pDiff = img.pixelBitlength - img.bits,
  7531. i = 0,
  7532. n = 0,
  7533. pixel,
  7534. pbl;
  7535. for (; i < len; i++) {
  7536. pixel = pixels[i];
  7537. pbl = 0;
  7538. while (pbl < pDiff) {
  7539. imgData[n++] = pixel >>> pbl & 0xff;
  7540. pbl = pbl + img.bits;
  7541. }
  7542. alphaData[i] = pixel >>> pbl & 0xff;
  7543. }
  7544. }
  7545. /*
  7546. * processes 16 bit RGBA and grayscale + alpha images
  7547. */
  7548. if (img.bits === 16) {
  7549. var pixels = new Uint32Array(img.decodePixels().buffer),
  7550. len = pixels.length,
  7551. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  7552. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  7553. hasColors = img.colors > 1,
  7554. i = 0,
  7555. n = 0,
  7556. a = 0,
  7557. pixel;
  7558. while (i < len) {
  7559. pixel = pixels[i++];
  7560. imgData[n++] = pixel >>> 0 & 0xFF;
  7561. if (hasColors) {
  7562. imgData[n++] = pixel >>> 16 & 0xFF;
  7563. pixel = pixels[i++];
  7564. imgData[n++] = pixel >>> 0 & 0xFF;
  7565. }
  7566. alphaData[a++] = pixel >>> 16 & 0xFF;
  7567. }
  7568. bpc = 8;
  7569. }
  7570. if (canCompress(compression)) {
  7571. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  7572. smask = compressBytes(alphaData, img.width, 1, compression);
  7573. } else {
  7574. imageData = imgData;
  7575. smask = alphaData;
  7576. decode = null;
  7577. }
  7578. }
  7579. /*
  7580. * Indexed png. Each pixel is a palette index.
  7581. */
  7582. if (img.colorType === 3) {
  7583. colorSpace = this.color_spaces.INDEXED;
  7584. pal = img.palette;
  7585. if (img.transparency.indexed) {
  7586. var trans = img.transparency.indexed;
  7587. var total = 0,
  7588. i = 0,
  7589. len = trans.length;
  7590. for (; i < len; ++i) {
  7591. total += trans[i];
  7592. }total = total / 255;
  7593. /*
  7594. * a single color is specified as 100% transparent (0),
  7595. * so we set trns to use a /Mask with that index
  7596. */
  7597. if (total === len - 1 && trans.indexOf(0) !== -1) {
  7598. trns = [trans.indexOf(0)];
  7599. /*
  7600. * there's more than one colour within the palette that specifies
  7601. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  7602. */
  7603. } else if (total !== len) {
  7604. var pixels = img.decodePixels(),
  7605. alphaData = new Uint8Array(pixels.length),
  7606. i = 0,
  7607. len = pixels.length;
  7608. for (; i < len; i++) {
  7609. alphaData[i] = trans[pixels[i]];
  7610. }smask = compressBytes(alphaData, img.width, 1);
  7611. }
  7612. }
  7613. }
  7614. var predictor = getPredictorFromCompression(compression);
  7615. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
  7616. //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  7617. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  7618. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  7619. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  7620. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  7621. }
  7622. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  7623. };
  7624. })(jsPDF.API);
  7625. /**
  7626. * jsPDF Autoprint Plugin
  7627. *
  7628. * Licensed under the MIT License.
  7629. * http://opensource.org/licenses/mit-license
  7630. */
  7631. (function (jsPDFAPI) {
  7632. 'use strict';
  7633. jsPDFAPI.autoPrint = function () {
  7634. 'use strict';
  7635. var refAutoPrintTag;
  7636. this.internal.events.subscribe('postPutResources', function () {
  7637. refAutoPrintTag = this.internal.newObject();
  7638. this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
  7639. });
  7640. this.internal.events.subscribe("putCatalog", function () {
  7641. this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
  7642. });
  7643. return this;
  7644. };
  7645. })(jsPDF.API);
  7646. /** @preserve
  7647. * jsPDF split_text_to_size plugin - MIT license.
  7648. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7649. * 2014 Diego Casorran, https://github.com/diegocr
  7650. */
  7651. /**
  7652. *
  7653. * ====================================================================
  7654. */
  7655. ;(function (API) {
  7656. 'use strict';
  7657. /**
  7658. Returns an array of length matching length of the 'word' string, with each
  7659. cell ocupied by the width of the char in that position.
  7660. @function
  7661. @param word {String}
  7662. @param widths {Object}
  7663. @param kerning {Object}
  7664. @returns {Array}
  7665. */
  7666. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  7667. if (!options) {
  7668. options = {};
  7669. }
  7670. var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
  7671. widthsFractionOf = widths.fof ? widths.fof : 1,
  7672. kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
  7673. kerningFractionOf = kerning.fof ? kerning.fof : 1;
  7674. // console.log("widths, kergnings", widths, kerning)
  7675. var i,
  7676. l,
  7677. char_code,
  7678. prior_char_code = 0 // for kerning
  7679. ,
  7680. default_char_width = widths[0] || widthsFractionOf,
  7681. output = [];
  7682. for (i = 0, l = text.length; i < l; i++) {
  7683. char_code = text.charCodeAt(i);
  7684. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  7685. prior_char_code = char_code;
  7686. }
  7687. return output;
  7688. };
  7689. var getArraySum = function getArraySum(array) {
  7690. var i = array.length,
  7691. output = 0;
  7692. while (i) {
  7693. ;i--;
  7694. output += array[i];
  7695. }
  7696. return output;
  7697. };
  7698. /**
  7699. Returns a widths of string in a given font, if the font size is set as 1 point.
  7700. In other words, this is "proportional" value. For 1 unit of font size, the length
  7701. of the string will be that much.
  7702. Multiply by font size to get actual width in *points*
  7703. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  7704. @public
  7705. @function
  7706. @param
  7707. @returns {Type}
  7708. */
  7709. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  7710. return getArraySum(getCharWidthsArray.call(this, text, options));
  7711. };
  7712. /**
  7713. returns array of lines
  7714. */
  7715. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  7716. var answer = [];
  7717. // 1st, chop off the piece that can fit on the hanging line.
  7718. var i = 0,
  7719. l = word.length,
  7720. workingLen = 0;
  7721. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  7722. workingLen += widths_array[i];i++;
  7723. }
  7724. // this is first line.
  7725. answer.push(word.slice(0, i));
  7726. // 2nd. Split the rest into maxLen pieces.
  7727. var startOfLine = i;
  7728. workingLen = 0;
  7729. while (i !== l) {
  7730. if (workingLen + widths_array[i] > maxLen) {
  7731. answer.push(word.slice(startOfLine, i));
  7732. workingLen = 0;
  7733. startOfLine = i;
  7734. }
  7735. workingLen += widths_array[i];i++;
  7736. }
  7737. if (startOfLine !== i) {
  7738. answer.push(word.slice(startOfLine, i));
  7739. }
  7740. return answer;
  7741. };
  7742. // Note, all sizing inputs for this function must be in "font measurement units"
  7743. // By default, for PDF, it's "point".
  7744. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  7745. // at this time works only on Western scripts, ones with space char
  7746. // separating the words. Feel free to expand.
  7747. if (!options) {
  7748. options = {};
  7749. }
  7750. var line = [],
  7751. lines = [line],
  7752. line_length = options.textIndent || 0,
  7753. separator_length = 0,
  7754. current_word_length = 0,
  7755. word,
  7756. widths_array,
  7757. words = text.split(' '),
  7758. spaceCharWidth = getCharWidthsArray(' ', options)[0],
  7759. i,
  7760. l,
  7761. tmp,
  7762. lineIndent;
  7763. if (options.lineIndent === -1) {
  7764. lineIndent = words[0].length + 2;
  7765. } else {
  7766. lineIndent = options.lineIndent || 0;
  7767. }
  7768. if (lineIndent) {
  7769. var pad = Array(lineIndent).join(" "),
  7770. wrds = [];
  7771. words.map(function (wrd) {
  7772. wrd = wrd.split(/\s*\n/);
  7773. if (wrd.length > 1) {
  7774. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  7775. return (idx && wrd.length ? "\n" : "") + wrd;
  7776. }));
  7777. } else {
  7778. wrds.push(wrd[0]);
  7779. }
  7780. });
  7781. words = wrds;
  7782. lineIndent = getStringUnitWidth(pad, options);
  7783. }
  7784. for (i = 0, l = words.length; i < l; i++) {
  7785. var force = 0;
  7786. word = words[i];
  7787. if (lineIndent && word[0] == "\n") {
  7788. word = word.substr(1);
  7789. force = 1;
  7790. }
  7791. widths_array = getCharWidthsArray(word, options);
  7792. current_word_length = getArraySum(widths_array);
  7793. if (line_length + separator_length + current_word_length > maxlen || force) {
  7794. if (current_word_length > maxlen) {
  7795. // this happens when you have space-less long URLs for example.
  7796. // we just chop these to size. We do NOT insert hiphens
  7797. tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
  7798. // first line we add to existing line object
  7799. line.push(tmp.shift()); // it's ok to have extra space indicator there
  7800. // last line we make into new line object
  7801. line = [tmp.pop()];
  7802. // lines in the middle we apped to lines object as whole lines
  7803. while (tmp.length) {
  7804. lines.push([tmp.shift()]); // single fragment occupies whole line
  7805. }
  7806. current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
  7807. } else {
  7808. // just put it on a new line
  7809. line = [word];
  7810. }
  7811. // now we attach new line to lines
  7812. lines.push(line);
  7813. line_length = current_word_length + lineIndent;
  7814. separator_length = spaceCharWidth;
  7815. } else {
  7816. line.push(word);
  7817. line_length += separator_length + current_word_length;
  7818. separator_length = spaceCharWidth;
  7819. }
  7820. }
  7821. if (lineIndent) {
  7822. var postProcess = function postProcess(ln, idx) {
  7823. return (idx ? pad : '') + ln.join(" ");
  7824. };
  7825. } else {
  7826. var postProcess = function postProcess(ln) {
  7827. return ln.join(" ");
  7828. };
  7829. }
  7830. return lines.map(postProcess);
  7831. };
  7832. /**
  7833. Splits a given string into an array of strings. Uses 'size' value
  7834. (in measurement units declared as default for the jsPDF instance)
  7835. and the font's "widths" and "Kerning" tables, where available, to
  7836. determine display length of a given string for a given font.
  7837. We use character's 100% of unit size (height) as width when Width
  7838. table or other default width is not available.
  7839. @public
  7840. @function
  7841. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  7842. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  7843. @param options {Object} Optional flags needed for chopper to do the right thing.
  7844. @returns {Array} with strings chopped to size.
  7845. */
  7846. API.splitTextToSize = function (text, maxlen, options) {
  7847. 'use strict';
  7848. if (!options) {
  7849. options = {};
  7850. }
  7851. var fsize = options.fontSize || this.internal.getFontSize(),
  7852. newOptions = function (options) {
  7853. var widths = { 0: 1 },
  7854. kerning = {};
  7855. if (!options.widths || !options.kerning) {
  7856. var f = this.internal.getFont(options.fontName, options.fontStyle),
  7857. encoding = 'Unicode';
  7858. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  7859. // Actual JavaScript-native String's 16bit char codes used.
  7860. // no multi-byte logic here
  7861. if (f.metadata[encoding]) {
  7862. return {
  7863. widths: f.metadata[encoding].widths || widths,
  7864. kerning: f.metadata[encoding].kerning || kerning
  7865. };
  7866. }
  7867. } else {
  7868. return {
  7869. widths: options.widths,
  7870. kerning: options.kerning
  7871. };
  7872. }
  7873. // then use default values
  7874. return {
  7875. widths: widths,
  7876. kerning: kerning
  7877. };
  7878. }.call(this, options);
  7879. // first we split on end-of-line chars
  7880. var paragraphs;
  7881. if (Array.isArray(text)) {
  7882. paragraphs = text;
  7883. } else {
  7884. paragraphs = text.split(/\r?\n/);
  7885. }
  7886. // now we convert size (max length of line) into "font size units"
  7887. // at present time, the "font size unit" is always 'point'
  7888. // 'proportional' means, "in proportion to font size"
  7889. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
  7890. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  7891. // this may change in the future?
  7892. // until then, proportional_maxlen is likely to be in 'points'
  7893. // If first line is to be indented (shorter or longer) than maxLen
  7894. // we indicate that by using CSS-style "text-indent" option.
  7895. // here it's in font units too (which is likely 'points')
  7896. // it can be negative (which makes the first line longer than maxLen)
  7897. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  7898. newOptions.lineIndent = options.lineIndent;
  7899. var i,
  7900. l,
  7901. output = [];
  7902. for (i = 0, l = paragraphs.length; i < l; i++) {
  7903. output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
  7904. }
  7905. return output;
  7906. };
  7907. })(jsPDF.API);
  7908. /** @preserve
  7909. jsPDF standard_fonts_metrics plugin
  7910. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7911. MIT license.
  7912. */
  7913. /**
  7914. *
  7915. * ====================================================================
  7916. */
  7917. ;(function (API) {
  7918. 'use strict';
  7919. /*
  7920. # reference (Python) versions of 'compress' and 'uncompress'
  7921. # only 'uncompress' function is featured lower as JavaScript
  7922. # if you want to unit test "roundtrip", just transcribe the reference
  7923. # 'compress' function from Python into JavaScript
  7924. def compress(data):
  7925. keys = '0123456789abcdef'
  7926. values = 'klmnopqrstuvwxyz'
  7927. mapping = dict(zip(keys, values))
  7928. vals = []
  7929. for key in data.keys():
  7930. value = data[key]
  7931. try:
  7932. keystring = hex(key)[2:]
  7933. keystring = keystring[:-1] + mapping[keystring[-1:]]
  7934. except:
  7935. keystring = key.join(["'","'"])
  7936. #print('Keystring is %s' % keystring)
  7937. try:
  7938. if value < 0:
  7939. valuestring = hex(value)[3:]
  7940. numberprefix = '-'
  7941. else:
  7942. valuestring = hex(value)[2:]
  7943. numberprefix = ''
  7944. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  7945. except:
  7946. if type(value) == dict:
  7947. valuestring = compress(value)
  7948. else:
  7949. raise Exception("Don't know what to do with value type %s" % type(value))
  7950. vals.append(keystring+valuestring)
  7951. return '{' + ''.join(vals) + '}'
  7952. def uncompress(data):
  7953. decoded = '0123456789abcdef'
  7954. encoded = 'klmnopqrstuvwxyz'
  7955. mapping = dict(zip(encoded, decoded))
  7956. sign = +1
  7957. stringmode = False
  7958. stringparts = []
  7959. output = {}
  7960. activeobject = output
  7961. parentchain = []
  7962. keyparts = ''
  7963. valueparts = ''
  7964. key = None
  7965. ending = set(encoded)
  7966. i = 1
  7967. l = len(data) - 1 # stripping starting, ending {}
  7968. while i != l: # stripping {}
  7969. # -, {, }, ' are special.
  7970. ch = data[i]
  7971. i += 1
  7972. if ch == "'":
  7973. if stringmode:
  7974. # end of string mode
  7975. stringmode = False
  7976. key = ''.join(stringparts)
  7977. else:
  7978. # start of string mode
  7979. stringmode = True
  7980. stringparts = []
  7981. elif stringmode == True:
  7982. #print("Adding %s to stringpart" % ch)
  7983. stringparts.append(ch)
  7984. elif ch == '{':
  7985. # start of object
  7986. parentchain.append( [activeobject, key] )
  7987. activeobject = {}
  7988. key = None
  7989. #DEBUG = True
  7990. elif ch == '}':
  7991. # end of object
  7992. parent, key = parentchain.pop()
  7993. parent[key] = activeobject
  7994. key = None
  7995. activeobject = parent
  7996. #DEBUG = False
  7997. elif ch == '-':
  7998. sign = -1
  7999. else:
  8000. # must be number
  8001. if key == None:
  8002. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  8003. if ch in ending:
  8004. #debug("End of key")
  8005. keyparts += mapping[ch]
  8006. key = int(keyparts, 16) * sign
  8007. sign = +1
  8008. keyparts = ''
  8009. else:
  8010. keyparts += ch
  8011. else:
  8012. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  8013. if ch in ending:
  8014. #debug("End of value")
  8015. valueparts += mapping[ch]
  8016. activeobject[key] = int(valueparts, 16) * sign
  8017. sign = +1
  8018. key = None
  8019. valueparts = ''
  8020. else:
  8021. valueparts += ch
  8022. #debug(activeobject)
  8023. return output
  8024. */
  8025. /**
  8026. Uncompresses data compressed into custom, base16-like format.
  8027. @public
  8028. @function
  8029. @param
  8030. @returns {Type}
  8031. */
  8032. var uncompress = function uncompress(data) {
  8033. var decoded = '0123456789abcdef',
  8034. encoded = 'klmnopqrstuvwxyz',
  8035. mapping = {};
  8036. for (var i = 0; i < encoded.length; i++) {
  8037. mapping[encoded[i]] = decoded[i];
  8038. }
  8039. var undef,
  8040. output = {},
  8041. sign = 1,
  8042. stringparts // undef. will be [] in string mode
  8043. ,
  8044. activeobject = output,
  8045. parentchain = [],
  8046. parent_key_pair,
  8047. keyparts = '',
  8048. valueparts = '',
  8049. key // undef. will be Truthy when Key is resolved.
  8050. ,
  8051. datalen = data.length - 1 // stripping ending }
  8052. ,
  8053. ch;
  8054. i = 1; // stripping starting {
  8055. while (i != datalen) {
  8056. // - { } ' are special.
  8057. ch = data[i];
  8058. i += 1;
  8059. if (ch == "'") {
  8060. if (stringparts) {
  8061. // end of string mode
  8062. key = stringparts.join('');
  8063. stringparts = undef;
  8064. } else {
  8065. // start of string mode
  8066. stringparts = [];
  8067. }
  8068. } else if (stringparts) {
  8069. stringparts.push(ch);
  8070. } else if (ch == '{') {
  8071. // start of object
  8072. parentchain.push([activeobject, key]);
  8073. activeobject = {};
  8074. key = undef;
  8075. } else if (ch == '}') {
  8076. // end of object
  8077. parent_key_pair = parentchain.pop();
  8078. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  8079. key = undef;
  8080. activeobject = parent_key_pair[0];
  8081. } else if (ch == '-') {
  8082. sign = -1;
  8083. } else {
  8084. // must be number
  8085. if (key === undef) {
  8086. if (mapping.hasOwnProperty(ch)) {
  8087. keyparts += mapping[ch];
  8088. key = parseInt(keyparts, 16) * sign;
  8089. sign = +1;
  8090. keyparts = '';
  8091. } else {
  8092. keyparts += ch;
  8093. }
  8094. } else {
  8095. if (mapping.hasOwnProperty(ch)) {
  8096. valueparts += mapping[ch];
  8097. activeobject[key] = parseInt(valueparts, 16) * sign;
  8098. sign = +1;
  8099. key = undef;
  8100. valueparts = '';
  8101. } else {
  8102. valueparts += ch;
  8103. }
  8104. }
  8105. }
  8106. } // end while
  8107. return output;
  8108. };
  8109. // encoding = 'Unicode'
  8110. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  8111. // Actual 16bit char codes used.
  8112. // no multi-byte logic here
  8113. // Unicode characters to WinAnsiEncoding:
  8114. // {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}
  8115. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  8116. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  8117. // as well as give strings with some (supported by these fonts) Unicode characters and
  8118. // these will be mapped to win cp1252
  8119. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  8120. var encodingBlock = {
  8121. 'codePages': ['WinAnsiEncoding'],
  8122. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  8123. },
  8124. encodings = { 'Unicode': {
  8125. 'Courier': encodingBlock,
  8126. 'Courier-Bold': encodingBlock,
  8127. 'Courier-BoldOblique': encodingBlock,
  8128. 'Courier-Oblique': encodingBlock,
  8129. 'Helvetica': encodingBlock,
  8130. 'Helvetica-Bold': encodingBlock,
  8131. 'Helvetica-BoldOblique': encodingBlock,
  8132. 'Helvetica-Oblique': encodingBlock,
  8133. 'Times-Roman': encodingBlock,
  8134. 'Times-Bold': encodingBlock,
  8135. 'Times-BoldItalic': encodingBlock,
  8136. 'Times-Italic': encodingBlock
  8137. // , 'Symbol'
  8138. // , 'ZapfDingbats'
  8139. } }
  8140. /**
  8141. Resources:
  8142. Font metrics data is reprocessed derivative of contents of
  8143. "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
  8144. Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
  8145. This file and the 14 PostScript(R) AFM files it accompanies may be used,
  8146. copied, and distributed for any purpose and without charge, with or without
  8147. modification, provided that all copyright notices are retained; that the AFM
  8148. files are not distributed without this file; that all modifications to this
  8149. file or any of the AFM files are prominently noted in the modified file(s);
  8150. and that this paragraph is not modified. Adobe Systems has no responsibility
  8151. or obligation to support the use of the AFM files.
  8152. */
  8153. ,
  8154. fontMetrics = { 'Unicode': {
  8155. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  8156. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  8157. // width is 476/1000 or 47.6% of its height (regardless of font size)
  8158. // At this time this value applies to "widths" and "kerning" numbers.
  8159. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  8160. // key 'fof' represents the "fontMetricsFractionOf" value
  8161. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8162. '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}}}"),
  8163. '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}}}"),
  8164. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8165. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8166. '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}}}")
  8167. //, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
  8168. , '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}}}"),
  8169. '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}}}")
  8170. //, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
  8171. , 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  8172. '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}}}"),
  8173. '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}}}"),
  8174. '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}}}")
  8175. } };
  8176. /*
  8177. This event handler is fired when a new jsPDF object is initialized
  8178. This event handler appends metrics data to standard fonts within
  8179. that jsPDF instance. The metrics are mapped over Unicode character
  8180. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  8181. standard PDF fonts.
  8182. Future:
  8183. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  8184. char codes to StandardEncoding character codes. The encoding table is to be used
  8185. somewhere around "pdfEscape" call.
  8186. */
  8187. API.events.push(['addFont', function (font) {
  8188. var metrics,
  8189. unicode_section,
  8190. encoding = 'Unicode',
  8191. encodingBlock;
  8192. metrics = fontMetrics[encoding][font.PostScriptName];
  8193. if (metrics) {
  8194. if (font.metadata[encoding]) {
  8195. unicode_section = font.metadata[encoding];
  8196. } else {
  8197. unicode_section = font.metadata[encoding] = {};
  8198. }
  8199. unicode_section.widths = metrics.widths;
  8200. unicode_section.kerning = metrics.kerning;
  8201. }
  8202. encodingBlock = encodings[encoding][font.PostScriptName];
  8203. if (encodingBlock) {
  8204. if (font.metadata[encoding]) {
  8205. unicode_section = font.metadata[encoding];
  8206. } else {
  8207. unicode_section = font.metadata[encoding] = {};
  8208. }
  8209. unicode_section.encoding = encodingBlock;
  8210. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  8211. font.encoding = encodingBlock.codePages[0];
  8212. }
  8213. }
  8214. }]); // end of adding event handler
  8215. })(jsPDF.API);
  8216. /** @preserve
  8217. jsPDF SVG plugin
  8218. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  8219. */
  8220. /**
  8221. *
  8222. * ====================================================================
  8223. */
  8224. ;(function (jsPDFAPI) {
  8225. 'use strict';
  8226. /**
  8227. Parses SVG XML and converts only some of the SVG elements into
  8228. PDF elements.
  8229. Supports:
  8230. paths
  8231. @public
  8232. @function
  8233. @param
  8234. @returns {Type}
  8235. */
  8236. jsPDFAPI.addSVG = function (svgtext, x, y, w, h) {
  8237. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  8238. var undef;
  8239. if (x === undef || y === undef) {
  8240. throw new Error("addSVG needs values for 'x' and 'y'");
  8241. }
  8242. function InjectCSS(cssbody, document) {
  8243. var styletag = document.createElement('style');
  8244. styletag.type = 'text/css';
  8245. if (styletag.styleSheet) {
  8246. // ie
  8247. styletag.styleSheet.cssText = cssbody;
  8248. } else {
  8249. // others
  8250. styletag.appendChild(document.createTextNode(cssbody));
  8251. }
  8252. document.getElementsByTagName("head")[0].appendChild(styletag);
  8253. }
  8254. function createWorkerNode(document) {
  8255. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  8256. ,
  8257. frame = document.createElement('iframe');
  8258. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  8259. frame.name = frameID;
  8260. frame.setAttribute("width", 0);
  8261. frame.setAttribute("height", 0);
  8262. frame.setAttribute("frameborder", "0");
  8263. frame.setAttribute("scrolling", "no");
  8264. frame.setAttribute("seamless", "seamless");
  8265. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  8266. document.body.appendChild(frame);
  8267. return frame;
  8268. }
  8269. function attachSVGToWorkerNode(svgtext, frame) {
  8270. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  8271. framedoc.write(svgtext);
  8272. framedoc.close();
  8273. return framedoc.getElementsByTagName('svg')[0];
  8274. }
  8275. function convertPathToPDFLinesArgs(path) {
  8276. 'use strict';
  8277. // we will use 'lines' method call. it needs:
  8278. // - starting coordinate pair
  8279. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  8280. // - scale array [horizontal, vertical] ratios
  8281. // - style (stroke, fill, both)
  8282. var x = parseFloat(path[1]),
  8283. y = parseFloat(path[2]),
  8284. vectors = [],
  8285. position = 3,
  8286. len = path.length;
  8287. while (position < len) {
  8288. if (path[position] === 'c') {
  8289. 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])]);
  8290. position += 7;
  8291. } else if (path[position] === 'l') {
  8292. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  8293. position += 3;
  8294. } else {
  8295. position += 1;
  8296. }
  8297. }
  8298. return [x, y, vectors];
  8299. }
  8300. var workernode = createWorkerNode(document),
  8301. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  8302. scale = [1, 1],
  8303. svgw = parseFloat(svgnode.getAttribute('width')),
  8304. svgh = parseFloat(svgnode.getAttribute('height'));
  8305. if (svgw && svgh) {
  8306. // setting both w and h makes image stretch to size.
  8307. // this may distort the image, but fits your demanded size
  8308. if (w && h) {
  8309. scale = [w / svgw, h / svgh];
  8310. }
  8311. // if only one is set, that value is set as max and SVG
  8312. // is scaled proportionately.
  8313. else if (w) {
  8314. scale = [w / svgw, w / svgw];
  8315. } else if (h) {
  8316. scale = [h / svgh, h / svgh];
  8317. }
  8318. }
  8319. var i,
  8320. l,
  8321. tmp,
  8322. linesargs,
  8323. items = svgnode.childNodes;
  8324. for (i = 0, l = items.length; i < l; i++) {
  8325. tmp = items[i];
  8326. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  8327. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
  8328. // path start x coordinate
  8329. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  8330. // path start y coordinate
  8331. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  8332. // the rest of lines are vectors. these will adjust with scale value auto.
  8333. this.lines.call(this, linesargs[2] // lines
  8334. , linesargs[0] // starting x
  8335. , linesargs[1] // starting y
  8336. , scale);
  8337. }
  8338. }
  8339. // clean up
  8340. // workernode.parentNode.removeChild(workernode)
  8341. return this;
  8342. };
  8343. })(jsPDF.API);
  8344. /** ====================================================================
  8345. * jsPDF total_pages plugin
  8346. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  8347. *
  8348. *
  8349. * ====================================================================
  8350. */
  8351. (function (jsPDFAPI) {
  8352. 'use strict';
  8353. jsPDFAPI.putTotalPages = function (pageExpression) {
  8354. 'use strict';
  8355. var replaceExpression = new RegExp(pageExpression, 'g');
  8356. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  8357. for (var i = 0; i < this.internal.pages[n].length; i++) {
  8358. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
  8359. }
  8360. }
  8361. return this;
  8362. };
  8363. })(jsPDF.API);
  8364. /** ====================================================================
  8365. * jsPDF XMP metadata plugin
  8366. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  8367. *
  8368. *
  8369. * ====================================================================
  8370. */
  8371. /*global jsPDF */
  8372. /**
  8373. * Adds XMP formatted metadata to PDF
  8374. *
  8375. * @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.
  8376. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  8377. * @function
  8378. * @returns {jsPDF}
  8379. * @methodOf jsPDF#
  8380. * @name addMetadata
  8381. */
  8382. (function (jsPDFAPI) {
  8383. 'use strict';
  8384. var xmpmetadata = "";
  8385. var xmpnamespaceuri = "";
  8386. var metadata_object_number = "";
  8387. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  8388. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  8389. xmpmetadata = metadata;
  8390. this.internal.events.subscribe('postPutResources', function () {
  8391. if (!xmpmetadata) {
  8392. metadata_object_number = "";
  8393. } else {
  8394. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  8395. 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>';
  8396. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  8397. var xmpmeta_ending = '</x:xmpmeta>';
  8398. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  8399. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  8400. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  8401. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  8402. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  8403. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  8404. metadata_object_number = this.internal.newObject();
  8405. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  8406. this.internal.write('stream');
  8407. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  8408. this.internal.write('endstream');
  8409. this.internal.write('endobj');
  8410. }
  8411. });
  8412. this.internal.events.subscribe('putCatalog', function () {
  8413. if (metadata_object_number) {
  8414. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  8415. }
  8416. });
  8417. return this;
  8418. };
  8419. })(jsPDF.API);
  8420. /* Blob.js
  8421. * A Blob implementation.
  8422. * 2014-07-24
  8423. *
  8424. * By Eli Grey, http://eligrey.com
  8425. * By Devin Samarin, https://github.com/dsamarin
  8426. * License: X11/MIT
  8427. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  8428. */
  8429. /*global self, unescape */
  8430. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  8431. plusplus: true */
  8432. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  8433. (function (view) {
  8434. "use strict";
  8435. view.URL = view.URL || view.webkitURL;
  8436. if (view.Blob && view.URL) {
  8437. try {
  8438. new Blob;
  8439. return;
  8440. } catch (e) {}
  8441. }
  8442. // Internally we use a BlobBuilder implementation to base Blob off of
  8443. // in order to support older browsers that only have BlobBuilder
  8444. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  8445. var
  8446. get_class = function(object) {
  8447. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  8448. }
  8449. , FakeBlobBuilder = function BlobBuilder() {
  8450. this.data = [];
  8451. }
  8452. , FakeBlob = function Blob(data, type, encoding) {
  8453. this.data = data;
  8454. this.size = data.length;
  8455. this.type = type;
  8456. this.encoding = encoding;
  8457. }
  8458. , FBB_proto = FakeBlobBuilder.prototype
  8459. , FB_proto = FakeBlob.prototype
  8460. , FileReaderSync = view.FileReaderSync
  8461. , FileException = function(type) {
  8462. this.code = this[this.name = type];
  8463. }
  8464. , file_ex_codes = (
  8465. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
  8466. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  8467. ).split(" ")
  8468. , file_ex_code = file_ex_codes.length
  8469. , real_URL = view.URL || view.webkitURL || view
  8470. , real_create_object_URL = real_URL.createObjectURL
  8471. , real_revoke_object_URL = real_URL.revokeObjectURL
  8472. , URL = real_URL
  8473. , btoa = view.btoa
  8474. , atob = view.atob
  8475. , ArrayBuffer = view.ArrayBuffer
  8476. , Uint8Array = view.Uint8Array
  8477. , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/
  8478. ;
  8479. FakeBlob.fake = FB_proto.fake = true;
  8480. while (file_ex_code--) {
  8481. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  8482. }
  8483. // Polyfill URL
  8484. if (!real_URL.createObjectURL) {
  8485. URL = view.URL = function(uri) {
  8486. var
  8487. uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8488. , uri_origin
  8489. ;
  8490. uri_info.href = uri;
  8491. if (!("origin" in uri_info)) {
  8492. if (uri_info.protocol.toLowerCase() === "data:") {
  8493. uri_info.origin = null;
  8494. } else {
  8495. uri_origin = uri.match(origin);
  8496. uri_info.origin = uri_origin && uri_origin[1];
  8497. }
  8498. }
  8499. return uri_info;
  8500. };
  8501. }
  8502. URL.createObjectURL = function(blob) {
  8503. var
  8504. type = blob.type
  8505. , data_URI_header
  8506. ;
  8507. if (type === null) {
  8508. type = "application/octet-stream";
  8509. }
  8510. if (blob instanceof FakeBlob) {
  8511. data_URI_header = "data:" + type;
  8512. if (blob.encoding === "base64") {
  8513. return data_URI_header + ";base64," + blob.data;
  8514. } else if (blob.encoding === "URI") {
  8515. return data_URI_header + "," + decodeURIComponent(blob.data);
  8516. } if (btoa) {
  8517. return data_URI_header + ";base64," + btoa(blob.data);
  8518. } else {
  8519. return data_URI_header + "," + encodeURIComponent(blob.data);
  8520. }
  8521. } else if (real_create_object_URL) {
  8522. return real_create_object_URL.call(real_URL, blob);
  8523. }
  8524. };
  8525. URL.revokeObjectURL = function(object_URL) {
  8526. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  8527. real_revoke_object_URL.call(real_URL, object_URL);
  8528. }
  8529. };
  8530. FBB_proto.append = function(data/*, endings*/) {
  8531. var bb = this.data;
  8532. // decode data to a binary string
  8533. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  8534. var
  8535. str = ""
  8536. , buf = new Uint8Array(data)
  8537. , i = 0
  8538. , buf_len = buf.length
  8539. ;
  8540. for (; i < buf_len; i++) {
  8541. str += String.fromCharCode(buf[i]);
  8542. }
  8543. bb.push(str);
  8544. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  8545. if (FileReaderSync) {
  8546. var fr = new FileReaderSync;
  8547. bb.push(fr.readAsBinaryString(data));
  8548. } else {
  8549. // async FileReader won't work as BlobBuilder is sync
  8550. throw new FileException("NOT_READABLE_ERR");
  8551. }
  8552. } else if (data instanceof FakeBlob) {
  8553. if (data.encoding === "base64" && atob) {
  8554. bb.push(atob(data.data));
  8555. } else if (data.encoding === "URI") {
  8556. bb.push(decodeURIComponent(data.data));
  8557. } else if (data.encoding === "raw") {
  8558. bb.push(data.data);
  8559. }
  8560. } else {
  8561. if (typeof data !== "string") {
  8562. data += ""; // convert unsupported types to strings
  8563. }
  8564. // decode UTF-16 to binary string
  8565. bb.push(unescape(encodeURIComponent(data)));
  8566. }
  8567. };
  8568. FBB_proto.getBlob = function(type) {
  8569. if (!arguments.length) {
  8570. type = null;
  8571. }
  8572. return new FakeBlob(this.data.join(""), type, "raw");
  8573. };
  8574. FBB_proto.toString = function() {
  8575. return "[object BlobBuilder]";
  8576. };
  8577. FB_proto.slice = function(start, end, type) {
  8578. var args = arguments.length;
  8579. if (args < 3) {
  8580. type = null;
  8581. }
  8582. return new FakeBlob(
  8583. this.data.slice(start, args > 1 ? end : this.data.length)
  8584. , type
  8585. , this.encoding
  8586. );
  8587. };
  8588. FB_proto.toString = function() {
  8589. return "[object Blob]";
  8590. };
  8591. FB_proto.close = function() {
  8592. this.size = 0;
  8593. delete this.data;
  8594. };
  8595. return FakeBlobBuilder;
  8596. }(view));
  8597. view.Blob = function(blobParts, options) {
  8598. var type = options ? (options.type || "") : "";
  8599. var builder = new BlobBuilder();
  8600. if (blobParts) {
  8601. for (var i = 0, len = blobParts.length; i < len; i++) {
  8602. if (Uint8Array && blobParts[i] instanceof Uint8Array) {
  8603. builder.append(blobParts[i].buffer);
  8604. }
  8605. else {
  8606. builder.append(blobParts[i]);
  8607. }
  8608. }
  8609. }
  8610. var blob = builder.getBlob(type);
  8611. if (!blob.slice && blob.webkitSlice) {
  8612. blob.slice = blob.webkitSlice;
  8613. }
  8614. return blob;
  8615. };
  8616. var getPrototypeOf = Object.getPrototypeOf || function(object) {
  8617. return object.__proto__;
  8618. };
  8619. view.Blob.prototype = getPrototypeOf(new view.Blob());
  8620. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
  8621. /* FileSaver.js
  8622. * A saveAs() FileSaver implementation.
  8623. * 1.1.20151003
  8624. *
  8625. * By Eli Grey, http://eligrey.com
  8626. * License: MIT
  8627. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  8628. */
  8629. /*global self */
  8630. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  8631. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  8632. var saveAs = saveAs || (function(view) {
  8633. "use strict";
  8634. // IE <10 is explicitly unsupported
  8635. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  8636. return;
  8637. }
  8638. var
  8639. doc = view.document
  8640. // only get URL when necessary in case Blob.js hasn't overridden it yet
  8641. , get_URL = function() {
  8642. return view.URL || view.webkitURL || view;
  8643. }
  8644. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  8645. , can_use_save_link = "download" in save_link
  8646. , click = function(node) {
  8647. var event = new MouseEvent("click");
  8648. node.dispatchEvent(event);
  8649. }
  8650. , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
  8651. , webkit_req_fs = view.webkitRequestFileSystem
  8652. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  8653. , throw_outside = function(ex) {
  8654. (view.setImmediate || view.setTimeout)(function() {
  8655. throw ex;
  8656. }, 0);
  8657. }
  8658. , force_saveable_type = "application/octet-stream"
  8659. , fs_min_size = 0
  8660. // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  8661. // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  8662. // for the reasoning behind the timeout and revocation flow
  8663. , arbitrary_revoke_timeout = 500 // in ms
  8664. , revoke = function(file) {
  8665. var revoker = function() {
  8666. if (typeof file === "string") { // file is an object URL
  8667. get_URL().revokeObjectURL(file);
  8668. } else { // file is a File
  8669. file.remove();
  8670. }
  8671. };
  8672. if (view.chrome) {
  8673. revoker();
  8674. } else {
  8675. setTimeout(revoker, arbitrary_revoke_timeout);
  8676. }
  8677. }
  8678. , dispatch = function(filesaver, event_types, event) {
  8679. event_types = [].concat(event_types);
  8680. var i = event_types.length;
  8681. while (i--) {
  8682. var listener = filesaver["on" + event_types[i]];
  8683. if (typeof listener === "function") {
  8684. try {
  8685. listener.call(filesaver, event || filesaver);
  8686. } catch (ex) {
  8687. throw_outside(ex);
  8688. }
  8689. }
  8690. }
  8691. }
  8692. , auto_bom = function(blob) {
  8693. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  8694. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  8695. return new Blob(["\ufeff", blob], {type: blob.type});
  8696. }
  8697. return blob;
  8698. }
  8699. , FileSaver = function(blob, name, no_auto_bom) {
  8700. if (!no_auto_bom) {
  8701. blob = auto_bom(blob);
  8702. }
  8703. // First try a.download, then web filesystem, then object URLs
  8704. var
  8705. filesaver = this
  8706. , type = blob.type
  8707. , blob_changed = false
  8708. , object_url
  8709. , target_view
  8710. , dispatch_all = function() {
  8711. dispatch(filesaver, "writestart progress write writeend".split(" "));
  8712. }
  8713. // on any filesys errors revert to saving with object URLs
  8714. , fs_error = function() {
  8715. if (target_view && is_safari && typeof FileReader !== "undefined") {
  8716. // Safari doesn't allow downloading of blob urls
  8717. var reader = new FileReader();
  8718. reader.onloadend = function() {
  8719. var base64Data = reader.result;
  8720. target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
  8721. filesaver.readyState = filesaver.DONE;
  8722. dispatch_all();
  8723. };
  8724. reader.readAsDataURL(blob);
  8725. filesaver.readyState = filesaver.INIT;
  8726. return;
  8727. }
  8728. // don't create more object URLs than needed
  8729. if (blob_changed || !object_url) {
  8730. object_url = get_URL().createObjectURL(blob);
  8731. }
  8732. if (target_view) {
  8733. target_view.location.href = object_url;
  8734. } else {
  8735. var new_tab = view.open(object_url, "_blank");
  8736. if (new_tab == undefined && is_safari) {
  8737. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  8738. view.location.href = object_url
  8739. }
  8740. }
  8741. filesaver.readyState = filesaver.DONE;
  8742. dispatch_all();
  8743. revoke(object_url);
  8744. }
  8745. , abortable = function(func) {
  8746. return function() {
  8747. if (filesaver.readyState !== filesaver.DONE) {
  8748. return func.apply(this, arguments);
  8749. }
  8750. };
  8751. }
  8752. , create_if_not_found = {create: true, exclusive: false}
  8753. , slice
  8754. ;
  8755. filesaver.readyState = filesaver.INIT;
  8756. if (!name) {
  8757. name = "download";
  8758. }
  8759. if (can_use_save_link) {
  8760. object_url = get_URL().createObjectURL(blob);
  8761. setTimeout(function() {
  8762. save_link.href = object_url;
  8763. save_link.download = name;
  8764. click(save_link);
  8765. dispatch_all();
  8766. revoke(object_url);
  8767. filesaver.readyState = filesaver.DONE;
  8768. });
  8769. return;
  8770. }
  8771. // Object and web filesystem URLs have a problem saving in Google Chrome when
  8772. // viewed in a tab, so I force save with application/octet-stream
  8773. // http://code.google.com/p/chromium/issues/detail?id=91158
  8774. // Update: Google errantly closed 91158, I submitted it again:
  8775. // https://code.google.com/p/chromium/issues/detail?id=389642
  8776. if (view.chrome && type && type !== force_saveable_type) {
  8777. slice = blob.slice || blob.webkitSlice;
  8778. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  8779. blob_changed = true;
  8780. }
  8781. // Since I can't be sure that the guessed media type will trigger a download
  8782. // in WebKit, I append .download to the filename.
  8783. // https://bugs.webkit.org/show_bug.cgi?id=65440
  8784. if (webkit_req_fs && name !== "download") {
  8785. name += ".download";
  8786. }
  8787. if (type === force_saveable_type || webkit_req_fs) {
  8788. target_view = view;
  8789. }
  8790. if (!req_fs) {
  8791. fs_error();
  8792. return;
  8793. }
  8794. fs_min_size += blob.size;
  8795. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  8796. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  8797. var save = function() {
  8798. dir.getFile(name, create_if_not_found, abortable(function(file) {
  8799. file.createWriter(abortable(function(writer) {
  8800. writer.onwriteend = function(event) {
  8801. target_view.location.href = file.toURL();
  8802. filesaver.readyState = filesaver.DONE;
  8803. dispatch(filesaver, "writeend", event);
  8804. revoke(file);
  8805. };
  8806. writer.onerror = function() {
  8807. var error = writer.error;
  8808. if (error.code !== error.ABORT_ERR) {
  8809. fs_error();
  8810. }
  8811. };
  8812. "writestart progress write abort".split(" ").forEach(function(event) {
  8813. writer["on" + event] = filesaver["on" + event];
  8814. });
  8815. writer.write(blob);
  8816. filesaver.abort = function() {
  8817. writer.abort();
  8818. filesaver.readyState = filesaver.DONE;
  8819. };
  8820. filesaver.readyState = filesaver.WRITING;
  8821. }), fs_error);
  8822. }), fs_error);
  8823. };
  8824. dir.getFile(name, {create: false}, abortable(function(file) {
  8825. // delete file if it already exists
  8826. file.remove();
  8827. save();
  8828. }), abortable(function(ex) {
  8829. if (ex.code === ex.NOT_FOUND_ERR) {
  8830. save();
  8831. } else {
  8832. fs_error();
  8833. }
  8834. }));
  8835. }), fs_error);
  8836. }), fs_error);
  8837. }
  8838. , FS_proto = FileSaver.prototype
  8839. , saveAs = function(blob, name, no_auto_bom) {
  8840. return new FileSaver(blob, name, no_auto_bom);
  8841. }
  8842. ;
  8843. // IE 10+ (native saveAs)
  8844. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  8845. return function(blob, name, no_auto_bom) {
  8846. if (!no_auto_bom) {
  8847. blob = auto_bom(blob);
  8848. }
  8849. return navigator.msSaveOrOpenBlob(blob, name || "download");
  8850. };
  8851. }
  8852. FS_proto.abort = function() {
  8853. var filesaver = this;
  8854. filesaver.readyState = filesaver.DONE;
  8855. dispatch(filesaver, "abort");
  8856. };
  8857. FS_proto.readyState = FS_proto.INIT = 0;
  8858. FS_proto.WRITING = 1;
  8859. FS_proto.DONE = 2;
  8860. FS_proto.error =
  8861. FS_proto.onwritestart =
  8862. FS_proto.onprogress =
  8863. FS_proto.onwrite =
  8864. FS_proto.onabort =
  8865. FS_proto.onerror =
  8866. FS_proto.onwriteend =
  8867. null;
  8868. return saveAs;
  8869. }(
  8870. typeof self !== "undefined" && self
  8871. || typeof window !== "undefined" && window
  8872. || undefined.content
  8873. ));
  8874. // `self` is undefined in Firefox for Android content script context
  8875. // while `this` is nsIContentFrameMessageManager
  8876. // with an attribute `content` that corresponds to the window
  8877. if (typeof module !== "undefined" && module.exports) {
  8878. module.exports.saveAs = saveAs;
  8879. } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  8880. define([], function() {
  8881. return saveAs;
  8882. });
  8883. }
  8884. /*
  8885. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  8886. *
  8887. * Licensed under the MIT License.
  8888. * http://opensource.org/licenses/mit-license
  8889. */
  8890. void function(global, callback) {
  8891. if (typeof module === 'object') {
  8892. module.exports = callback();
  8893. } else if (typeof define === 'function') {
  8894. define(callback);
  8895. } else {
  8896. global.adler32cs = callback();
  8897. }
  8898. }(jsPDF, function() {
  8899. var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
  8900. typeof Uint8Array === 'function';
  8901. var _Buffer = null, _isBuffer = (function() {
  8902. if (!_hasArrayBuffer)
  8903. return function _isBuffer() { return false };
  8904. try {
  8905. var buffer = {};
  8906. if (typeof buffer.Buffer === 'function')
  8907. _Buffer = buffer.Buffer;
  8908. } catch (error) {}
  8909. return function _isBuffer(value) {
  8910. return value instanceof ArrayBuffer ||
  8911. _Buffer !== null && value instanceof _Buffer;
  8912. };
  8913. }());
  8914. var _utf8ToBinary = (function() {
  8915. if (_Buffer !== null) {
  8916. return function _utf8ToBinary(utf8String) {
  8917. return new _Buffer(utf8String, 'utf8').toString('binary');
  8918. };
  8919. } else {
  8920. return function _utf8ToBinary(utf8String) {
  8921. return unescape(encodeURIComponent(utf8String));
  8922. };
  8923. }
  8924. }());
  8925. var MOD = 65521;
  8926. var _update = function _update(checksum, binaryString) {
  8927. var a = checksum & 0xFFFF, b = checksum >>> 16;
  8928. for (var i = 0, length = binaryString.length; i < length; i++) {
  8929. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  8930. b = (b + a) % MOD;
  8931. }
  8932. return (b << 16 | a) >>> 0;
  8933. };
  8934. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  8935. var a = checksum & 0xFFFF, b = checksum >>> 16;
  8936. for (var i = 0, length = uint8Array.length, x; i < length; i++) {
  8937. a = (a + uint8Array[i]) % MOD;
  8938. b = (b + a) % MOD;
  8939. }
  8940. return (b << 16 | a) >>> 0
  8941. };
  8942. var exports = {};
  8943. var Adler32 = exports.Adler32 = (function() {
  8944. var ctor = function Adler32(checksum) {
  8945. if (!(this instanceof ctor)) {
  8946. throw new TypeError(
  8947. 'Constructor cannot called be as a function.');
  8948. }
  8949. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  8950. throw new Error(
  8951. 'First arguments needs to be a finite number.');
  8952. }
  8953. this.checksum = checksum >>> 0;
  8954. };
  8955. var proto = ctor.prototype = {};
  8956. proto.constructor = ctor;
  8957. ctor.from = function(from) {
  8958. from.prototype = proto;
  8959. return from;
  8960. }(function from(binaryString) {
  8961. if (!(this instanceof ctor)) {
  8962. throw new TypeError(
  8963. 'Constructor cannot called be as a function.');
  8964. }
  8965. if (binaryString == null)
  8966. throw new Error('First argument needs to be a string.');
  8967. this.checksum = _update(1, binaryString.toString());
  8968. });
  8969. ctor.fromUtf8 = function(fromUtf8) {
  8970. fromUtf8.prototype = proto;
  8971. return fromUtf8;
  8972. }(function fromUtf8(utf8String) {
  8973. if (!(this instanceof ctor)) {
  8974. throw new TypeError(
  8975. 'Constructor cannot called be as a function.');
  8976. }
  8977. if (utf8String == null)
  8978. throw new Error('First argument needs to be a string.');
  8979. var binaryString = _utf8ToBinary(utf8String.toString());
  8980. this.checksum = _update(1, binaryString);
  8981. });
  8982. if (_hasArrayBuffer) {
  8983. ctor.fromBuffer = function(fromBuffer) {
  8984. fromBuffer.prototype = proto;
  8985. return fromBuffer;
  8986. }(function fromBuffer(buffer) {
  8987. if (!(this instanceof ctor)) {
  8988. throw new TypeError(
  8989. 'Constructor cannot called be as a function.');
  8990. }
  8991. if (!_isBuffer(buffer))
  8992. throw new Error('First argument needs to be ArrayBuffer.');
  8993. var array = new Uint8Array(buffer);
  8994. return this.checksum = _updateUint8Array(1, array);
  8995. });
  8996. }
  8997. proto.update = function update(binaryString) {
  8998. if (binaryString == null)
  8999. throw new Error('First argument needs to be a string.');
  9000. binaryString = binaryString.toString();
  9001. return this.checksum = _update(this.checksum, binaryString);
  9002. };
  9003. proto.updateUtf8 = function updateUtf8(utf8String) {
  9004. if (utf8String == null)
  9005. throw new Error('First argument needs to be a string.');
  9006. var binaryString = _utf8ToBinary(utf8String.toString());
  9007. return this.checksum = _update(this.checksum, binaryString);
  9008. };
  9009. if (_hasArrayBuffer) {
  9010. proto.updateBuffer = function updateBuffer(buffer) {
  9011. if (!_isBuffer(buffer))
  9012. throw new Error('First argument needs to be ArrayBuffer.');
  9013. var array = new Uint8Array(buffer);
  9014. return this.checksum = _updateUint8Array(this.checksum, array);
  9015. };
  9016. }
  9017. proto.clone = function clone() {
  9018. return new Adler32(this.checksum);
  9019. };
  9020. return ctor;
  9021. }());
  9022. exports.from = function from(binaryString) {
  9023. if (binaryString == null)
  9024. throw new Error('First argument needs to be a string.');
  9025. return _update(1, binaryString.toString());
  9026. };
  9027. exports.fromUtf8 = function fromUtf8(utf8String) {
  9028. if (utf8String == null)
  9029. throw new Error('First argument needs to be a string.');
  9030. var binaryString = _utf8ToBinary(utf8String.toString());
  9031. return _update(1, binaryString);
  9032. };
  9033. if (_hasArrayBuffer) {
  9034. exports.fromBuffer = function fromBuffer(buffer) {
  9035. if (!_isBuffer(buffer))
  9036. throw new Error('First argument need to be ArrayBuffer.');
  9037. var array = new Uint8Array(buffer);
  9038. return _updateUint8Array(1, array);
  9039. };
  9040. }
  9041. return exports;
  9042. });
  9043. /**
  9044. * CssColors
  9045. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  9046. *
  9047. * Licensed under the MIT License.
  9048. * http://opensource.org/licenses/mit-license
  9049. */
  9050. /**
  9051. * Usage CssColors('red');
  9052. * Returns RGB hex color with '#' prefix
  9053. */
  9054. var CssColors = {};
  9055. CssColors._colorsTable = {
  9056. "aliceblue" : "#f0f8ff",
  9057. "antiquewhite" : "#faebd7",
  9058. "aqua" : "#00ffff",
  9059. "aquamarine" : "#7fffd4",
  9060. "azure" : "#f0ffff",
  9061. "beige" : "#f5f5dc",
  9062. "bisque" : "#ffe4c4",
  9063. "black" : "#000000",
  9064. "blanchedalmond" : "#ffebcd",
  9065. "blue" : "#0000ff",
  9066. "blueviolet" : "#8a2be2",
  9067. "brown" : "#a52a2a",
  9068. "burlywood" : "#deb887",
  9069. "cadetblue" : "#5f9ea0",
  9070. "chartreuse" : "#7fff00",
  9071. "chocolate" : "#d2691e",
  9072. "coral" : "#ff7f50",
  9073. "cornflowerblue" : "#6495ed",
  9074. "cornsilk" : "#fff8dc",
  9075. "crimson" : "#dc143c",
  9076. "cyan" : "#00ffff",
  9077. "darkblue" : "#00008b",
  9078. "darkcyan" : "#008b8b",
  9079. "darkgoldenrod" : "#b8860b",
  9080. "darkgray" : "#a9a9a9",
  9081. "darkgreen" : "#006400",
  9082. "darkkhaki" : "#bdb76b",
  9083. "darkmagenta" : "#8b008b",
  9084. "darkolivegreen" : "#556b2f",
  9085. "darkorange" : "#ff8c00",
  9086. "darkorchid" : "#9932cc",
  9087. "darkred" : "#8b0000",
  9088. "darksalmon" : "#e9967a",
  9089. "darkseagreen" : "#8fbc8f",
  9090. "darkslateblue" : "#483d8b",
  9091. "darkslategray" : "#2f4f4f",
  9092. "darkturquoise" : "#00ced1",
  9093. "darkviolet" : "#9400d3",
  9094. "deeppink" : "#ff1493",
  9095. "deepskyblue" : "#00bfff",
  9096. "dimgray" : "#696969",
  9097. "dodgerblue" : "#1e90ff",
  9098. "firebrick" : "#b22222",
  9099. "floralwhite" : "#fffaf0",
  9100. "forestgreen" : "#228b22",
  9101. "fuchsia" : "#ff00ff",
  9102. "gainsboro" : "#dcdcdc",
  9103. "ghostwhite" : "#f8f8ff",
  9104. "gold" : "#ffd700",
  9105. "goldenrod" : "#daa520",
  9106. "gray" : "#808080",
  9107. "green" : "#008000",
  9108. "greenyellow" : "#adff2f",
  9109. "honeydew" : "#f0fff0",
  9110. "hotpink" : "#ff69b4",
  9111. "indianred " : "#cd5c5c",
  9112. "indigo" : "#4b0082",
  9113. "ivory" : "#fffff0",
  9114. "khaki" : "#f0e68c",
  9115. "lavender" : "#e6e6fa",
  9116. "lavenderblush" : "#fff0f5",
  9117. "lawngreen" : "#7cfc00",
  9118. "lemonchiffon" : "#fffacd",
  9119. "lightblue" : "#add8e6",
  9120. "lightcoral" : "#f08080",
  9121. "lightcyan" : "#e0ffff",
  9122. "lightgoldenrodyellow" : "#fafad2",
  9123. "lightgrey" : "#d3d3d3",
  9124. "lightgreen" : "#90ee90",
  9125. "lightpink" : "#ffb6c1",
  9126. "lightsalmon" : "#ffa07a",
  9127. "lightseagreen" : "#20b2aa",
  9128. "lightskyblue" : "#87cefa",
  9129. "lightslategray" : "#778899",
  9130. "lightsteelblue" : "#b0c4de",
  9131. "lightyellow" : "#ffffe0",
  9132. "lime" : "#00ff00",
  9133. "limegreen" : "#32cd32",
  9134. "linen" : "#faf0e6",
  9135. "magenta" : "#ff00ff",
  9136. "maroon" : "#800000",
  9137. "mediumaquamarine" : "#66cdaa",
  9138. "mediumblue" : "#0000cd",
  9139. "mediumorchid" : "#ba55d3",
  9140. "mediumpurple" : "#9370d8",
  9141. "mediumseagreen" : "#3cb371",
  9142. "mediumslateblue" : "#7b68ee",
  9143. "mediumspringgreen" : "#00fa9a",
  9144. "mediumturquoise" : "#48d1cc",
  9145. "mediumvioletred" : "#c71585",
  9146. "midnightblue" : "#191970",
  9147. "mintcream" : "#f5fffa",
  9148. "mistyrose" : "#ffe4e1",
  9149. "moccasin" : "#ffe4b5",
  9150. "navajowhite" : "#ffdead",
  9151. "navy" : "#000080",
  9152. "oldlace" : "#fdf5e6",
  9153. "olive" : "#808000",
  9154. "olivedrab" : "#6b8e23",
  9155. "orange" : "#ffa500",
  9156. "orangered" : "#ff4500",
  9157. "orchid" : "#da70d6",
  9158. "palegoldenrod" : "#eee8aa",
  9159. "palegreen" : "#98fb98",
  9160. "paleturquoise" : "#afeeee",
  9161. "palevioletred" : "#d87093",
  9162. "papayawhip" : "#ffefd5",
  9163. "peachpuff" : "#ffdab9",
  9164. "peru" : "#cd853f",
  9165. "pink" : "#ffc0cb",
  9166. "plum" : "#dda0dd",
  9167. "powderblue" : "#b0e0e6",
  9168. "purple" : "#800080",
  9169. "red" : "#ff0000",
  9170. "rosybrown" : "#bc8f8f",
  9171. "royalblue" : "#4169e1",
  9172. "saddlebrown" : "#8b4513",
  9173. "salmon" : "#fa8072",
  9174. "sandybrown" : "#f4a460",
  9175. "seagreen" : "#2e8b57",
  9176. "seashell" : "#fff5ee",
  9177. "sienna" : "#a0522d",
  9178. "silver" : "#c0c0c0",
  9179. "skyblue" : "#87ceeb",
  9180. "slateblue" : "#6a5acd",
  9181. "slategray" : "#708090",
  9182. "snow" : "#fffafa",
  9183. "springgreen" : "#00ff7f",
  9184. "steelblue" : "#4682b4",
  9185. "tan" : "#d2b48c",
  9186. "teal" : "#008080",
  9187. "thistle" : "#d8bfd8",
  9188. "tomato" : "#ff6347",
  9189. "turquoise" : "#40e0d0",
  9190. "violet" : "#ee82ee",
  9191. "wheat" : "#f5deb3",
  9192. "white" : "#ffffff",
  9193. "whitesmoke" : "#f5f5f5",
  9194. "yellow" : "#ffff00",
  9195. "yellowgreen" : "#9acd32"
  9196. };
  9197. CssColors.colorNameToHex = function(color) {
  9198. color = color.toLowerCase();
  9199. if (typeof this._colorsTable[color] != 'undefined')
  9200. return this._colorsTable[color];
  9201. return false;
  9202. };
  9203. /*
  9204. Deflate.js - https://github.com/gildas-lormeau/zip.js
  9205. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  9206. Redistribution and use in source and binary forms, with or without
  9207. modification, are permitted provided that the following conditions are met:
  9208. 1. Redistributions of source code must retain the above copyright notice,
  9209. this list of conditions and the following disclaimer.
  9210. 2. Redistributions in binary form must reproduce the above copyright
  9211. notice, this list of conditions and the following disclaimer in
  9212. the documentation and/or other materials provided with the distribution.
  9213. 3. The names of the authors may not be used to endorse or promote products
  9214. derived from this software without specific prior written permission.
  9215. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  9216. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9217. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  9218. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  9219. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9220. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  9221. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  9222. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  9223. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  9224. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9225. */
  9226. /*
  9227. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  9228. * JZlib is based on zlib-1.1.3, so all credit should go authors
  9229. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  9230. * and contributors of zlib.
  9231. */
  9232. var Deflater = (function(obj) {
  9233. // Global
  9234. var MAX_BITS = 15;
  9235. var D_CODES = 30;
  9236. var BL_CODES = 19;
  9237. var LENGTH_CODES = 29;
  9238. var LITERALS = 256;
  9239. var L_CODES = (LITERALS + 1 + LENGTH_CODES);
  9240. var HEAP_SIZE = (2 * L_CODES + 1);
  9241. var END_BLOCK = 256;
  9242. // Bit length codes must not exceed MAX_BL_BITS bits
  9243. var MAX_BL_BITS = 7;
  9244. // repeat previous bit length 3-6 times (2 bits of repeat count)
  9245. var REP_3_6 = 16;
  9246. // repeat a zero length 3-10 times (3 bits of repeat count)
  9247. var REPZ_3_10 = 17;
  9248. // repeat a zero length 11-138 times (7 bits of repeat count)
  9249. var REPZ_11_138 = 18;
  9250. // The lengths of the bit length codes are sent in order of decreasing
  9251. // probability, to avoid transmitting the lengths for unused bit
  9252. // length codes.
  9253. var Buf_size = 8 * 2;
  9254. // JZlib version : "1.0.2"
  9255. var Z_DEFAULT_COMPRESSION = -1;
  9256. // compression strategy
  9257. var Z_FILTERED = 1;
  9258. var Z_HUFFMAN_ONLY = 2;
  9259. var Z_DEFAULT_STRATEGY = 0;
  9260. var Z_NO_FLUSH = 0;
  9261. var Z_PARTIAL_FLUSH = 1;
  9262. var Z_FULL_FLUSH = 3;
  9263. var Z_FINISH = 4;
  9264. var Z_OK = 0;
  9265. var Z_STREAM_END = 1;
  9266. var Z_NEED_DICT = 2;
  9267. var Z_STREAM_ERROR = -2;
  9268. var Z_DATA_ERROR = -3;
  9269. var Z_BUF_ERROR = -5;
  9270. // Tree
  9271. // see definition of array dist_code below
  9272. 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,
  9273. 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,
  9274. 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,
  9275. 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,
  9276. 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,
  9277. 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,
  9278. 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,
  9279. 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,
  9280. 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,
  9281. 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,
  9282. 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,
  9283. 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,
  9284. 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,
  9285. 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 ];
  9286. function Tree() {
  9287. var that = this;
  9288. // dyn_tree; // the dynamic tree
  9289. // max_code; // largest code with non zero frequency
  9290. // stat_desc; // the corresponding static tree
  9291. // Compute the optimal bit lengths for a tree and update the total bit
  9292. // length
  9293. // for the current block.
  9294. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  9295. // above are the tree nodes sorted by increasing frequency.
  9296. // OUT assertions: the field len is set to the optimal bit length, the
  9297. // array bl_count contains the frequencies for each bit length.
  9298. // The length opt_len is updated; static_len is also updated if stree is
  9299. // not null.
  9300. function gen_bitlen(s) {
  9301. var tree = that.dyn_tree;
  9302. var stree = that.stat_desc.static_tree;
  9303. var extra = that.stat_desc.extra_bits;
  9304. var base = that.stat_desc.extra_base;
  9305. var max_length = that.stat_desc.max_length;
  9306. var h; // heap index
  9307. var n, m; // iterate over the tree elements
  9308. var bits; // bit length
  9309. var xbits; // extra bits
  9310. var f; // frequency
  9311. var overflow = 0; // number of elements with bit length too large
  9312. for (bits = 0; bits <= MAX_BITS; bits++)
  9313. s.bl_count[bits] = 0;
  9314. // In a first pass, compute the optimal bit lengths (which may
  9315. // overflow in the case of the bit length tree).
  9316. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  9317. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9318. n = s.heap[h];
  9319. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  9320. if (bits > max_length) {
  9321. bits = max_length;
  9322. overflow++;
  9323. }
  9324. tree[n * 2 + 1] = bits;
  9325. // We overwrite tree[n*2+1] which is no longer needed
  9326. if (n > that.max_code)
  9327. continue; // not a leaf node
  9328. s.bl_count[bits]++;
  9329. xbits = 0;
  9330. if (n >= base)
  9331. xbits = extra[n - base];
  9332. f = tree[n * 2];
  9333. s.opt_len += f * (bits + xbits);
  9334. if (stree)
  9335. s.static_len += f * (stree[n * 2 + 1] + xbits);
  9336. }
  9337. if (overflow === 0)
  9338. return;
  9339. // This happens for example on obj2 and pic of the Calgary corpus
  9340. // Find the first bit length which could increase:
  9341. do {
  9342. bits = max_length - 1;
  9343. while (s.bl_count[bits] === 0)
  9344. bits--;
  9345. s.bl_count[bits]--; // move one leaf down the tree
  9346. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  9347. s.bl_count[max_length]--;
  9348. // The brother of the overflow item also moves one step up,
  9349. // but this does not affect bl_count[max_length]
  9350. overflow -= 2;
  9351. } while (overflow > 0);
  9352. for (bits = max_length; bits !== 0; bits--) {
  9353. n = s.bl_count[bits];
  9354. while (n !== 0) {
  9355. m = s.heap[--h];
  9356. if (m > that.max_code)
  9357. continue;
  9358. if (tree[m * 2 + 1] != bits) {
  9359. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  9360. tree[m * 2 + 1] = bits;
  9361. }
  9362. n--;
  9363. }
  9364. }
  9365. }
  9366. // Reverse the first len bits of a code, using straightforward code (a
  9367. // faster
  9368. // method would use a table)
  9369. // IN assertion: 1 <= len <= 15
  9370. function bi_reverse(code, // the value to invert
  9371. len // its bit length
  9372. ) {
  9373. var res = 0;
  9374. do {
  9375. res |= code & 1;
  9376. code >>>= 1;
  9377. res <<= 1;
  9378. } while (--len > 0);
  9379. return res >>> 1;
  9380. }
  9381. // Generate the codes for a given tree and bit counts (which need not be
  9382. // optimal).
  9383. // IN assertion: the array bl_count contains the bit length statistics for
  9384. // the given tree and the field len is set for all tree elements.
  9385. // OUT assertion: the field code is set for all tree elements of non
  9386. // zero code length.
  9387. function gen_codes(tree, // the tree to decorate
  9388. max_code, // largest code with non zero frequency
  9389. bl_count // number of codes at each bit length
  9390. ) {
  9391. var next_code = []; // next code value for each
  9392. // bit length
  9393. var code = 0; // running code value
  9394. var bits; // bit index
  9395. var n; // code index
  9396. var len;
  9397. // The distribution counts are first used to generate the code values
  9398. // without bit reversal.
  9399. for (bits = 1; bits <= MAX_BITS; bits++) {
  9400. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  9401. }
  9402. // Check that the bit counts in bl_count are consistent. The last code
  9403. // must be all ones.
  9404. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9405. // "inconsistent bit counts");
  9406. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9407. for (n = 0; n <= max_code; n++) {
  9408. len = tree[n * 2 + 1];
  9409. if (len === 0)
  9410. continue;
  9411. // Now reverse the bits
  9412. tree[n * 2] = bi_reverse(next_code[len]++, len);
  9413. }
  9414. }
  9415. // Construct one Huffman tree and assigns the code bit strings and lengths.
  9416. // Update the total bit length for the current block.
  9417. // IN assertion: the field freq is set for all tree elements.
  9418. // OUT assertions: the fields len and code are set to the optimal bit length
  9419. // and corresponding code. The length opt_len is updated; static_len is
  9420. // also updated if stree is not null. The field max_code is set.
  9421. that.build_tree = function(s) {
  9422. var tree = that.dyn_tree;
  9423. var stree = that.stat_desc.static_tree;
  9424. var elems = that.stat_desc.elems;
  9425. var n, m; // iterate over heap elements
  9426. var max_code = -1; // largest code with non zero frequency
  9427. var node; // new node being created
  9428. // Construct the initial heap, with least frequent element in
  9429. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9430. // heap[0] is not used.
  9431. s.heap_len = 0;
  9432. s.heap_max = HEAP_SIZE;
  9433. for (n = 0; n < elems; n++) {
  9434. if (tree[n * 2] !== 0) {
  9435. s.heap[++s.heap_len] = max_code = n;
  9436. s.depth[n] = 0;
  9437. } else {
  9438. tree[n * 2 + 1] = 0;
  9439. }
  9440. }
  9441. // The pkzip format requires that at least one distance code exists,
  9442. // and that at least one bit should be sent even if there is only one
  9443. // possible code. So to avoid special checks later on we force at least
  9444. // two codes of non zero frequency.
  9445. while (s.heap_len < 2) {
  9446. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  9447. tree[node * 2] = 1;
  9448. s.depth[node] = 0;
  9449. s.opt_len--;
  9450. if (stree)
  9451. s.static_len -= stree[node * 2 + 1];
  9452. // node is 0 or 1 so it does not have extra bits
  9453. }
  9454. that.max_code = max_code;
  9455. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9456. // establish sub-heaps of increasing lengths:
  9457. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  9458. s.pqdownheap(tree, n);
  9459. // Construct the Huffman tree by repeatedly combining the least two
  9460. // frequent nodes.
  9461. node = elems; // next internal node of the tree
  9462. do {
  9463. // n = node of least frequency
  9464. n = s.heap[1];
  9465. s.heap[1] = s.heap[s.heap_len--];
  9466. s.pqdownheap(tree, 1);
  9467. m = s.heap[1]; // m = node of next least frequency
  9468. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  9469. s.heap[--s.heap_max] = m;
  9470. // Create a new node father of n and m
  9471. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  9472. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  9473. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  9474. // and insert the new node in the heap
  9475. s.heap[1] = node++;
  9476. s.pqdownheap(tree, 1);
  9477. } while (s.heap_len >= 2);
  9478. s.heap[--s.heap_max] = s.heap[1];
  9479. // At this point, the fields freq and dad are set. We can now
  9480. // generate the bit lengths.
  9481. gen_bitlen(s);
  9482. // The field len is now set, we can generate the bit codes
  9483. gen_codes(tree, that.max_code, s.bl_count);
  9484. };
  9485. }
  9486. 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,
  9487. 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,
  9488. 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,
  9489. 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,
  9490. 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,
  9491. 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,
  9492. 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 ];
  9493. 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 ];
  9494. 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,
  9495. 24576 ];
  9496. // Mapping from a distance to a distance code. dist is the distance - 1 and
  9497. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  9498. // used.
  9499. Tree.d_code = function(dist) {
  9500. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  9501. };
  9502. // extra bits for each length code
  9503. 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 ];
  9504. // extra bits for each distance code
  9505. 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 ];
  9506. // extra bits for each bit length code
  9507. Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
  9508. Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  9509. // StaticTree
  9510. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  9511. var that = this;
  9512. that.static_tree = static_tree;
  9513. that.extra_bits = extra_bits;
  9514. that.extra_base = extra_base;
  9515. that.elems = elems;
  9516. that.max_length = max_length;
  9517. }
  9518. 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,
  9519. 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,
  9520. 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,
  9521. 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,
  9522. 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,
  9523. 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,
  9524. 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,
  9525. 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,
  9526. 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,
  9527. 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,
  9528. 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,
  9529. 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,
  9530. 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,
  9531. 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,
  9532. 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,
  9533. 99, 8, 227, 8 ];
  9534. 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,
  9535. 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
  9536. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9537. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  9538. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9539. // Deflate
  9540. var MAX_MEM_LEVEL = 9;
  9541. var DEF_MEM_LEVEL = 8;
  9542. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  9543. var that = this;
  9544. that.good_length = good_length;
  9545. that.max_lazy = max_lazy;
  9546. that.nice_length = nice_length;
  9547. that.max_chain = max_chain;
  9548. that.func = func;
  9549. }
  9550. var STORED = 0;
  9551. var FAST = 1;
  9552. var SLOW = 2;
  9553. 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),
  9554. 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),
  9555. new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
  9556. var z_errmsg = [ "need dictionary", // Z_NEED_DICT
  9557. // 2
  9558. "stream end", // Z_STREAM_END 1
  9559. "", // Z_OK 0
  9560. "", // Z_ERRNO (-1)
  9561. "stream error", // Z_STREAM_ERROR (-2)
  9562. "data error", // Z_DATA_ERROR (-3)
  9563. "", // Z_MEM_ERROR (-4)
  9564. "buffer error", // Z_BUF_ERROR (-5)
  9565. "",// Z_VERSION_ERROR (-6)
  9566. "" ];
  9567. // block not completed, need more input or more output
  9568. var NeedMore = 0;
  9569. // block flush performed
  9570. var BlockDone = 1;
  9571. // finish started, need only more output at next deflate
  9572. var FinishStarted = 2;
  9573. // finish done, accept no more input or output
  9574. var FinishDone = 3;
  9575. // preset dictionary flag in zlib header
  9576. var PRESET_DICT = 0x20;
  9577. var INIT_STATE = 42;
  9578. var BUSY_STATE = 113;
  9579. var FINISH_STATE = 666;
  9580. // The deflate compression method
  9581. var Z_DEFLATED = 8;
  9582. var STORED_BLOCK = 0;
  9583. var STATIC_TREES = 1;
  9584. var DYN_TREES = 2;
  9585. var MIN_MATCH = 3;
  9586. var MAX_MATCH = 258;
  9587. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  9588. function smaller(tree, n, m, depth) {
  9589. var tn2 = tree[n * 2];
  9590. var tm2 = tree[m * 2];
  9591. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  9592. }
  9593. function Deflate() {
  9594. var that = this;
  9595. var strm; // pointer back to this zlib stream
  9596. var status; // as the name implies
  9597. // pending_buf; // output still pending
  9598. var pending_buf_size; // size of pending_buf
  9599. // pending_out; // next pending byte to output to the stream
  9600. // pending; // nb of bytes in the pending buffer
  9601. var method; // STORED (for zip only) or DEFLATED
  9602. var last_flush; // value of flush param for previous deflate call
  9603. var w_size; // LZ77 window size (32K by default)
  9604. var w_bits; // log2(w_size) (8..16)
  9605. var w_mask; // w_size - 1
  9606. var window;
  9607. // Sliding window. Input bytes are read into the second half of the window,
  9608. // and move to the first half later to keep a dictionary of at least wSize
  9609. // bytes. With this organization, matches are limited to a distance of
  9610. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  9611. // performed with a length multiple of the block size. Also, it limits
  9612. // the window size to 64K, which is quite useful on MSDOS.
  9613. // To do: use the user input buffer as sliding window.
  9614. var window_size;
  9615. // Actual size of window: 2*wSize, except when the user input buffer
  9616. // is directly used as sliding window.
  9617. var prev;
  9618. // Link to older string with same hash index. To limit the size of this
  9619. // array to 64K, this link is maintained only for the last 32K strings.
  9620. // An index in this array is thus a window index modulo 32K.
  9621. var head; // Heads of the hash chains or NIL.
  9622. var ins_h; // hash index of string to be inserted
  9623. var hash_size; // number of elements in hash table
  9624. var hash_bits; // log2(hash_size)
  9625. var hash_mask; // hash_size-1
  9626. // Number of bits by which ins_h must be shifted at each input
  9627. // step. It must be such that after MIN_MATCH steps, the oldest
  9628. // byte no longer takes part in the hash key, that is:
  9629. // hash_shift * MIN_MATCH >= hash_bits
  9630. var hash_shift;
  9631. // Window position at the beginning of the current output block. Gets
  9632. // negative when the window is moved backwards.
  9633. var block_start;
  9634. var match_length; // length of best match
  9635. var prev_match; // previous match
  9636. var match_available; // set if previous match exists
  9637. var strstart; // start of string to insert
  9638. var match_start; // start of matching string
  9639. var lookahead; // number of valid bytes ahead in window
  9640. // Length of the best match at previous step. Matches not greater than this
  9641. // are discarded. This is used in the lazy match evaluation.
  9642. var prev_length;
  9643. // To speed up deflation, hash chains are never searched beyond this
  9644. // length. A higher limit improves compression ratio but degrades the speed.
  9645. var max_chain_length;
  9646. // Attempt to find a better match only when the current match is strictly
  9647. // smaller than this value. This mechanism is used only for compression
  9648. // levels >= 4.
  9649. var max_lazy_match;
  9650. // Insert new strings in the hash table only if the match length is not
  9651. // greater than this length. This saves time but degrades compression.
  9652. // max_insert_length is used only for compression levels <= 3.
  9653. var level; // compression level (1..9)
  9654. var strategy; // favor or force Huffman coding
  9655. // Use a faster search when the previous match is longer than this
  9656. var good_match;
  9657. // Stop searching when current match exceeds this
  9658. var nice_match;
  9659. var dyn_ltree; // literal and length tree
  9660. var dyn_dtree; // distance tree
  9661. var bl_tree; // Huffman tree for bit lengths
  9662. var l_desc = new Tree(); // desc for literal tree
  9663. var d_desc = new Tree(); // desc for distance tree
  9664. var bl_desc = new Tree(); // desc for bit length tree
  9665. // that.heap_len; // number of elements in the heap
  9666. // that.heap_max; // element of largest frequency
  9667. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  9668. // The same heap array is used to build all trees.
  9669. // Depth of each subtree used as tie breaker for trees of equal frequency
  9670. that.depth = [];
  9671. var l_buf; // index for literals or lengths */
  9672. // Size of match buffer for literals/lengths. There are 4 reasons for
  9673. // limiting lit_bufsize to 64K:
  9674. // - frequencies can be kept in 16 bit counters
  9675. // - if compression is not successful for the first block, all input
  9676. // data is still in the window so we can still emit a stored block even
  9677. // when input comes from standard input. (This can also be done for
  9678. // all blocks if lit_bufsize is not greater than 32K.)
  9679. // - if compression is not successful for a file smaller than 64K, we can
  9680. // even emit a stored file instead of a stored block (saving 5 bytes).
  9681. // This is applicable only for zip (not gzip or zlib).
  9682. // - creating new Huffman trees less frequently may not provide fast
  9683. // adaptation to changes in the input data statistics. (Take for
  9684. // example a binary file with poorly compressible code followed by
  9685. // a highly compressible string table.) Smaller buffer sizes give
  9686. // fast adaptation but have of course the overhead of transmitting
  9687. // trees more frequently.
  9688. // - I can't count above 4
  9689. var lit_bufsize;
  9690. var last_lit; // running index in l_buf
  9691. // Buffer for distances. To simplify the code, d_buf and l_buf have
  9692. // the same number of elements. To use different lengths, an extra flag
  9693. // array would be necessary.
  9694. var d_buf; // index of pendig_buf
  9695. // that.opt_len; // bit length of current block with optimal trees
  9696. // that.static_len; // bit length of current block with static trees
  9697. var matches; // number of string matches in current block
  9698. var last_eob_len; // bit length of EOB code for last block
  9699. // Output buffer. bits are inserted starting at the bottom (least
  9700. // significant bits).
  9701. var bi_buf;
  9702. // Number of valid bits in bi_buf. All bits above the last valid bit
  9703. // are always zero.
  9704. var bi_valid;
  9705. // number of codes at each bit length for an optimal tree
  9706. that.bl_count = [];
  9707. // heap used to build the Huffman trees
  9708. that.heap = [];
  9709. dyn_ltree = [];
  9710. dyn_dtree = [];
  9711. bl_tree = [];
  9712. function lm_init() {
  9713. var i;
  9714. window_size = 2 * w_size;
  9715. head[hash_size - 1] = 0;
  9716. for (i = 0; i < hash_size - 1; i++) {
  9717. head[i] = 0;
  9718. }
  9719. // Set the default configuration parameters:
  9720. max_lazy_match = config_table[level].max_lazy;
  9721. good_match = config_table[level].good_length;
  9722. nice_match = config_table[level].nice_length;
  9723. max_chain_length = config_table[level].max_chain;
  9724. strstart = 0;
  9725. block_start = 0;
  9726. lookahead = 0;
  9727. match_length = prev_length = MIN_MATCH - 1;
  9728. match_available = 0;
  9729. ins_h = 0;
  9730. }
  9731. function init_block() {
  9732. var i;
  9733. // Initialize the trees.
  9734. for (i = 0; i < L_CODES; i++)
  9735. dyn_ltree[i * 2] = 0;
  9736. for (i = 0; i < D_CODES; i++)
  9737. dyn_dtree[i * 2] = 0;
  9738. for (i = 0; i < BL_CODES; i++)
  9739. bl_tree[i * 2] = 0;
  9740. dyn_ltree[END_BLOCK * 2] = 1;
  9741. that.opt_len = that.static_len = 0;
  9742. last_lit = matches = 0;
  9743. }
  9744. // Initialize the tree data structures for a new zlib stream.
  9745. function tr_init() {
  9746. l_desc.dyn_tree = dyn_ltree;
  9747. l_desc.stat_desc = StaticTree.static_l_desc;
  9748. d_desc.dyn_tree = dyn_dtree;
  9749. d_desc.stat_desc = StaticTree.static_d_desc;
  9750. bl_desc.dyn_tree = bl_tree;
  9751. bl_desc.stat_desc = StaticTree.static_bl_desc;
  9752. bi_buf = 0;
  9753. bi_valid = 0;
  9754. last_eob_len = 8; // enough lookahead for inflate
  9755. // Initialize the first block of the first file:
  9756. init_block();
  9757. }
  9758. // Restore the heap property by moving down the tree starting at node k,
  9759. // exchanging a node with the smallest of its two sons if necessary,
  9760. // stopping
  9761. // when the heap property is re-established (each father smaller than its
  9762. // two sons).
  9763. that.pqdownheap = function(tree, // the tree to restore
  9764. k // node to move down
  9765. ) {
  9766. var heap = that.heap;
  9767. var v = heap[k];
  9768. var j = k << 1; // left son of k
  9769. while (j <= that.heap_len) {
  9770. // Set j to the smallest of the two sons:
  9771. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  9772. j++;
  9773. }
  9774. // Exit if v is smaller than both sons
  9775. if (smaller(tree, v, heap[j], that.depth))
  9776. break;
  9777. // Exchange v with the smallest son
  9778. heap[k] = heap[j];
  9779. k = j;
  9780. // And continue down the tree, setting j to the left son of k
  9781. j <<= 1;
  9782. }
  9783. heap[k] = v;
  9784. };
  9785. // Scan a literal or distance tree to determine the frequencies of the codes
  9786. // in the bit length tree.
  9787. function scan_tree(tree,// the tree to be scanned
  9788. max_code // and its largest code of non zero frequency
  9789. ) {
  9790. var n; // iterates over all tree elements
  9791. var prevlen = -1; // last emitted length
  9792. var curlen; // length of current code
  9793. var nextlen = tree[0 * 2 + 1]; // length of next code
  9794. var count = 0; // repeat count of the current code
  9795. var max_count = 7; // max repeat count
  9796. var min_count = 4; // min repeat count
  9797. if (nextlen === 0) {
  9798. max_count = 138;
  9799. min_count = 3;
  9800. }
  9801. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  9802. for (n = 0; n <= max_code; n++) {
  9803. curlen = nextlen;
  9804. nextlen = tree[(n + 1) * 2 + 1];
  9805. if (++count < max_count && curlen == nextlen) {
  9806. continue;
  9807. } else if (count < min_count) {
  9808. bl_tree[curlen * 2] += count;
  9809. } else if (curlen !== 0) {
  9810. if (curlen != prevlen)
  9811. bl_tree[curlen * 2]++;
  9812. bl_tree[REP_3_6 * 2]++;
  9813. } else if (count <= 10) {
  9814. bl_tree[REPZ_3_10 * 2]++;
  9815. } else {
  9816. bl_tree[REPZ_11_138 * 2]++;
  9817. }
  9818. count = 0;
  9819. prevlen = curlen;
  9820. if (nextlen === 0) {
  9821. max_count = 138;
  9822. min_count = 3;
  9823. } else if (curlen == nextlen) {
  9824. max_count = 6;
  9825. min_count = 3;
  9826. } else {
  9827. max_count = 7;
  9828. min_count = 4;
  9829. }
  9830. }
  9831. }
  9832. // Construct the Huffman tree for the bit lengths and return the index in
  9833. // bl_order of the last bit length code to send.
  9834. function build_bl_tree() {
  9835. var max_blindex; // index of last bit length code of non zero freq
  9836. // Determine the bit length frequencies for literal and distance trees
  9837. scan_tree(dyn_ltree, l_desc.max_code);
  9838. scan_tree(dyn_dtree, d_desc.max_code);
  9839. // Build the bit length tree:
  9840. bl_desc.build_tree(that);
  9841. // opt_len now includes the length of the tree representations, except
  9842. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  9843. // counts.
  9844. // Determine the number of bit length codes to send. The pkzip format
  9845. // requires that at least 4 bit length codes be sent. (appnote.txt says
  9846. // 3 but the actual value used is 4.)
  9847. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  9848. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  9849. break;
  9850. }
  9851. // Update opt_len to include the bit length tree and counts
  9852. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  9853. return max_blindex;
  9854. }
  9855. // Output a byte on the stream.
  9856. // IN assertion: there is enough room in pending_buf.
  9857. function put_byte(p) {
  9858. that.pending_buf[that.pending++] = p;
  9859. }
  9860. function put_short(w) {
  9861. put_byte(w & 0xff);
  9862. put_byte((w >>> 8) & 0xff);
  9863. }
  9864. function putShortMSB(b) {
  9865. put_byte((b >> 8) & 0xff);
  9866. put_byte((b & 0xff) & 0xff);
  9867. }
  9868. function send_bits(value, length) {
  9869. var val, len = length;
  9870. if (bi_valid > Buf_size - len) {
  9871. val = value;
  9872. // bi_buf |= (val << bi_valid);
  9873. bi_buf |= ((val << bi_valid) & 0xffff);
  9874. put_short(bi_buf);
  9875. bi_buf = val >>> (Buf_size - bi_valid);
  9876. bi_valid += len - Buf_size;
  9877. } else {
  9878. // bi_buf |= (value) << bi_valid;
  9879. bi_buf |= (((value) << bi_valid) & 0xffff);
  9880. bi_valid += len;
  9881. }
  9882. }
  9883. function send_code(c, tree) {
  9884. var c2 = c * 2;
  9885. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  9886. }
  9887. // Send a literal or distance tree in compressed form, using the codes in
  9888. // bl_tree.
  9889. function send_tree(tree,// the tree to be sent
  9890. max_code // and its largest code of non zero frequency
  9891. ) {
  9892. var n; // iterates over all tree elements
  9893. var prevlen = -1; // last emitted length
  9894. var curlen; // length of current code
  9895. var nextlen = tree[0 * 2 + 1]; // length of next code
  9896. var count = 0; // repeat count of the current code
  9897. var max_count = 7; // max repeat count
  9898. var min_count = 4; // min repeat count
  9899. if (nextlen === 0) {
  9900. max_count = 138;
  9901. min_count = 3;
  9902. }
  9903. for (n = 0; n <= max_code; n++) {
  9904. curlen = nextlen;
  9905. nextlen = tree[(n + 1) * 2 + 1];
  9906. if (++count < max_count && curlen == nextlen) {
  9907. continue;
  9908. } else if (count < min_count) {
  9909. do {
  9910. send_code(curlen, bl_tree);
  9911. } while (--count !== 0);
  9912. } else if (curlen !== 0) {
  9913. if (curlen != prevlen) {
  9914. send_code(curlen, bl_tree);
  9915. count--;
  9916. }
  9917. send_code(REP_3_6, bl_tree);
  9918. send_bits(count - 3, 2);
  9919. } else if (count <= 10) {
  9920. send_code(REPZ_3_10, bl_tree);
  9921. send_bits(count - 3, 3);
  9922. } else {
  9923. send_code(REPZ_11_138, bl_tree);
  9924. send_bits(count - 11, 7);
  9925. }
  9926. count = 0;
  9927. prevlen = curlen;
  9928. if (nextlen === 0) {
  9929. max_count = 138;
  9930. min_count = 3;
  9931. } else if (curlen == nextlen) {
  9932. max_count = 6;
  9933. min_count = 3;
  9934. } else {
  9935. max_count = 7;
  9936. min_count = 4;
  9937. }
  9938. }
  9939. }
  9940. // Send the header for a block using dynamic Huffman trees: the counts, the
  9941. // lengths of the bit length codes, the literal tree and the distance tree.
  9942. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  9943. function send_all_trees(lcodes, dcodes, blcodes) {
  9944. var rank; // index in bl_order
  9945. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  9946. send_bits(dcodes - 1, 5);
  9947. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  9948. for (rank = 0; rank < blcodes; rank++) {
  9949. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  9950. }
  9951. send_tree(dyn_ltree, lcodes - 1); // literal tree
  9952. send_tree(dyn_dtree, dcodes - 1); // distance tree
  9953. }
  9954. // Flush the bit buffer, keeping at most 7 bits in it.
  9955. function bi_flush() {
  9956. if (bi_valid == 16) {
  9957. put_short(bi_buf);
  9958. bi_buf = 0;
  9959. bi_valid = 0;
  9960. } else if (bi_valid >= 8) {
  9961. put_byte(bi_buf & 0xff);
  9962. bi_buf >>>= 8;
  9963. bi_valid -= 8;
  9964. }
  9965. }
  9966. // Send one empty static block to give enough lookahead for inflate.
  9967. // This takes 10 bits, of which 7 may remain in the bit buffer.
  9968. // The current inflate code requires 9 bits of lookahead. If the
  9969. // last two codes for the previous block (real code plus EOB) were coded
  9970. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  9971. // the last real code. In this case we send two empty static blocks instead
  9972. // of one. (There are no problems if the previous block is stored or fixed.)
  9973. // To simplify the code, we assume the worst case of last real code encoded
  9974. // on one bit only.
  9975. function _tr_align() {
  9976. send_bits(STATIC_TREES << 1, 3);
  9977. send_code(END_BLOCK, StaticTree.static_ltree);
  9978. bi_flush();
  9979. // Of the 10 bits for the empty block, we have already sent
  9980. // (10 - bi_valid) bits. The lookahead for the last real code (before
  9981. // the EOB of the previous block) was thus at least one plus the length
  9982. // of the EOB plus what we have just sent of the empty static block.
  9983. if (1 + last_eob_len + 10 - bi_valid < 9) {
  9984. send_bits(STATIC_TREES << 1, 3);
  9985. send_code(END_BLOCK, StaticTree.static_ltree);
  9986. bi_flush();
  9987. }
  9988. last_eob_len = 7;
  9989. }
  9990. // Save the match info and tally the frequency counts. Return true if
  9991. // the current block must be flushed.
  9992. function _tr_tally(dist, // distance of matched string
  9993. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  9994. ) {
  9995. var out_length, in_length, dcode;
  9996. that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
  9997. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  9998. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  9999. last_lit++;
  10000. if (dist === 0) {
  10001. // lc is the unmatched char
  10002. dyn_ltree[lc * 2]++;
  10003. } else {
  10004. matches++;
  10005. // Here, lc is the match length - MIN_MATCH
  10006. dist--; // dist = match distance - 1
  10007. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  10008. dyn_dtree[Tree.d_code(dist) * 2]++;
  10009. }
  10010. if ((last_lit & 0x1fff) === 0 && level > 2) {
  10011. // Compute an upper bound for the compressed length
  10012. out_length = last_lit * 8;
  10013. in_length = strstart - block_start;
  10014. for (dcode = 0; dcode < D_CODES; dcode++) {
  10015. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  10016. }
  10017. out_length >>>= 3;
  10018. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  10019. return true;
  10020. }
  10021. return (last_lit == lit_bufsize - 1);
  10022. // We avoid equality with lit_bufsize because of wraparound at 64K
  10023. // on 16 bit machines and because stored blocks are restricted to
  10024. // 64K-1 bytes.
  10025. }
  10026. // Send the block data compressed using the given Huffman trees
  10027. function compress_block(ltree, dtree) {
  10028. var dist; // distance of matched string
  10029. var lc; // match length or unmatched char (if dist === 0)
  10030. var lx = 0; // running index in l_buf
  10031. var code; // the code to send
  10032. var extra; // number of extra bits to send
  10033. if (last_lit !== 0) {
  10034. do {
  10035. dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
  10036. lc = (that.pending_buf[l_buf + lx]) & 0xff;
  10037. lx++;
  10038. if (dist === 0) {
  10039. send_code(lc, ltree); // send a literal byte
  10040. } else {
  10041. // Here, lc is the match length - MIN_MATCH
  10042. code = Tree._length_code[lc];
  10043. send_code(code + LITERALS + 1, ltree); // send the length
  10044. // code
  10045. extra = Tree.extra_lbits[code];
  10046. if (extra !== 0) {
  10047. lc -= Tree.base_length[code];
  10048. send_bits(lc, extra); // send the extra length bits
  10049. }
  10050. dist--; // dist is now the match distance - 1
  10051. code = Tree.d_code(dist);
  10052. send_code(code, dtree); // send the distance code
  10053. extra = Tree.extra_dbits[code];
  10054. if (extra !== 0) {
  10055. dist -= Tree.base_dist[code];
  10056. send_bits(dist, extra); // send the extra distance bits
  10057. }
  10058. } // literal or match pair ?
  10059. // Check that the overlay between pending_buf and d_buf+l_buf is
  10060. // ok:
  10061. } while (lx < last_lit);
  10062. }
  10063. send_code(END_BLOCK, ltree);
  10064. last_eob_len = ltree[END_BLOCK * 2 + 1];
  10065. }
  10066. // Flush the bit buffer and align the output on a byte boundary
  10067. function bi_windup() {
  10068. if (bi_valid > 8) {
  10069. put_short(bi_buf);
  10070. } else if (bi_valid > 0) {
  10071. put_byte(bi_buf & 0xff);
  10072. }
  10073. bi_buf = 0;
  10074. bi_valid = 0;
  10075. }
  10076. // Copy a stored block, storing first the length and its
  10077. // one's complement if requested.
  10078. function copy_block(buf, // the input data
  10079. len, // its length
  10080. header // true if block header must be written
  10081. ) {
  10082. bi_windup(); // align on byte boundary
  10083. last_eob_len = 8; // enough lookahead for inflate
  10084. if (header) {
  10085. put_short(len);
  10086. put_short(~len);
  10087. }
  10088. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  10089. that.pending += len;
  10090. }
  10091. // Send a stored block
  10092. function _tr_stored_block(buf, // input block
  10093. stored_len, // length of input block
  10094. eof // true if this is the last block for a file
  10095. ) {
  10096. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  10097. copy_block(buf, stored_len, true); // with header
  10098. }
  10099. // Determine the best encoding for the current block: dynamic trees, static
  10100. // trees or store, and output the encoded block to the zip file.
  10101. function _tr_flush_block(buf, // input block, or NULL if too old
  10102. stored_len, // length of input block
  10103. eof // true if this is the last block for a file
  10104. ) {
  10105. var opt_lenb, static_lenb;// opt_len and static_len in bytes
  10106. var max_blindex = 0; // index of last bit length code of non zero freq
  10107. // Build the Huffman trees unless a stored block is forced
  10108. if (level > 0) {
  10109. // Construct the literal and distance trees
  10110. l_desc.build_tree(that);
  10111. d_desc.build_tree(that);
  10112. // At this point, opt_len and static_len are the total bit lengths
  10113. // of
  10114. // the compressed block data, excluding the tree representations.
  10115. // Build the bit length tree for the above two trees, and get the
  10116. // index
  10117. // in bl_order of the last bit length code to send.
  10118. max_blindex = build_bl_tree();
  10119. // Determine the best encoding. Compute first the block length in
  10120. // bytes
  10121. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  10122. static_lenb = (that.static_len + 3 + 7) >>> 3;
  10123. if (static_lenb <= opt_lenb)
  10124. opt_lenb = static_lenb;
  10125. } else {
  10126. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  10127. }
  10128. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  10129. // 4: two words for the lengths
  10130. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  10131. // Otherwise we can't have processed more than WSIZE input bytes
  10132. // since
  10133. // the last block flush, because compression would have been
  10134. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  10135. // transform a block into a stored block.
  10136. _tr_stored_block(buf, stored_len, eof);
  10137. } else if (static_lenb == opt_lenb) {
  10138. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  10139. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  10140. } else {
  10141. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  10142. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  10143. compress_block(dyn_ltree, dyn_dtree);
  10144. }
  10145. // The above check is made mod 2^32, for files larger than 512 MB
  10146. // and uLong implemented on 32 bits.
  10147. init_block();
  10148. if (eof) {
  10149. bi_windup();
  10150. }
  10151. }
  10152. function flush_block_only(eof) {
  10153. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  10154. block_start = strstart;
  10155. strm.flush_pending();
  10156. }
  10157. // Fill the window when the lookahead becomes insufficient.
  10158. // Updates strstart and lookahead.
  10159. //
  10160. // IN assertion: lookahead < MIN_LOOKAHEAD
  10161. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  10162. // At least one byte has been read, or avail_in === 0; reads are
  10163. // performed for at least two bytes (required for the zip translate_eol
  10164. // option -- not supported here).
  10165. function fill_window() {
  10166. var n, m;
  10167. var p;
  10168. var more; // Amount of free space at the end of the window.
  10169. do {
  10170. more = (window_size - lookahead - strstart);
  10171. // Deal with !@#$% 64K limit:
  10172. if (more === 0 && strstart === 0 && lookahead === 0) {
  10173. more = w_size;
  10174. } else if (more == -1) {
  10175. // Very unlikely, but possible on 16 bit machine if strstart ==
  10176. // 0
  10177. // and lookahead == 1 (input done one byte at time)
  10178. more--;
  10179. // If the window is almost full and there is insufficient
  10180. // lookahead,
  10181. // move the upper half to the lower one to make room in the
  10182. // upper half.
  10183. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  10184. window.set(window.subarray(w_size, w_size + w_size), 0);
  10185. match_start -= w_size;
  10186. strstart -= w_size; // we now have strstart >= MAX_DIST
  10187. block_start -= w_size;
  10188. // Slide the hash table (could be avoided with 32 bit values
  10189. // at the expense of memory usage). We slide even when level ==
  10190. // 0
  10191. // to keep the hash table consistent if we switch back to level
  10192. // > 0
  10193. // later. (Using level 0 permanently is not an optimal usage of
  10194. // zlib, so we don't care about this pathological case.)
  10195. n = hash_size;
  10196. p = n;
  10197. do {
  10198. m = (head[--p] & 0xffff);
  10199. head[p] = (m >= w_size ? m - w_size : 0);
  10200. } while (--n !== 0);
  10201. n = w_size;
  10202. p = n;
  10203. do {
  10204. m = (prev[--p] & 0xffff);
  10205. prev[p] = (m >= w_size ? m - w_size : 0);
  10206. // If n is not on any hash chain, prev[n] is garbage but
  10207. // its value will never be used.
  10208. } while (--n !== 0);
  10209. more += w_size;
  10210. }
  10211. if (strm.avail_in === 0)
  10212. return;
  10213. // If there was no sliding:
  10214. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  10215. // more == window_size - lookahead - strstart
  10216. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  10217. // => more >= window_size - 2*WSIZE + 2
  10218. // In the BIG_MEM or MMAP case (not yet supported),
  10219. // window_size == input_size + MIN_LOOKAHEAD &&
  10220. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  10221. // Otherwise, window_size == 2*WSIZE so more >= 2.
  10222. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  10223. n = strm.read_buf(window, strstart + lookahead, more);
  10224. lookahead += n;
  10225. // Initialize the hash value now that we have some input:
  10226. if (lookahead >= MIN_MATCH) {
  10227. ins_h = window[strstart] & 0xff;
  10228. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10229. }
  10230. // If the whole input has less than MIN_MATCH bytes, ins_h is
  10231. // garbage,
  10232. // but this is not important since only literal bytes will be
  10233. // emitted.
  10234. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  10235. }
  10236. // Copy without compression as much as possible from the input stream,
  10237. // return
  10238. // the current block state.
  10239. // This function does not insert new strings in the dictionary since
  10240. // uncompressible data is probably not useful. This function is used
  10241. // only for the level=0 compression option.
  10242. // NOTE: this function should be optimized to avoid extra copying from
  10243. // window to pending_buf.
  10244. function deflate_stored(flush) {
  10245. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  10246. // to pending_buf_size, and each stored block has a 5 byte header:
  10247. var max_block_size = 0xffff;
  10248. var max_start;
  10249. if (max_block_size > pending_buf_size - 5) {
  10250. max_block_size = pending_buf_size - 5;
  10251. }
  10252. // Copy as much as possible from input to output:
  10253. while (true) {
  10254. // Fill the window as much as possible:
  10255. if (lookahead <= 1) {
  10256. fill_window();
  10257. if (lookahead === 0 && flush == Z_NO_FLUSH)
  10258. return NeedMore;
  10259. if (lookahead === 0)
  10260. break; // flush the current block
  10261. }
  10262. strstart += lookahead;
  10263. lookahead = 0;
  10264. // Emit a stored block if pending_buf will be full:
  10265. max_start = block_start + max_block_size;
  10266. if (strstart === 0 || strstart >= max_start) {
  10267. // strstart === 0 is possible when wraparound on 16-bit machine
  10268. lookahead = (strstart - max_start);
  10269. strstart = max_start;
  10270. flush_block_only(false);
  10271. if (strm.avail_out === 0)
  10272. return NeedMore;
  10273. }
  10274. // Flush if we may have to slide, otherwise block_start may become
  10275. // negative and the data will be gone:
  10276. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  10277. flush_block_only(false);
  10278. if (strm.avail_out === 0)
  10279. return NeedMore;
  10280. }
  10281. }
  10282. flush_block_only(flush == Z_FINISH);
  10283. if (strm.avail_out === 0)
  10284. return (flush == Z_FINISH) ? FinishStarted : NeedMore;
  10285. return flush == Z_FINISH ? FinishDone : BlockDone;
  10286. }
  10287. function longest_match(cur_match) {
  10288. var chain_length = max_chain_length; // max hash chain length
  10289. var scan = strstart; // current string
  10290. var match; // matched string
  10291. var len; // length of current match
  10292. var best_len = prev_length; // best match length so far
  10293. var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  10294. var _nice_match = nice_match;
  10295. // Stop when cur_match becomes <= limit. To simplify the code,
  10296. // we prevent matches with the string of window index 0.
  10297. var wmask = w_mask;
  10298. var strend = strstart + MAX_MATCH;
  10299. var scan_end1 = window[scan + best_len - 1];
  10300. var scan_end = window[scan + best_len];
  10301. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  10302. // 16.
  10303. // It is easy to get rid of this optimization if necessary.
  10304. // Do not waste too much time if we already have a good match:
  10305. if (prev_length >= good_match) {
  10306. chain_length >>= 2;
  10307. }
  10308. // Do not look for matches beyond the end of the input. This is
  10309. // necessary
  10310. // to make deflate deterministic.
  10311. if (_nice_match > lookahead)
  10312. _nice_match = lookahead;
  10313. do {
  10314. match = cur_match;
  10315. // Skip to next match if the match length cannot increase
  10316. // or if the match length is less than 2:
  10317. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
  10318. || window[++match] != window[scan + 1])
  10319. continue;
  10320. // The check at best_len-1 can be removed because it will be made
  10321. // again later. (This heuristic is not always a win.)
  10322. // It is not necessary to compare scan[2] and match[2] since they
  10323. // are always equal when the other bytes match, given that
  10324. // the hash keys are equal and that HASH_BITS >= 8.
  10325. scan += 2;
  10326. match++;
  10327. // We check for insufficient lookahead only every 8th comparison;
  10328. // the 256th check will be made at strstart+258.
  10329. do {
  10330. } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10331. && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  10332. && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  10333. len = MAX_MATCH - (strend - scan);
  10334. scan = strend - MAX_MATCH;
  10335. if (len > best_len) {
  10336. match_start = cur_match;
  10337. best_len = len;
  10338. if (len >= _nice_match)
  10339. break;
  10340. scan_end1 = window[scan + best_len - 1];
  10341. scan_end = window[scan + best_len];
  10342. }
  10343. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  10344. if (best_len <= lookahead)
  10345. return best_len;
  10346. return lookahead;
  10347. }
  10348. // Compress as much as possible from the input stream, return the current
  10349. // block state.
  10350. // This function does not perform lazy evaluation of matches and inserts
  10351. // new strings in the dictionary only for unmatched strings or for short
  10352. // matches. It is used only for the fast compression options.
  10353. function deflate_fast(flush) {
  10354. // short hash_head = 0; // head of the hash chain
  10355. var hash_head = 0; // head of the hash chain
  10356. var bflush; // set if current block must be flushed
  10357. while (true) {
  10358. // Make sure that we always have enough lookahead, except
  10359. // at the end of the input file. We need MAX_MATCH bytes
  10360. // for the next match, plus MIN_MATCH bytes to insert the
  10361. // string following the next match.
  10362. if (lookahead < MIN_LOOKAHEAD) {
  10363. fill_window();
  10364. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10365. return NeedMore;
  10366. }
  10367. if (lookahead === 0)
  10368. break; // flush the current block
  10369. }
  10370. // Insert the string window[strstart .. strstart+2] in the
  10371. // dictionary, and set hash_head to the head of the hash chain:
  10372. if (lookahead >= MIN_MATCH) {
  10373. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10374. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10375. hash_head = (head[ins_h] & 0xffff);
  10376. prev[strstart & w_mask] = head[ins_h];
  10377. head[ins_h] = strstart;
  10378. }
  10379. // Find the longest match, discarding those <= prev_length.
  10380. // At this point we have always match_length < MIN_MATCH
  10381. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10382. // To simplify the code, we prevent matches with the string
  10383. // of window index 0 (in particular we have to avoid a match
  10384. // of the string with itself at the start of the input file).
  10385. if (strategy != Z_HUFFMAN_ONLY) {
  10386. match_length = longest_match(hash_head);
  10387. }
  10388. // longest_match() sets match_start
  10389. }
  10390. if (match_length >= MIN_MATCH) {
  10391. // check_match(strstart, match_start, match_length);
  10392. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  10393. lookahead -= match_length;
  10394. // Insert new strings in the hash table only if the match length
  10395. // is not too large. This saves time but degrades compression.
  10396. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  10397. match_length--; // string at strstart already in hash table
  10398. do {
  10399. strstart++;
  10400. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10401. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10402. hash_head = (head[ins_h] & 0xffff);
  10403. prev[strstart & w_mask] = head[ins_h];
  10404. head[ins_h] = strstart;
  10405. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  10406. // always MIN_MATCH bytes ahead.
  10407. } while (--match_length !== 0);
  10408. strstart++;
  10409. } else {
  10410. strstart += match_length;
  10411. match_length = 0;
  10412. ins_h = window[strstart] & 0xff;
  10413. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  10414. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  10415. // not
  10416. // matter since it will be recomputed at next deflate call.
  10417. }
  10418. } else {
  10419. // No match, output a literal byte
  10420. bflush = _tr_tally(0, window[strstart] & 0xff);
  10421. lookahead--;
  10422. strstart++;
  10423. }
  10424. if (bflush) {
  10425. flush_block_only(false);
  10426. if (strm.avail_out === 0)
  10427. return NeedMore;
  10428. }
  10429. }
  10430. flush_block_only(flush == Z_FINISH);
  10431. if (strm.avail_out === 0) {
  10432. if (flush == Z_FINISH)
  10433. return FinishStarted;
  10434. else
  10435. return NeedMore;
  10436. }
  10437. return flush == Z_FINISH ? FinishDone : BlockDone;
  10438. }
  10439. // Same as above, but achieves better compression. We use a lazy
  10440. // evaluation for matches: a match is finally adopted only if there is
  10441. // no better match at the next window position.
  10442. function deflate_slow(flush) {
  10443. // short hash_head = 0; // head of hash chain
  10444. var hash_head = 0; // head of hash chain
  10445. var bflush; // set if current block must be flushed
  10446. var max_insert;
  10447. // Process the input block.
  10448. while (true) {
  10449. // Make sure that we always have enough lookahead, except
  10450. // at the end of the input file. We need MAX_MATCH bytes
  10451. // for the next match, plus MIN_MATCH bytes to insert the
  10452. // string following the next match.
  10453. if (lookahead < MIN_LOOKAHEAD) {
  10454. fill_window();
  10455. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  10456. return NeedMore;
  10457. }
  10458. if (lookahead === 0)
  10459. break; // flush the current block
  10460. }
  10461. // Insert the string window[strstart .. strstart+2] in the
  10462. // dictionary, and set hash_head to the head of the hash chain:
  10463. if (lookahead >= MIN_MATCH) {
  10464. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10465. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10466. hash_head = (head[ins_h] & 0xffff);
  10467. prev[strstart & w_mask] = head[ins_h];
  10468. head[ins_h] = strstart;
  10469. }
  10470. // Find the longest match, discarding those <= prev_length.
  10471. prev_length = match_length;
  10472. prev_match = match_start;
  10473. match_length = MIN_MATCH - 1;
  10474. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  10475. // To simplify the code, we prevent matches with the string
  10476. // of window index 0 (in particular we have to avoid a match
  10477. // of the string with itself at the start of the input file).
  10478. if (strategy != Z_HUFFMAN_ONLY) {
  10479. match_length = longest_match(hash_head);
  10480. }
  10481. // longest_match() sets match_start
  10482. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  10483. // If prev_match is also MIN_MATCH, match_start is garbage
  10484. // but we will ignore the current match anyway.
  10485. match_length = MIN_MATCH - 1;
  10486. }
  10487. }
  10488. // If there was a match at the previous step and the current
  10489. // match is not better, output the previous match:
  10490. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  10491. max_insert = strstart + lookahead - MIN_MATCH;
  10492. // Do not insert strings in hash table beyond this.
  10493. // check_match(strstart-1, prev_match, prev_length);
  10494. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  10495. // Insert in hash table all strings up to the end of the match.
  10496. // strstart-1 and strstart are already inserted. If there is not
  10497. // enough lookahead, the last two strings are not inserted in
  10498. // the hash table.
  10499. lookahead -= prev_length - 1;
  10500. prev_length -= 2;
  10501. do {
  10502. if (++strstart <= max_insert) {
  10503. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10504. // prev[strstart&w_mask]=hash_head=head[ins_h];
  10505. hash_head = (head[ins_h] & 0xffff);
  10506. prev[strstart & w_mask] = head[ins_h];
  10507. head[ins_h] = strstart;
  10508. }
  10509. } while (--prev_length !== 0);
  10510. match_available = 0;
  10511. match_length = MIN_MATCH - 1;
  10512. strstart++;
  10513. if (bflush) {
  10514. flush_block_only(false);
  10515. if (strm.avail_out === 0)
  10516. return NeedMore;
  10517. }
  10518. } else if (match_available !== 0) {
  10519. // If there was no match at the previous position, output a
  10520. // single literal. If there was a match but the current match
  10521. // is longer, truncate the previous match to a single literal.
  10522. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10523. if (bflush) {
  10524. flush_block_only(false);
  10525. }
  10526. strstart++;
  10527. lookahead--;
  10528. if (strm.avail_out === 0)
  10529. return NeedMore;
  10530. } else {
  10531. // There is no previous match to compare with, wait for
  10532. // the next step to decide.
  10533. match_available = 1;
  10534. strstart++;
  10535. lookahead--;
  10536. }
  10537. }
  10538. if (match_available !== 0) {
  10539. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  10540. match_available = 0;
  10541. }
  10542. flush_block_only(flush == Z_FINISH);
  10543. if (strm.avail_out === 0) {
  10544. if (flush == Z_FINISH)
  10545. return FinishStarted;
  10546. else
  10547. return NeedMore;
  10548. }
  10549. return flush == Z_FINISH ? FinishDone : BlockDone;
  10550. }
  10551. function deflateReset(strm) {
  10552. strm.total_in = strm.total_out = 0;
  10553. strm.msg = null; //
  10554. that.pending = 0;
  10555. that.pending_out = 0;
  10556. status = BUSY_STATE;
  10557. last_flush = Z_NO_FLUSH;
  10558. tr_init();
  10559. lm_init();
  10560. return Z_OK;
  10561. }
  10562. that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
  10563. if (!_method)
  10564. _method = Z_DEFLATED;
  10565. if (!memLevel)
  10566. memLevel = DEF_MEM_LEVEL;
  10567. if (!_strategy)
  10568. _strategy = Z_DEFAULT_STRATEGY;
  10569. // byte[] my_version=ZLIB_VERSION;
  10570. //
  10571. // if (!version || version[0] != my_version[0]
  10572. // || stream_size != sizeof(z_stream)) {
  10573. // return Z_VERSION_ERROR;
  10574. // }
  10575. strm.msg = null;
  10576. if (_level == Z_DEFAULT_COMPRESSION)
  10577. _level = 6;
  10578. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  10579. || _strategy > Z_HUFFMAN_ONLY) {
  10580. return Z_STREAM_ERROR;
  10581. }
  10582. strm.dstate = that;
  10583. w_bits = bits;
  10584. w_size = 1 << w_bits;
  10585. w_mask = w_size - 1;
  10586. hash_bits = memLevel + 7;
  10587. hash_size = 1 << hash_bits;
  10588. hash_mask = hash_size - 1;
  10589. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  10590. window = new Uint8Array(w_size * 2);
  10591. prev = [];
  10592. head = [];
  10593. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  10594. // We overlay pending_buf and d_buf+l_buf. This works since the average
  10595. // output size for (length,distance) codes is <= 24 bits.
  10596. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  10597. pending_buf_size = lit_bufsize * 4;
  10598. d_buf = Math.floor(lit_bufsize / 2);
  10599. l_buf = (1 + 2) * lit_bufsize;
  10600. level = _level;
  10601. strategy = _strategy;
  10602. method = _method & 0xff;
  10603. return deflateReset(strm);
  10604. };
  10605. that.deflateEnd = function() {
  10606. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  10607. return Z_STREAM_ERROR;
  10608. }
  10609. // Deallocate in reverse order of allocations:
  10610. that.pending_buf = null;
  10611. head = null;
  10612. prev = null;
  10613. window = null;
  10614. // free
  10615. that.dstate = null;
  10616. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  10617. };
  10618. that.deflateParams = function(strm, _level, _strategy) {
  10619. var err = Z_OK;
  10620. if (_level == Z_DEFAULT_COMPRESSION) {
  10621. _level = 6;
  10622. }
  10623. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  10624. return Z_STREAM_ERROR;
  10625. }
  10626. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  10627. // Flush the last buffer:
  10628. err = strm.deflate(Z_PARTIAL_FLUSH);
  10629. }
  10630. if (level != _level) {
  10631. level = _level;
  10632. max_lazy_match = config_table[level].max_lazy;
  10633. good_match = config_table[level].good_length;
  10634. nice_match = config_table[level].nice_length;
  10635. max_chain_length = config_table[level].max_chain;
  10636. }
  10637. strategy = _strategy;
  10638. return err;
  10639. };
  10640. that.deflateSetDictionary = function(strm, dictionary, dictLength) {
  10641. var length = dictLength;
  10642. var n, index = 0;
  10643. if (!dictionary || status != INIT_STATE)
  10644. return Z_STREAM_ERROR;
  10645. if (length < MIN_MATCH)
  10646. return Z_OK;
  10647. if (length > w_size - MIN_LOOKAHEAD) {
  10648. length = w_size - MIN_LOOKAHEAD;
  10649. index = dictLength - length; // use the tail of the dictionary
  10650. }
  10651. window.set(dictionary.subarray(index, index + length), 0);
  10652. strstart = length;
  10653. block_start = length;
  10654. // Insert all strings in the hash table (except for the last two bytes).
  10655. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  10656. // call of fill_window.
  10657. ins_h = window[0] & 0xff;
  10658. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  10659. for (n = 0; n <= length - MIN_MATCH; n++) {
  10660. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  10661. prev[n & w_mask] = head[ins_h];
  10662. head[ins_h] = n;
  10663. }
  10664. return Z_OK;
  10665. };
  10666. that.deflate = function(_strm, flush) {
  10667. var i, header, level_flags, old_flush, bstate;
  10668. if (flush > Z_FINISH || flush < 0) {
  10669. return Z_STREAM_ERROR;
  10670. }
  10671. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
  10672. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  10673. return Z_STREAM_ERROR;
  10674. }
  10675. if (_strm.avail_out === 0) {
  10676. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10677. return Z_BUF_ERROR;
  10678. }
  10679. strm = _strm; // just in case
  10680. old_flush = last_flush;
  10681. last_flush = flush;
  10682. // Write the zlib header
  10683. if (status == INIT_STATE) {
  10684. header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  10685. level_flags = ((level - 1) & 0xff) >> 1;
  10686. if (level_flags > 3)
  10687. level_flags = 3;
  10688. header |= (level_flags << 6);
  10689. if (strstart !== 0)
  10690. header |= PRESET_DICT;
  10691. header += 31 - (header % 31);
  10692. status = BUSY_STATE;
  10693. putShortMSB(header);
  10694. }
  10695. // Flush as much pending output as possible
  10696. if (that.pending !== 0) {
  10697. strm.flush_pending();
  10698. if (strm.avail_out === 0) {
  10699. // console.log(" avail_out==0");
  10700. // Since avail_out is 0, deflate will be called again with
  10701. // more output space, but possibly with both pending and
  10702. // avail_in equal to zero. There won't be anything to do,
  10703. // but this is not an error situation so make sure we
  10704. // return OK instead of BUF_ERROR at next call of deflate:
  10705. last_flush = -1;
  10706. return Z_OK;
  10707. }
  10708. // Make sure there is something to do and avoid duplicate
  10709. // consecutive
  10710. // flushes. For repeated and useless calls with Z_FINISH, we keep
  10711. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  10712. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  10713. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10714. return Z_BUF_ERROR;
  10715. }
  10716. // User must not provide more input after the first FINISH:
  10717. if (status == FINISH_STATE && strm.avail_in !== 0) {
  10718. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  10719. return Z_BUF_ERROR;
  10720. }
  10721. // Start a new block or continue the current one.
  10722. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
  10723. bstate = -1;
  10724. switch (config_table[level].func) {
  10725. case STORED:
  10726. bstate = deflate_stored(flush);
  10727. break;
  10728. case FAST:
  10729. bstate = deflate_fast(flush);
  10730. break;
  10731. case SLOW:
  10732. bstate = deflate_slow(flush);
  10733. break;
  10734. default:
  10735. }
  10736. if (bstate == FinishStarted || bstate == FinishDone) {
  10737. status = FINISH_STATE;
  10738. }
  10739. if (bstate == NeedMore || bstate == FinishStarted) {
  10740. if (strm.avail_out === 0) {
  10741. last_flush = -1; // avoid BUF_ERROR next call, see above
  10742. }
  10743. return Z_OK;
  10744. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  10745. // of deflate should use the same flush parameter to make sure
  10746. // that the flush is complete. So we don't have to output an
  10747. // empty block here, this will be done at next call. This also
  10748. // ensures that for a very small output buffer, we emit at most
  10749. // one empty block.
  10750. }
  10751. if (bstate == BlockDone) {
  10752. if (flush == Z_PARTIAL_FLUSH) {
  10753. _tr_align();
  10754. } else { // FULL_FLUSH or SYNC_FLUSH
  10755. _tr_stored_block(0, 0, false);
  10756. // For a full flush, this empty block will be recognized
  10757. // as a special marker by inflate_sync().
  10758. if (flush == Z_FULL_FLUSH) {
  10759. // state.head[s.hash_size-1]=0;
  10760. for (i = 0; i < hash_size/*-1*/; i++)
  10761. // forget history
  10762. head[i] = 0;
  10763. }
  10764. }
  10765. strm.flush_pending();
  10766. if (strm.avail_out === 0) {
  10767. last_flush = -1; // avoid BUF_ERROR at next call, see above
  10768. return Z_OK;
  10769. }
  10770. }
  10771. }
  10772. if (flush != Z_FINISH)
  10773. return Z_OK;
  10774. return Z_STREAM_END;
  10775. };
  10776. }
  10777. // ZStream
  10778. function ZStream() {
  10779. var that = this;
  10780. that.next_in_index = 0;
  10781. that.next_out_index = 0;
  10782. // that.next_in; // next input byte
  10783. that.avail_in = 0; // number of bytes available at next_in
  10784. that.total_in = 0; // total nb of input bytes read so far
  10785. // that.next_out; // next output byte should be put there
  10786. that.avail_out = 0; // remaining free space at next_out
  10787. that.total_out = 0; // total nb of bytes output so far
  10788. // that.msg;
  10789. // that.dstate;
  10790. }
  10791. ZStream.prototype = {
  10792. deflateInit : function(level, bits) {
  10793. var that = this;
  10794. that.dstate = new Deflate();
  10795. if (!bits)
  10796. bits = MAX_BITS;
  10797. return that.dstate.deflateInit(that, level, bits);
  10798. },
  10799. deflate : function(flush) {
  10800. var that = this;
  10801. if (!that.dstate) {
  10802. return Z_STREAM_ERROR;
  10803. }
  10804. return that.dstate.deflate(that, flush);
  10805. },
  10806. deflateEnd : function() {
  10807. var that = this;
  10808. if (!that.dstate)
  10809. return Z_STREAM_ERROR;
  10810. var ret = that.dstate.deflateEnd();
  10811. that.dstate = null;
  10812. return ret;
  10813. },
  10814. deflateParams : function(level, strategy) {
  10815. var that = this;
  10816. if (!that.dstate)
  10817. return Z_STREAM_ERROR;
  10818. return that.dstate.deflateParams(that, level, strategy);
  10819. },
  10820. deflateSetDictionary : function(dictionary, dictLength) {
  10821. var that = this;
  10822. if (!that.dstate)
  10823. return Z_STREAM_ERROR;
  10824. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  10825. },
  10826. // Read a new buffer from the current input stream, update the
  10827. // total number of bytes read. All deflate() input goes through
  10828. // this function so some applications may wish to modify it to avoid
  10829. // allocating a large strm->next_in buffer and copying from it.
  10830. // (See also flush_pending()).
  10831. read_buf : function(buf, start, size) {
  10832. var that = this;
  10833. var len = that.avail_in;
  10834. if (len > size)
  10835. len = size;
  10836. if (len === 0)
  10837. return 0;
  10838. that.avail_in -= len;
  10839. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  10840. that.next_in_index += len;
  10841. that.total_in += len;
  10842. return len;
  10843. },
  10844. // Flush as much pending output as possible. All deflate() output goes
  10845. // through this function so some applications may wish to modify it
  10846. // to avoid allocating a large strm->next_out buffer and copying into it.
  10847. // (See also read_buf()).
  10848. flush_pending : function() {
  10849. var that = this;
  10850. var len = that.dstate.pending;
  10851. if (len > that.avail_out)
  10852. len = that.avail_out;
  10853. if (len === 0)
  10854. return;
  10855. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  10856. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  10857. // len)) {
  10858. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  10859. // that.next_out_index + ", " + len);
  10860. // console.log("avail_out=" + that.avail_out);
  10861. // }
  10862. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  10863. that.next_out_index += len;
  10864. that.dstate.pending_out += len;
  10865. that.total_out += len;
  10866. that.avail_out -= len;
  10867. that.dstate.pending -= len;
  10868. if (that.dstate.pending === 0) {
  10869. that.dstate.pending_out = 0;
  10870. }
  10871. }
  10872. };
  10873. // Deflater
  10874. return function Deflater(level) {
  10875. var that = this;
  10876. var z = new ZStream();
  10877. var bufsize = 512;
  10878. var flush = Z_NO_FLUSH;
  10879. var buf = new Uint8Array(bufsize);
  10880. if (typeof level == "undefined")
  10881. level = Z_DEFAULT_COMPRESSION;
  10882. z.deflateInit(level);
  10883. z.next_out = buf;
  10884. that.append = function(data, onprogress) {
  10885. var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
  10886. if (!data.length)
  10887. return;
  10888. z.next_in_index = 0;
  10889. z.next_in = data;
  10890. z.avail_in = data.length;
  10891. do {
  10892. z.next_out_index = 0;
  10893. z.avail_out = bufsize;
  10894. err = z.deflate(flush);
  10895. if (err != Z_OK)
  10896. throw "deflating: " + z.msg;
  10897. if (z.next_out_index)
  10898. if (z.next_out_index == bufsize)
  10899. buffers.push(new Uint8Array(buf));
  10900. else
  10901. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  10902. bufferSize += z.next_out_index;
  10903. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  10904. onprogress(z.next_in_index);
  10905. lastIndex = z.next_in_index;
  10906. }
  10907. } while (z.avail_in > 0 || z.avail_out === 0);
  10908. array = new Uint8Array(bufferSize);
  10909. buffers.forEach(function(chunk) {
  10910. array.set(chunk, bufferIndex);
  10911. bufferIndex += chunk.length;
  10912. });
  10913. return array;
  10914. };
  10915. that.flush = function() {
  10916. var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
  10917. do {
  10918. z.next_out_index = 0;
  10919. z.avail_out = bufsize;
  10920. err = z.deflate(Z_FINISH);
  10921. if (err != Z_STREAM_END && err != Z_OK)
  10922. throw "deflating: " + z.msg;
  10923. if (bufsize - z.avail_out > 0)
  10924. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  10925. bufferSize += z.next_out_index;
  10926. } while (z.avail_in > 0 || z.avail_out === 0);
  10927. z.deflateEnd();
  10928. array = new Uint8Array(bufferSize);
  10929. buffers.forEach(function(chunk) {
  10930. array.set(chunk, bufferIndex);
  10931. bufferIndex += chunk.length;
  10932. });
  10933. return array;
  10934. };
  10935. };
  10936. })(undefined);
  10937. /*
  10938. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  10939. Copyright (c) 2016 Niklas von Hertzen
  10940. Released under License
  10941. */
  10942. !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){
  10943. (function (global){
  10944. /*! http://mths.be/punycode v1.2.4 by @mathias */
  10945. ;(function(root) {
  10946. /** Detect free variables */
  10947. var freeExports = typeof exports == 'object' && exports;
  10948. var freeModule = typeof module == 'object' && module &&
  10949. module.exports == freeExports && module;
  10950. var freeGlobal = typeof global == 'object' && global;
  10951. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  10952. root = freeGlobal;
  10953. }
  10954. /**
  10955. * The `punycode` object.
  10956. * @name punycode
  10957. * @type Object
  10958. */
  10959. var punycode,
  10960. /** Highest positive signed 32-bit float value */
  10961. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  10962. /** Bootstring parameters */
  10963. base = 36,
  10964. tMin = 1,
  10965. tMax = 26,
  10966. skew = 38,
  10967. damp = 700,
  10968. initialBias = 72,
  10969. initialN = 128, // 0x80
  10970. delimiter = '-', // '\x2D'
  10971. /** Regular expressions */
  10972. regexPunycode = /^xn--/,
  10973. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  10974. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  10975. /** Error messages */
  10976. errors = {
  10977. 'overflow': 'Overflow: input needs wider integers to process',
  10978. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  10979. 'invalid-input': 'Invalid input'
  10980. },
  10981. /** Convenience shortcuts */
  10982. baseMinusTMin = base - tMin,
  10983. floor = Math.floor,
  10984. stringFromCharCode = String.fromCharCode,
  10985. /** Temporary variable */
  10986. key;
  10987. /*--------------------------------------------------------------------------*/
  10988. /**
  10989. * A generic error utility function.
  10990. * @private
  10991. * @param {String} type The error type.
  10992. * @returns {Error} Throws a `RangeError` with the applicable error message.
  10993. */
  10994. function error(type) {
  10995. throw RangeError(errors[type]);
  10996. }
  10997. /**
  10998. * A generic `Array#map` utility function.
  10999. * @private
  11000. * @param {Array} array The array to iterate over.
  11001. * @param {Function} callback The function that gets called for every array
  11002. * item.
  11003. * @returns {Array} A new array of values returned by the callback function.
  11004. */
  11005. function map(array, fn) {
  11006. var length = array.length;
  11007. while (length--) {
  11008. array[length] = fn(array[length]);
  11009. }
  11010. return array;
  11011. }
  11012. /**
  11013. * A simple `Array#map`-like wrapper to work with domain name strings.
  11014. * @private
  11015. * @param {String} domain The domain name.
  11016. * @param {Function} callback The function that gets called for every
  11017. * character.
  11018. * @returns {Array} A new string of characters returned by the callback
  11019. * function.
  11020. */
  11021. function mapDomain(string, fn) {
  11022. return map(string.split(regexSeparators), fn).join('.');
  11023. }
  11024. /**
  11025. * Creates an array containing the numeric code points of each Unicode
  11026. * character in the string. While JavaScript uses UCS-2 internally,
  11027. * this function will convert a pair of surrogate halves (each of which
  11028. * UCS-2 exposes as separate characters) into a single code point,
  11029. * matching UTF-16.
  11030. * @see `punycode.ucs2.encode`
  11031. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11032. * @memberOf punycode.ucs2
  11033. * @name decode
  11034. * @param {String} string The Unicode input string (UCS-2).
  11035. * @returns {Array} The new array of code points.
  11036. */
  11037. function ucs2decode(string) {
  11038. var output = [],
  11039. counter = 0,
  11040. length = string.length,
  11041. value,
  11042. extra;
  11043. while (counter < length) {
  11044. value = string.charCodeAt(counter++);
  11045. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11046. // high surrogate, and there is a next character
  11047. extra = string.charCodeAt(counter++);
  11048. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11049. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11050. } else {
  11051. // unmatched surrogate; only append this code unit, in case the next
  11052. // code unit is the high surrogate of a surrogate pair
  11053. output.push(value);
  11054. counter--;
  11055. }
  11056. } else {
  11057. output.push(value);
  11058. }
  11059. }
  11060. return output;
  11061. }
  11062. /**
  11063. * Creates a string based on an array of numeric code points.
  11064. * @see `punycode.ucs2.decode`
  11065. * @memberOf punycode.ucs2
  11066. * @name encode
  11067. * @param {Array} codePoints The array of numeric code points.
  11068. * @returns {String} The new Unicode string (UCS-2).
  11069. */
  11070. function ucs2encode(array) {
  11071. return map(array, function(value) {
  11072. var output = '';
  11073. if (value > 0xFFFF) {
  11074. value -= 0x10000;
  11075. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11076. value = 0xDC00 | value & 0x3FF;
  11077. }
  11078. output += stringFromCharCode(value);
  11079. return output;
  11080. }).join('');
  11081. }
  11082. /**
  11083. * Converts a basic code point into a digit/integer.
  11084. * @see `digitToBasic()`
  11085. * @private
  11086. * @param {Number} codePoint The basic numeric code point value.
  11087. * @returns {Number} The numeric value of a basic code point (for use in
  11088. * representing integers) in the range `0` to `base - 1`, or `base` if
  11089. * the code point does not represent a value.
  11090. */
  11091. function basicToDigit(codePoint) {
  11092. if (codePoint - 48 < 10) {
  11093. return codePoint - 22;
  11094. }
  11095. if (codePoint - 65 < 26) {
  11096. return codePoint - 65;
  11097. }
  11098. if (codePoint - 97 < 26) {
  11099. return codePoint - 97;
  11100. }
  11101. return base;
  11102. }
  11103. /**
  11104. * Converts a digit/integer into a basic code point.
  11105. * @see `basicToDigit()`
  11106. * @private
  11107. * @param {Number} digit The numeric value of a basic code point.
  11108. * @returns {Number} The basic code point whose value (when used for
  11109. * representing integers) is `digit`, which needs to be in the range
  11110. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11111. * used; else, the lowercase form is used. The behavior is undefined
  11112. * if `flag` is non-zero and `digit` has no uppercase form.
  11113. */
  11114. function digitToBasic(digit, flag) {
  11115. // 0..25 map to ASCII a..z or A..Z
  11116. // 26..35 map to ASCII 0..9
  11117. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11118. }
  11119. /**
  11120. * Bias adaptation function as per section 3.4 of RFC 3492.
  11121. * http://tools.ietf.org/html/rfc3492#section-3.4
  11122. * @private
  11123. */
  11124. function adapt(delta, numPoints, firstTime) {
  11125. var k = 0;
  11126. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11127. delta += floor(delta / numPoints);
  11128. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  11129. delta = floor(delta / baseMinusTMin);
  11130. }
  11131. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11132. }
  11133. /**
  11134. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11135. * symbols.
  11136. * @memberOf punycode
  11137. * @param {String} input The Punycode string of ASCII-only symbols.
  11138. * @returns {String} The resulting string of Unicode symbols.
  11139. */
  11140. function decode(input) {
  11141. // Don't use UCS-2
  11142. var output = [],
  11143. inputLength = input.length,
  11144. out,
  11145. i = 0,
  11146. n = initialN,
  11147. bias = initialBias,
  11148. basic,
  11149. j,
  11150. index,
  11151. oldi,
  11152. w,
  11153. k,
  11154. digit,
  11155. t,
  11156. /** Cached calculation results */
  11157. baseMinusT;
  11158. // Handle the basic code points: let `basic` be the number of input code
  11159. // points before the last delimiter, or `0` if there is none, then copy
  11160. // the first basic code points to the output.
  11161. basic = input.lastIndexOf(delimiter);
  11162. if (basic < 0) {
  11163. basic = 0;
  11164. }
  11165. for (j = 0; j < basic; ++j) {
  11166. // if it's not a basic code point
  11167. if (input.charCodeAt(j) >= 0x80) {
  11168. error('not-basic');
  11169. }
  11170. output.push(input.charCodeAt(j));
  11171. }
  11172. // Main decoding loop: start just after the last delimiter if any basic code
  11173. // points were copied; start at the beginning otherwise.
  11174. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  11175. // `index` is the index of the next character to be consumed.
  11176. // Decode a generalized variable-length integer into `delta`,
  11177. // which gets added to `i`. The overflow checking is easier
  11178. // if we increase `i` as we go, then subtract off its starting
  11179. // value at the end to obtain `delta`.
  11180. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  11181. if (index >= inputLength) {
  11182. error('invalid-input');
  11183. }
  11184. digit = basicToDigit(input.charCodeAt(index++));
  11185. if (digit >= base || digit > floor((maxInt - i) / w)) {
  11186. error('overflow');
  11187. }
  11188. i += digit * w;
  11189. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11190. if (digit < t) {
  11191. break;
  11192. }
  11193. baseMinusT = base - t;
  11194. if (w > floor(maxInt / baseMinusT)) {
  11195. error('overflow');
  11196. }
  11197. w *= baseMinusT;
  11198. }
  11199. out = output.length + 1;
  11200. bias = adapt(i - oldi, out, oldi == 0);
  11201. // `i` was supposed to wrap around from `out` to `0`,
  11202. // incrementing `n` each time, so we'll fix that now:
  11203. if (floor(i / out) > maxInt - n) {
  11204. error('overflow');
  11205. }
  11206. n += floor(i / out);
  11207. i %= out;
  11208. // Insert `n` at position `i` of the output
  11209. output.splice(i++, 0, n);
  11210. }
  11211. return ucs2encode(output);
  11212. }
  11213. /**
  11214. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  11215. * symbols.
  11216. * @memberOf punycode
  11217. * @param {String} input The string of Unicode symbols.
  11218. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  11219. */
  11220. function encode(input) {
  11221. var n,
  11222. delta,
  11223. handledCPCount,
  11224. basicLength,
  11225. bias,
  11226. j,
  11227. m,
  11228. q,
  11229. k,
  11230. t,
  11231. currentValue,
  11232. output = [],
  11233. /** `inputLength` will hold the number of code points in `input`. */
  11234. inputLength,
  11235. /** Cached calculation results */
  11236. handledCPCountPlusOne,
  11237. baseMinusT,
  11238. qMinusT;
  11239. // Convert the input in UCS-2 to Unicode
  11240. input = ucs2decode(input);
  11241. // Cache the length
  11242. inputLength = input.length;
  11243. // Initialize the state
  11244. n = initialN;
  11245. delta = 0;
  11246. bias = initialBias;
  11247. // Handle the basic code points
  11248. for (j = 0; j < inputLength; ++j) {
  11249. currentValue = input[j];
  11250. if (currentValue < 0x80) {
  11251. output.push(stringFromCharCode(currentValue));
  11252. }
  11253. }
  11254. handledCPCount = basicLength = output.length;
  11255. // `handledCPCount` is the number of code points that have been handled;
  11256. // `basicLength` is the number of basic code points.
  11257. // Finish the basic string - if it is not empty - with a delimiter
  11258. if (basicLength) {
  11259. output.push(delimiter);
  11260. }
  11261. // Main encoding loop:
  11262. while (handledCPCount < inputLength) {
  11263. // All non-basic code points < n have been handled already. Find the next
  11264. // larger one:
  11265. for (m = maxInt, j = 0; j < inputLength; ++j) {
  11266. currentValue = input[j];
  11267. if (currentValue >= n && currentValue < m) {
  11268. m = currentValue;
  11269. }
  11270. }
  11271. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  11272. // but guard against overflow
  11273. handledCPCountPlusOne = handledCPCount + 1;
  11274. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  11275. error('overflow');
  11276. }
  11277. delta += (m - n) * handledCPCountPlusOne;
  11278. n = m;
  11279. for (j = 0; j < inputLength; ++j) {
  11280. currentValue = input[j];
  11281. if (currentValue < n && ++delta > maxInt) {
  11282. error('overflow');
  11283. }
  11284. if (currentValue == n) {
  11285. // Represent delta as a generalized variable-length integer
  11286. for (q = delta, k = base; /* no condition */; k += base) {
  11287. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  11288. if (q < t) {
  11289. break;
  11290. }
  11291. qMinusT = q - t;
  11292. baseMinusT = base - t;
  11293. output.push(
  11294. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  11295. );
  11296. q = floor(qMinusT / baseMinusT);
  11297. }
  11298. output.push(stringFromCharCode(digitToBasic(q, 0)));
  11299. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  11300. delta = 0;
  11301. ++handledCPCount;
  11302. }
  11303. }
  11304. ++delta;
  11305. ++n;
  11306. }
  11307. return output.join('');
  11308. }
  11309. /**
  11310. * Converts a Punycode string representing a domain name to Unicode. Only the
  11311. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  11312. * matter if you call it on a string that has already been converted to
  11313. * Unicode.
  11314. * @memberOf punycode
  11315. * @param {String} domain The Punycode domain name to convert to Unicode.
  11316. * @returns {String} The Unicode representation of the given Punycode
  11317. * string.
  11318. */
  11319. function toUnicode(domain) {
  11320. return mapDomain(domain, function(string) {
  11321. return regexPunycode.test(string)
  11322. ? decode(string.slice(4).toLowerCase())
  11323. : string;
  11324. });
  11325. }
  11326. /**
  11327. * Converts a Unicode string representing a domain name to Punycode. Only the
  11328. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  11329. * matter if you call it with a domain that's already in ASCII.
  11330. * @memberOf punycode
  11331. * @param {String} domain The domain name to convert, as a Unicode string.
  11332. * @returns {String} The Punycode representation of the given domain name.
  11333. */
  11334. function toASCII(domain) {
  11335. return mapDomain(domain, function(string) {
  11336. return regexNonASCII.test(string)
  11337. ? 'xn--' + encode(string)
  11338. : string;
  11339. });
  11340. }
  11341. /*--------------------------------------------------------------------------*/
  11342. /** Define the public API */
  11343. punycode = {
  11344. /**
  11345. * A string representing the current Punycode.js version number.
  11346. * @memberOf punycode
  11347. * @type String
  11348. */
  11349. 'version': '1.2.4',
  11350. /**
  11351. * An object of methods to convert from JavaScript's internal character
  11352. * representation (UCS-2) to Unicode code points, and back.
  11353. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  11354. * @memberOf punycode
  11355. * @type Object
  11356. */
  11357. 'ucs2': {
  11358. 'decode': ucs2decode,
  11359. 'encode': ucs2encode
  11360. },
  11361. 'decode': decode,
  11362. 'encode': encode,
  11363. 'toASCII': toASCII,
  11364. 'toUnicode': toUnicode
  11365. };
  11366. /** Expose `punycode` */
  11367. // Some AMD build optimizers, like r.js, check for specific condition patterns
  11368. // like the following:
  11369. if (
  11370. typeof define == 'function' &&
  11371. typeof define.amd == 'object' &&
  11372. define.amd
  11373. ) {
  11374. define('punycode', function() {
  11375. return punycode;
  11376. });
  11377. } else if (freeExports && !freeExports.nodeType) {
  11378. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  11379. freeModule.exports = punycode;
  11380. } else { // in Narwhal or RingoJS v0.7.0-
  11381. for (key in punycode) {
  11382. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  11383. }
  11384. }
  11385. } else { // in Rhino or a web browser
  11386. root.punycode = punycode;
  11387. }
  11388. }(this));
  11389. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11390. },{}],2:[function(_dereq_,module,exports){
  11391. var log = _dereq_('./log');
  11392. function restoreOwnerScroll(ownerDocument, x, y) {
  11393. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  11394. ownerDocument.defaultView.scrollTo(x, y);
  11395. }
  11396. }
  11397. function cloneCanvasContents(canvas, clonedCanvas) {
  11398. try {
  11399. if (clonedCanvas) {
  11400. clonedCanvas.width = canvas.width;
  11401. clonedCanvas.height = canvas.height;
  11402. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  11403. }
  11404. } catch(e) {
  11405. log("Unable to copy canvas content from", canvas, e);
  11406. }
  11407. }
  11408. function cloneNode(node, javascriptEnabled) {
  11409. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  11410. var child = node.firstChild;
  11411. while(child) {
  11412. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  11413. clone.appendChild(cloneNode(child, javascriptEnabled));
  11414. }
  11415. child = child.nextSibling;
  11416. }
  11417. if (node.nodeType === 1) {
  11418. clone._scrollTop = node.scrollTop;
  11419. clone._scrollLeft = node.scrollLeft;
  11420. if (node.nodeName === "CANVAS") {
  11421. cloneCanvasContents(node, clone);
  11422. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  11423. clone.value = node.value;
  11424. }
  11425. }
  11426. return clone;
  11427. }
  11428. function initNode(node) {
  11429. if (node.nodeType === 1) {
  11430. node.scrollTop = node._scrollTop;
  11431. node.scrollLeft = node._scrollLeft;
  11432. var child = node.firstChild;
  11433. while(child) {
  11434. initNode(child);
  11435. child = child.nextSibling;
  11436. }
  11437. }
  11438. }
  11439. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  11440. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  11441. var container = containerDocument.createElement("iframe");
  11442. container.className = "html2canvas-container";
  11443. container.style.visibility = "hidden";
  11444. container.style.position = "fixed";
  11445. container.style.left = "-10000px";
  11446. container.style.top = "0px";
  11447. container.style.border = "0";
  11448. container.width = width;
  11449. container.height = height;
  11450. container.scrolling = "no"; // ios won't scroll without it
  11451. containerDocument.body.appendChild(container);
  11452. return new Promise(function(resolve) {
  11453. var documentClone = container.contentWindow.document;
  11454. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  11455. if window url is about:blank, we can assign the url to current by writing onto the document
  11456. */
  11457. container.contentWindow.onload = container.onload = function() {
  11458. var interval = setInterval(function() {
  11459. if (documentClone.body.childNodes.length > 0) {
  11460. initNode(documentClone.documentElement);
  11461. clearInterval(interval);
  11462. if (options.type === "view") {
  11463. container.contentWindow.scrollTo(x, y);
  11464. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  11465. documentClone.documentElement.style.top = (-y) + "px";
  11466. documentClone.documentElement.style.left = (-x) + "px";
  11467. documentClone.documentElement.style.position = 'absolute';
  11468. }
  11469. }
  11470. resolve(container);
  11471. }
  11472. }, 50);
  11473. };
  11474. documentClone.open();
  11475. documentClone.write("<!DOCTYPE html><html></html>");
  11476. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  11477. restoreOwnerScroll(ownerDocument, x, y);
  11478. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  11479. documentClone.close();
  11480. });
  11481. };
  11482. },{"./log":13}],3:[function(_dereq_,module,exports){
  11483. // http://dev.w3.org/csswg/css-color/
  11484. function Color(value) {
  11485. this.r = 0;
  11486. this.g = 0;
  11487. this.b = 0;
  11488. this.a = null;
  11489. var result = this.fromArray(value) ||
  11490. this.namedColor(value) ||
  11491. this.rgb(value) ||
  11492. this.rgba(value) ||
  11493. this.hex6(value) ||
  11494. this.hex3(value);
  11495. }
  11496. Color.prototype.darken = function(amount) {
  11497. var a = 1 - amount;
  11498. return new Color([
  11499. Math.round(this.r * a),
  11500. Math.round(this.g * a),
  11501. Math.round(this.b * a),
  11502. this.a
  11503. ]);
  11504. };
  11505. Color.prototype.isTransparent = function() {
  11506. return this.a === 0;
  11507. };
  11508. Color.prototype.isBlack = function() {
  11509. return this.r === 0 && this.g === 0 && this.b === 0;
  11510. };
  11511. Color.prototype.fromArray = function(array) {
  11512. if (Array.isArray(array)) {
  11513. this.r = Math.min(array[0], 255);
  11514. this.g = Math.min(array[1], 255);
  11515. this.b = Math.min(array[2], 255);
  11516. if (array.length > 3) {
  11517. this.a = array[3];
  11518. }
  11519. }
  11520. return (Array.isArray(array));
  11521. };
  11522. var _hex3 = /^#([a-f0-9]{3})$/i;
  11523. Color.prototype.hex3 = function(value) {
  11524. var match = null;
  11525. if ((match = value.match(_hex3)) !== null) {
  11526. this.r = parseInt(match[1][0] + match[1][0], 16);
  11527. this.g = parseInt(match[1][1] + match[1][1], 16);
  11528. this.b = parseInt(match[1][2] + match[1][2], 16);
  11529. }
  11530. return match !== null;
  11531. };
  11532. var _hex6 = /^#([a-f0-9]{6})$/i;
  11533. Color.prototype.hex6 = function(value) {
  11534. var match = null;
  11535. if ((match = value.match(_hex6)) !== null) {
  11536. this.r = parseInt(match[1].substring(0, 2), 16);
  11537. this.g = parseInt(match[1].substring(2, 4), 16);
  11538. this.b = parseInt(match[1].substring(4, 6), 16);
  11539. }
  11540. return match !== null;
  11541. };
  11542. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  11543. Color.prototype.rgb = function(value) {
  11544. var match = null;
  11545. if ((match = value.match(_rgb)) !== null) {
  11546. this.r = Number(match[1]);
  11547. this.g = Number(match[2]);
  11548. this.b = Number(match[3]);
  11549. }
  11550. return match !== null;
  11551. };
  11552. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  11553. Color.prototype.rgba = function(value) {
  11554. var match = null;
  11555. if ((match = value.match(_rgba)) !== null) {
  11556. this.r = Number(match[1]);
  11557. this.g = Number(match[2]);
  11558. this.b = Number(match[3]);
  11559. this.a = Number(match[4]);
  11560. }
  11561. return match !== null;
  11562. };
  11563. Color.prototype.toString = function() {
  11564. return this.a !== null && this.a !== 1 ?
  11565. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  11566. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  11567. };
  11568. Color.prototype.namedColor = function(value) {
  11569. value = value.toLowerCase();
  11570. var color = colors[value];
  11571. if (color) {
  11572. this.r = color[0];
  11573. this.g = color[1];
  11574. this.b = color[2];
  11575. } else if (value === "transparent") {
  11576. this.r = this.g = this.b = this.a = 0;
  11577. return true;
  11578. }
  11579. return !!color;
  11580. };
  11581. Color.prototype.isColor = true;
  11582. // 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}, {}))
  11583. var colors = {
  11584. "aliceblue": [240, 248, 255],
  11585. "antiquewhite": [250, 235, 215],
  11586. "aqua": [0, 255, 255],
  11587. "aquamarine": [127, 255, 212],
  11588. "azure": [240, 255, 255],
  11589. "beige": [245, 245, 220],
  11590. "bisque": [255, 228, 196],
  11591. "black": [0, 0, 0],
  11592. "blanchedalmond": [255, 235, 205],
  11593. "blue": [0, 0, 255],
  11594. "blueviolet": [138, 43, 226],
  11595. "brown": [165, 42, 42],
  11596. "burlywood": [222, 184, 135],
  11597. "cadetblue": [95, 158, 160],
  11598. "chartreuse": [127, 255, 0],
  11599. "chocolate": [210, 105, 30],
  11600. "coral": [255, 127, 80],
  11601. "cornflowerblue": [100, 149, 237],
  11602. "cornsilk": [255, 248, 220],
  11603. "crimson": [220, 20, 60],
  11604. "cyan": [0, 255, 255],
  11605. "darkblue": [0, 0, 139],
  11606. "darkcyan": [0, 139, 139],
  11607. "darkgoldenrod": [184, 134, 11],
  11608. "darkgray": [169, 169, 169],
  11609. "darkgreen": [0, 100, 0],
  11610. "darkgrey": [169, 169, 169],
  11611. "darkkhaki": [189, 183, 107],
  11612. "darkmagenta": [139, 0, 139],
  11613. "darkolivegreen": [85, 107, 47],
  11614. "darkorange": [255, 140, 0],
  11615. "darkorchid": [153, 50, 204],
  11616. "darkred": [139, 0, 0],
  11617. "darksalmon": [233, 150, 122],
  11618. "darkseagreen": [143, 188, 143],
  11619. "darkslateblue": [72, 61, 139],
  11620. "darkslategray": [47, 79, 79],
  11621. "darkslategrey": [47, 79, 79],
  11622. "darkturquoise": [0, 206, 209],
  11623. "darkviolet": [148, 0, 211],
  11624. "deeppink": [255, 20, 147],
  11625. "deepskyblue": [0, 191, 255],
  11626. "dimgray": [105, 105, 105],
  11627. "dimgrey": [105, 105, 105],
  11628. "dodgerblue": [30, 144, 255],
  11629. "firebrick": [178, 34, 34],
  11630. "floralwhite": [255, 250, 240],
  11631. "forestgreen": [34, 139, 34],
  11632. "fuchsia": [255, 0, 255],
  11633. "gainsboro": [220, 220, 220],
  11634. "ghostwhite": [248, 248, 255],
  11635. "gold": [255, 215, 0],
  11636. "goldenrod": [218, 165, 32],
  11637. "gray": [128, 128, 128],
  11638. "green": [0, 128, 0],
  11639. "greenyellow": [173, 255, 47],
  11640. "grey": [128, 128, 128],
  11641. "honeydew": [240, 255, 240],
  11642. "hotpink": [255, 105, 180],
  11643. "indianred": [205, 92, 92],
  11644. "indigo": [75, 0, 130],
  11645. "ivory": [255, 255, 240],
  11646. "khaki": [240, 230, 140],
  11647. "lavender": [230, 230, 250],
  11648. "lavenderblush": [255, 240, 245],
  11649. "lawngreen": [124, 252, 0],
  11650. "lemonchiffon": [255, 250, 205],
  11651. "lightblue": [173, 216, 230],
  11652. "lightcoral": [240, 128, 128],
  11653. "lightcyan": [224, 255, 255],
  11654. "lightgoldenrodyellow": [250, 250, 210],
  11655. "lightgray": [211, 211, 211],
  11656. "lightgreen": [144, 238, 144],
  11657. "lightgrey": [211, 211, 211],
  11658. "lightpink": [255, 182, 193],
  11659. "lightsalmon": [255, 160, 122],
  11660. "lightseagreen": [32, 178, 170],
  11661. "lightskyblue": [135, 206, 250],
  11662. "lightslategray": [119, 136, 153],
  11663. "lightslategrey": [119, 136, 153],
  11664. "lightsteelblue": [176, 196, 222],
  11665. "lightyellow": [255, 255, 224],
  11666. "lime": [0, 255, 0],
  11667. "limegreen": [50, 205, 50],
  11668. "linen": [250, 240, 230],
  11669. "magenta": [255, 0, 255],
  11670. "maroon": [128, 0, 0],
  11671. "mediumaquamarine": [102, 205, 170],
  11672. "mediumblue": [0, 0, 205],
  11673. "mediumorchid": [186, 85, 211],
  11674. "mediumpurple": [147, 112, 219],
  11675. "mediumseagreen": [60, 179, 113],
  11676. "mediumslateblue": [123, 104, 238],
  11677. "mediumspringgreen": [0, 250, 154],
  11678. "mediumturquoise": [72, 209, 204],
  11679. "mediumvioletred": [199, 21, 133],
  11680. "midnightblue": [25, 25, 112],
  11681. "mintcream": [245, 255, 250],
  11682. "mistyrose": [255, 228, 225],
  11683. "moccasin": [255, 228, 181],
  11684. "navajowhite": [255, 222, 173],
  11685. "navy": [0, 0, 128],
  11686. "oldlace": [253, 245, 230],
  11687. "olive": [128, 128, 0],
  11688. "olivedrab": [107, 142, 35],
  11689. "orange": [255, 165, 0],
  11690. "orangered": [255, 69, 0],
  11691. "orchid": [218, 112, 214],
  11692. "palegoldenrod": [238, 232, 170],
  11693. "palegreen": [152, 251, 152],
  11694. "paleturquoise": [175, 238, 238],
  11695. "palevioletred": [219, 112, 147],
  11696. "papayawhip": [255, 239, 213],
  11697. "peachpuff": [255, 218, 185],
  11698. "peru": [205, 133, 63],
  11699. "pink": [255, 192, 203],
  11700. "plum": [221, 160, 221],
  11701. "powderblue": [176, 224, 230],
  11702. "purple": [128, 0, 128],
  11703. "rebeccapurple": [102, 51, 153],
  11704. "red": [255, 0, 0],
  11705. "rosybrown": [188, 143, 143],
  11706. "royalblue": [65, 105, 225],
  11707. "saddlebrown": [139, 69, 19],
  11708. "salmon": [250, 128, 114],
  11709. "sandybrown": [244, 164, 96],
  11710. "seagreen": [46, 139, 87],
  11711. "seashell": [255, 245, 238],
  11712. "sienna": [160, 82, 45],
  11713. "silver": [192, 192, 192],
  11714. "skyblue": [135, 206, 235],
  11715. "slateblue": [106, 90, 205],
  11716. "slategray": [112, 128, 144],
  11717. "slategrey": [112, 128, 144],
  11718. "snow": [255, 250, 250],
  11719. "springgreen": [0, 255, 127],
  11720. "steelblue": [70, 130, 180],
  11721. "tan": [210, 180, 140],
  11722. "teal": [0, 128, 128],
  11723. "thistle": [216, 191, 216],
  11724. "tomato": [255, 99, 71],
  11725. "turquoise": [64, 224, 208],
  11726. "violet": [238, 130, 238],
  11727. "wheat": [245, 222, 179],
  11728. "white": [255, 255, 255],
  11729. "whitesmoke": [245, 245, 245],
  11730. "yellow": [255, 255, 0],
  11731. "yellowgreen": [154, 205, 50]
  11732. };
  11733. module.exports = Color;
  11734. },{}],4:[function(_dereq_,module,exports){
  11735. var Support = _dereq_('./support');
  11736. var CanvasRenderer = _dereq_('./renderers/canvas');
  11737. var ImageLoader = _dereq_('./imageloader');
  11738. var NodeParser = _dereq_('./nodeparser');
  11739. var NodeContainer = _dereq_('./nodecontainer');
  11740. var log = _dereq_('./log');
  11741. var utils = _dereq_('./utils');
  11742. var createWindowClone = _dereq_('./clone');
  11743. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  11744. var getBounds = utils.getBounds;
  11745. var html2canvasNodeAttribute = "data-html2canvas-node";
  11746. var html2canvasCloneIndex = 0;
  11747. function html2canvas(nodeList, options) {
  11748. var index = html2canvasCloneIndex++;
  11749. options = options || {};
  11750. if (options.logging) {
  11751. log.options.logging = true;
  11752. log.options.start = Date.now();
  11753. }
  11754. options.async = typeof(options.async) === "undefined" ? true : options.async;
  11755. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  11756. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  11757. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  11758. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  11759. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  11760. options.strict = !!options.strict;
  11761. if (typeof(nodeList) === "string") {
  11762. if (typeof(options.proxy) !== "string") {
  11763. return Promise.reject("Proxy must be used when rendering url");
  11764. }
  11765. var width = options.width != null ? options.width : window.innerWidth;
  11766. var height = options.height != null ? options.height : window.innerHeight;
  11767. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  11768. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  11769. });
  11770. }
  11771. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  11772. node.setAttribute(html2canvasNodeAttribute + index, index);
  11773. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  11774. if (typeof(options.onrendered) === "function") {
  11775. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  11776. options.onrendered(canvas);
  11777. }
  11778. return canvas;
  11779. });
  11780. }
  11781. html2canvas.CanvasRenderer = CanvasRenderer;
  11782. html2canvas.NodeContainer = NodeContainer;
  11783. html2canvas.log = log;
  11784. html2canvas.utils = utils;
  11785. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  11786. return Promise.reject("No canvas support");
  11787. } : html2canvas;
  11788. module.exports = html2canvasExport;
  11789. if (typeof(define) === 'function' && define.amd) {
  11790. define('html2canvas', [], function() {
  11791. return html2canvasExport;
  11792. });
  11793. }
  11794. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  11795. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  11796. log("Document cloned");
  11797. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  11798. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  11799. document.querySelector(selector).removeAttribute(attributeName);
  11800. var clonedWindow = container.contentWindow;
  11801. var node = clonedWindow.document.querySelector(selector);
  11802. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  11803. return oncloneHandler.then(function() {
  11804. return renderWindow(node, container, options, windowWidth, windowHeight);
  11805. });
  11806. });
  11807. }
  11808. function renderWindow(node, container, options, windowWidth, windowHeight) {
  11809. var clonedWindow = container.contentWindow;
  11810. var support = new Support(clonedWindow.document);
  11811. var imageLoader = new ImageLoader(options, support);
  11812. var bounds = getBounds(node);
  11813. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  11814. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  11815. var renderer = new options.renderer(width, height, imageLoader, options, document);
  11816. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  11817. return parser.ready.then(function() {
  11818. log("Finished rendering");
  11819. var canvas;
  11820. if (options.type === "view") {
  11821. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  11822. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  11823. canvas = renderer.canvas;
  11824. } else {
  11825. 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});
  11826. }
  11827. cleanupContainer(container, options);
  11828. return canvas;
  11829. });
  11830. }
  11831. function cleanupContainer(container, options) {
  11832. if (options.removeContainer) {
  11833. container.parentNode.removeChild(container);
  11834. log("Cleaned up container");
  11835. }
  11836. }
  11837. function crop(canvas, bounds) {
  11838. var croppedCanvas = document.createElement("canvas");
  11839. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  11840. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  11841. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  11842. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  11843. croppedCanvas.width = bounds.width;
  11844. croppedCanvas.height = bounds.height;
  11845. var width = x2-x1;
  11846. var height = y2-y1;
  11847. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  11848. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  11849. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  11850. return croppedCanvas;
  11851. }
  11852. function documentWidth (doc) {
  11853. return Math.max(
  11854. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  11855. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  11856. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  11857. );
  11858. }
  11859. function documentHeight (doc) {
  11860. return Math.max(
  11861. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  11862. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  11863. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  11864. );
  11865. }
  11866. function absoluteUrl(url) {
  11867. var link = document.createElement("a");
  11868. link.href = url;
  11869. link.href = link.href;
  11870. return link;
  11871. }
  11872. },{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
  11873. var log = _dereq_('./log');
  11874. var smallImage = _dereq_('./utils').smallImage;
  11875. function DummyImageContainer(src) {
  11876. this.src = src;
  11877. log("DummyImageContainer for", src);
  11878. if (!this.promise || !this.image) {
  11879. log("Initiating DummyImageContainer");
  11880. DummyImageContainer.prototype.image = new Image();
  11881. var image = this.image;
  11882. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  11883. image.onload = resolve;
  11884. image.onerror = reject;
  11885. image.src = smallImage();
  11886. if (image.complete === true) {
  11887. resolve(image);
  11888. }
  11889. });
  11890. }
  11891. }
  11892. module.exports = DummyImageContainer;
  11893. },{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
  11894. var smallImage = _dereq_('./utils').smallImage;
  11895. function Font(family, size) {
  11896. var container = document.createElement('div'),
  11897. img = document.createElement('img'),
  11898. span = document.createElement('span'),
  11899. sampleText = 'Hidden Text',
  11900. baseline,
  11901. middle;
  11902. container.style.visibility = "hidden";
  11903. container.style.fontFamily = family;
  11904. container.style.fontSize = size;
  11905. container.style.margin = 0;
  11906. container.style.padding = 0;
  11907. document.body.appendChild(container);
  11908. img.src = smallImage();
  11909. img.width = 1;
  11910. img.height = 1;
  11911. img.style.margin = 0;
  11912. img.style.padding = 0;
  11913. img.style.verticalAlign = "baseline";
  11914. span.style.fontFamily = family;
  11915. span.style.fontSize = size;
  11916. span.style.margin = 0;
  11917. span.style.padding = 0;
  11918. span.appendChild(document.createTextNode(sampleText));
  11919. container.appendChild(span);
  11920. container.appendChild(img);
  11921. baseline = (img.offsetTop - span.offsetTop) + 1;
  11922. container.removeChild(span);
  11923. container.appendChild(document.createTextNode(sampleText));
  11924. container.style.lineHeight = "normal";
  11925. img.style.verticalAlign = "super";
  11926. middle = (img.offsetTop-container.offsetTop) + 1;
  11927. document.body.removeChild(container);
  11928. this.baseline = baseline;
  11929. this.lineWidth = 1;
  11930. this.middle = middle;
  11931. }
  11932. module.exports = Font;
  11933. },{"./utils":26}],7:[function(_dereq_,module,exports){
  11934. var Font = _dereq_('./font');
  11935. function FontMetrics() {
  11936. this.data = {};
  11937. }
  11938. FontMetrics.prototype.getMetrics = function(family, size) {
  11939. if (this.data[family + "-" + size] === undefined) {
  11940. this.data[family + "-" + size] = new Font(family, size);
  11941. }
  11942. return this.data[family + "-" + size];
  11943. };
  11944. module.exports = FontMetrics;
  11945. },{"./font":6}],8:[function(_dereq_,module,exports){
  11946. var utils = _dereq_('./utils');
  11947. var getBounds = utils.getBounds;
  11948. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  11949. function FrameContainer(container, sameOrigin, options) {
  11950. this.image = null;
  11951. this.src = container;
  11952. var self = this;
  11953. var bounds = getBounds(container);
  11954. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  11955. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  11956. container.contentWindow.onload = container.onload = function() {
  11957. resolve(container);
  11958. };
  11959. } else {
  11960. resolve(container);
  11961. }
  11962. })).then(function(container) {
  11963. var html2canvas = _dereq_('./core');
  11964. 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});
  11965. }).then(function(canvas) {
  11966. return self.image = canvas;
  11967. });
  11968. }
  11969. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  11970. var container = this.src;
  11971. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  11972. };
  11973. module.exports = FrameContainer;
  11974. },{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
  11975. function GradientContainer(imageData) {
  11976. this.src = imageData.value;
  11977. this.colorStops = [];
  11978. this.type = null;
  11979. this.x0 = 0.5;
  11980. this.y0 = 0.5;
  11981. this.x1 = 0.5;
  11982. this.y1 = 0.5;
  11983. this.promise = Promise.resolve(true);
  11984. }
  11985. GradientContainer.TYPES = {
  11986. LINEAR: 1,
  11987. RADIAL: 2
  11988. };
  11989. // TODO: support hsl[a], negative %/length values
  11990. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  11991. 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;
  11992. module.exports = GradientContainer;
  11993. },{}],10:[function(_dereq_,module,exports){
  11994. function ImageContainer(src, cors) {
  11995. this.src = src;
  11996. this.image = new Image();
  11997. var self = this;
  11998. this.tainted = null;
  11999. this.promise = new Promise(function(resolve, reject) {
  12000. self.image.onload = resolve;
  12001. self.image.onerror = reject;
  12002. if (cors) {
  12003. self.image.crossOrigin = "anonymous";
  12004. }
  12005. self.image.src = src;
  12006. if (self.image.complete === true) {
  12007. resolve(self.image);
  12008. }
  12009. });
  12010. }
  12011. module.exports = ImageContainer;
  12012. },{}],11:[function(_dereq_,module,exports){
  12013. var log = _dereq_('./log');
  12014. var ImageContainer = _dereq_('./imagecontainer');
  12015. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  12016. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  12017. var FrameContainer = _dereq_('./framecontainer');
  12018. var SVGContainer = _dereq_('./svgcontainer');
  12019. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  12020. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  12021. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  12022. var bind = _dereq_('./utils').bind;
  12023. function ImageLoader(options, support) {
  12024. this.link = null;
  12025. this.options = options;
  12026. this.support = support;
  12027. this.origin = this.getOrigin(window.location.href);
  12028. }
  12029. ImageLoader.prototype.findImages = function(nodes) {
  12030. var images = [];
  12031. nodes.reduce(function(imageNodes, container) {
  12032. switch(container.node.nodeName) {
  12033. case "IMG":
  12034. return imageNodes.concat([{
  12035. args: [container.node.src],
  12036. method: "url"
  12037. }]);
  12038. case "svg":
  12039. case "IFRAME":
  12040. return imageNodes.concat([{
  12041. args: [container.node],
  12042. method: container.node.nodeName
  12043. }]);
  12044. }
  12045. return imageNodes;
  12046. }, []).forEach(this.addImage(images, this.loadImage), this);
  12047. return images;
  12048. };
  12049. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  12050. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  12051. return images;
  12052. };
  12053. ImageLoader.prototype.addImage = function(images, callback) {
  12054. return function(newImage) {
  12055. newImage.args.forEach(function(image) {
  12056. if (!this.imageExists(images, image)) {
  12057. images.splice(0, 0, callback.call(this, newImage));
  12058. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  12059. }
  12060. }, this);
  12061. };
  12062. };
  12063. ImageLoader.prototype.hasImageBackground = function(imageData) {
  12064. return imageData.method !== "none";
  12065. };
  12066. ImageLoader.prototype.loadImage = function(imageData) {
  12067. if (imageData.method === "url") {
  12068. var src = imageData.args[0];
  12069. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  12070. return new SVGContainer(src);
  12071. } else if (src.match(/data:image\/.*;base64,/i)) {
  12072. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  12073. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  12074. return new ImageContainer(src, false);
  12075. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  12076. return new ImageContainer(src, true);
  12077. } else if (this.options.proxy) {
  12078. return new ProxyImageContainer(src, this.options.proxy);
  12079. } else {
  12080. return new DummyImageContainer(src);
  12081. }
  12082. } else if (imageData.method === "linear-gradient") {
  12083. return new LinearGradientContainer(imageData);
  12084. } else if (imageData.method === "gradient") {
  12085. return new WebkitGradientContainer(imageData);
  12086. } else if (imageData.method === "svg") {
  12087. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  12088. } else if (imageData.method === "IFRAME") {
  12089. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  12090. } else {
  12091. return new DummyImageContainer(imageData);
  12092. }
  12093. };
  12094. ImageLoader.prototype.isSVG = function(src) {
  12095. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  12096. };
  12097. ImageLoader.prototype.imageExists = function(images, src) {
  12098. return images.some(function(image) {
  12099. return image.src === src;
  12100. });
  12101. };
  12102. ImageLoader.prototype.isSameOrigin = function(url) {
  12103. return (this.getOrigin(url) === this.origin);
  12104. };
  12105. ImageLoader.prototype.getOrigin = function(url) {
  12106. var link = this.link || (this.link = document.createElement("a"));
  12107. link.href = url;
  12108. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  12109. return link.protocol + link.hostname + link.port;
  12110. };
  12111. ImageLoader.prototype.getPromise = function(container) {
  12112. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  12113. var dummy = new DummyImageContainer(container.src);
  12114. return dummy.promise.then(function(image) {
  12115. container.image = image;
  12116. });
  12117. });
  12118. };
  12119. ImageLoader.prototype.get = function(src) {
  12120. var found = null;
  12121. return this.images.some(function(img) {
  12122. return (found = img).src === src;
  12123. }) ? found : null;
  12124. };
  12125. ImageLoader.prototype.fetch = function(nodes) {
  12126. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  12127. this.images.forEach(function(image, index) {
  12128. image.promise.then(function() {
  12129. log("Succesfully loaded image #"+ (index+1), image);
  12130. }, function(e) {
  12131. log("Failed loading image #"+ (index+1), image, e);
  12132. });
  12133. });
  12134. this.ready = Promise.all(this.images.map(this.getPromise, this));
  12135. log("Finished searching images");
  12136. return this;
  12137. };
  12138. ImageLoader.prototype.timeout = function(container, timeout) {
  12139. var timer;
  12140. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  12141. timer = setTimeout(function() {
  12142. log("Timed out loading image", container);
  12143. reject(container);
  12144. }, timeout);
  12145. })]).then(function(container) {
  12146. clearTimeout(timer);
  12147. return container;
  12148. });
  12149. promise['catch'](function() {
  12150. clearTimeout(timer);
  12151. });
  12152. return promise;
  12153. };
  12154. module.exports = ImageLoader;
  12155. },{"./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){
  12156. var GradientContainer = _dereq_('./gradientcontainer');
  12157. var Color = _dereq_('./color');
  12158. function LinearGradientContainer(imageData) {
  12159. GradientContainer.apply(this, arguments);
  12160. this.type = GradientContainer.TYPES.LINEAR;
  12161. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
  12162. !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
  12163. if (hasDirection) {
  12164. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  12165. switch(position) {
  12166. case "left":
  12167. this.x0 = 0;
  12168. this.x1 = 1;
  12169. break;
  12170. case "top":
  12171. this.y0 = 0;
  12172. this.y1 = 1;
  12173. break;
  12174. case "right":
  12175. this.x0 = 1;
  12176. this.x1 = 0;
  12177. break;
  12178. case "bottom":
  12179. this.y0 = 1;
  12180. this.y1 = 0;
  12181. break;
  12182. case "to":
  12183. var y0 = this.y0;
  12184. var x0 = this.x0;
  12185. this.y0 = this.y1;
  12186. this.x0 = this.x1;
  12187. this.x1 = x0;
  12188. this.y1 = y0;
  12189. break;
  12190. case "center":
  12191. break; // centered by default
  12192. // Firefox internally converts position keywords to percentages:
  12193. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  12194. default: // percentage or absolute length
  12195. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  12196. var ratio = parseFloat(position, 10) * 1e-2;
  12197. if (isNaN(ratio)) { // invalid or unhandled value
  12198. break;
  12199. }
  12200. if (index === 0) {
  12201. this.y0 = ratio;
  12202. this.y1 = 1 - this.y0;
  12203. } else {
  12204. this.x0 = ratio;
  12205. this.x1 = 1 - this.x0;
  12206. }
  12207. break;
  12208. }
  12209. }, this);
  12210. } else {
  12211. this.y0 = 0;
  12212. this.y1 = 1;
  12213. }
  12214. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  12215. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  12216. var value = +colorStopMatch[2];
  12217. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  12218. return {
  12219. color: new Color(colorStopMatch[1]),
  12220. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  12221. stop: unit === "%" ? value / 100 : null
  12222. };
  12223. });
  12224. if (this.colorStops[0].stop === null) {
  12225. this.colorStops[0].stop = 0;
  12226. }
  12227. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  12228. this.colorStops[this.colorStops.length - 1].stop = 1;
  12229. }
  12230. // calculates and fills-in explicit stop positions when omitted from rule
  12231. this.colorStops.forEach(function(colorStop, index) {
  12232. if (colorStop.stop === null) {
  12233. this.colorStops.slice(index).some(function(find, count) {
  12234. if (find.stop !== null) {
  12235. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  12236. return true;
  12237. } else {
  12238. return false;
  12239. }
  12240. }, this);
  12241. }
  12242. }, this);
  12243. }
  12244. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  12245. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  12246. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  12247. module.exports = LinearGradientContainer;
  12248. },{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
  12249. var logger = function() {
  12250. if (logger.options.logging && window.console && window.console.log) {
  12251. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  12252. }
  12253. };
  12254. logger.options = {logging: false};
  12255. module.exports = logger;
  12256. },{}],14:[function(_dereq_,module,exports){
  12257. var Color = _dereq_('./color');
  12258. var utils = _dereq_('./utils');
  12259. var getBounds = utils.getBounds;
  12260. var parseBackgrounds = utils.parseBackgrounds;
  12261. var offsetBounds = utils.offsetBounds;
  12262. function NodeContainer(node, parent) {
  12263. this.node = node;
  12264. this.parent = parent;
  12265. this.stack = null;
  12266. this.bounds = null;
  12267. this.borders = null;
  12268. this.clip = [];
  12269. this.backgroundClip = [];
  12270. this.offsetBounds = null;
  12271. this.visible = null;
  12272. this.computedStyles = null;
  12273. this.colors = {};
  12274. this.styles = {};
  12275. this.backgroundImages = null;
  12276. this.transformData = null;
  12277. this.transformMatrix = null;
  12278. this.isPseudoElement = false;
  12279. this.opacity = null;
  12280. }
  12281. NodeContainer.prototype.cloneTo = function(stack) {
  12282. stack.visible = this.visible;
  12283. stack.borders = this.borders;
  12284. stack.bounds = this.bounds;
  12285. stack.clip = this.clip;
  12286. stack.backgroundClip = this.backgroundClip;
  12287. stack.computedStyles = this.computedStyles;
  12288. stack.styles = this.styles;
  12289. stack.backgroundImages = this.backgroundImages;
  12290. stack.opacity = this.opacity;
  12291. };
  12292. NodeContainer.prototype.getOpacity = function() {
  12293. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  12294. };
  12295. NodeContainer.prototype.assignStack = function(stack) {
  12296. this.stack = stack;
  12297. stack.children.push(this);
  12298. };
  12299. NodeContainer.prototype.isElementVisible = function() {
  12300. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  12301. this.css('display') !== "none" &&
  12302. this.css('visibility') !== "hidden" &&
  12303. !this.node.hasAttribute("data-html2canvas-ignore") &&
  12304. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  12305. );
  12306. };
  12307. NodeContainer.prototype.css = function(attribute) {
  12308. if (!this.computedStyles) {
  12309. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  12310. }
  12311. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  12312. };
  12313. NodeContainer.prototype.prefixedCss = function(attribute) {
  12314. var prefixes = ["webkit", "moz", "ms", "o"];
  12315. var value = this.css(attribute);
  12316. if (value === undefined) {
  12317. prefixes.some(function(prefix) {
  12318. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  12319. return value !== undefined;
  12320. }, this);
  12321. }
  12322. return value === undefined ? null : value;
  12323. };
  12324. NodeContainer.prototype.computedStyle = function(type) {
  12325. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  12326. };
  12327. NodeContainer.prototype.cssInt = function(attribute) {
  12328. var value = parseInt(this.css(attribute), 10);
  12329. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  12330. };
  12331. NodeContainer.prototype.color = function(attribute) {
  12332. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  12333. };
  12334. NodeContainer.prototype.cssFloat = function(attribute) {
  12335. var value = parseFloat(this.css(attribute));
  12336. return (isNaN(value)) ? 0 : value;
  12337. };
  12338. NodeContainer.prototype.fontWeight = function() {
  12339. var weight = this.css("fontWeight");
  12340. switch(parseInt(weight, 10)){
  12341. case 401:
  12342. weight = "bold";
  12343. break;
  12344. case 400:
  12345. weight = "normal";
  12346. break;
  12347. }
  12348. return weight;
  12349. };
  12350. NodeContainer.prototype.parseClip = function() {
  12351. var matches = this.css('clip').match(this.CLIP);
  12352. if (matches) {
  12353. return {
  12354. top: parseInt(matches[1], 10),
  12355. right: parseInt(matches[2], 10),
  12356. bottom: parseInt(matches[3], 10),
  12357. left: parseInt(matches[4], 10)
  12358. };
  12359. }
  12360. return null;
  12361. };
  12362. NodeContainer.prototype.parseBackgroundImages = function() {
  12363. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  12364. };
  12365. NodeContainer.prototype.cssList = function(property, index) {
  12366. var value = (this.css(property) || '').split(',');
  12367. value = value[index || 0] || value[0] || 'auto';
  12368. value = value.trim().split(' ');
  12369. if (value.length === 1) {
  12370. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  12371. }
  12372. return value;
  12373. };
  12374. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  12375. var size = this.cssList("backgroundSize", index);
  12376. var width, height;
  12377. if (isPercentage(size[0])) {
  12378. width = bounds.width * parseFloat(size[0]) / 100;
  12379. } else if (/contain|cover/.test(size[0])) {
  12380. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  12381. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  12382. } else {
  12383. width = parseInt(size[0], 10);
  12384. }
  12385. if (size[0] === 'auto' && size[1] === 'auto') {
  12386. height = image.height;
  12387. } else if (size[1] === 'auto') {
  12388. height = width / image.width * image.height;
  12389. } else if (isPercentage(size[1])) {
  12390. height = bounds.height * parseFloat(size[1]) / 100;
  12391. } else {
  12392. height = parseInt(size[1], 10);
  12393. }
  12394. if (size[0] === 'auto') {
  12395. width = height / image.height * image.width;
  12396. }
  12397. return {width: width, height: height};
  12398. };
  12399. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  12400. var position = this.cssList('backgroundPosition', index);
  12401. var left, top;
  12402. if (isPercentage(position[0])){
  12403. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  12404. } else {
  12405. left = parseInt(position[0], 10);
  12406. }
  12407. if (position[1] === 'auto') {
  12408. top = left / image.width * image.height;
  12409. } else if (isPercentage(position[1])){
  12410. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  12411. } else {
  12412. top = parseInt(position[1], 10);
  12413. }
  12414. if (position[0] === 'auto') {
  12415. left = top / image.height * image.width;
  12416. }
  12417. return {left: left, top: top};
  12418. };
  12419. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  12420. return this.cssList("backgroundRepeat", index)[0];
  12421. };
  12422. NodeContainer.prototype.parseTextShadows = function() {
  12423. var textShadow = this.css("textShadow");
  12424. var results = [];
  12425. if (textShadow && textShadow !== 'none') {
  12426. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  12427. for (var i = 0; shadows && (i < shadows.length); i++) {
  12428. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  12429. results.push({
  12430. color: new Color(s[0]),
  12431. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  12432. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  12433. blur: s[3] ? s[3].replace('px', '') : 0
  12434. });
  12435. }
  12436. }
  12437. return results;
  12438. };
  12439. NodeContainer.prototype.parseTransform = function() {
  12440. if (!this.transformData) {
  12441. if (this.hasTransform()) {
  12442. var offset = this.parseBounds();
  12443. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  12444. origin[0] += offset.left;
  12445. origin[1] += offset.top;
  12446. this.transformData = {
  12447. origin: origin,
  12448. matrix: this.parseTransformMatrix()
  12449. };
  12450. } else {
  12451. this.transformData = {
  12452. origin: [0, 0],
  12453. matrix: [1, 0, 0, 1, 0, 0]
  12454. };
  12455. }
  12456. }
  12457. return this.transformData;
  12458. };
  12459. NodeContainer.prototype.parseTransformMatrix = function() {
  12460. if (!this.transformMatrix) {
  12461. var transform = this.prefixedCss("transform");
  12462. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  12463. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  12464. }
  12465. return this.transformMatrix;
  12466. };
  12467. NodeContainer.prototype.parseBounds = function() {
  12468. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  12469. };
  12470. NodeContainer.prototype.hasTransform = function() {
  12471. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  12472. };
  12473. NodeContainer.prototype.getValue = function() {
  12474. var value = this.node.value || "";
  12475. if (this.node.tagName === "SELECT") {
  12476. value = selectionValue(this.node);
  12477. } else if (this.node.type === "password") {
  12478. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  12479. }
  12480. return value.length === 0 ? (this.node.placeholder || "") : value;
  12481. };
  12482. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  12483. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  12484. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  12485. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  12486. function selectionValue(node) {
  12487. var option = node.options[node.selectedIndex || 0];
  12488. return option ? (option.text || "") : "";
  12489. }
  12490. function parseMatrix(match) {
  12491. if (match && match[1] === "matrix") {
  12492. return match[2].split(",").map(function(s) {
  12493. return parseFloat(s.trim());
  12494. });
  12495. } else if (match && match[1] === "matrix3d") {
  12496. var matrix3d = match[2].split(",").map(function(s) {
  12497. return parseFloat(s.trim());
  12498. });
  12499. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  12500. }
  12501. }
  12502. function isPercentage(value) {
  12503. return value.toString().indexOf("%") !== -1;
  12504. }
  12505. function removePx(str) {
  12506. return str.replace("px", "");
  12507. }
  12508. function asFloat(str) {
  12509. return parseFloat(str);
  12510. }
  12511. module.exports = NodeContainer;
  12512. },{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
  12513. var log = _dereq_('./log');
  12514. var punycode = _dereq_('punycode');
  12515. var NodeContainer = _dereq_('./nodecontainer');
  12516. var TextContainer = _dereq_('./textcontainer');
  12517. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  12518. var FontMetrics = _dereq_('./fontmetrics');
  12519. var Color = _dereq_('./color');
  12520. var StackingContext = _dereq_('./stackingcontext');
  12521. var utils = _dereq_('./utils');
  12522. var bind = utils.bind;
  12523. var getBounds = utils.getBounds;
  12524. var parseBackgrounds = utils.parseBackgrounds;
  12525. var offsetBounds = utils.offsetBounds;
  12526. function NodeParser(element, renderer, support, imageLoader, options) {
  12527. log("Starting NodeParser");
  12528. this.renderer = renderer;
  12529. this.options = options;
  12530. this.range = null;
  12531. this.support = support;
  12532. this.renderQueue = [];
  12533. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  12534. var parent = new NodeContainer(element, null);
  12535. if (options.background) {
  12536. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  12537. }
  12538. if (element === element.ownerDocument.documentElement) {
  12539. // http://www.w3.org/TR/css3-background/#special-backgrounds
  12540. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  12541. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  12542. }
  12543. parent.visibile = parent.isElementVisible();
  12544. this.createPseudoHideStyles(element.ownerDocument);
  12545. this.disableAnimations(element.ownerDocument);
  12546. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  12547. return container.visible = container.isElementVisible();
  12548. }).map(this.getPseudoElements, this));
  12549. this.fontMetrics = new FontMetrics();
  12550. log("Fetched nodes, total:", this.nodes.length);
  12551. log("Calculate overflow clips");
  12552. this.calculateOverflowClips();
  12553. log("Start fetching images");
  12554. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  12555. this.ready = this.images.ready.then(bind(function() {
  12556. log("Images loaded, starting parsing");
  12557. log("Creating stacking contexts");
  12558. this.createStackingContexts();
  12559. log("Sorting stacking contexts");
  12560. this.sortStackingContexts(this.stack);
  12561. this.parse(this.stack);
  12562. log("Render queue created with " + this.renderQueue.length + " items");
  12563. return new Promise(bind(function(resolve) {
  12564. if (!options.async) {
  12565. this.renderQueue.forEach(this.paint, this);
  12566. resolve();
  12567. } else if (typeof(options.async) === "function") {
  12568. options.async.call(this, this.renderQueue, resolve);
  12569. } else if (this.renderQueue.length > 0){
  12570. this.renderIndex = 0;
  12571. this.asyncRenderer(this.renderQueue, resolve);
  12572. } else {
  12573. resolve();
  12574. }
  12575. }, this));
  12576. }, this));
  12577. }
  12578. NodeParser.prototype.calculateOverflowClips = function() {
  12579. this.nodes.forEach(function(container) {
  12580. if (isElement(container)) {
  12581. if (isPseudoElement(container)) {
  12582. container.appendToDOM();
  12583. }
  12584. container.borders = this.parseBorders(container);
  12585. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  12586. var cssClip = container.parseClip();
  12587. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  12588. clip.push([["rect",
  12589. container.bounds.left + cssClip.left,
  12590. container.bounds.top + cssClip.top,
  12591. cssClip.right - cssClip.left,
  12592. cssClip.bottom - cssClip.top
  12593. ]]);
  12594. }
  12595. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  12596. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  12597. if (isPseudoElement(container)) {
  12598. container.cleanDOM();
  12599. }
  12600. } else if (isTextNode(container)) {
  12601. container.clip = hasParentClip(container) ? container.parent.clip : [];
  12602. }
  12603. if (!isPseudoElement(container)) {
  12604. container.bounds = null;
  12605. }
  12606. }, this);
  12607. };
  12608. function hasParentClip(container) {
  12609. return container.parent && container.parent.clip.length;
  12610. }
  12611. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  12612. asyncTimer = asyncTimer || Date.now();
  12613. this.paint(queue[this.renderIndex++]);
  12614. if (queue.length === this.renderIndex) {
  12615. resolve();
  12616. } else if (asyncTimer + 20 > Date.now()) {
  12617. this.asyncRenderer(queue, resolve, asyncTimer);
  12618. } else {
  12619. setTimeout(bind(function() {
  12620. this.asyncRenderer(queue, resolve);
  12621. }, this), 0);
  12622. }
  12623. };
  12624. NodeParser.prototype.createPseudoHideStyles = function(document) {
  12625. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  12626. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  12627. };
  12628. NodeParser.prototype.disableAnimations = function(document) {
  12629. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  12630. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  12631. };
  12632. NodeParser.prototype.createStyles = function(document, styles) {
  12633. var hidePseudoElements = document.createElement('style');
  12634. hidePseudoElements.innerHTML = styles;
  12635. document.body.appendChild(hidePseudoElements);
  12636. };
  12637. NodeParser.prototype.getPseudoElements = function(container) {
  12638. var nodes = [[container]];
  12639. if (container.node.nodeType === Node.ELEMENT_NODE) {
  12640. var before = this.getPseudoElement(container, ":before");
  12641. var after = this.getPseudoElement(container, ":after");
  12642. if (before) {
  12643. nodes.push(before);
  12644. }
  12645. if (after) {
  12646. nodes.push(after);
  12647. }
  12648. }
  12649. return flatten(nodes);
  12650. };
  12651. function toCamelCase(str) {
  12652. return str.replace(/(\-[a-z])/g, function(match){
  12653. return match.toUpperCase().replace('-','');
  12654. });
  12655. }
  12656. NodeParser.prototype.getPseudoElement = function(container, type) {
  12657. var style = container.computedStyle(type);
  12658. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  12659. return null;
  12660. }
  12661. var content = stripQuotes(style.content);
  12662. var isImage = content.substr(0, 3) === 'url';
  12663. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  12664. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  12665. for (var i = style.length-1; i >= 0; i--) {
  12666. var property = toCamelCase(style.item(i));
  12667. pseudoNode.style[property] = style[property];
  12668. }
  12669. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  12670. if (isImage) {
  12671. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  12672. return [pseudoContainer];
  12673. } else {
  12674. var text = document.createTextNode(content);
  12675. pseudoNode.appendChild(text);
  12676. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  12677. }
  12678. };
  12679. NodeParser.prototype.getChildren = function(parentContainer) {
  12680. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  12681. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  12682. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  12683. }, this));
  12684. };
  12685. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  12686. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  12687. container.cloneTo(stack);
  12688. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  12689. parentStack.contexts.push(stack);
  12690. container.stack = stack;
  12691. };
  12692. NodeParser.prototype.createStackingContexts = function() {
  12693. this.nodes.forEach(function(container) {
  12694. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  12695. this.newStackingContext(container, true);
  12696. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  12697. this.newStackingContext(container, false);
  12698. } else {
  12699. container.assignStack(container.parent.stack);
  12700. }
  12701. }, this);
  12702. };
  12703. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  12704. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  12705. };
  12706. NodeParser.prototype.isRootElement = function(container) {
  12707. return container.parent === null;
  12708. };
  12709. NodeParser.prototype.sortStackingContexts = function(stack) {
  12710. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  12711. stack.contexts.forEach(this.sortStackingContexts, this);
  12712. };
  12713. NodeParser.prototype.parseTextBounds = function(container) {
  12714. return function(text, index, textList) {
  12715. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  12716. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  12717. var offset = textList.slice(0, index).join("").length;
  12718. return this.getRangeBounds(container.node, offset, text.length);
  12719. } else if (container.node && typeof(container.node.data) === "string") {
  12720. var replacementNode = container.node.splitText(text.length);
  12721. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  12722. container.node = replacementNode;
  12723. return bounds;
  12724. }
  12725. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  12726. container.node = container.node.splitText(text.length);
  12727. }
  12728. return {};
  12729. };
  12730. };
  12731. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  12732. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  12733. var parent = node.parentNode,
  12734. backupText = node.cloneNode(true);
  12735. wrapper.appendChild(node.cloneNode(true));
  12736. parent.replaceChild(wrapper, node);
  12737. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  12738. parent.replaceChild(backupText, wrapper);
  12739. return bounds;
  12740. };
  12741. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  12742. var range = this.range || (this.range = node.ownerDocument.createRange());
  12743. range.setStart(node, offset);
  12744. range.setEnd(node, offset + length);
  12745. return range.getBoundingClientRect();
  12746. };
  12747. function ClearTransform() {}
  12748. NodeParser.prototype.parse = function(stack) {
  12749. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  12750. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  12751. var descendantElements = stack.children.filter(isElement);
  12752. var descendantNonFloats = descendantElements.filter(not(isFloating));
  12753. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  12754. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  12755. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  12756. 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.
  12757. var text = stack.children.filter(isTextNode).filter(hasText);
  12758. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  12759. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  12760. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  12761. this.renderQueue.push(container);
  12762. if (isStackingContext(container)) {
  12763. this.parse(container);
  12764. this.renderQueue.push(new ClearTransform());
  12765. }
  12766. }, this);
  12767. };
  12768. NodeParser.prototype.paint = function(container) {
  12769. try {
  12770. if (container instanceof ClearTransform) {
  12771. this.renderer.ctx.restore();
  12772. } else if (isTextNode(container)) {
  12773. if (isPseudoElement(container.parent)) {
  12774. container.parent.appendToDOM();
  12775. }
  12776. this.paintText(container);
  12777. if (isPseudoElement(container.parent)) {
  12778. container.parent.cleanDOM();
  12779. }
  12780. } else {
  12781. this.paintNode(container);
  12782. }
  12783. } catch(e) {
  12784. log(e);
  12785. if (this.options.strict) {
  12786. throw e;
  12787. }
  12788. }
  12789. };
  12790. NodeParser.prototype.paintNode = function(container) {
  12791. if (isStackingContext(container)) {
  12792. this.renderer.setOpacity(container.opacity);
  12793. this.renderer.ctx.save();
  12794. if (container.hasTransform()) {
  12795. this.renderer.setTransform(container.parseTransform());
  12796. }
  12797. }
  12798. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  12799. this.paintCheckbox(container);
  12800. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  12801. this.paintRadio(container);
  12802. } else {
  12803. this.paintElement(container);
  12804. }
  12805. };
  12806. NodeParser.prototype.paintElement = function(container) {
  12807. var bounds = container.parseBounds();
  12808. this.renderer.clip(container.backgroundClip, function() {
  12809. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  12810. }, this);
  12811. this.renderer.clip(container.clip, function() {
  12812. this.renderer.renderBorders(container.borders.borders);
  12813. }, this);
  12814. this.renderer.clip(container.backgroundClip, function() {
  12815. switch (container.node.nodeName) {
  12816. case "svg":
  12817. case "IFRAME":
  12818. var imgContainer = this.images.get(container.node);
  12819. if (imgContainer) {
  12820. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  12821. } else {
  12822. log("Error loading <" + container.node.nodeName + ">", container.node);
  12823. }
  12824. break;
  12825. case "IMG":
  12826. var imageContainer = this.images.get(container.node.src);
  12827. if (imageContainer) {
  12828. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  12829. } else {
  12830. log("Error loading <img>", container.node.src);
  12831. }
  12832. break;
  12833. case "CANVAS":
  12834. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  12835. break;
  12836. case "SELECT":
  12837. case "INPUT":
  12838. case "TEXTAREA":
  12839. this.paintFormValue(container);
  12840. break;
  12841. }
  12842. }, this);
  12843. };
  12844. NodeParser.prototype.paintCheckbox = function(container) {
  12845. var b = container.parseBounds();
  12846. var size = Math.min(b.width, b.height);
  12847. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  12848. var r = [3, 3];
  12849. var radius = [r, r, r, r];
  12850. var borders = [1,1,1,1].map(function(w) {
  12851. return {color: new Color('#A5A5A5'), width: w};
  12852. });
  12853. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  12854. this.renderer.clip(container.backgroundClip, function() {
  12855. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  12856. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  12857. if (container.node.checked) {
  12858. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  12859. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  12860. }
  12861. }, this);
  12862. };
  12863. NodeParser.prototype.paintRadio = function(container) {
  12864. var bounds = container.parseBounds();
  12865. var size = Math.min(bounds.width, bounds.height) - 2;
  12866. this.renderer.clip(container.backgroundClip, function() {
  12867. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  12868. if (container.node.checked) {
  12869. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  12870. }
  12871. }, this);
  12872. };
  12873. NodeParser.prototype.paintFormValue = function(container) {
  12874. var value = container.getValue();
  12875. if (value.length > 0) {
  12876. var document = container.node.ownerDocument;
  12877. var wrapper = document.createElement('html2canvaswrapper');
  12878. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  12879. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  12880. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  12881. 'boxSizing', 'whiteSpace', 'wordWrap'];
  12882. properties.forEach(function(property) {
  12883. try {
  12884. wrapper.style[property] = container.css(property);
  12885. } catch(e) {
  12886. // Older IE has issues with "border"
  12887. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  12888. }
  12889. });
  12890. var bounds = container.parseBounds();
  12891. wrapper.style.position = "fixed";
  12892. wrapper.style.left = bounds.left + "px";
  12893. wrapper.style.top = bounds.top + "px";
  12894. wrapper.textContent = value;
  12895. document.body.appendChild(wrapper);
  12896. this.paintText(new TextContainer(wrapper.firstChild, container));
  12897. document.body.removeChild(wrapper);
  12898. }
  12899. };
  12900. NodeParser.prototype.paintText = function(container) {
  12901. container.applyTextTransform();
  12902. var characters = punycode.ucs2.decode(container.node.data);
  12903. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  12904. return punycode.ucs2.encode([character]);
  12905. });
  12906. var weight = container.parent.fontWeight();
  12907. var size = container.parent.css('fontSize');
  12908. var family = container.parent.css('fontFamily');
  12909. var shadows = container.parent.parseTextShadows();
  12910. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  12911. if (shadows.length) {
  12912. // TODO: support multiple text shadows
  12913. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  12914. } else {
  12915. this.renderer.clearShadow();
  12916. }
  12917. this.renderer.clip(container.parent.clip, function() {
  12918. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  12919. if (bounds) {
  12920. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  12921. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  12922. }
  12923. }, this);
  12924. }, this);
  12925. };
  12926. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  12927. switch(container.css("textDecoration").split(" ")[0]) {
  12928. case "underline":
  12929. // Draws a line at the baseline of the font
  12930. // 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
  12931. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  12932. break;
  12933. case "overline":
  12934. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  12935. break;
  12936. case "line-through":
  12937. // TODO try and find exact position for line-through
  12938. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  12939. break;
  12940. }
  12941. };
  12942. var borderColorTransforms = {
  12943. inset: [
  12944. ["darken", 0.60],
  12945. ["darken", 0.10],
  12946. ["darken", 0.10],
  12947. ["darken", 0.60]
  12948. ]
  12949. };
  12950. NodeParser.prototype.parseBorders = function(container) {
  12951. var nodeBounds = container.parseBounds();
  12952. var radius = getBorderRadiusData(container);
  12953. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  12954. var style = container.css('border' + side + 'Style');
  12955. var color = container.color('border' + side + 'Color');
  12956. if (style === "inset" && color.isBlack()) {
  12957. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  12958. }
  12959. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  12960. return {
  12961. width: container.cssInt('border' + side + 'Width'),
  12962. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  12963. args: null
  12964. };
  12965. });
  12966. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  12967. return {
  12968. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  12969. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  12970. };
  12971. };
  12972. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  12973. return borders.map(function(border, borderSide) {
  12974. if (border.width > 0) {
  12975. var bx = nodeBounds.left;
  12976. var by = nodeBounds.top;
  12977. var bw = nodeBounds.width;
  12978. var bh = nodeBounds.height - (borders[2].width);
  12979. switch(borderSide) {
  12980. case 0:
  12981. // top border
  12982. bh = borders[0].width;
  12983. border.args = drawSide({
  12984. c1: [bx, by],
  12985. c2: [bx + bw, by],
  12986. c3: [bx + bw - borders[1].width, by + bh],
  12987. c4: [bx + borders[3].width, by + bh]
  12988. }, radius[0], radius[1],
  12989. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  12990. break;
  12991. case 1:
  12992. // right border
  12993. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  12994. bw = borders[1].width;
  12995. border.args = drawSide({
  12996. c1: [bx + bw, by],
  12997. c2: [bx + bw, by + bh + borders[2].width],
  12998. c3: [bx, by + bh],
  12999. c4: [bx, by + borders[0].width]
  13000. }, radius[1], radius[2],
  13001. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  13002. break;
  13003. case 2:
  13004. // bottom border
  13005. by = (by + nodeBounds.height) - (borders[2].width);
  13006. bh = borders[2].width;
  13007. border.args = drawSide({
  13008. c1: [bx + bw, by + bh],
  13009. c2: [bx, by + bh],
  13010. c3: [bx + borders[3].width, by],
  13011. c4: [bx + bw - borders[3].width, by]
  13012. }, radius[2], radius[3],
  13013. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  13014. break;
  13015. case 3:
  13016. // left border
  13017. bw = borders[3].width;
  13018. border.args = drawSide({
  13019. c1: [bx, by + bh + borders[2].width],
  13020. c2: [bx, by],
  13021. c3: [bx + bw, by + borders[0].width],
  13022. c4: [bx + bw, by + bh]
  13023. }, radius[3], radius[0],
  13024. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  13025. break;
  13026. }
  13027. }
  13028. return border;
  13029. });
  13030. }
  13031. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  13032. var backgroundClip = container.css('backgroundClip'),
  13033. borderArgs = [];
  13034. switch(backgroundClip) {
  13035. case "content-box":
  13036. case "padding-box":
  13037. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  13038. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  13039. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  13040. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  13041. break;
  13042. default:
  13043. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  13044. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  13045. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  13046. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  13047. break;
  13048. }
  13049. return borderArgs;
  13050. };
  13051. function getCurvePoints(x, y, r1, r2) {
  13052. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  13053. var ox = (r1) * kappa, // control point offset horizontal
  13054. oy = (r2) * kappa, // control point offset vertical
  13055. xm = x + r1, // x-middle
  13056. ym = y + r2; // y-middle
  13057. return {
  13058. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  13059. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  13060. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  13061. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  13062. };
  13063. }
  13064. function calculateCurvePoints(bounds, borderRadius, borders) {
  13065. var x = bounds.left,
  13066. y = bounds.top,
  13067. width = bounds.width,
  13068. height = bounds.height,
  13069. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  13070. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  13071. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  13072. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  13073. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  13074. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  13075. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  13076. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  13077. var topWidth = width - trh,
  13078. rightHeight = height - brv,
  13079. bottomWidth = width - brh,
  13080. leftHeight = height - blv;
  13081. return {
  13082. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  13083. 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),
  13084. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  13085. 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),
  13086. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  13087. 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),
  13088. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  13089. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  13090. };
  13091. }
  13092. function bezierCurve(start, startControl, endControl, end) {
  13093. var lerp = function (a, b, t) {
  13094. return {
  13095. x: a.x + (b.x - a.x) * t,
  13096. y: a.y + (b.y - a.y) * t
  13097. };
  13098. };
  13099. return {
  13100. start: start,
  13101. startControl: startControl,
  13102. endControl: endControl,
  13103. end: end,
  13104. subdivide: function(t) {
  13105. var ab = lerp(start, startControl, t),
  13106. bc = lerp(startControl, endControl, t),
  13107. cd = lerp(endControl, end, t),
  13108. abbc = lerp(ab, bc, t),
  13109. bccd = lerp(bc, cd, t),
  13110. dest = lerp(abbc, bccd, t);
  13111. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  13112. },
  13113. curveTo: function(borderArgs) {
  13114. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  13115. },
  13116. curveToReversed: function(borderArgs) {
  13117. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  13118. }
  13119. };
  13120. }
  13121. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  13122. var borderArgs = [];
  13123. if (radius1[0] > 0 || radius1[1] > 0) {
  13124. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  13125. outer1[1].curveTo(borderArgs);
  13126. } else {
  13127. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  13128. }
  13129. if (radius2[0] > 0 || radius2[1] > 0) {
  13130. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  13131. outer2[0].curveTo(borderArgs);
  13132. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  13133. inner2[0].curveToReversed(borderArgs);
  13134. } else {
  13135. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  13136. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  13137. }
  13138. if (radius1[0] > 0 || radius1[1] > 0) {
  13139. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  13140. inner1[1].curveToReversed(borderArgs);
  13141. } else {
  13142. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  13143. }
  13144. return borderArgs;
  13145. }
  13146. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  13147. if (radius1[0] > 0 || radius1[1] > 0) {
  13148. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  13149. corner1[0].curveTo(borderArgs);
  13150. corner1[1].curveTo(borderArgs);
  13151. } else {
  13152. borderArgs.push(["line", x, y]);
  13153. }
  13154. if (radius2[0] > 0 || radius2[1] > 0) {
  13155. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  13156. }
  13157. }
  13158. function negativeZIndex(container) {
  13159. return container.cssInt("zIndex") < 0;
  13160. }
  13161. function positiveZIndex(container) {
  13162. return container.cssInt("zIndex") > 0;
  13163. }
  13164. function zIndex0(container) {
  13165. return container.cssInt("zIndex") === 0;
  13166. }
  13167. function inlineLevel(container) {
  13168. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13169. }
  13170. function isStackingContext(container) {
  13171. return (container instanceof StackingContext);
  13172. }
  13173. function hasText(container) {
  13174. return container.node.data.trim().length > 0;
  13175. }
  13176. function noLetterSpacing(container) {
  13177. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  13178. }
  13179. function getBorderRadiusData(container) {
  13180. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  13181. var value = container.css('border' + side + 'Radius');
  13182. var arr = value.split(" ");
  13183. if (arr.length <= 1) {
  13184. arr[1] = arr[0];
  13185. }
  13186. return arr.map(asInt);
  13187. });
  13188. }
  13189. function renderableNode(node) {
  13190. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  13191. }
  13192. function isPositionedForStacking(container) {
  13193. var position = container.css("position");
  13194. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  13195. return zIndex !== "auto";
  13196. }
  13197. function isPositioned(container) {
  13198. return container.css("position") !== "static";
  13199. }
  13200. function isFloating(container) {
  13201. return container.css("float") !== "none";
  13202. }
  13203. function isInlineBlock(container) {
  13204. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  13205. }
  13206. function not(callback) {
  13207. var context = this;
  13208. return function() {
  13209. return !callback.apply(context, arguments);
  13210. };
  13211. }
  13212. function isElement(container) {
  13213. return container.node.nodeType === Node.ELEMENT_NODE;
  13214. }
  13215. function isPseudoElement(container) {
  13216. return container.isPseudoElement === true;
  13217. }
  13218. function isTextNode(container) {
  13219. return container.node.nodeType === Node.TEXT_NODE;
  13220. }
  13221. function zIndexSort(contexts) {
  13222. return function(a, b) {
  13223. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  13224. };
  13225. }
  13226. function hasOpacity(container) {
  13227. return container.getOpacity() < 1;
  13228. }
  13229. function asInt(value) {
  13230. return parseInt(value, 10);
  13231. }
  13232. function getWidth(border) {
  13233. return border.width;
  13234. }
  13235. function nonIgnoredElement(nodeContainer) {
  13236. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  13237. }
  13238. function flatten(arrays) {
  13239. return [].concat.apply([], arrays);
  13240. }
  13241. function stripQuotes(content) {
  13242. var first = content.substr(0, 1);
  13243. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  13244. }
  13245. function getWords(characters) {
  13246. var words = [], i = 0, onWordBoundary = false, word;
  13247. while(characters.length) {
  13248. if (isWordBoundary(characters[i]) === onWordBoundary) {
  13249. word = characters.splice(0, i);
  13250. if (word.length) {
  13251. words.push(punycode.ucs2.encode(word));
  13252. }
  13253. onWordBoundary =! onWordBoundary;
  13254. i = 0;
  13255. } else {
  13256. i++;
  13257. }
  13258. if (i >= characters.length) {
  13259. word = characters.splice(0, i);
  13260. if (word.length) {
  13261. words.push(punycode.ucs2.encode(word));
  13262. }
  13263. }
  13264. }
  13265. return words;
  13266. }
  13267. function isWordBoundary(characterCode) {
  13268. return [
  13269. 32, // <space>
  13270. 13, // \r
  13271. 10, // \n
  13272. 9, // \t
  13273. 45 // -
  13274. ].indexOf(characterCode) !== -1;
  13275. }
  13276. function hasUnicode(string) {
  13277. return (/[^\u0000-\u00ff]/).test(string);
  13278. }
  13279. module.exports = NodeParser;
  13280. },{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
  13281. var XHR = _dereq_('./xhr');
  13282. var utils = _dereq_('./utils');
  13283. var log = _dereq_('./log');
  13284. var createWindowClone = _dereq_('./clone');
  13285. var decode64 = utils.decode64;
  13286. function Proxy(src, proxyUrl, document) {
  13287. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  13288. if (!proxyUrl) {
  13289. return Promise.reject("No proxy configured");
  13290. }
  13291. var callback = createCallback(supportsCORS);
  13292. var url = createProxyUrl(proxyUrl, src, callback);
  13293. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  13294. return decode64(response.content);
  13295. }));
  13296. }
  13297. var proxyCount = 0;
  13298. function ProxyURL(src, proxyUrl, document) {
  13299. var supportsCORSImage = ('crossOrigin' in new Image());
  13300. var callback = createCallback(supportsCORSImage);
  13301. var url = createProxyUrl(proxyUrl, src, callback);
  13302. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  13303. return "data:" + response.type + ";base64," + response.content;
  13304. }));
  13305. }
  13306. function jsonp(document, url, callback) {
  13307. return new Promise(function(resolve, reject) {
  13308. var s = document.createElement("script");
  13309. var cleanup = function() {
  13310. delete window.html2canvas.proxy[callback];
  13311. document.body.removeChild(s);
  13312. };
  13313. window.html2canvas.proxy[callback] = function(response) {
  13314. cleanup();
  13315. resolve(response);
  13316. };
  13317. s.src = url;
  13318. s.onerror = function(e) {
  13319. cleanup();
  13320. reject(e);
  13321. };
  13322. document.body.appendChild(s);
  13323. });
  13324. }
  13325. function createCallback(useCORS) {
  13326. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  13327. }
  13328. function createProxyUrl(proxyUrl, src, callback) {
  13329. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  13330. }
  13331. function documentFromHTML(src) {
  13332. return function(html) {
  13333. var parser = new DOMParser(), doc;
  13334. try {
  13335. doc = parser.parseFromString(html, "text/html");
  13336. } catch(e) {
  13337. log("DOMParser not supported, falling back to createHTMLDocument");
  13338. doc = document.implementation.createHTMLDocument("");
  13339. try {
  13340. doc.open();
  13341. doc.write(html);
  13342. doc.close();
  13343. } catch(ee) {
  13344. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  13345. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  13346. }
  13347. }
  13348. var b = doc.querySelector("base");
  13349. if (!b || !b.href.host) {
  13350. var base = doc.createElement("base");
  13351. base.href = src;
  13352. doc.head.insertBefore(base, doc.head.firstChild);
  13353. }
  13354. return doc;
  13355. };
  13356. }
  13357. function loadUrlDocument(src, proxy, document, width, height, options) {
  13358. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  13359. return createWindowClone(doc, document, width, height, options, 0, 0);
  13360. });
  13361. }
  13362. exports.Proxy = Proxy;
  13363. exports.ProxyURL = ProxyURL;
  13364. exports.loadUrlDocument = loadUrlDocument;
  13365. },{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
  13366. var ProxyURL = _dereq_('./proxy').ProxyURL;
  13367. function ProxyImageContainer(src, proxy) {
  13368. var link = document.createElement("a");
  13369. link.href = src;
  13370. src = link.href;
  13371. this.src = src;
  13372. this.image = new Image();
  13373. var self = this;
  13374. this.promise = new Promise(function(resolve, reject) {
  13375. self.image.crossOrigin = "Anonymous";
  13376. self.image.onload = resolve;
  13377. self.image.onerror = reject;
  13378. new ProxyURL(src, proxy, document).then(function(url) {
  13379. self.image.src = url;
  13380. })['catch'](reject);
  13381. });
  13382. }
  13383. module.exports = ProxyImageContainer;
  13384. },{"./proxy":16}],18:[function(_dereq_,module,exports){
  13385. var NodeContainer = _dereq_('./nodecontainer');
  13386. function PseudoElementContainer(node, parent, type) {
  13387. NodeContainer.call(this, node, parent);
  13388. this.isPseudoElement = true;
  13389. this.before = type === ":before";
  13390. }
  13391. PseudoElementContainer.prototype.cloneTo = function(stack) {
  13392. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  13393. stack.isPseudoElement = true;
  13394. stack.before = this.before;
  13395. };
  13396. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  13397. PseudoElementContainer.prototype.appendToDOM = function() {
  13398. if (this.before) {
  13399. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  13400. } else {
  13401. this.parent.node.appendChild(this.node);
  13402. }
  13403. this.parent.node.className += " " + this.getHideClass();
  13404. };
  13405. PseudoElementContainer.prototype.cleanDOM = function() {
  13406. this.node.parentNode.removeChild(this.node);
  13407. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  13408. };
  13409. PseudoElementContainer.prototype.getHideClass = function() {
  13410. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  13411. };
  13412. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  13413. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  13414. module.exports = PseudoElementContainer;
  13415. },{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
  13416. var log = _dereq_('./log');
  13417. function Renderer(width, height, images, options, document) {
  13418. this.width = width;
  13419. this.height = height;
  13420. this.images = images;
  13421. this.options = options;
  13422. this.document = document;
  13423. }
  13424. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  13425. var paddingLeft = container.cssInt('paddingLeft'),
  13426. paddingTop = container.cssInt('paddingTop'),
  13427. paddingRight = container.cssInt('paddingRight'),
  13428. paddingBottom = container.cssInt('paddingBottom'),
  13429. borders = borderData.borders;
  13430. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  13431. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  13432. this.drawImage(
  13433. imageContainer,
  13434. 0,
  13435. 0,
  13436. imageContainer.image.width || width,
  13437. imageContainer.image.height || height,
  13438. bounds.left + paddingLeft + borders[3].width,
  13439. bounds.top + paddingTop + borders[0].width,
  13440. width,
  13441. height
  13442. );
  13443. };
  13444. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  13445. if (bounds.height > 0 && bounds.width > 0) {
  13446. this.renderBackgroundColor(container, bounds);
  13447. this.renderBackgroundImage(container, bounds, borderData);
  13448. }
  13449. };
  13450. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  13451. var color = container.color("backgroundColor");
  13452. if (!color.isTransparent()) {
  13453. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  13454. }
  13455. };
  13456. Renderer.prototype.renderBorders = function(borders) {
  13457. borders.forEach(this.renderBorder, this);
  13458. };
  13459. Renderer.prototype.renderBorder = function(data) {
  13460. if (!data.color.isTransparent() && data.args !== null) {
  13461. this.drawShape(data.args, data.color);
  13462. }
  13463. };
  13464. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  13465. var backgroundImages = container.parseBackgroundImages();
  13466. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  13467. switch(backgroundImage.method) {
  13468. case "url":
  13469. var image = this.images.get(backgroundImage.args[0]);
  13470. if (image) {
  13471. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  13472. } else {
  13473. log("Error loading background-image", backgroundImage.args[0]);
  13474. }
  13475. break;
  13476. case "linear-gradient":
  13477. case "gradient":
  13478. var gradientImage = this.images.get(backgroundImage.value);
  13479. if (gradientImage) {
  13480. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  13481. } else {
  13482. log("Error loading background-image", backgroundImage.args[0]);
  13483. }
  13484. break;
  13485. case "none":
  13486. break;
  13487. default:
  13488. log("Unknown background-image type", backgroundImage.args[0]);
  13489. }
  13490. }, this);
  13491. };
  13492. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  13493. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  13494. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  13495. var repeat = container.parseBackgroundRepeat(index);
  13496. switch (repeat) {
  13497. case "repeat-x":
  13498. case "repeat no-repeat":
  13499. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  13500. break;
  13501. case "repeat-y":
  13502. case "no-repeat repeat":
  13503. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  13504. break;
  13505. case "no-repeat":
  13506. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  13507. break;
  13508. default:
  13509. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  13510. break;
  13511. }
  13512. };
  13513. module.exports = Renderer;
  13514. },{"./log":13}],20:[function(_dereq_,module,exports){
  13515. var Renderer = _dereq_('../renderer');
  13516. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  13517. var log = _dereq_('../log');
  13518. function CanvasRenderer(width, height) {
  13519. Renderer.apply(this, arguments);
  13520. this.canvas = this.options.canvas || this.document.createElement("canvas");
  13521. if (!this.options.canvas) {
  13522. this.canvas.width = width;
  13523. this.canvas.height = height;
  13524. }
  13525. this.ctx = this.canvas.getContext("2d");
  13526. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  13527. this.ctx.textBaseline = "bottom";
  13528. this.variables = {};
  13529. log("Initialized CanvasRenderer with size", width, "x", height);
  13530. }
  13531. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  13532. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  13533. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  13534. return this.ctx;
  13535. };
  13536. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  13537. this.setFillStyle(color).fillRect(left, top, width, height);
  13538. };
  13539. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  13540. this.setFillStyle(color);
  13541. this.ctx.beginPath();
  13542. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  13543. this.ctx.closePath();
  13544. this.ctx.fill();
  13545. };
  13546. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  13547. this.circle(left, top, size, color);
  13548. this.ctx.strokeStyle = strokeColor.toString();
  13549. this.ctx.stroke();
  13550. };
  13551. CanvasRenderer.prototype.drawShape = function(shape, color) {
  13552. this.shape(shape);
  13553. this.setFillStyle(color).fill();
  13554. };
  13555. CanvasRenderer.prototype.taints = function(imageContainer) {
  13556. if (imageContainer.tainted === null) {
  13557. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  13558. try {
  13559. this.taintCtx.getImageData(0, 0, 1, 1);
  13560. imageContainer.tainted = false;
  13561. } catch(e) {
  13562. this.taintCtx = document.createElement("canvas").getContext("2d");
  13563. imageContainer.tainted = true;
  13564. }
  13565. }
  13566. return imageContainer.tainted;
  13567. };
  13568. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  13569. if (!this.taints(imageContainer) || this.options.allowTaint) {
  13570. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  13571. }
  13572. };
  13573. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  13574. this.ctx.save();
  13575. shapes.filter(hasEntries).forEach(function(shape) {
  13576. this.shape(shape).clip();
  13577. }, this);
  13578. callback.call(context);
  13579. this.ctx.restore();
  13580. };
  13581. CanvasRenderer.prototype.shape = function(shape) {
  13582. this.ctx.beginPath();
  13583. shape.forEach(function(point, index) {
  13584. if (point[0] === "rect") {
  13585. this.ctx.rect.apply(this.ctx, point.slice(1));
  13586. } else {
  13587. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  13588. }
  13589. }, this);
  13590. this.ctx.closePath();
  13591. return this.ctx;
  13592. };
  13593. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  13594. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  13595. };
  13596. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  13597. this.setVariable("shadowColor", color.toString())
  13598. .setVariable("shadowOffsetY", offsetX)
  13599. .setVariable("shadowOffsetX", offsetY)
  13600. .setVariable("shadowBlur", blur);
  13601. };
  13602. CanvasRenderer.prototype.clearShadow = function() {
  13603. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  13604. };
  13605. CanvasRenderer.prototype.setOpacity = function(opacity) {
  13606. this.ctx.globalAlpha = opacity;
  13607. };
  13608. CanvasRenderer.prototype.setTransform = function(transform) {
  13609. this.ctx.translate(transform.origin[0], transform.origin[1]);
  13610. this.ctx.transform.apply(this.ctx, transform.matrix);
  13611. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  13612. };
  13613. CanvasRenderer.prototype.setVariable = function(property, value) {
  13614. if (this.variables[property] !== value) {
  13615. this.variables[property] = this.ctx[property] = value;
  13616. }
  13617. return this;
  13618. };
  13619. CanvasRenderer.prototype.text = function(text, left, bottom) {
  13620. this.ctx.fillText(text, left, bottom);
  13621. };
  13622. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  13623. var shape = [
  13624. ["line", Math.round(left), Math.round(top)],
  13625. ["line", Math.round(left + width), Math.round(top)],
  13626. ["line", Math.round(left + width), Math.round(height + top)],
  13627. ["line", Math.round(left), Math.round(height + top)]
  13628. ];
  13629. this.clip([shape], function() {
  13630. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  13631. }, this);
  13632. };
  13633. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  13634. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  13635. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  13636. this.ctx.translate(offsetX, offsetY);
  13637. this.ctx.fill();
  13638. this.ctx.translate(-offsetX, -offsetY);
  13639. };
  13640. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  13641. if (gradientImage instanceof LinearGradientContainer) {
  13642. var gradient = this.ctx.createLinearGradient(
  13643. bounds.left + bounds.width * gradientImage.x0,
  13644. bounds.top + bounds.height * gradientImage.y0,
  13645. bounds.left + bounds.width * gradientImage.x1,
  13646. bounds.top + bounds.height * gradientImage.y1);
  13647. gradientImage.colorStops.forEach(function(colorStop) {
  13648. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  13649. });
  13650. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  13651. }
  13652. };
  13653. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  13654. var image = imageContainer.image;
  13655. if(image.width === size.width && image.height === size.height) {
  13656. return image;
  13657. }
  13658. var ctx, canvas = document.createElement('canvas');
  13659. canvas.width = size.width;
  13660. canvas.height = size.height;
  13661. ctx = canvas.getContext("2d");
  13662. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  13663. return canvas;
  13664. };
  13665. function hasEntries(array) {
  13666. return array.length > 0;
  13667. }
  13668. module.exports = CanvasRenderer;
  13669. },{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
  13670. var NodeContainer = _dereq_('./nodecontainer');
  13671. function StackingContext(hasOwnStacking, opacity, element, parent) {
  13672. NodeContainer.call(this, element, parent);
  13673. this.ownStacking = hasOwnStacking;
  13674. this.contexts = [];
  13675. this.children = [];
  13676. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  13677. }
  13678. StackingContext.prototype = Object.create(NodeContainer.prototype);
  13679. StackingContext.prototype.getParentStack = function(context) {
  13680. var parentStack = (this.parent) ? this.parent.stack : null;
  13681. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  13682. };
  13683. module.exports = StackingContext;
  13684. },{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
  13685. function Support(document) {
  13686. this.rangeBounds = this.testRangeBounds(document);
  13687. this.cors = this.testCORS();
  13688. this.svg = this.testSVG();
  13689. }
  13690. Support.prototype.testRangeBounds = function(document) {
  13691. var range, testElement, rangeBounds, rangeHeight, support = false;
  13692. if (document.createRange) {
  13693. range = document.createRange();
  13694. if (range.getBoundingClientRect) {
  13695. testElement = document.createElement('boundtest');
  13696. testElement.style.height = "123px";
  13697. testElement.style.display = "block";
  13698. document.body.appendChild(testElement);
  13699. range.selectNode(testElement);
  13700. rangeBounds = range.getBoundingClientRect();
  13701. rangeHeight = rangeBounds.height;
  13702. if (rangeHeight === 123) {
  13703. support = true;
  13704. }
  13705. document.body.removeChild(testElement);
  13706. }
  13707. }
  13708. return support;
  13709. };
  13710. Support.prototype.testCORS = function() {
  13711. return typeof((new Image()).crossOrigin) !== "undefined";
  13712. };
  13713. Support.prototype.testSVG = function() {
  13714. var img = new Image();
  13715. var canvas = document.createElement("canvas");
  13716. var ctx = canvas.getContext("2d");
  13717. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  13718. try {
  13719. ctx.drawImage(img, 0, 0);
  13720. canvas.toDataURL();
  13721. } catch(e) {
  13722. return false;
  13723. }
  13724. return true;
  13725. };
  13726. module.exports = Support;
  13727. },{}],23:[function(_dereq_,module,exports){
  13728. var XHR = _dereq_('./xhr');
  13729. var decode64 = _dereq_('./utils').decode64;
  13730. function SVGContainer(src) {
  13731. this.src = src;
  13732. this.image = null;
  13733. var self = this;
  13734. this.promise = this.hasFabric().then(function() {
  13735. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  13736. }).then(function(svg) {
  13737. return new Promise(function(resolve) {
  13738. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  13739. });
  13740. });
  13741. }
  13742. SVGContainer.prototype.hasFabric = function() {
  13743. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  13744. };
  13745. SVGContainer.prototype.inlineFormatting = function(src) {
  13746. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  13747. };
  13748. SVGContainer.prototype.removeContentType = function(src) {
  13749. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  13750. };
  13751. SVGContainer.prototype.isInline = function(src) {
  13752. return (/^data:image\/svg\+xml/i.test(src));
  13753. };
  13754. SVGContainer.prototype.createCanvas = function(resolve) {
  13755. var self = this;
  13756. return function (objects, options) {
  13757. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  13758. self.image = canvas.lowerCanvasEl;
  13759. canvas
  13760. .setWidth(options.width)
  13761. .setHeight(options.height)
  13762. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  13763. .renderAll();
  13764. resolve(canvas.lowerCanvasEl);
  13765. };
  13766. };
  13767. SVGContainer.prototype.decode64 = function(str) {
  13768. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  13769. };
  13770. module.exports = SVGContainer;
  13771. },{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
  13772. var SVGContainer = _dereq_('./svgcontainer');
  13773. function SVGNodeContainer(node, _native) {
  13774. this.src = node;
  13775. this.image = null;
  13776. var self = this;
  13777. this.promise = _native ? new Promise(function(resolve, reject) {
  13778. self.image = new Image();
  13779. self.image.onload = resolve;
  13780. self.image.onerror = reject;
  13781. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  13782. if (self.image.complete === true) {
  13783. resolve(self.image);
  13784. }
  13785. }) : this.hasFabric().then(function() {
  13786. return new Promise(function(resolve) {
  13787. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  13788. });
  13789. });
  13790. }
  13791. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  13792. module.exports = SVGNodeContainer;
  13793. },{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
  13794. var NodeContainer = _dereq_('./nodecontainer');
  13795. function TextContainer(node, parent) {
  13796. NodeContainer.call(this, node, parent);
  13797. }
  13798. TextContainer.prototype = Object.create(NodeContainer.prototype);
  13799. TextContainer.prototype.applyTextTransform = function() {
  13800. this.node.data = this.transform(this.parent.css("textTransform"));
  13801. };
  13802. TextContainer.prototype.transform = function(transform) {
  13803. var text = this.node.data;
  13804. switch(transform){
  13805. case "lowercase":
  13806. return text.toLowerCase();
  13807. case "capitalize":
  13808. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  13809. case "uppercase":
  13810. return text.toUpperCase();
  13811. default:
  13812. return text;
  13813. }
  13814. };
  13815. function capitalize(m, p1, p2) {
  13816. if (m.length > 0) {
  13817. return p1 + p2.toUpperCase();
  13818. }
  13819. }
  13820. module.exports = TextContainer;
  13821. },{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
  13822. exports.smallImage = function smallImage() {
  13823. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  13824. };
  13825. exports.bind = function(callback, context) {
  13826. return function() {
  13827. return callback.apply(context, arguments);
  13828. };
  13829. };
  13830. /*
  13831. * base64-arraybuffer
  13832. * https://github.com/niklasvh/base64-arraybuffer
  13833. *
  13834. * Copyright (c) 2012 Niklas von Hertzen
  13835. * Licensed under the MIT license.
  13836. */
  13837. exports.decode64 = function(base64) {
  13838. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  13839. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  13840. var output = "";
  13841. for (i = 0; i < len; i+=4) {
  13842. encoded1 = chars.indexOf(base64[i]);
  13843. encoded2 = chars.indexOf(base64[i+1]);
  13844. encoded3 = chars.indexOf(base64[i+2]);
  13845. encoded4 = chars.indexOf(base64[i+3]);
  13846. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  13847. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  13848. byte3 = ((encoded3 & 3) << 6) | encoded4;
  13849. if (encoded3 === 64) {
  13850. output += String.fromCharCode(byte1);
  13851. } else if (encoded4 === 64 || encoded4 === -1) {
  13852. output += String.fromCharCode(byte1, byte2);
  13853. } else{
  13854. output += String.fromCharCode(byte1, byte2, byte3);
  13855. }
  13856. }
  13857. return output;
  13858. };
  13859. exports.getBounds = function(node) {
  13860. if (node.getBoundingClientRect) {
  13861. var clientRect = node.getBoundingClientRect();
  13862. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  13863. return {
  13864. top: clientRect.top,
  13865. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  13866. right: clientRect.left + width,
  13867. left: clientRect.left,
  13868. width: width,
  13869. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  13870. };
  13871. }
  13872. return {};
  13873. };
  13874. exports.offsetBounds = function(node) {
  13875. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  13876. return {
  13877. top: node.offsetTop + parent.top,
  13878. bottom: node.offsetTop + node.offsetHeight + parent.top,
  13879. right: node.offsetLeft + parent.left + node.offsetWidth,
  13880. left: node.offsetLeft + parent.left,
  13881. width: node.offsetWidth,
  13882. height: node.offsetHeight
  13883. };
  13884. };
  13885. exports.parseBackgrounds = function(backgroundImage) {
  13886. var whitespace = ' \r\n\t',
  13887. method, definition, prefix, prefix_i, block, results = [],
  13888. mode = 0, numParen = 0, quote, args;
  13889. var appendResult = function() {
  13890. if(method) {
  13891. if (definition.substr(0, 1) === '"') {
  13892. definition = definition.substr(1, definition.length - 2);
  13893. }
  13894. if (definition) {
  13895. args.push(definition);
  13896. }
  13897. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  13898. prefix = method.substr(0, prefix_i);
  13899. method = method.substr(prefix_i);
  13900. }
  13901. results.push({
  13902. prefix: prefix,
  13903. method: method.toLowerCase(),
  13904. value: block,
  13905. args: args,
  13906. image: null
  13907. });
  13908. }
  13909. args = [];
  13910. method = prefix = definition = block = '';
  13911. };
  13912. args = [];
  13913. method = prefix = definition = block = '';
  13914. backgroundImage.split("").forEach(function(c) {
  13915. if (mode === 0 && whitespace.indexOf(c) > -1) {
  13916. return;
  13917. }
  13918. switch(c) {
  13919. case '"':
  13920. if(!quote) {
  13921. quote = c;
  13922. } else if(quote === c) {
  13923. quote = null;
  13924. }
  13925. break;
  13926. case '(':
  13927. if(quote) {
  13928. break;
  13929. } else if(mode === 0) {
  13930. mode = 1;
  13931. block += c;
  13932. return;
  13933. } else {
  13934. numParen++;
  13935. }
  13936. break;
  13937. case ')':
  13938. if (quote) {
  13939. break;
  13940. } else if(mode === 1) {
  13941. if(numParen === 0) {
  13942. mode = 0;
  13943. block += c;
  13944. appendResult();
  13945. return;
  13946. } else {
  13947. numParen--;
  13948. }
  13949. }
  13950. break;
  13951. case ',':
  13952. if (quote) {
  13953. break;
  13954. } else if(mode === 0) {
  13955. appendResult();
  13956. return;
  13957. } else if (mode === 1) {
  13958. if (numParen === 0 && !method.match(/^url$/i)) {
  13959. args.push(definition);
  13960. definition = '';
  13961. block += c;
  13962. return;
  13963. }
  13964. }
  13965. break;
  13966. }
  13967. block += c;
  13968. if (mode === 0) {
  13969. method += c;
  13970. } else {
  13971. definition += c;
  13972. }
  13973. });
  13974. appendResult();
  13975. return results;
  13976. };
  13977. },{}],27:[function(_dereq_,module,exports){
  13978. var GradientContainer = _dereq_('./gradientcontainer');
  13979. function WebkitGradientContainer(imageData) {
  13980. GradientContainer.apply(this, arguments);
  13981. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  13982. }
  13983. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  13984. module.exports = WebkitGradientContainer;
  13985. },{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
  13986. function XHR(url) {
  13987. return new Promise(function(resolve, reject) {
  13988. var xhr = new XMLHttpRequest();
  13989. xhr.open('GET', url);
  13990. xhr.onload = function() {
  13991. if (xhr.status === 200) {
  13992. resolve(xhr.responseText);
  13993. } else {
  13994. reject(new Error(xhr.statusText));
  13995. }
  13996. };
  13997. xhr.onerror = function() {
  13998. reject(new Error("Network Error"));
  13999. };
  14000. xhr.send();
  14001. });
  14002. }
  14003. module.exports = XHR;
  14004. },{}]},{},[4])(4)
  14005. });
  14006. // Generated by CoffeeScript 1.4.0
  14007. /*
  14008. # PNG.js
  14009. # Copyright (c) 2011 Devon Govett
  14010. # MIT LICENSE
  14011. #
  14012. #
  14013. */
  14014. (function(global) {
  14015. var PNG;
  14016. PNG = (function() {
  14017. var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  14018. PNG.load = function(url, canvas, callback) {
  14019. var xhr,
  14020. _this = this;
  14021. if (typeof canvas === 'function') {
  14022. callback = canvas;
  14023. }
  14024. xhr = new XMLHttpRequest;
  14025. xhr.open("GET", url, true);
  14026. xhr.responseType = "arraybuffer";
  14027. xhr.onload = function() {
  14028. var data, png;
  14029. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  14030. png = new PNG(data);
  14031. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  14032. png.render(canvas);
  14033. }
  14034. return typeof callback === "function" ? callback(png) : void 0;
  14035. };
  14036. return xhr.send(null);
  14037. };
  14038. APNG_DISPOSE_OP_NONE = 0;
  14039. APNG_DISPOSE_OP_BACKGROUND = 1;
  14040. APNG_DISPOSE_OP_PREVIOUS = 2;
  14041. APNG_BLEND_OP_SOURCE = 0;
  14042. APNG_BLEND_OP_OVER = 1;
  14043. function PNG(data) {
  14044. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  14045. this.data = data;
  14046. this.pos = 8;
  14047. this.palette = [];
  14048. this.imgData = [];
  14049. this.transparency = {};
  14050. this.animation = null;
  14051. this.text = {};
  14052. frame = null;
  14053. while (true) {
  14054. chunkSize = this.readUInt32();
  14055. section = ((function() {
  14056. var _i, _results;
  14057. _results = [];
  14058. for (i = _i = 0; _i < 4; i = ++_i) {
  14059. _results.push(String.fromCharCode(this.data[this.pos++]));
  14060. }
  14061. return _results;
  14062. }).call(this)).join('');
  14063. switch (section) {
  14064. case 'IHDR':
  14065. this.width = this.readUInt32();
  14066. this.height = this.readUInt32();
  14067. this.bits = this.data[this.pos++];
  14068. this.colorType = this.data[this.pos++];
  14069. this.compressionMethod = this.data[this.pos++];
  14070. this.filterMethod = this.data[this.pos++];
  14071. this.interlaceMethod = this.data[this.pos++];
  14072. break;
  14073. case 'acTL':
  14074. this.animation = {
  14075. numFrames: this.readUInt32(),
  14076. numPlays: this.readUInt32() || Infinity,
  14077. frames: []
  14078. };
  14079. break;
  14080. case 'PLTE':
  14081. this.palette = this.read(chunkSize);
  14082. break;
  14083. case 'fcTL':
  14084. if (frame) {
  14085. this.animation.frames.push(frame);
  14086. }
  14087. this.pos += 4;
  14088. frame = {
  14089. width: this.readUInt32(),
  14090. height: this.readUInt32(),
  14091. xOffset: this.readUInt32(),
  14092. yOffset: this.readUInt32()
  14093. };
  14094. delayNum = this.readUInt16();
  14095. delayDen = this.readUInt16() || 100;
  14096. frame.delay = 1000 * delayNum / delayDen;
  14097. frame.disposeOp = this.data[this.pos++];
  14098. frame.blendOp = this.data[this.pos++];
  14099. frame.data = [];
  14100. break;
  14101. case 'IDAT':
  14102. case 'fdAT':
  14103. if (section === 'fdAT') {
  14104. this.pos += 4;
  14105. chunkSize -= 4;
  14106. }
  14107. data = (frame != null ? frame.data : void 0) || this.imgData;
  14108. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  14109. data.push(this.data[this.pos++]);
  14110. }
  14111. break;
  14112. case 'tRNS':
  14113. this.transparency = {};
  14114. switch (this.colorType) {
  14115. case 3:
  14116. palLen = this.palette.length/3;
  14117. this.transparency.indexed = this.read(chunkSize);
  14118. if(this.transparency.indexed.length > palLen)
  14119. throw new Error('More transparent colors than palette size');
  14120. /*
  14121. * According to the PNG spec trns should be increased to the same size as palette if shorter
  14122. */
  14123. //palShort = 255 - this.transparency.indexed.length;
  14124. palShort = palLen - this.transparency.indexed.length;
  14125. if (palShort > 0) {
  14126. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  14127. this.transparency.indexed.push(255);
  14128. }
  14129. }
  14130. break;
  14131. case 0:
  14132. this.transparency.grayscale = this.read(chunkSize)[0];
  14133. break;
  14134. case 2:
  14135. this.transparency.rgb = this.read(chunkSize);
  14136. }
  14137. break;
  14138. case 'tEXt':
  14139. text = this.read(chunkSize);
  14140. index = text.indexOf(0);
  14141. key = String.fromCharCode.apply(String, text.slice(0, index));
  14142. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  14143. break;
  14144. case 'IEND':
  14145. if (frame) {
  14146. this.animation.frames.push(frame);
  14147. }
  14148. this.colors = (function() {
  14149. switch (this.colorType) {
  14150. case 0:
  14151. case 3:
  14152. case 4:
  14153. return 1;
  14154. case 2:
  14155. case 6:
  14156. return 3;
  14157. }
  14158. }).call(this);
  14159. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  14160. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  14161. this.pixelBitlength = this.bits * colors;
  14162. this.colorSpace = (function() {
  14163. switch (this.colors) {
  14164. case 1:
  14165. return 'DeviceGray';
  14166. case 3:
  14167. return 'DeviceRGB';
  14168. }
  14169. }).call(this);
  14170. this.imgData = new Uint8Array(this.imgData);
  14171. return;
  14172. default:
  14173. this.pos += chunkSize;
  14174. }
  14175. this.pos += 4;
  14176. if (this.pos > this.data.length) {
  14177. throw new Error("Incomplete or corrupt PNG file");
  14178. }
  14179. }
  14180. return;
  14181. }
  14182. PNG.prototype.read = function(bytes) {
  14183. var i, _i, _results;
  14184. _results = [];
  14185. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  14186. _results.push(this.data[this.pos++]);
  14187. }
  14188. return _results;
  14189. };
  14190. PNG.prototype.readUInt32 = function() {
  14191. var b1, b2, b3, b4;
  14192. b1 = this.data[this.pos++] << 24;
  14193. b2 = this.data[this.pos++] << 16;
  14194. b3 = this.data[this.pos++] << 8;
  14195. b4 = this.data[this.pos++];
  14196. return b1 | b2 | b3 | b4;
  14197. };
  14198. PNG.prototype.readUInt16 = function() {
  14199. var b1, b2;
  14200. b1 = this.data[this.pos++] << 8;
  14201. b2 = this.data[this.pos++];
  14202. return b1 | b2;
  14203. };
  14204. PNG.prototype.decodePixels = function(data) {
  14205. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  14206. if (data == null) {
  14207. data = this.imgData;
  14208. }
  14209. if (data.length === 0) {
  14210. return new Uint8Array(0);
  14211. }
  14212. data = new FlateStream(data);
  14213. data = data.getBytes();
  14214. pixelBytes = this.pixelBitlength / 8;
  14215. scanlineLength = pixelBytes * this.width;
  14216. pixels = new Uint8Array(scanlineLength * this.height);
  14217. length = data.length;
  14218. row = 0;
  14219. pos = 0;
  14220. c = 0;
  14221. while (pos < length) {
  14222. switch (data[pos++]) {
  14223. case 0:
  14224. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  14225. pixels[c++] = data[pos++];
  14226. }
  14227. break;
  14228. case 1:
  14229. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  14230. abyte = data[pos++];
  14231. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14232. pixels[c++] = (abyte + left) % 256;
  14233. }
  14234. break;
  14235. case 2:
  14236. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  14237. abyte = data[pos++];
  14238. col = (i - (i % pixelBytes)) / pixelBytes;
  14239. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14240. pixels[c++] = (upper + abyte) % 256;
  14241. }
  14242. break;
  14243. case 3:
  14244. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  14245. abyte = data[pos++];
  14246. col = (i - (i % pixelBytes)) / pixelBytes;
  14247. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14248. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14249. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  14250. }
  14251. break;
  14252. case 4:
  14253. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  14254. abyte = data[pos++];
  14255. col = (i - (i % pixelBytes)) / pixelBytes;
  14256. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  14257. if (row === 0) {
  14258. upper = upperLeft = 0;
  14259. } else {
  14260. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  14261. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
  14262. }
  14263. p = left + upper - upperLeft;
  14264. pa = Math.abs(p - left);
  14265. pb = Math.abs(p - upper);
  14266. pc = Math.abs(p - upperLeft);
  14267. if (pa <= pb && pa <= pc) {
  14268. paeth = left;
  14269. } else if (pb <= pc) {
  14270. paeth = upper;
  14271. } else {
  14272. paeth = upperLeft;
  14273. }
  14274. pixels[c++] = (abyte + paeth) % 256;
  14275. }
  14276. break;
  14277. default:
  14278. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  14279. }
  14280. row++;
  14281. }
  14282. return pixels;
  14283. };
  14284. PNG.prototype.decodePalette = function() {
  14285. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  14286. palette = this.palette;
  14287. transparency = this.transparency.indexed || [];
  14288. ret = new Uint8Array((transparency.length || 0) + palette.length);
  14289. pos = 0;
  14290. length = palette.length;
  14291. c = 0;
  14292. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  14293. ret[pos++] = palette[i];
  14294. ret[pos++] = palette[i + 1];
  14295. ret[pos++] = palette[i + 2];
  14296. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  14297. }
  14298. return ret;
  14299. };
  14300. PNG.prototype.copyToImageData = function(imageData, pixels) {
  14301. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  14302. colors = this.colors;
  14303. palette = null;
  14304. alpha = this.hasAlphaChannel;
  14305. if (this.palette.length) {
  14306. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  14307. colors = 4;
  14308. alpha = true;
  14309. }
  14310. data = imageData.data || imageData;
  14311. length = data.length;
  14312. input = palette || pixels;
  14313. i = j = 0;
  14314. if (colors === 1) {
  14315. while (i < length) {
  14316. k = palette ? pixels[i / 4] * 4 : j;
  14317. v = input[k++];
  14318. data[i++] = v;
  14319. data[i++] = v;
  14320. data[i++] = v;
  14321. data[i++] = alpha ? input[k++] : 255;
  14322. j = k;
  14323. }
  14324. } else {
  14325. while (i < length) {
  14326. k = palette ? pixels[i / 4] * 4 : j;
  14327. data[i++] = input[k++];
  14328. data[i++] = input[k++];
  14329. data[i++] = input[k++];
  14330. data[i++] = alpha ? input[k++] : 255;
  14331. j = k;
  14332. }
  14333. }
  14334. };
  14335. PNG.prototype.decode = function() {
  14336. var ret;
  14337. ret = new Uint8Array(this.width * this.height * 4);
  14338. this.copyToImageData(ret, this.decodePixels());
  14339. return ret;
  14340. };
  14341. try {
  14342. scratchCanvas = global.document.createElement('canvas');
  14343. scratchCtx = scratchCanvas.getContext('2d');
  14344. } catch(e) {
  14345. return -1;
  14346. }
  14347. makeImage = function(imageData) {
  14348. var img;
  14349. scratchCtx.width = imageData.width;
  14350. scratchCtx.height = imageData.height;
  14351. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  14352. scratchCtx.putImageData(imageData, 0, 0);
  14353. img = new Image;
  14354. img.src = scratchCanvas.toDataURL();
  14355. return img;
  14356. };
  14357. PNG.prototype.decodeFrames = function(ctx) {
  14358. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  14359. if (!this.animation) {
  14360. return;
  14361. }
  14362. _ref = this.animation.frames;
  14363. _results = [];
  14364. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  14365. frame = _ref[i];
  14366. imageData = ctx.createImageData(frame.width, frame.height);
  14367. pixels = this.decodePixels(new Uint8Array(frame.data));
  14368. this.copyToImageData(imageData, pixels);
  14369. frame.imageData = imageData;
  14370. _results.push(frame.image = makeImage(imageData));
  14371. }
  14372. return _results;
  14373. };
  14374. PNG.prototype.renderFrame = function(ctx, number) {
  14375. var frame, frames, prev;
  14376. frames = this.animation.frames;
  14377. frame = frames[number];
  14378. prev = frames[number - 1];
  14379. if (number === 0) {
  14380. ctx.clearRect(0, 0, this.width, this.height);
  14381. }
  14382. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  14383. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  14384. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  14385. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  14386. }
  14387. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  14388. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  14389. }
  14390. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  14391. };
  14392. PNG.prototype.animate = function(ctx) {
  14393. var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
  14394. _this = this;
  14395. frameNumber = 0;
  14396. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  14397. return (doFrame = function() {
  14398. var f, frame;
  14399. f = frameNumber++ % numFrames;
  14400. frame = frames[f];
  14401. _this.renderFrame(ctx, f);
  14402. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  14403. return _this.animation._timeout = setTimeout(doFrame, frame.delay);
  14404. }
  14405. })();
  14406. };
  14407. PNG.prototype.stopAnimation = function() {
  14408. var _ref;
  14409. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  14410. };
  14411. PNG.prototype.render = function(canvas) {
  14412. var ctx, data;
  14413. if (canvas._png) {
  14414. canvas._png.stopAnimation();
  14415. }
  14416. canvas._png = this;
  14417. canvas.width = this.width;
  14418. canvas.height = this.height;
  14419. ctx = canvas.getContext("2d");
  14420. if (this.animation) {
  14421. this.decodeFrames(ctx);
  14422. return this.animate(ctx);
  14423. } else {
  14424. data = ctx.createImageData(this.width, this.height);
  14425. this.copyToImageData(data, this.decodePixels());
  14426. return ctx.putImageData(data, 0, 0);
  14427. }
  14428. };
  14429. return PNG;
  14430. })();
  14431. global.PNG = PNG;
  14432. })(typeof window !== "undefined" && window || undefined);
  14433. /*
  14434. * Extracted from pdf.js
  14435. * https://github.com/andreasgal/pdf.js
  14436. *
  14437. * Copyright (c) 2011 Mozilla Foundation
  14438. *
  14439. * Contributors: Andreas Gal <gal@mozilla.com>
  14440. * Chris G Jones <cjones@mozilla.com>
  14441. * Shaon Barman <shaon.barman@gmail.com>
  14442. * Vivien Nicolas <21@vingtetun.org>
  14443. * Justin D'Arcangelo <justindarc@gmail.com>
  14444. * Yury Delendik
  14445. *
  14446. *
  14447. */
  14448. var DecodeStream = (function() {
  14449. function constructor() {
  14450. this.pos = 0;
  14451. this.bufferLength = 0;
  14452. this.eof = false;
  14453. this.buffer = null;
  14454. }
  14455. constructor.prototype = {
  14456. ensureBuffer: function decodestream_ensureBuffer(requested) {
  14457. var buffer = this.buffer;
  14458. var current = buffer ? buffer.byteLength : 0;
  14459. if (requested < current)
  14460. return buffer;
  14461. var size = 512;
  14462. while (size < requested)
  14463. size <<= 1;
  14464. var buffer2 = new Uint8Array(size);
  14465. for (var i = 0; i < current; ++i)
  14466. buffer2[i] = buffer[i];
  14467. return this.buffer = buffer2;
  14468. },
  14469. getByte: function decodestream_getByte() {
  14470. var pos = this.pos;
  14471. while (this.bufferLength <= pos) {
  14472. if (this.eof)
  14473. return null;
  14474. this.readBlock();
  14475. }
  14476. return this.buffer[this.pos++];
  14477. },
  14478. getBytes: function decodestream_getBytes(length) {
  14479. var pos = this.pos;
  14480. if (length) {
  14481. this.ensureBuffer(pos + length);
  14482. var end = pos + length;
  14483. while (!this.eof && this.bufferLength < end)
  14484. this.readBlock();
  14485. var bufEnd = this.bufferLength;
  14486. if (end > bufEnd)
  14487. end = bufEnd;
  14488. } else {
  14489. while (!this.eof)
  14490. this.readBlock();
  14491. var end = this.bufferLength;
  14492. }
  14493. this.pos = end;
  14494. return this.buffer.subarray(pos, end);
  14495. },
  14496. lookChar: function decodestream_lookChar() {
  14497. var pos = this.pos;
  14498. while (this.bufferLength <= pos) {
  14499. if (this.eof)
  14500. return null;
  14501. this.readBlock();
  14502. }
  14503. return String.fromCharCode(this.buffer[this.pos]);
  14504. },
  14505. getChar: function decodestream_getChar() {
  14506. var pos = this.pos;
  14507. while (this.bufferLength <= pos) {
  14508. if (this.eof)
  14509. return null;
  14510. this.readBlock();
  14511. }
  14512. return String.fromCharCode(this.buffer[this.pos++]);
  14513. },
  14514. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  14515. var end = start + length;
  14516. while (this.bufferLength <= end && !this.eof)
  14517. this.readBlock();
  14518. return new Stream(this.buffer, start, length, dict);
  14519. },
  14520. skip: function decodestream_skip(n) {
  14521. if (!n)
  14522. n = 1;
  14523. this.pos += n;
  14524. },
  14525. reset: function decodestream_reset() {
  14526. this.pos = 0;
  14527. }
  14528. };
  14529. return constructor;
  14530. })();
  14531. var FlateStream = (function() {
  14532. if (typeof Uint32Array === 'undefined') {
  14533. return undefined;
  14534. }
  14535. var codeLenCodeMap = new Uint32Array([
  14536. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  14537. ]);
  14538. var lengthDecode = new Uint32Array([
  14539. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  14540. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  14541. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  14542. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  14543. ]);
  14544. var distDecode = new Uint32Array([
  14545. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  14546. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  14547. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  14548. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  14549. ]);
  14550. var fixedLitCodeTab = [new Uint32Array([
  14551. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  14552. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  14553. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  14554. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  14555. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  14556. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  14557. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  14558. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  14559. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  14560. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  14561. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  14562. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  14563. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  14564. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  14565. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  14566. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  14567. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  14568. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  14569. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  14570. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  14571. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  14572. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  14573. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  14574. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  14575. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  14576. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  14577. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  14578. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  14579. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  14580. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  14581. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  14582. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  14583. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  14584. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  14585. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  14586. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  14587. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  14588. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  14589. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  14590. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  14591. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  14592. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  14593. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  14594. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  14595. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  14596. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  14597. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  14598. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  14599. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  14600. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  14601. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  14602. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  14603. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  14604. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  14605. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  14606. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  14607. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  14608. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  14609. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  14610. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  14611. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  14612. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  14613. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  14614. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  14615. ]), 9];
  14616. var fixedDistCodeTab = [new Uint32Array([
  14617. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  14618. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  14619. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  14620. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  14621. ]), 5];
  14622. function error(e) {
  14623. throw new Error(e)
  14624. }
  14625. function constructor(bytes) {
  14626. //var bytes = stream.getBytes();
  14627. var bytesPos = 0;
  14628. var cmf = bytes[bytesPos++];
  14629. var flg = bytes[bytesPos++];
  14630. if (cmf == -1 || flg == -1)
  14631. error('Invalid header in flate stream');
  14632. if ((cmf & 0x0f) != 0x08)
  14633. error('Unknown compression method in flate stream');
  14634. if ((((cmf << 8) + flg) % 31) != 0)
  14635. error('Bad FCHECK in flate stream');
  14636. if (flg & 0x20)
  14637. error('FDICT bit set in flate stream');
  14638. this.bytes = bytes;
  14639. this.bytesPos = bytesPos;
  14640. this.codeSize = 0;
  14641. this.codeBuf = 0;
  14642. DecodeStream.call(this);
  14643. }
  14644. constructor.prototype = Object.create(DecodeStream.prototype);
  14645. constructor.prototype.getBits = function(bits) {
  14646. var codeSize = this.codeSize;
  14647. var codeBuf = this.codeBuf;
  14648. var bytes = this.bytes;
  14649. var bytesPos = this.bytesPos;
  14650. var b;
  14651. while (codeSize < bits) {
  14652. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14653. error('Bad encoding in flate stream');
  14654. codeBuf |= b << codeSize;
  14655. codeSize += 8;
  14656. }
  14657. b = codeBuf & ((1 << bits) - 1);
  14658. this.codeBuf = codeBuf >> bits;
  14659. this.codeSize = codeSize -= bits;
  14660. this.bytesPos = bytesPos;
  14661. return b;
  14662. };
  14663. constructor.prototype.getCode = function(table) {
  14664. var codes = table[0];
  14665. var maxLen = table[1];
  14666. var codeSize = this.codeSize;
  14667. var codeBuf = this.codeBuf;
  14668. var bytes = this.bytes;
  14669. var bytesPos = this.bytesPos;
  14670. while (codeSize < maxLen) {
  14671. var b;
  14672. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14673. error('Bad encoding in flate stream');
  14674. codeBuf |= (b << codeSize);
  14675. codeSize += 8;
  14676. }
  14677. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  14678. var codeLen = code >> 16;
  14679. var codeVal = code & 0xffff;
  14680. if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
  14681. error('Bad encoding in flate stream');
  14682. this.codeBuf = (codeBuf >> codeLen);
  14683. this.codeSize = (codeSize - codeLen);
  14684. this.bytesPos = bytesPos;
  14685. return codeVal;
  14686. };
  14687. constructor.prototype.generateHuffmanTable = function(lengths) {
  14688. var n = lengths.length;
  14689. // find max code length
  14690. var maxLen = 0;
  14691. for (var i = 0; i < n; ++i) {
  14692. if (lengths[i] > maxLen)
  14693. maxLen = lengths[i];
  14694. }
  14695. // build the table
  14696. var size = 1 << maxLen;
  14697. var codes = new Uint32Array(size);
  14698. for (var len = 1, code = 0, skip = 2;
  14699. len <= maxLen;
  14700. ++len, code <<= 1, skip <<= 1) {
  14701. for (var val = 0; val < n; ++val) {
  14702. if (lengths[val] == len) {
  14703. // bit-reverse the code
  14704. var code2 = 0;
  14705. var t = code;
  14706. for (var i = 0; i < len; ++i) {
  14707. code2 = (code2 << 1) | (t & 1);
  14708. t >>= 1;
  14709. }
  14710. // fill the table entries
  14711. for (var i = code2; i < size; i += skip)
  14712. codes[i] = (len << 16) | val;
  14713. ++code;
  14714. }
  14715. }
  14716. }
  14717. return [codes, maxLen];
  14718. };
  14719. constructor.prototype.readBlock = function() {
  14720. function repeat(stream, array, len, offset, what) {
  14721. var repeat = stream.getBits(len) + offset;
  14722. while (repeat-- > 0)
  14723. array[i++] = what;
  14724. }
  14725. // read block header
  14726. var hdr = this.getBits(3);
  14727. if (hdr & 1)
  14728. this.eof = true;
  14729. hdr >>= 1;
  14730. if (hdr == 0) { // uncompressed block
  14731. var bytes = this.bytes;
  14732. var bytesPos = this.bytesPos;
  14733. var b;
  14734. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14735. error('Bad block header in flate stream');
  14736. var blockLen = b;
  14737. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14738. error('Bad block header in flate stream');
  14739. blockLen |= (b << 8);
  14740. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14741. error('Bad block header in flate stream');
  14742. var check = b;
  14743. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  14744. error('Bad block header in flate stream');
  14745. check |= (b << 8);
  14746. if (check != (~blockLen & 0xffff))
  14747. error('Bad uncompressed block length in flate stream');
  14748. this.codeBuf = 0;
  14749. this.codeSize = 0;
  14750. var bufferLength = this.bufferLength;
  14751. var buffer = this.ensureBuffer(bufferLength + blockLen);
  14752. var end = bufferLength + blockLen;
  14753. this.bufferLength = end;
  14754. for (var n = bufferLength; n < end; ++n) {
  14755. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  14756. this.eof = true;
  14757. break;
  14758. }
  14759. buffer[n] = b;
  14760. }
  14761. this.bytesPos = bytesPos;
  14762. return;
  14763. }
  14764. var litCodeTable;
  14765. var distCodeTable;
  14766. if (hdr == 1) { // compressed block, fixed codes
  14767. litCodeTable = fixedLitCodeTab;
  14768. distCodeTable = fixedDistCodeTab;
  14769. } else if (hdr == 2) { // compressed block, dynamic codes
  14770. var numLitCodes = this.getBits(5) + 257;
  14771. var numDistCodes = this.getBits(5) + 1;
  14772. var numCodeLenCodes = this.getBits(4) + 4;
  14773. // build the code lengths code table
  14774. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  14775. var i = 0;
  14776. while (i < numCodeLenCodes)
  14777. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  14778. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  14779. // build the literal and distance code tables
  14780. var len = 0;
  14781. var i = 0;
  14782. var codes = numLitCodes + numDistCodes;
  14783. var codeLengths = new Array(codes);
  14784. while (i < codes) {
  14785. var code = this.getCode(codeLenCodeTab);
  14786. if (code == 16) {
  14787. repeat(this, codeLengths, 2, 3, len);
  14788. } else if (code == 17) {
  14789. repeat(this, codeLengths, 3, 3, len = 0);
  14790. } else if (code == 18) {
  14791. repeat(this, codeLengths, 7, 11, len = 0);
  14792. } else {
  14793. codeLengths[i++] = len = code;
  14794. }
  14795. }
  14796. litCodeTable =
  14797. this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  14798. distCodeTable =
  14799. this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  14800. } else {
  14801. error('Unknown block type in flate stream');
  14802. }
  14803. var buffer = this.buffer;
  14804. var limit = buffer ? buffer.length : 0;
  14805. var pos = this.bufferLength;
  14806. while (true) {
  14807. var code1 = this.getCode(litCodeTable);
  14808. if (code1 < 256) {
  14809. if (pos + 1 >= limit) {
  14810. buffer = this.ensureBuffer(pos + 1);
  14811. limit = buffer.length;
  14812. }
  14813. buffer[pos++] = code1;
  14814. continue;
  14815. }
  14816. if (code1 == 256) {
  14817. this.bufferLength = pos;
  14818. return;
  14819. }
  14820. code1 -= 257;
  14821. code1 = lengthDecode[code1];
  14822. var code2 = code1 >> 16;
  14823. if (code2 > 0)
  14824. code2 = this.getBits(code2);
  14825. var len = (code1 & 0xffff) + code2;
  14826. code1 = this.getCode(distCodeTable);
  14827. code1 = distDecode[code1];
  14828. code2 = code1 >> 16;
  14829. if (code2 > 0)
  14830. code2 = this.getBits(code2);
  14831. var dist = (code1 & 0xffff) + code2;
  14832. if (pos + len >= limit) {
  14833. buffer = this.ensureBuffer(pos + len);
  14834. limit = buffer.length;
  14835. }
  14836. for (var k = 0; k < len; ++k, ++pos)
  14837. buffer[pos] = buffer[pos - dist];
  14838. }
  14839. };
  14840. return constructor;
  14841. })();
  14842. /**
  14843. * JavaScript Polyfill functions for jsPDF
  14844. * Collected from public resources by
  14845. * https://github.com/diegocr
  14846. */
  14847. (function (global) {
  14848. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  14849. if (typeof global.btoa === 'undefined') {
  14850. global.btoa = function(data) {
  14851. // discuss at: http://phpjs.org/functions/base64_encode/
  14852. // original by: Tyler Akins (http://rumkin.com)
  14853. // improved by: Bayron Guevara
  14854. // improved by: Thunder.m
  14855. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14856. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14857. // improved by: Rafal Kukawski (http://kukawski.pl)
  14858. // bugfixed by: Pellentesque Malesuada
  14859. // example 1: base64_encode('Kevin van Zonneveld');
  14860. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  14861. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
  14862. if (!data) {
  14863. return data;
  14864. }
  14865. do { // pack three octets into four hexets
  14866. o1 = data.charCodeAt(i++);
  14867. o2 = data.charCodeAt(i++);
  14868. o3 = data.charCodeAt(i++);
  14869. bits = o1 << 16 | o2 << 8 | o3;
  14870. h1 = bits >> 18 & 0x3f;
  14871. h2 = bits >> 12 & 0x3f;
  14872. h3 = bits >> 6 & 0x3f;
  14873. h4 = bits & 0x3f;
  14874. // use hexets to index into b64, and append result to encoded string
  14875. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  14876. } while (i < data.length);
  14877. enc = tmp_arr.join('');
  14878. var r = data.length % 3;
  14879. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  14880. };
  14881. }
  14882. if (typeof global.atob === 'undefined') {
  14883. global.atob = function(data) {
  14884. // discuss at: http://phpjs.org/functions/base64_decode/
  14885. // original by: Tyler Akins (http://rumkin.com)
  14886. // improved by: Thunder.m
  14887. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14888. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14889. // input by: Aman Gupta
  14890. // input by: Brett Zamir (http://brett-zamir.me)
  14891. // bugfixed by: Onno Marsman
  14892. // bugfixed by: Pellentesque Malesuada
  14893. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14894. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  14895. // returns 1: 'Kevin van Zonneveld'
  14896. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
  14897. if (!data) {
  14898. return data;
  14899. }
  14900. data += '';
  14901. do { // unpack four hexets into three octets using index points in b64
  14902. h1 = b64.indexOf(data.charAt(i++));
  14903. h2 = b64.indexOf(data.charAt(i++));
  14904. h3 = b64.indexOf(data.charAt(i++));
  14905. h4 = b64.indexOf(data.charAt(i++));
  14906. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  14907. o1 = bits >> 16 & 0xff;
  14908. o2 = bits >> 8 & 0xff;
  14909. o3 = bits & 0xff;
  14910. if (h3 == 64) {
  14911. tmp_arr[ac++] = String.fromCharCode(o1);
  14912. } else if (h4 == 64) {
  14913. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  14914. } else {
  14915. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  14916. }
  14917. } while (i < data.length);
  14918. dec = tmp_arr.join('');
  14919. return dec;
  14920. };
  14921. }
  14922. if (!Array.prototype.map) {
  14923. Array.prototype.map = function(fun /*, thisArg */) {
  14924. if (this === void 0 || this === null || typeof fun !== "function")
  14925. throw new TypeError();
  14926. var t = Object(this), len = t.length >>> 0, res = new Array(len);
  14927. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  14928. for (var i = 0; i < len; i++) {
  14929. // NOTE: Absolute correctness would demand Object.defineProperty
  14930. // be used. But this method is fairly new, and failure is
  14931. // possible only if Object.prototype or Array.prototype
  14932. // has a property |i| (very unlikely), so use a less-correct
  14933. // but more portable alternative.
  14934. if (i in t)
  14935. res[i] = fun.call(thisArg, t[i], i, t);
  14936. }
  14937. return res;
  14938. };
  14939. }
  14940. if(!Array.isArray) {
  14941. Array.isArray = function(arg) {
  14942. return Object.prototype.toString.call(arg) === '[object Array]';
  14943. };
  14944. }
  14945. if (!Array.prototype.forEach) {
  14946. Array.prototype.forEach = function(fun, thisArg) {
  14947. "use strict";
  14948. if (this === void 0 || this === null || typeof fun !== "function")
  14949. throw new TypeError();
  14950. var t = Object(this), len = t.length >>> 0;
  14951. for (var i = 0; i < len; i++) {
  14952. if (i in t)
  14953. fun.call(thisArg, t[i], i, t);
  14954. }
  14955. };
  14956. }
  14957. if (!Object.keys) {
  14958. Object.keys = (function () {
  14959. 'use strict';
  14960. var hasOwnProperty = Object.prototype.hasOwnProperty,
  14961. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  14962. dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
  14963. 'isPrototypeOf','propertyIsEnumerable','constructor'],
  14964. dontEnumsLength = dontEnums.length;
  14965. return function (obj) {
  14966. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  14967. throw new TypeError();
  14968. }
  14969. var result = [], prop, i;
  14970. for (prop in obj) {
  14971. if (hasOwnProperty.call(obj, prop)) {
  14972. result.push(prop);
  14973. }
  14974. }
  14975. if (hasDontEnumBug) {
  14976. for (i = 0; i < dontEnumsLength; i++) {
  14977. if (hasOwnProperty.call(obj, dontEnums[i])) {
  14978. result.push(dontEnums[i]);
  14979. }
  14980. }
  14981. }
  14982. return result;
  14983. };
  14984. }());
  14985. }
  14986. if (!String.prototype.trim) {
  14987. String.prototype.trim = function () {
  14988. return this.replace(/^\s+|\s+$/g, '');
  14989. };
  14990. }
  14991. if (!String.prototype.trimLeft) {
  14992. String.prototype.trimLeft = function() {
  14993. return this.replace(/^\s+/g, "");
  14994. };
  14995. }
  14996. if (!String.prototype.trimRight) {
  14997. String.prototype.trimRight = function() {
  14998. return this.replace(/\s+$/g, "");
  14999. };
  15000. }
  15001. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  15002. var jsPDF = jsPDF;
  15003. return jsPDF;
  15004. }));