jspdf.js 829 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.jsPDF = factory());
  5. }(this, (function () { 'use strict';
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  7. return typeof obj;
  8. } : function (obj) {
  9. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  10. };
  11. /** @preserve
  12. * jsPDF - PDF Document creation from JavaScript
  13. * Version 1.4.1 Built on 2018-08-07T15:40:19.341Z
  14. * CommitID 7192086662
  15. *
  16. * Copyright (c) 2010-2016 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. * @name jsPDF
  42. * @class
  43. * @param orientation {String/Object} Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l") <br />
  44. * Can also be an options object.
  45. * @param unit {String} Measurement unit to be used when coordinates are specified.<br />
  46. * Possible values are "pt" (points), "mm" (Default), "cm", "in" or "px".
  47. * @param format {String/Array} The format of the first page. Can be <ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
  48. * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array , e.g. [595.28, 841.89]
  49. * @returns {jsPDF}
  50. * @description
  51. * If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
  52. * ```
  53. * {
  54. * orientation: 'p',
  55. * unit: 'mm',
  56. * format: 'a4',
  57. * hotfixes: [] // an array of hotfix strings to enable
  58. * }
  59. * ```
  60. */
  61. var jsPDF = function (global) {
  62. var pdfVersion = '1.3',
  63. pageFormats = { // Size in pt of various paper formats
  64. 'a0': [2383.94, 3370.39],
  65. 'a1': [1683.78, 2383.94],
  66. 'a2': [1190.55, 1683.78],
  67. 'a3': [841.89, 1190.55],
  68. 'a4': [595.28, 841.89],
  69. 'a5': [419.53, 595.28],
  70. 'a6': [297.64, 419.53],
  71. 'a7': [209.76, 297.64],
  72. 'a8': [147.40, 209.76],
  73. 'a9': [104.88, 147.40],
  74. 'a10': [73.70, 104.88],
  75. 'b0': [2834.65, 4008.19],
  76. 'b1': [2004.09, 2834.65],
  77. 'b2': [1417.32, 2004.09],
  78. 'b3': [1000.63, 1417.32],
  79. 'b4': [708.66, 1000.63],
  80. 'b5': [498.90, 708.66],
  81. 'b6': [354.33, 498.90],
  82. 'b7': [249.45, 354.33],
  83. 'b8': [175.75, 249.45],
  84. 'b9': [124.72, 175.75],
  85. 'b10': [87.87, 124.72],
  86. 'c0': [2599.37, 3676.54],
  87. 'c1': [1836.85, 2599.37],
  88. 'c2': [1298.27, 1836.85],
  89. 'c3': [918.43, 1298.27],
  90. 'c4': [649.13, 918.43],
  91. 'c5': [459.21, 649.13],
  92. 'c6': [323.15, 459.21],
  93. 'c7': [229.61, 323.15],
  94. 'c8': [161.57, 229.61],
  95. 'c9': [113.39, 161.57],
  96. 'c10': [79.37, 113.39],
  97. 'dl': [311.81, 623.62],
  98. 'letter': [612, 792],
  99. 'government-letter': [576, 756],
  100. 'legal': [612, 1008],
  101. 'junior-legal': [576, 360],
  102. 'ledger': [1224, 792],
  103. 'tabloid': [792, 1224],
  104. 'credit-card': [153, 243]
  105. };
  106. /**
  107. * jsPDF's Internal PubSub Implementation.
  108. * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
  109. * Backward compatible rewritten on 2014 by
  110. * Diego Casorran, https://github.com/diegocr
  111. *
  112. * @class
  113. * @name PubSub
  114. * @ignore This should not be in the public docs.
  115. */
  116. function PubSub(context) {
  117. var topics = {};
  118. this.subscribe = function (topic, callback, once) {
  119. if (typeof callback !== 'function') {
  120. return false;
  121. }
  122. if (!topics.hasOwnProperty(topic)) {
  123. topics[topic] = {};
  124. }
  125. var id = Math.random().toString(35);
  126. topics[topic][id] = [callback, !!once];
  127. return id;
  128. };
  129. this.unsubscribe = function (token) {
  130. for (var topic in topics) {
  131. if (topics[topic][token]) {
  132. delete topics[topic][token];
  133. return true;
  134. }
  135. }
  136. return false;
  137. };
  138. this.publish = function (topic) {
  139. if (topics.hasOwnProperty(topic)) {
  140. var args = Array.prototype.slice.call(arguments, 1),
  141. idr = [];
  142. for (var id in topics[topic]) {
  143. var sub = topics[topic][id];
  144. try {
  145. sub[0].apply(context, args);
  146. } catch (ex) {
  147. if (global.console) {
  148. console.error('jsPDF PubSub Error', ex.message, ex);
  149. }
  150. }
  151. if (sub[1]) idr.push(id);
  152. }
  153. if (idr.length) idr.forEach(this.unsubscribe);
  154. }
  155. };
  156. }
  157. /**
  158. * @constructor
  159. * @private
  160. */
  161. function jsPDF(orientation, unit, format, compressPdf) {
  162. var options = {};
  163. if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
  164. options = orientation;
  165. orientation = options.orientation;
  166. unit = options.unit || unit;
  167. format = options.format || format;
  168. compressPdf = options.compress || options.compressPdf || compressPdf;
  169. }
  170. // Default options
  171. unit = unit || 'mm';
  172. format = format || 'a4';
  173. orientation = ('' + (orientation || 'P')).toLowerCase();
  174. var format_as_string = ('' + format).toLowerCase(),
  175. compress = !!compressPdf && typeof Uint8Array === 'function',
  176. textColor = options.textColor || '0 g',
  177. drawColor = options.drawColor || '0 G',
  178. activeFontSize = options.fontSize || 16,
  179. activeCharSpace = options.charSpace || 0,
  180. R2L = options.R2L || false,
  181. lineHeightProportion = options.lineHeight || 1.15,
  182. lineWidth = options.lineWidth || 0.200025,
  183. // 2mm
  184. fileId = '00000000000000000000000000000000',
  185. objectNumber = 2,
  186. // 'n' Current object number
  187. outToPages = !1,
  188. // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  189. offsets = [],
  190. // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  191. fonts = {},
  192. // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  193. fontmap = {},
  194. // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  195. activeFontKey,
  196. // will be string representing the KEY of the font as combination of fontName + fontStyle
  197. k,
  198. // Scale factor
  199. tmp,
  200. page = 0,
  201. currentPage,
  202. pages = [],
  203. pagesContext = [],
  204. // same index as pages and pagedim
  205. pagedim = [],
  206. content = [],
  207. additionalObjects = [],
  208. lineCapID = 0,
  209. lineJoinID = 0,
  210. content_length = 0,
  211. pageWidth,
  212. pageHeight,
  213. pageMode,
  214. zoomMode,
  215. layoutMode,
  216. creationDate,
  217. documentProperties = {
  218. 'title': '',
  219. 'subject': '',
  220. 'author': '',
  221. 'keywords': '',
  222. 'creator': ''
  223. },
  224. API = {},
  225. events = new PubSub(API),
  226. hotfixes = options.hotfixes || [],
  227. /////////////////////
  228. // Private functions
  229. /////////////////////
  230. generateColorString = function generateColorString(options) {
  231. var color;
  232. var ch1 = options.ch1;
  233. var ch2 = options.ch2;
  234. var ch3 = options.ch3;
  235. var ch4 = options.ch4;
  236. var precision = options.precision;
  237. var letterArray = options.pdfColorType === "draw" ? ['G', 'RG', 'K'] : ['g', 'rg', 'k'];
  238. if (typeof ch1 === "string" && ch1.charAt(0) !== '#') {
  239. var rgbColor = new RGBColor(ch1);
  240. if (rgbColor.ok) {
  241. ch1 = rgbColor.toHex();
  242. }
  243. }
  244. //convert short rgb to long form
  245. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{3}$/.test(ch1)) {
  246. ch1 = '#' + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];
  247. }
  248. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{6}$/.test(ch1)) {
  249. var hex = parseInt(ch1.substr(1), 16);
  250. ch1 = hex >> 16 & 255;
  251. ch2 = hex >> 8 & 255;
  252. ch3 = hex & 255;
  253. }
  254. if (typeof ch2 === "undefined" || typeof ch4 === "undefined" && ch1 === ch2 && ch2 === ch3) {
  255. // Gray color space.
  256. if (typeof ch1 === "string") {
  257. color = ch1 + " " + letterArray[0];
  258. } else {
  259. switch (options.precision) {
  260. case 2:
  261. color = f2(ch1 / 255) + " " + letterArray[0];
  262. break;
  263. case 3:
  264. default:
  265. color = f3(ch1 / 255) + " " + letterArray[0];
  266. }
  267. }
  268. } else if (typeof ch4 === "undefined" || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === "object") {
  269. // assume RGB
  270. if (typeof ch1 === "string") {
  271. color = [ch1, ch2, ch3, letterArray[1]].join(" ");
  272. } else {
  273. switch (options.precision) {
  274. case 2:
  275. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), letterArray[1]].join(" ");
  276. break;
  277. default:
  278. case 3:
  279. color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), letterArray[1]].join(" ");
  280. }
  281. }
  282. // assume RGBA
  283. if (ch4 && ch4.a === 0) {
  284. //TODO Implement transparency.
  285. //WORKAROUND use white for now
  286. color = ['255', '255', '255', letterArray[1]].join(" ");
  287. }
  288. } else {
  289. // assume CMYK
  290. if (typeof ch1 === 'string') {
  291. color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");
  292. } else {
  293. switch (options.precision) {
  294. case 2:
  295. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), letterArray[2]].join(" ");
  296. break;
  297. case 3:
  298. default:
  299. color = [f3(ch1), f3(ch2), f3(ch3), f3(ch4), letterArray[2]].join(" ");
  300. }
  301. }
  302. }
  303. return color;
  304. },
  305. convertDateToPDFDate = function convertDateToPDFDate(parmDate) {
  306. var padd2 = function padd2(number) {
  307. return ('0' + parseInt(number)).slice(-2);
  308. };
  309. var result = '';
  310. var tzoffset = parmDate.getTimezoneOffset(),
  311. tzsign = tzoffset < 0 ? '+' : '-',
  312. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  313. tzmin = Math.abs(tzoffset % 60),
  314. timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  315. result = ['D:', parmDate.getFullYear(), padd2(parmDate.getMonth() + 1), padd2(parmDate.getDate()), padd2(parmDate.getHours()), padd2(parmDate.getMinutes()), padd2(parmDate.getSeconds()), timeZoneString].join('');
  316. return result;
  317. },
  318. convertPDFDateToDate = function convertPDFDateToDate(parmPDFDate) {
  319. var year = parseInt(parmPDFDate.substr(2, 4), 10);
  320. var month = parseInt(parmPDFDate.substr(6, 2), 10) - 1;
  321. var date = parseInt(parmPDFDate.substr(8, 2), 10);
  322. var hour = parseInt(parmPDFDate.substr(10, 2), 10);
  323. var minutes = parseInt(parmPDFDate.substr(12, 2), 10);
  324. var seconds = parseInt(parmPDFDate.substr(14, 2), 10);
  325. var timeZoneHour = parseInt(parmPDFDate.substr(16, 2), 10);
  326. var timeZoneMinutes = parseInt(parmPDFDate.substr(20, 2), 10);
  327. var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);
  328. return resultingDate;
  329. },
  330. setCreationDate = function setCreationDate(date) {
  331. var tmpCreationDateString;
  332. var regexPDFCreationDate = /^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|\-0[0-9]|\-1[0-1])\'(0[0-9]|[1-5][0-9])\'?$/;
  333. if ((typeof date === 'undefined' ? 'undefined' : _typeof(date)) === undefined) {
  334. date = new Date();
  335. }
  336. if ((typeof date === 'undefined' ? 'undefined' : _typeof(date)) === "object" && Object.prototype.toString.call(date) === "[object Date]") {
  337. tmpCreationDateString = convertDateToPDFDate(date);
  338. } else if (regexPDFCreationDate.test(date)) {
  339. tmpCreationDateString = date;
  340. } else {
  341. tmpCreationDateString = convertDateToPDFDate(new Date());
  342. }
  343. creationDate = tmpCreationDateString;
  344. return creationDate;
  345. },
  346. getCreationDate = function getCreationDate(type) {
  347. var result = creationDate;
  348. if (type === "jsDate") {
  349. result = convertPDFDateToDate(creationDate);
  350. }
  351. return result;
  352. },
  353. setFileId = function setFileId(value) {
  354. value = value || "12345678901234567890123456789012".split('').map(function () {
  355. return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16));
  356. }).join('');
  357. fileId = value;
  358. return fileId;
  359. },
  360. getFileId = function getFileId() {
  361. return fileId;
  362. },
  363. f2 = function f2(number) {
  364. return number.toFixed(2); // Ie, %.2f
  365. },
  366. f3 = function f3(number) {
  367. return number.toFixed(3); // Ie, %.3f
  368. },
  369. out = function out(string) {
  370. string = typeof string === "string" ? string : string.toString();
  371. if (outToPages) {
  372. /* set by beginPage */
  373. pages[currentPage].push(string);
  374. } else {
  375. // +1 for '\n' that will be used to join 'content'
  376. content_length += string.length + 1;
  377. content.push(string);
  378. }
  379. },
  380. newObject = function newObject() {
  381. // Begin a new object
  382. objectNumber++;
  383. offsets[objectNumber] = content_length;
  384. out(objectNumber + ' 0 obj');
  385. return objectNumber;
  386. },
  387. // Does not output the object until after the pages have been output.
  388. // Returns an object containing the objectId and content.
  389. // All pages have been added so the object ID can be estimated to start right after.
  390. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  391. newAdditionalObject = function newAdditionalObject() {
  392. var objId = pages.length * 2 + 1;
  393. objId += additionalObjects.length;
  394. var obj = {
  395. objId: objId,
  396. content: ''
  397. };
  398. additionalObjects.push(obj);
  399. return obj;
  400. },
  401. // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  402. newObjectDeferred = function newObjectDeferred() {
  403. objectNumber++;
  404. offsets[objectNumber] = function () {
  405. return content_length;
  406. };
  407. return objectNumber;
  408. },
  409. newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
  410. offsets[oid] = content_length;
  411. },
  412. putStream = function putStream(str) {
  413. out('stream');
  414. out(str);
  415. out('endstream');
  416. },
  417. putPages = function putPages() {
  418. var n,
  419. p,
  420. arr,
  421. i,
  422. deflater,
  423. adler32,
  424. adler32cs,
  425. wPt,
  426. hPt,
  427. pageObjectNumbers = [];
  428. adler32cs = global.adler32cs || jsPDF.API.adler32cs;
  429. if (compress && typeof adler32cs === 'undefined') {
  430. compress = false;
  431. }
  432. // outToPages = false as set in endDocument(). out() writes to content.
  433. for (n = 1; n <= page; n++) {
  434. pageObjectNumbers.push(newObject());
  435. wPt = (pageWidth = pagedim[n].width) * k;
  436. hPt = (pageHeight = pagedim[n].height) * k;
  437. out('<</Type /Page');
  438. out('/Parent 1 0 R');
  439. out('/Resources 2 0 R');
  440. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  441. // Added for annotation plugin
  442. events.publish('putPage', {
  443. pageNumber: n,
  444. page: pages[n]
  445. });
  446. out('/Contents ' + (objectNumber + 1) + ' 0 R');
  447. out('>>');
  448. out('endobj');
  449. // Page content
  450. p = pages[n].join('\n');
  451. newObject();
  452. if (compress) {
  453. arr = [];
  454. i = p.length;
  455. while (i--) {
  456. arr[i] = p.charCodeAt(i);
  457. }
  458. adler32 = adler32cs.from(p);
  459. deflater = new Deflater(6);
  460. deflater.append(new Uint8Array(arr));
  461. p = deflater.flush();
  462. arr = new Uint8Array(p.length + 6);
  463. arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
  464. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
  465. p = String.fromCharCode.apply(null, arr);
  466. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  467. } else {
  468. out('<</Length ' + p.length + '>>');
  469. }
  470. putStream(p);
  471. out('endobj');
  472. }
  473. offsets[1] = content_length;
  474. out('1 0 obj');
  475. out('<</Type /Pages');
  476. var kids = '/Kids [';
  477. for (i = 0; i < page; i++) {
  478. kids += pageObjectNumbers[i] + ' 0 R ';
  479. }
  480. out(kids + ']');
  481. out('/Count ' + page);
  482. out('>>');
  483. out('endobj');
  484. events.publish('postPutPages');
  485. },
  486. putFont = function putFont(font) {
  487. events.publish('putFont', {
  488. font: font,
  489. out: out,
  490. newObject: newObject
  491. });
  492. if (font.isAlreadyPutted !== true) {
  493. font.objectNumber = newObject();
  494. out('<<');
  495. out('/Type /Font');
  496. out('/BaseFont /' + font.postScriptName);
  497. out('/Subtype /Type1');
  498. if (typeof font.encoding === 'string') {
  499. out('/Encoding /' + font.encoding);
  500. }
  501. out('/FirstChar 32');
  502. out('/LastChar 255');
  503. out('>>');
  504. out('endobj');
  505. }
  506. },
  507. putFonts = function putFonts() {
  508. for (var fontKey in fonts) {
  509. if (fonts.hasOwnProperty(fontKey)) {
  510. putFont(fonts[fontKey]);
  511. }
  512. }
  513. },
  514. putXobjectDict = function putXobjectDict() {
  515. // Loop through images, or other data objects
  516. events.publish('putXobjectDict');
  517. },
  518. putResourceDictionary = function putResourceDictionary() {
  519. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  520. out('/Font <<');
  521. // Do this for each font, the '1' bit is the index of the font
  522. for (var fontKey in fonts) {
  523. if (fonts.hasOwnProperty(fontKey)) {
  524. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  525. }
  526. }
  527. out('>>');
  528. out('/XObject <<');
  529. putXobjectDict();
  530. out('>>');
  531. },
  532. putResources = function putResources() {
  533. putFonts();
  534. events.publish('putResources');
  535. // Resource dictionary
  536. offsets[2] = content_length;
  537. out('2 0 obj');
  538. out('<<');
  539. putResourceDictionary();
  540. out('>>');
  541. out('endobj');
  542. events.publish('postPutResources');
  543. },
  544. putAdditionalObjects = function putAdditionalObjects() {
  545. events.publish('putAdditionalObjects');
  546. for (var i = 0; i < additionalObjects.length; i++) {
  547. var obj = additionalObjects[i];
  548. offsets[obj.objId] = content_length;
  549. out(obj.objId + ' 0 obj');
  550. out(obj.content); out('endobj');
  551. }
  552. objectNumber += additionalObjects.length;
  553. events.publish('postPutAdditionalObjects');
  554. },
  555. addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  556. // this is mapping structure for quick font key lookup.
  557. // returns the KEY of the font (ex: "F1") for a given
  558. // pair of font name and type (ex: "Arial". "Italic")
  559. if (!fontmap.hasOwnProperty(fontName)) {
  560. fontmap[fontName] = {};
  561. }
  562. fontmap[fontName][fontStyle] = fontKey;
  563. },
  564. /**
  565. * FontObject describes a particular font as member of an instnace of jsPDF
  566. *
  567. * It's a collection of properties like 'id' (to be used in PDF stream),
  568. * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  569. *
  570. * @class
  571. * @public
  572. * @property id {String} PDF-document-instance-specific label assinged to the font.
  573. * @property postScriptName {String} PDF specification full name for the font
  574. * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  575. * @name FontObject
  576. * @ignore This should not be in the public docs.
  577. */
  578. addFont = function addFont(postScriptName, fontName, fontStyle, encoding) {
  579. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  580. // This is FontObject
  581. font = fonts[fontKey] = {
  582. 'id': fontKey,
  583. 'postScriptName': postScriptName,
  584. 'fontName': fontName,
  585. 'fontStyle': fontStyle,
  586. 'encoding': encoding,
  587. 'metadata': {}
  588. };
  589. addToFontDictionary(fontKey, fontName, fontStyle);
  590. events.publish('addFont', font);
  591. return fontKey;
  592. },
  593. addFonts = function addFonts() {
  594. var HELVETICA = "helvetica",
  595. TIMES = "times",
  596. COURIER = "courier",
  597. NORMAL = "normal",
  598. BOLD = "bold",
  599. ITALIC = "italic",
  600. BOLD_ITALIC = "bolditalic",
  601. ZAPF = "zapfdingbats",
  602. SYMBOL = "symbol",
  603. standardFonts = [['Helvetica', HELVETICA, NORMAL, 'WinAnsiEncoding'], ['Helvetica-Bold', HELVETICA, BOLD, 'WinAnsiEncoding'], ['Helvetica-Oblique', HELVETICA, ITALIC, 'WinAnsiEncoding'], ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC, 'WinAnsiEncoding'], ['Courier', COURIER, NORMAL, 'WinAnsiEncoding'], ['Courier-Bold', COURIER, BOLD, 'WinAnsiEncoding'], ['Courier-Oblique', COURIER, ITALIC, 'WinAnsiEncoding'], ['Courier-BoldOblique', COURIER, BOLD_ITALIC, 'WinAnsiEncoding'], ['Times-Roman', TIMES, NORMAL, 'WinAnsiEncoding'], ['Times-Bold', TIMES, BOLD, 'WinAnsiEncoding'], ['Times-Italic', TIMES, ITALIC, 'WinAnsiEncoding'], ['Times-BoldItalic', TIMES, BOLD_ITALIC, 'WinAnsiEncoding'], ['ZapfDingbats', ZAPF, NORMAL, null], ['Symbol', SYMBOL, NORMAL, null]];
  604. for (var i = 0, l = standardFonts.length; i < l; i++) {
  605. var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], standardFonts[i][3]);
  606. // adding aliases for standard fonts, this time matching the capitalization
  607. var parts = standardFonts[i][0].split('-');
  608. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  609. }
  610. events.publish('addFonts', {
  611. fonts: fonts,
  612. dictionary: fontmap
  613. });
  614. },
  615. SAFE = function __safeCall(fn) {
  616. fn.foo = function __safeCallWrapper() {
  617. try {
  618. return fn.apply(this, arguments);
  619. } catch (e) {
  620. var stack = e.stack || '';
  621. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  622. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  623. if (global.console) {
  624. global.console.error(m, e);
  625. if (global.alert) alert(m);
  626. } else {
  627. throw new Error(m);
  628. }
  629. }
  630. };
  631. fn.foo.bar = fn;
  632. return fn.foo;
  633. },
  634. to8bitStream = function to8bitStream(text, flags) {
  635. /**
  636. * PDF 1.3 spec:
  637. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  638. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  639. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  640. * to be a meaningful beginning of a word or phrase.) The remainder of the
  641. * string consists of Unicode character codes, according to the UTF-16 encoding
  642. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  643. * are represented as 2 bytes per character, with the high-order byte appearing first
  644. * in the string."
  645. *
  646. * In other words, if there are chars in a string with char code above 255, we
  647. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  648. *
  649. * HOWEVER!
  650. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  651. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  652. *
  653. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  654. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  655. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  656. * code page. There, however, all characters in the stream are treated as GIDs,
  657. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  658. * that is tied to a font).
  659. *
  660. * To signal this "special" PDFEscape / to8bitStream handling mode,
  661. * API.text() function sets (unless you overwrite it with manual values
  662. * given to API.text(.., flags) )
  663. * flags.autoencode = true
  664. * flags.noBOM = true
  665. *
  666. * ===================================================================================
  667. * `flags` properties relied upon:
  668. * .sourceEncoding = string with encoding label.
  669. * "Unicode" by default. = encoding of the incoming text.
  670. * pass some non-existing encoding name
  671. * (ex: 'Do not touch my strings! I know what I am doing.')
  672. * to make encoding code skip the encoding step.
  673. * .outputEncoding = Either valid PDF encoding name
  674. * (must be supported by jsPDF font metrics, otherwise no encoding)
  675. * or a JS object, where key = sourceCharCode, value = outputCharCode
  676. * missing keys will be treated as: sourceCharCode === outputCharCode
  677. * .noBOM
  678. * See comment higher above for explanation for why this is important
  679. * .autoencode
  680. * See comment higher above for explanation for why this is important
  681. */
  682. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  683. flags = flags || {};
  684. sourceEncoding = flags.sourceEncoding || 'Unicode';
  685. outputEncoding = flags.outputEncoding;
  686. // This 'encoding' section relies on font metrics format
  687. // attached to font objects by, among others,
  688. // "Willow Systems' standard_font_metrics plugin"
  689. // see jspdf.plugin.standard_font_metrics.js for format
  690. // of the font.metadata.encoding Object.
  691. // It should be something like
  692. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  693. // .widths = {0:width, code:width, ..., 'fof':divisor}
  694. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  695. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  696. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  697. // each font has default encoding. Some have it clearly defined.
  698. if (!outputEncoding && fonts[activeFontKey].encoding) {
  699. outputEncoding = fonts[activeFontKey].encoding;
  700. }
  701. // Hmmm, the above did not work? Let's try again, in different place.
  702. if (!outputEncoding && encodingBlock.codePages) {
  703. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  704. }
  705. if (typeof outputEncoding === 'string') {
  706. outputEncoding = encodingBlock[outputEncoding];
  707. }
  708. // we want output encoding to be a JS Object, where
  709. // key = sourceEncoding's character code and
  710. // value = outputEncoding's character code.
  711. if (outputEncoding) {
  712. isUnicode = false;
  713. newtext = [];
  714. for (i = 0, l = text.length; i < l; i++) {
  715. ch = outputEncoding[text.charCodeAt(i)];
  716. if (ch) {
  717. newtext.push(String.fromCharCode(ch));
  718. } else {
  719. newtext.push(text[i]);
  720. }
  721. // since we are looping over chars anyway, might as well
  722. // check for residual unicodeness
  723. if (newtext[i].charCodeAt(0) >> 8) {
  724. /* more than 255 */
  725. isUnicode = true;
  726. }
  727. }
  728. text = newtext.join('');
  729. }
  730. }
  731. i = text.length;
  732. // isUnicode may be set to false above. Hence the triple-equal to undefined
  733. while (isUnicode === undefined && i !== 0) {
  734. if (text.charCodeAt(i - 1) >> 8) {
  735. /* more than 255 */
  736. isUnicode = true;
  737. }
  738. i--;
  739. }
  740. if (!isUnicode) {
  741. return text;
  742. }
  743. newtext = flags.noBOM ? [] : [254, 255];
  744. for (i = 0, l = text.length; i < l; i++) {
  745. ch = text.charCodeAt(i);
  746. bch = ch >> 8; // divide by 256
  747. if (bch >> 8) {
  748. /* something left after dividing by 256 second time */
  749. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  750. }
  751. newtext.push(bch);
  752. newtext.push(ch - (bch << 8));
  753. }
  754. return String.fromCharCode.apply(undefined, newtext);
  755. },
  756. pdfEscape = function pdfEscape(text, flags) {
  757. /**
  758. * Replace '/', '(', and ')' with pdf-safe versions
  759. *
  760. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  761. * we also need to reference a unicode font and embed it - royal pain in the rear.
  762. *
  763. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  764. * which JavaScript Strings are happy to provide. So, while we still cannot display
  765. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  766. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  767. * is still parseable.
  768. * This will allow immediate support for unicode in document properties strings.
  769. */
  770. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  771. },
  772. putInfo = function putInfo() {
  773. out('/Producer (jsPDF ' + jsPDF.version + ')');
  774. for (var key in documentProperties) {
  775. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  776. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  777. }
  778. }
  779. out('/CreationDate (' + creationDate + ')');
  780. },
  781. putCatalog = function putCatalog() {
  782. out('/Type /Catalog');
  783. out('/Pages 1 0 R');
  784. // PDF13ref Section 7.2.1
  785. if (!zoomMode) zoomMode = 'fullwidth';
  786. switch (zoomMode) {
  787. case 'fullwidth':
  788. out('/OpenAction [3 0 R /FitH null]');
  789. break;
  790. case 'fullheight':
  791. out('/OpenAction [3 0 R /FitV null]');
  792. break;
  793. case 'fullpage':
  794. out('/OpenAction [3 0 R /Fit]');
  795. break;
  796. case 'original':
  797. out('/OpenAction [3 0 R /XYZ null null 1]');
  798. break;
  799. default:
  800. var pcn = '' + zoomMode;
  801. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  802. if (typeof zoomMode === 'number') {
  803. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  804. }
  805. }
  806. if (!layoutMode) layoutMode = 'continuous';
  807. switch (layoutMode) {
  808. case 'continuous':
  809. out('/PageLayout /OneColumn');
  810. break;
  811. case 'single':
  812. out('/PageLayout /SinglePage');
  813. break;
  814. case 'two':
  815. case 'twoleft':
  816. out('/PageLayout /TwoColumnLeft');
  817. break;
  818. case 'tworight':
  819. out('/PageLayout /TwoColumnRight');
  820. break;
  821. }
  822. if (pageMode) {
  823. /**
  824. * A name object specifying how the document should be displayed when opened:
  825. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  826. * UseOutlines : Document outline visible
  827. * UseThumbs : Thumbnail images visible
  828. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  829. */
  830. out('/PageMode /' + pageMode);
  831. }
  832. events.publish('putCatalog');
  833. },
  834. putTrailer = function putTrailer() {
  835. out('/Size ' + (objectNumber + 1));
  836. out('/Root ' + objectNumber + ' 0 R');
  837. out('/Info ' + (objectNumber - 1) + ' 0 R');
  838. out("/ID [ <" + fileId + "> <" + fileId + "> ]");
  839. },
  840. beginPage = function beginPage(width, height) {
  841. // Dimensions are stored as user units and converted to points on output
  842. var orientation = typeof height === 'string' && height.toLowerCase();
  843. if (typeof width === 'string') {
  844. var format = width.toLowerCase();
  845. if (pageFormats.hasOwnProperty(format)) {
  846. width = pageFormats[format][0] / k;
  847. height = pageFormats[format][1] / k;
  848. }
  849. }
  850. if (Array.isArray(width)) {
  851. height = width[1];
  852. width = width[0];
  853. }
  854. if (orientation) {
  855. switch (orientation.substr(0, 1)) {
  856. case 'l':
  857. if (height > width) orientation = 's';
  858. break;
  859. case 'p':
  860. if (width > height) orientation = 's';
  861. break;
  862. }
  863. if (orientation === 's') {
  864. tmp = width;
  865. width = height;
  866. height = tmp;
  867. }
  868. }
  869. outToPages = true;
  870. pages[++page] = [];
  871. pagedim[page] = {
  872. width: Number(width) || pageWidth,
  873. height: Number(height) || pageHeight
  874. };
  875. pagesContext[page] = {};
  876. _setPage(page);
  877. },
  878. _addPage = function _addPage() {
  879. beginPage.apply(this, arguments);
  880. // Set line width
  881. out(f2(lineWidth * k) + ' w');
  882. // Set draw color
  883. out(drawColor);
  884. // resurrecting non-default line caps, joins
  885. if (lineCapID !== 0) {
  886. out(lineCapID + ' J');
  887. }
  888. if (lineJoinID !== 0) {
  889. out(lineJoinID + ' j');
  890. }
  891. events.publish('addPage', {
  892. pageNumber: page
  893. });
  894. },
  895. _deletePage = function _deletePage(n) {
  896. if (n > 0 && n <= page) {
  897. pages.splice(n, 1);
  898. pagedim.splice(n, 1);
  899. page--;
  900. if (currentPage > page) {
  901. currentPage = page;
  902. }
  903. this.setPage(currentPage);
  904. }
  905. },
  906. _setPage = function _setPage(n) {
  907. if (n > 0 && n <= page) {
  908. currentPage = n;
  909. pageWidth = pagedim[n].width;
  910. pageHeight = pagedim[n].height;
  911. }
  912. },
  913. /**
  914. * Returns a document-specific font key - a label assigned to a
  915. * font name + font type combination at the time the font was added
  916. * to the font inventory.
  917. *
  918. * Font key is used as label for the desired font for a block of text
  919. * to be added to the PDF document stream.
  920. * @private
  921. * @function
  922. * @param fontName {String} can be undefined on "falthy" to indicate "use current"
  923. * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  924. * @returns {String} Font key.
  925. */
  926. _getFont = function _getFont(fontName, fontStyle, options) {
  927. var key = undefined,
  928. fontNameLowerCase;
  929. options = options || {};
  930. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  931. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  932. fontNameLowerCase = fontName.toLowerCase();
  933. if (fontmap[fontNameLowerCase] !== undefined && fontmap[fontNameLowerCase][fontStyle] !== undefined) {
  934. key = fontmap[fontNameLowerCase][fontStyle];
  935. } else if (fontmap[fontName] !== undefined && fontmap[fontName][fontStyle] !== undefined) {
  936. key = fontmap[fontName][fontStyle];
  937. } else {
  938. if (options.disableWarning === false) {
  939. console.warn("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
  940. }
  941. }
  942. if (!key && !options.noFallback) {
  943. key = fontmap['times'][fontStyle];
  944. if (key == null) {
  945. key = fontmap['times']['normal'];
  946. }
  947. }
  948. return key;
  949. },
  950. buildDocument = function buildDocument() {
  951. outToPages = false; // switches out() to content
  952. objectNumber = 2;
  953. content_length = 0;
  954. content = [];
  955. offsets = [];
  956. additionalObjects = [];
  957. // Added for AcroForm
  958. events.publish('buildDocument');
  959. // putHeader()
  960. out('%PDF-' + pdfVersion);
  961. out("%\xBA\xDF\xAC\xE0");
  962. putPages();
  963. // Must happen after putPages
  964. // Modifies current object Id
  965. putAdditionalObjects();
  966. putResources();
  967. // Info
  968. newObject();
  969. out('<<');
  970. putInfo();
  971. out('>>');
  972. out('endobj');
  973. // Catalog
  974. newObject();
  975. out('<<');
  976. putCatalog();
  977. out('>>');
  978. out('endobj');
  979. // Cross-ref
  980. var o = content_length,
  981. i,
  982. p = "0000000000";
  983. out('xref');
  984. out('0 ' + (objectNumber + 1));
  985. out(p + ' 65535 f ');
  986. for (i = 1; i <= objectNumber; i++) {
  987. var offset = offsets[i];
  988. if (typeof offset === 'function') {
  989. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  990. } else {
  991. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  992. }
  993. }
  994. // Trailer
  995. out('trailer');
  996. out('<<');
  997. putTrailer();
  998. out('>>');
  999. out('startxref');
  1000. out('' + o);
  1001. out('%%EOF');
  1002. outToPages = true;
  1003. return content.join('\n');
  1004. },
  1005. getStyle = function getStyle(style) {
  1006. // see path-painting operators in PDF spec
  1007. var op = 'S'; // stroke
  1008. if (style === 'F') {
  1009. op = 'f'; // fill
  1010. } else if (style === 'FD' || style === 'DF') {
  1011. op = 'B'; // both
  1012. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  1013. /*
  1014. Allow direct use of these PDF path-painting operators:
  1015. - f fill using nonzero winding number rule
  1016. - f* fill using even-odd rule
  1017. - B fill then stroke with fill using non-zero winding number rule
  1018. - B* fill then stroke with fill using even-odd rule
  1019. */
  1020. op = style;
  1021. }
  1022. return op;
  1023. },
  1024. getArrayBuffer = function getArrayBuffer() {
  1025. var data = buildDocument(),
  1026. len = data.length,
  1027. ab = new ArrayBuffer(len),
  1028. u8 = new Uint8Array(ab);
  1029. while (len--) {
  1030. u8[len] = data.charCodeAt(len);
  1031. }return ab;
  1032. },
  1033. getBlob = function getBlob() {
  1034. return new Blob([getArrayBuffer()], {
  1035. type: "application/pdf"
  1036. });
  1037. },
  1038. /**
  1039. * Generates the PDF document.
  1040. *
  1041. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1042. *
  1043. * @param {String} type A string identifying one of the possible output types.
  1044. * @param {Object} options An object providing some additional signalling to PDF generator.
  1045. * @function
  1046. * @returns {jsPDF}
  1047. * @methodOf jsPDF#
  1048. * @name output
  1049. */
  1050. _output = SAFE(function (type, options) {
  1051. var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
  1052. switch (type) {
  1053. case undefined:
  1054. return buildDocument();
  1055. case 'save':
  1056. if ((typeof navigator === 'undefined' ? 'undefined' : _typeof(navigator)) === "object" && navigator.getUserMedia) {
  1057. if (global.URL === undefined || global.URL.createObjectURL === undefined) {
  1058. return API.output('dataurlnewwindow');
  1059. }
  1060. }
  1061. saveAs(getBlob(), options);
  1062. if (typeof saveAs.unload === 'function') {
  1063. if (global.setTimeout) {
  1064. setTimeout(saveAs.unload, 911);
  1065. }
  1066. }
  1067. break;
  1068. case 'arraybuffer':
  1069. return getArrayBuffer();
  1070. case 'blob':
  1071. return getBlob();
  1072. case 'bloburi':
  1073. case 'bloburl':
  1074. // User is responsible of calling revokeObjectURL
  1075. return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
  1076. case 'datauristring':
  1077. case 'dataurlstring':
  1078. return datauri;
  1079. case 'dataurlnewwindow':
  1080. var nW = global.open(datauri);
  1081. if (nW || typeof safari === "undefined") return nW;
  1082. /* pass through */
  1083. case 'datauri':
  1084. case 'dataurl':
  1085. return global.document.location.href = datauri;
  1086. default:
  1087. throw new Error('Output type "' + type + '" is not supported.');
  1088. }
  1089. // @TODO: Add different output options
  1090. }),
  1091. /**
  1092. * Used to see if a supplied hotfix was requested when the pdf instance was created.
  1093. * @param {String} hotfixName - The name of the hotfix to check.
  1094. * @returns {boolean}
  1095. */
  1096. hasHotfix = function hasHotfix(hotfixName) {
  1097. return Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1;
  1098. };
  1099. switch (unit) {
  1100. case 'pt':
  1101. k = 1;
  1102. break;
  1103. case 'mm':
  1104. k = 72 / 25.4;
  1105. break;
  1106. case 'cm':
  1107. k = 72 / 2.54;
  1108. break;
  1109. case 'in':
  1110. k = 72;
  1111. break;
  1112. case 'px':
  1113. if (hasHotfix('px_scaling') == true) {
  1114. k = 72 / 96;
  1115. } else {
  1116. k = 96 / 72;
  1117. }
  1118. break;
  1119. case 'pc':
  1120. k = 12;
  1121. break;
  1122. case 'em':
  1123. k = 12;
  1124. break;
  1125. case 'ex':
  1126. k = 6;
  1127. break;
  1128. default:
  1129. throw 'Invalid unit: ' + unit;
  1130. }
  1131. setCreationDate();
  1132. setFileId();
  1133. //---------------------------------------
  1134. // Public API
  1135. /**
  1136. * Object exposing internal API to plugins
  1137. * @public
  1138. */
  1139. API.internal = {
  1140. 'pdfEscape': pdfEscape,
  1141. 'getStyle': getStyle,
  1142. /**
  1143. * Returns {FontObject} describing a particular font.
  1144. * @public
  1145. * @function
  1146. * @param fontName {String} (Optional) Font's family name
  1147. * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  1148. * @returns {FontObject}
  1149. */
  1150. 'getFont': function getFont() {
  1151. return fonts[_getFont.apply(API, arguments)];
  1152. },
  1153. 'getFontSize': function getFontSize() {
  1154. return activeFontSize;
  1155. },
  1156. 'getCharSpace': function getCharSpace() {
  1157. return activeCharSpace;
  1158. },
  1159. 'getTextColor': function getTextColor() {
  1160. var colorEncoded = textColor.split(' ');
  1161. if (colorEncoded.length === 2 && colorEncoded[1] === 'g') {
  1162. // convert grayscale value to rgb so that it can be converted to hex for consistency
  1163. var floatVal = parseFloat(colorEncoded[0]);
  1164. colorEncoded = [floatVal, floatVal, floatVal, 'r'];
  1165. }
  1166. var colorAsHex = '#';
  1167. for (var i = 0; i < 3; i++) {
  1168. colorAsHex += ('0' + Math.floor(parseFloat(colorEncoded[i]) * 255).toString(16)).slice(-2);
  1169. }
  1170. return colorAsHex;
  1171. },
  1172. 'getLineHeight': function getLineHeight() {
  1173. return activeFontSize * lineHeightProportion;
  1174. },
  1175. 'write': function write(string1 /*, string2, string3, etc */) {
  1176. out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
  1177. },
  1178. 'getCoordinateString': function getCoordinateString(value) {
  1179. return f2(value * k);
  1180. },
  1181. 'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
  1182. return f2((pageHeight - value) * k);
  1183. },
  1184. 'collections': {},
  1185. 'newObject': newObject,
  1186. 'newAdditionalObject': newAdditionalObject,
  1187. 'newObjectDeferred': newObjectDeferred,
  1188. 'newObjectDeferredBegin': newObjectDeferredBegin,
  1189. 'putStream': putStream,
  1190. 'events': events,
  1191. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  1192. // units of measurement.
  1193. // scaleFactor is set at initialization of the document and calculated against the stated
  1194. // default measurement units for the document.
  1195. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  1196. // through multiplication.
  1197. 'scaleFactor': k,
  1198. 'pageSize': {
  1199. getWidth: function getWidth() {
  1200. return pageWidth;
  1201. },
  1202. getHeight: function getHeight() {
  1203. return pageHeight;
  1204. }
  1205. },
  1206. 'output': function output(type, options) {
  1207. return _output(type, options);
  1208. },
  1209. 'getNumberOfPages': function getNumberOfPages() {
  1210. return pages.length - 1;
  1211. },
  1212. 'pages': pages,
  1213. 'out': out,
  1214. 'f2': f2,
  1215. 'getPageInfo': function getPageInfo(pageNumberOneBased) {
  1216. var objId = (pageNumberOneBased - 1) * 2 + 3;
  1217. return {
  1218. objId: objId,
  1219. pageNumber: pageNumberOneBased,
  1220. pageContext: pagesContext[pageNumberOneBased]
  1221. };
  1222. },
  1223. 'getCurrentPageInfo': function getCurrentPageInfo() {
  1224. var objId = (currentPage - 1) * 2 + 3;
  1225. return {
  1226. objId: objId,
  1227. pageNumber: currentPage,
  1228. pageContext: pagesContext[currentPage]
  1229. };
  1230. },
  1231. 'getPDFVersion': function getPDFVersion() {
  1232. return pdfVersion;
  1233. },
  1234. 'hasHotfix': hasHotfix //Expose the hasHotfix check so plugins can also check them.
  1235. };
  1236. /**
  1237. * Adds (and transfers the focus to) new page to the PDF document.
  1238. * @param format {String/Array} The format of the new page. Can be <ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
  1239. * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array , e.g. [595.28, 841.89]
  1240. * @param orientation {String} Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l")
  1241. * @function
  1242. * @returns {jsPDF}
  1243. *
  1244. * @methodOf jsPDF#
  1245. * @name addPage
  1246. */
  1247. API.addPage = function () {
  1248. _addPage.apply(this, arguments);
  1249. return this;
  1250. };
  1251. /**
  1252. * Adds (and transfers the focus to) new page to the PDF document.
  1253. * @function
  1254. * @returns {jsPDF}
  1255. *
  1256. * @methodOf jsPDF#
  1257. * @name setPage
  1258. * @param {Number} page Switch the active page to the page number specified
  1259. * @example
  1260. * doc = jsPDF()
  1261. * doc.addPage()
  1262. * doc.addPage()
  1263. * doc.text('I am on page 3', 10, 10)
  1264. * doc.setPage(1)
  1265. * doc.text('I am on page 1', 10, 10)
  1266. */
  1267. API.setPage = function () {
  1268. _setPage.apply(this, arguments);
  1269. return this;
  1270. };
  1271. API.insertPage = function (beforePage) {
  1272. this.addPage();
  1273. this.movePage(currentPage, beforePage);
  1274. return this;
  1275. };
  1276. API.movePage = function (targetPage, beforePage) {
  1277. if (targetPage > beforePage) {
  1278. var tmpPages = pages[targetPage];
  1279. var tmpPagedim = pagedim[targetPage];
  1280. var tmpPagesContext = pagesContext[targetPage];
  1281. for (var i = targetPage; i > beforePage; i--) {
  1282. pages[i] = pages[i - 1];
  1283. pagedim[i] = pagedim[i - 1];
  1284. pagesContext[i] = pagesContext[i - 1];
  1285. }
  1286. pages[beforePage] = tmpPages;
  1287. pagedim[beforePage] = tmpPagedim;
  1288. pagesContext[beforePage] = tmpPagesContext;
  1289. this.setPage(beforePage);
  1290. } else if (targetPage < beforePage) {
  1291. var tmpPages = pages[targetPage];
  1292. var tmpPagedim = pagedim[targetPage];
  1293. var tmpPagesContext = pagesContext[targetPage];
  1294. for (var i = targetPage; i < beforePage; i++) {
  1295. pages[i] = pages[i + 1];
  1296. pagedim[i] = pagedim[i + 1];
  1297. pagesContext[i] = pagesContext[i + 1];
  1298. }
  1299. pages[beforePage] = tmpPages;
  1300. pagedim[beforePage] = tmpPagedim;
  1301. pagesContext[beforePage] = tmpPagesContext;
  1302. this.setPage(beforePage);
  1303. }
  1304. return this;
  1305. };
  1306. API.deletePage = function () {
  1307. _deletePage.apply(this, arguments);
  1308. return this;
  1309. };
  1310. API.setCreationDate = function (date) {
  1311. setCreationDate(date);
  1312. return this;
  1313. };
  1314. API.getCreationDate = function (type) {
  1315. return getCreationDate(type);
  1316. };
  1317. API.setFileId = function (value) {
  1318. setFileId(value);
  1319. return this;
  1320. };
  1321. API.getFileId = function () {
  1322. return getFileId();
  1323. };
  1324. /**
  1325. * Set the display mode options of the page like zoom and layout.
  1326. *
  1327. * @param {integer|String} zoom You can pass an integer or percentage as
  1328. * a string. 2 will scale the document up 2x, '200%' will scale up by the
  1329. * same amount. You can also set it to 'fullwidth', 'fullheight',
  1330. * 'fullpage', or 'original'.
  1331. *
  1332. * Only certain PDF readers support this, such as Adobe Acrobat
  1333. *
  1334. * @param {String} layout Layout mode can be: 'continuous' - this is the
  1335. * default continuous scroll. 'single' - the single page mode only shows one
  1336. * page at a time. 'twoleft' - two column left mode, first page starts on
  1337. * the left, and 'tworight' - pages are laid out in two columns, with the
  1338. * first page on the right. This would be used for books.
  1339. * @param {String} pmode 'UseOutlines' - it shows the
  1340. * outline of the document on the left. 'UseThumbs' - shows thumbnails along
  1341. * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
  1342. *
  1343. * @function
  1344. * @returns {jsPDF}
  1345. * @name setDisplayMode
  1346. */
  1347. API.setDisplayMode = function (zoom, layout, pmode) {
  1348. zoomMode = zoom;
  1349. layoutMode = layout;
  1350. pageMode = pmode;
  1351. var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
  1352. if (validPageModes.indexOf(pmode) == -1) {
  1353. throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
  1354. }
  1355. return this;
  1356. };
  1357. /**
  1358. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1359. *
  1360. * @function
  1361. * @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.
  1362. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1363. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1364. * @param {Object} options 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.
  1365. * @returns {jsPDF}
  1366. * @methodOf jsPDF#
  1367. * @name text
  1368. */
  1369. API.text = function (text, x, y, options) {
  1370. /**
  1371. * Inserts something like this into PDF
  1372. * BT
  1373. * /F1 16 Tf % Font name + size
  1374. * 16 TL % How many units down for next line in multiline text
  1375. * 0 g % color
  1376. * 28.35 813.54 Td % position
  1377. * (line one) Tj
  1378. * T* (line two) Tj
  1379. * T* (line three) Tj
  1380. * ET
  1381. */
  1382. var xtra = '';
  1383. var isHex = false;
  1384. var lineHeight = lineHeightProportion;
  1385. var scope = this;
  1386. function ESC(s) {
  1387. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1388. return pdfEscape(s, flags);
  1389. }
  1390. function transformTextToSpecialArray(text) {
  1391. //we don't want to destroy original text array, so cloning it
  1392. var sa = text.concat();
  1393. var da = [];
  1394. var len = sa.length;
  1395. var curDa;
  1396. //we do array.join('text that must not be PDFescaped")
  1397. //thus, pdfEscape each component separately
  1398. while (len--) {
  1399. curDa = sa.shift();
  1400. if (typeof curDa === "string") {
  1401. da.push(curDa);
  1402. } else {
  1403. if (Object.prototype.toString.call(text) === '[object Array]' && curDa.length === 1) {
  1404. da.push(curDa[0]);
  1405. } else {
  1406. da.push([curDa[0], curDa[1], curDa[2]]);
  1407. }
  1408. }
  1409. }
  1410. return da;
  1411. }
  1412. function processTextByFunction(text, processingFunction) {
  1413. var result;
  1414. if (typeof text === 'string') {
  1415. result = processingFunction(text)[0];
  1416. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1417. //we don't want to destroy original text array, so cloning it
  1418. var sa = text.concat();
  1419. var da = [];
  1420. var len = sa.length;
  1421. var curDa;
  1422. var tmpResult;
  1423. //we do array.join('text that must not be PDFescaped")
  1424. //thus, pdfEscape each component separately
  1425. while (len--) {
  1426. curDa = sa.shift();
  1427. if (typeof curDa === "string") {
  1428. da.push(processingFunction(curDa)[0]);
  1429. } else if (Object.prototype.toString.call(curDa) === '[object Array]' && curDa[0] === "string") {
  1430. tmpResult = processingFunction(curDa[0], curDa[1], curDa[2]);
  1431. da.push([tmpResult[0], tmpResult[1], tmpResult[2]]);
  1432. }
  1433. }
  1434. result = da;
  1435. }
  1436. return result;
  1437. }
  1438. //backwardsCompatibility
  1439. var tmp;
  1440. // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1441. // in effort to make all calls have similar signature like
  1442. // function(data, coordinates... , miscellaneous)
  1443. // this method had its args flipped.
  1444. // code below allows backward compatibility with old arg order.
  1445. if (typeof text === 'number') {
  1446. tmp = y;
  1447. y = x;
  1448. x = text;
  1449. text = tmp;
  1450. }
  1451. var flags = arguments[3];
  1452. var angle = arguments[4];
  1453. var align = arguments[5];
  1454. if ((typeof flags === 'undefined' ? 'undefined' : _typeof(flags)) !== "object" || flags === null) {
  1455. if (typeof angle === 'string') {
  1456. align = angle;
  1457. angle = null;
  1458. }
  1459. if (typeof flags === 'string') {
  1460. align = flags;
  1461. flags = null;
  1462. }
  1463. if (typeof flags === 'number') {
  1464. angle = flags;
  1465. flags = null;
  1466. }
  1467. options = { flags: flags, angle: angle, align: align };
  1468. }
  1469. //Check if text is of type String
  1470. var textIsOfTypeString = false;
  1471. var tmpTextIsOfTypeString = true;
  1472. if (typeof text === 'string') {
  1473. textIsOfTypeString = true;
  1474. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1475. //we don't want to destroy original text array, so cloning it
  1476. var sa = text.concat();
  1477. var da = [];
  1478. var len = sa.length;
  1479. var curDa;
  1480. //we do array.join('text that must not be PDFescaped")
  1481. //thus, pdfEscape each component separately
  1482. while (len--) {
  1483. curDa = sa.shift();
  1484. if (typeof curDa !== "string" || Object.prototype.toString.call(curDa) === '[object Array]' && typeof curDa[0] !== "string") {
  1485. tmpTextIsOfTypeString = false;
  1486. }
  1487. }
  1488. textIsOfTypeString = tmpTextIsOfTypeString;
  1489. }
  1490. if (textIsOfTypeString === false) {
  1491. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1492. }
  1493. //Escaping
  1494. var activeFontEncoding = fonts[activeFontKey].encoding;
  1495. if (activeFontEncoding === "WinAnsiEncoding" || activeFontEncoding === "StandardEncoding") {
  1496. text = processTextByFunction(text, function (text, posX, posY) {
  1497. return [ESC(text), posX, posY];
  1498. });
  1499. }
  1500. //If there are any newlines in text, we assume
  1501. //the user wanted to print multiple lines, so break the
  1502. //text up into an array. If the text is already an array,
  1503. //we assume the user knows what they are doing.
  1504. //Convert text into an array anyway to simplify
  1505. //later code.
  1506. if (typeof text === 'string') {
  1507. if (text.match(/[\r?\n]/)) {
  1508. text = text.split(/\r\n|\r|\n/g);
  1509. } else {
  1510. text = [text];
  1511. }
  1512. }
  1513. //multiline
  1514. var maxWidth = options.maxWidth || 0;
  1515. if (maxWidth > 0) {
  1516. if (typeof text === 'string') {
  1517. text = scope.splitTextToSize(text, maxWidth);
  1518. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1519. text = scope.splitTextToSize(text.join(" "), maxWidth);
  1520. }
  1521. }
  1522. //creating Payload-Object to make text byRef
  1523. var payload = {
  1524. text: text,
  1525. x: x,
  1526. y: y,
  1527. options: options,
  1528. mutex: {
  1529. pdfEscape: pdfEscape,
  1530. activeFontKey: activeFontKey,
  1531. fonts: fonts,
  1532. activeFontSize: activeFontSize
  1533. }
  1534. };
  1535. events.publish('preProcessText', payload);
  1536. text = payload.text;
  1537. options = payload.options;
  1538. //angle
  1539. var angle = options.angle;
  1540. var k = scope.internal.scaleFactor;
  1541. var curY = (scope.internal.pageSize.getHeight() - y) * k;
  1542. var transformationMatrix = [];
  1543. if (angle) {
  1544. angle *= Math.PI / 180;
  1545. var c = Math.cos(angle),
  1546. s = Math.sin(angle);
  1547. var f2 = function f2(number) {
  1548. return number.toFixed(2);
  1549. };
  1550. transformationMatrix = [f2(c), f2(s), f2(s * -1), f2(c)];
  1551. }
  1552. //charSpace
  1553. var charSpace = options.charSpace;
  1554. if (charSpace !== undefined) {
  1555. xtra += charSpace + " Tc\n";
  1556. }
  1557. //lang
  1558. var lang = options.lang;
  1559. var tmpRenderingMode = -1;
  1560. var parmRenderingMode = options.renderingMode || options.stroke;
  1561. var pageContext = scope.internal.getCurrentPageInfo().pageContext;
  1562. switch (parmRenderingMode) {
  1563. case 0:
  1564. case false:
  1565. case 'fill':
  1566. tmpRenderingMode = 0;
  1567. break;
  1568. case 1:
  1569. case true:
  1570. case 'stroke':
  1571. tmpRenderingMode = 1;
  1572. break;
  1573. case 2:
  1574. case 'fillThenStroke':
  1575. tmpRenderingMode = 2;
  1576. break;
  1577. case 3:
  1578. case 'invisible':
  1579. tmpRenderingMode = 3;
  1580. break;
  1581. case 4:
  1582. case 'fillAndAddForClipping':
  1583. tmpRenderingMode = 4;
  1584. break;
  1585. case 5:
  1586. case 'strokeAndAddPathForClipping':
  1587. tmpRenderingMode = 5;
  1588. break;
  1589. case 6:
  1590. case 'fillThenStrokeAndAddToPathForClipping':
  1591. tmpRenderingMode = 6;
  1592. break;
  1593. case 7:
  1594. case 'addToPathForClipping':
  1595. tmpRenderingMode = 7;
  1596. break;
  1597. }
  1598. var usedRenderingMode = pageContext.usedRenderingMode || -1;
  1599. //if the coder wrote it explicitly to use a specific
  1600. //renderingMode, then use it
  1601. if (tmpRenderingMode !== -1) {
  1602. xtra += tmpRenderingMode + " Tr\n";
  1603. //otherwise check if we used the rendering Mode already
  1604. //if so then set the rendering Mode...
  1605. } else if (usedRenderingMode !== -1) {
  1606. xtra += "0 Tr\n";
  1607. }
  1608. if (tmpRenderingMode !== -1) {
  1609. pageContext.usedRenderingMode = tmpRenderingMode;
  1610. }
  1611. //align
  1612. var align = options.align || 'left';
  1613. var leading = activeFontSize * lineHeight;
  1614. var pageHeight = scope.internal.pageSize.getHeight();
  1615. var pageWidth = scope.internal.pageSize.getWidth();
  1616. var k = scope.internal.scaleFactor;
  1617. var activeFont = fonts[activeFontKey];
  1618. var charSpace = options.charSpace || activeCharSpace;
  1619. var maxWidth = options.maxWidth || 0;
  1620. var lineWidths;
  1621. var flags = {};
  1622. var wordSpacingPerLine = [];
  1623. if (Object.prototype.toString.call(text) === '[object Array]') {
  1624. var da = transformTextToSpecialArray(text);
  1625. var newY;
  1626. var maxLineLength;
  1627. var lineWidths;
  1628. if (align !== "left") {
  1629. lineWidths = da.map(function (v) {
  1630. return scope.getStringUnitWidth(v, { font: activeFont, charSpace: charSpace, fontSize: activeFontSize }) * activeFontSize / k;
  1631. });
  1632. }
  1633. var maxLineLength = Math.max.apply(Math, lineWidths);
  1634. //The first line uses the "main" Td setting,
  1635. //and the subsequent lines are offset by the
  1636. //previous line's x coordinate.
  1637. var prevWidth = 0;
  1638. var delta;
  1639. var newX;
  1640. if (align === "right") {
  1641. x -= lineWidths[0];
  1642. text = [];
  1643. for (var i = 0, len = da.length; i < len; i++) {
  1644. delta = maxLineLength - lineWidths[i];
  1645. if (i === 0) {
  1646. newX = x * k;
  1647. newY = (pageHeight - y) * k;
  1648. } else {
  1649. newX = (prevWidth - lineWidths[i]) * k;
  1650. newY = -leading;
  1651. }
  1652. text.push([da[i], newX, newY]);
  1653. prevWidth = lineWidths[i];
  1654. }
  1655. } else if (align === "center") {
  1656. x -= lineWidths[0] / 2;
  1657. text = [];
  1658. for (var i = 0, len = da.length; i < len; i++) {
  1659. delta = (maxLineLength - lineWidths[i]) / 2;
  1660. if (i === 0) {
  1661. newX = x * k;
  1662. newY = (pageHeight - y) * k;
  1663. } else {
  1664. newX = (prevWidth - lineWidths[i]) / 2 * k;
  1665. newY = -leading;
  1666. }
  1667. text.push([da[i], newX, newY]);
  1668. prevWidth = lineWidths[i];
  1669. }
  1670. } else if (align === "left") {
  1671. text = [];
  1672. for (var i = 0, len = da.length; i < len; i++) {
  1673. newY = i === 0 ? (pageHeight - y) * k : -leading;
  1674. newX = i === 0 ? x * k : 0;
  1675. //text.push([da[i], newX, newY]);
  1676. text.push(da[i]);
  1677. }
  1678. } else if (align === "justify") {
  1679. text = [];
  1680. var maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;
  1681. for (var i = 0, len = da.length; i < len; i++) {
  1682. newY = i === 0 ? (pageHeight - y) * k : -leading;
  1683. newX = i === 0 ? x * k : 0;
  1684. if (i < len - 1) {
  1685. wordSpacingPerLine.push(((maxWidth - lineWidths[i]) / (da[i].split(" ").length - 1) * k).toFixed(2));
  1686. }
  1687. text.push([da[i], newX, newY]);
  1688. }
  1689. } else {
  1690. throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".');
  1691. }
  1692. }
  1693. //R2L
  1694. var doReversing = typeof options.R2L === "boolean" ? options.R2L : R2L;
  1695. if (doReversing === true) {
  1696. text = processTextByFunction(text, function (text, posX, posY) {
  1697. return [text.split("").reverse().join(""), posX, posY];
  1698. });
  1699. }
  1700. //creating Payload-Object to make text byRef
  1701. var payload = {
  1702. text: text,
  1703. x: x,
  1704. y: y,
  1705. options: options,
  1706. mutex: {
  1707. pdfEscape: pdfEscape,
  1708. activeFontKey: activeFontKey,
  1709. fonts: fonts,
  1710. activeFontSize: activeFontSize
  1711. }
  1712. };
  1713. events.publish('postProcessText', payload);
  1714. text = payload.text;
  1715. isHex = payload.mutex.isHex;
  1716. var da = transformTextToSpecialArray(text);
  1717. text = [];
  1718. var variant = 0;
  1719. var len = da.length;
  1720. var posX;
  1721. var posY;
  1722. var content;
  1723. var wordSpacing = '';
  1724. for (var i = 0; i < len; i++) {
  1725. wordSpacing = '';
  1726. if (Object.prototype.toString.call(da[i]) !== '[object Array]') {
  1727. posX = parseFloat(x * k).toFixed(2);
  1728. posY = parseFloat((pageHeight - y) * k).toFixed(2);
  1729. content = (isHex ? "<" : "(") + da[i] + (isHex ? ">" : ")");
  1730. } else if (Object.prototype.toString.call(da[i]) === '[object Array]') {
  1731. posX = parseFloat(da[i][1]).toFixed(2);
  1732. posY = parseFloat(da[i][2]).toFixed(2);
  1733. content = (isHex ? "<" : "(") + da[i][0] + (isHex ? ">" : ")");
  1734. variant = 1;
  1735. }
  1736. if (wordSpacingPerLine !== undefined && wordSpacingPerLine[i] !== undefined) {
  1737. wordSpacing = wordSpacingPerLine[i] + " Tw\n";
  1738. }
  1739. //TODO: Kind of a hack?
  1740. if (transformationMatrix.length !== 0 && i === 0) {
  1741. text.push(wordSpacing + transformationMatrix.join(" ") + " " + posX + " " + posY + " Tm\n" + content);
  1742. } else if (variant === 1 || variant === 0 && i === 0) {
  1743. text.push(wordSpacing + posX + " " + posY + " Td\n" + content);
  1744. } else {
  1745. text.push(wordSpacing + content);
  1746. }
  1747. }
  1748. if (variant === 0) {
  1749. text = text.join(" Tj\nT* ");
  1750. } else {
  1751. text = text.join(" Tj\n");
  1752. }
  1753. text += " Tj\n";
  1754. var result = 'BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1755. (activeFontSize * lineHeight).toFixed(2) + ' TL\n' + // line spacing
  1756. textColor + '\n';
  1757. result += xtra;
  1758. result += text;
  1759. result += "ET";
  1760. out(result);
  1761. return scope;
  1762. };
  1763. /**
  1764. * Letter spacing method to print text with gaps
  1765. *
  1766. * @function
  1767. * @param {String|Array} text String to be added to the page.
  1768. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1769. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1770. * @param {Number} spacing Spacing (in units declared at inception)
  1771. * @returns {jsPDF}
  1772. * @methodOf jsPDF#
  1773. * @name lstext
  1774. * @deprecated We'll be removing this function. It doesn't take character width into account.
  1775. */
  1776. API.lstext = function (text, x, y, spacing) {
  1777. console.warn('jsPDF.lstext is deprecated');
  1778. for (var i = 0, len = text.length; i < len; i++, x += spacing) {
  1779. this.text(text[i], x, y);
  1780. }return this;
  1781. };
  1782. API.line = function (x1, y1, x2, y2) {
  1783. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  1784. };
  1785. API.clip = function () {
  1786. // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
  1787. // Call .clip() after calling .rect() with a style argument of null
  1788. out('W'); // clip
  1789. out('S'); // stroke path; necessary for clip to work
  1790. };
  1791. /**
  1792. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  1793. * We introduce the fixed version so as to not break API.
  1794. * @param fillRule
  1795. */
  1796. API.clip_fixed = function (fillRule) {
  1797. // Call .clip() after calling drawing ops with a style argument of null
  1798. // W is the PDF clipping op
  1799. if ('evenodd' === fillRule) {
  1800. out('W*');
  1801. } else {
  1802. out('W');
  1803. }
  1804. // End the path object without filling or stroking it.
  1805. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  1806. // (see Section 4.4.3, “Clipping Path Operators”)
  1807. out('n');
  1808. };
  1809. /**
  1810. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1811. * All data points in `lines` are relative to last line origin.
  1812. * `x`, `y` become x1,y1 for first line / curve in the set.
  1813. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1814. * 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.
  1815. *
  1816. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1817. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1818. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1819. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1820. * @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.
  1821. * @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.
  1822. * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1823. * @function
  1824. * @returns {jsPDF}
  1825. * @methodOf jsPDF#
  1826. * @name lines
  1827. */
  1828. API.lines = function (lines, x, y, scale, style, closed) {
  1829. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1830. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1831. // in effort to make all calls have similar signature like
  1832. // function(content, coordinateX, coordinateY , miscellaneous)
  1833. // this method had its args flipped.
  1834. // code below allows backward compatibility with old arg order.
  1835. if (typeof lines === 'number') {
  1836. tmp = y;
  1837. y = x;
  1838. x = lines;
  1839. lines = tmp;
  1840. }
  1841. scale = scale || [1, 1];
  1842. // starting point
  1843. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1844. scalex = scale[0];
  1845. scaley = scale[1];
  1846. l = lines.length;
  1847. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1848. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1849. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1850. x4 = x; // last / ending point = starting point for first item.
  1851. y4 = y; // last / ending point = starting point for first item.
  1852. for (i = 0; i < l; i++) {
  1853. leg = lines[i];
  1854. if (leg.length === 2) {
  1855. // simple line
  1856. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1857. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1858. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1859. } else {
  1860. // bezier curve
  1861. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1862. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1863. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1864. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1865. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1866. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1867. out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
  1868. }
  1869. }
  1870. if (closed) {
  1871. out(' h');
  1872. }
  1873. // stroking / filling / both the path
  1874. if (style !== null) {
  1875. out(getStyle(style));
  1876. }
  1877. return this;
  1878. };
  1879. /**
  1880. * Adds a rectangle to PDF
  1881. *
  1882. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1883. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1884. * @param {Number} w Width (in units declared at inception of PDF document)
  1885. * @param {Number} h Height (in units declared at inception of PDF document)
  1886. * @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.
  1887. * @function
  1888. * @returns {jsPDF}
  1889. * @methodOf jsPDF#
  1890. * @name rect
  1891. */
  1892. API.rect = function (x, y, w, h, style) {
  1893. var op = getStyle(style);
  1894. out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
  1895. if (style !== null) {
  1896. out(getStyle(style));
  1897. }
  1898. return this;
  1899. };
  1900. /**
  1901. * Adds a triangle to PDF
  1902. *
  1903. * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1904. * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1905. * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1906. * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1907. * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1908. * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1909. * @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.
  1910. * @function
  1911. * @returns {jsPDF}
  1912. * @methodOf jsPDF#
  1913. * @name triangle
  1914. */
  1915. API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  1916. this.lines([[x2 - x1, y2 - y1], // vector to point 2
  1917. [x3 - x2, y3 - y2], // vector to point 3
  1918. [x1 - x3, y1 - y3] // closing vector back to point 1
  1919. ], x1, y1, // start of path
  1920. [1, 1], style, true);
  1921. return this;
  1922. };
  1923. /**
  1924. * Adds a rectangle with rounded corners to PDF
  1925. *
  1926. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1927. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1928. * @param {Number} w Width (in units declared at inception of PDF document)
  1929. * @param {Number} h Height (in units declared at inception of PDF document)
  1930. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1931. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1932. * @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.
  1933. * @function
  1934. * @returns {jsPDF}
  1935. * @methodOf jsPDF#
  1936. * @name roundedRect
  1937. */
  1938. API.roundedRect = function (x, y, w, h, rx, ry, style) {
  1939. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  1940. 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
  1941. [1, 1], style);
  1942. return this;
  1943. };
  1944. /**
  1945. * Adds an ellipse to PDF
  1946. *
  1947. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1948. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1949. * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1950. * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1951. * @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.
  1952. * @function
  1953. * @returns {jsPDF}
  1954. * @methodOf jsPDF#
  1955. * @name ellipse
  1956. */
  1957. API.ellipse = function (x, y, rx, ry, style) {
  1958. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1959. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1960. 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(' '));
  1961. 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(' '));
  1962. 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(' '));
  1963. 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(' '));
  1964. if (style !== null) {
  1965. out(getStyle(style));
  1966. }
  1967. return this;
  1968. };
  1969. /**
  1970. * Adds an circle to PDF
  1971. *
  1972. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1973. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1974. * @param {Number} r Radius (in units declared at inception of PDF document)
  1975. * @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.
  1976. * @function
  1977. * @returns {jsPDF}
  1978. * @methodOf jsPDF#
  1979. * @name circle
  1980. */
  1981. API.circle = function (x, y, r, style) {
  1982. return this.ellipse(x, y, r, r, style);
  1983. };
  1984. /**
  1985. * Adds a properties to the PDF document
  1986. *
  1987. * @param {Object} A property_name-to-property_value object structure.
  1988. * @function
  1989. * @returns {jsPDF}
  1990. * @methodOf jsPDF#
  1991. * @name setProperties
  1992. */
  1993. API.setProperties = function (properties) {
  1994. // copying only those properties we can render.
  1995. for (var property in documentProperties) {
  1996. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1997. documentProperties[property] = properties[property];
  1998. }
  1999. }
  2000. return this;
  2001. };
  2002. /**
  2003. * Sets font size for upcoming text elements.
  2004. *
  2005. * @param {Number} size Font size in points.
  2006. * @function
  2007. * @returns {jsPDF}
  2008. * @methodOf jsPDF#
  2009. * @name setFontSize
  2010. */
  2011. API.setFontSize = function (size) {
  2012. activeFontSize = size;
  2013. return this;
  2014. };
  2015. /**
  2016. * Sets text font face, variant for upcoming text elements.
  2017. * See output of jsPDF.getFontList() for possible font names, styles.
  2018. *
  2019. * @param {String} fontName Font name or family. Example: "times"
  2020. * @param {String} fontStyle Font style or variant. Example: "italic"
  2021. * @function
  2022. * @returns {jsPDF}
  2023. * @methodOf jsPDF#
  2024. * @name setFont
  2025. */
  2026. API.setFont = function (fontName, fontStyle) {
  2027. activeFontKey = _getFont(fontName, fontStyle, { disableWarning: false });
  2028. return this;
  2029. };
  2030. /**
  2031. * Switches font style or variant for upcoming text elements,
  2032. * while keeping the font face or family same.
  2033. * See output of jsPDF.getFontList() for possible font names, styles.
  2034. *
  2035. * @param {String} style Font style or variant. Example: "italic"
  2036. * @function
  2037. * @returns {jsPDF}
  2038. * @methodOf jsPDF#
  2039. * @name setFontStyle
  2040. */
  2041. API.setFontStyle = API.setFontType = function (style) {
  2042. activeFontKey = _getFont(undefined, style);
  2043. // if font is not found, the above line blows up and we never go further
  2044. return this;
  2045. };
  2046. /**
  2047. * Returns an object - a tree of fontName to fontStyle relationships available to
  2048. * active PDF document.
  2049. *
  2050. * @public
  2051. * @function
  2052. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  2053. * @methodOf jsPDF#
  2054. * @name getFontList
  2055. */
  2056. API.getFontList = function () {
  2057. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  2058. var list = {},
  2059. fontName,
  2060. fontStyle,
  2061. tmp;
  2062. for (fontName in fontmap) {
  2063. if (fontmap.hasOwnProperty(fontName)) {
  2064. list[fontName] = tmp = [];
  2065. for (fontStyle in fontmap[fontName]) {
  2066. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  2067. tmp.push(fontStyle);
  2068. }
  2069. }
  2070. }
  2071. }
  2072. return list;
  2073. };
  2074. /**
  2075. * Add a custom font.
  2076. *
  2077. * @param {String} Postscript name of the Font. Example: "Menlo-Regular"
  2078. * @param {String} Name of font-family from @font-face definition. Example: "Menlo Regular"
  2079. * @param {String} Font style. Example: "normal"
  2080. * @function
  2081. * @returns the {fontKey} (same as the internal method)
  2082. * @methodOf jsPDF#
  2083. * @name addFont
  2084. */
  2085. API.addFont = function (postScriptName, fontName, fontStyle, encoding) {
  2086. encoding = encoding || 'Identity-H';
  2087. addFont(postScriptName, fontName, fontStyle, encoding);
  2088. };
  2089. /**
  2090. * Sets line width for upcoming lines.
  2091. *
  2092. * @param {Number} width Line width (in units declared at inception of PDF document)
  2093. * @function
  2094. * @returns {jsPDF}
  2095. * @methodOf jsPDF#
  2096. * @name setLineWidth
  2097. */
  2098. API.setLineWidth = function (width) {
  2099. out((width * k).toFixed(2) + ' w');
  2100. return this;
  2101. };
  2102. /**
  2103. * Sets the stroke color for upcoming elements.
  2104. *
  2105. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2106. * color space is implied.
  2107. *
  2108. * When only ch1 is given, "Gray" color space is implied and it
  2109. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2110. * if values are communicated as String types, or in range from 0 (black)
  2111. * to 255 (white) if communicated as Number type.
  2112. * The RGB-like 0-255 range is provided for backward compatibility.
  2113. *
  2114. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2115. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2116. * (max intensity) if values are communicated as String types, or
  2117. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2118. * as Number types.
  2119. * The RGB-like 0-255 range is provided for backward compatibility.
  2120. *
  2121. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2122. * value must be a in the range from 0.00 (0% concentration) to to
  2123. * 1.00 (100% concentration)
  2124. *
  2125. * Because JavaScript treats fixed point numbers badly (rounds to
  2126. * floating point nearest to binary representation) it is highly advised to
  2127. * communicate the fractional numbers as String types, not JavaScript Number type.
  2128. *
  2129. * @param {Number|String} ch1 Color channel value or {String} ch1 color value in hexadecimal, example: '#FFFFFF'
  2130. * @param {Number|String} ch2 Color channel value
  2131. * @param {Number|String} ch3 Color channel value
  2132. * @param {Number|String} ch4 Color channel value
  2133. *
  2134. * @function
  2135. * @returns {jsPDF}
  2136. * @methodOf jsPDF#
  2137. * @name setDrawColor
  2138. */
  2139. API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  2140. var options = {
  2141. "ch1": ch1,
  2142. "ch2": ch2,
  2143. "ch3": ch3,
  2144. "ch4": ch4,
  2145. "pdfColorType": "draw",
  2146. "precision": 2
  2147. };
  2148. out(generateColorString(options));
  2149. return this;
  2150. };
  2151. /**
  2152. * Sets the fill color for upcoming elements.
  2153. *
  2154. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2155. * color space is implied.
  2156. *
  2157. * When only ch1 is given, "Gray" color space is implied and it
  2158. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2159. * if values are communicated as String types, or in range from 0 (black)
  2160. * to 255 (white) if communicated as Number type.
  2161. * The RGB-like 0-255 range is provided for backward compatibility.
  2162. *
  2163. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2164. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2165. * (max intensity) if values are communicated as String types, or
  2166. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2167. * as Number types.
  2168. * The RGB-like 0-255 range is provided for backward compatibility.
  2169. *
  2170. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2171. * value must be a in the range from 0.00 (0% concentration) to to
  2172. * 1.00 (100% concentration)
  2173. *
  2174. * Because JavaScript treats fixed point numbers badly (rounds to
  2175. * floating point nearest to binary representation) it is highly advised to
  2176. * communicate the fractional numbers as String types, not JavaScript Number type.
  2177. *
  2178. * @param {Number|String} ch1 Color channel value or {String} ch1 color value in hexadecimal, example: '#FFFFFF'
  2179. * @param {Number|String} ch2 Color channel value
  2180. * @param {Number|String} ch3 Color channel value
  2181. * @param {Number|String} ch4 Color channel value
  2182. *
  2183. * @function
  2184. * @returns {jsPDF}
  2185. * @methodOf jsPDF#
  2186. * @name setFillColor
  2187. */
  2188. API.setFillColor = function (ch1, ch2, ch3, ch4) {
  2189. var options = {
  2190. "ch1": ch1,
  2191. "ch2": ch2,
  2192. "ch3": ch3,
  2193. "ch4": ch4,
  2194. "pdfColorType": "fill",
  2195. "precision": 2
  2196. };
  2197. out(generateColorString(options));
  2198. return this;
  2199. };
  2200. /**
  2201. * Sets the text color for upcoming elements.
  2202. *
  2203. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2204. * color space is implied.
  2205. *
  2206. * When only ch1 is given, "Gray" color space is implied and it
  2207. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2208. * if values are communicated as String types, or in range from 0 (black)
  2209. * to 255 (white) if communicated as Number type.
  2210. * The RGB-like 0-255 range is provided for backward compatibility.
  2211. *
  2212. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2213. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2214. * (max intensity) if values are communicated as String types, or
  2215. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2216. * as Number types.
  2217. * The RGB-like 0-255 range is provided for backward compatibility.
  2218. *
  2219. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2220. * value must be a in the range from 0.00 (0% concentration) to to
  2221. * 1.00 (100% concentration)
  2222. *
  2223. * Because JavaScript treats fixed point numbers badly (rounds to
  2224. * floating point nearest to binary representation) it is highly advised to
  2225. * communicate the fractional numbers as String types, not JavaScript Number type.
  2226. *
  2227. * @param {Number|String} ch1 Color channel value or {String} ch1 color value in hexadecimal, example: '#FFFFFF'
  2228. * @param {Number|String} ch2 Color channel value
  2229. * @param {Number|String} ch3 Color channel value
  2230. * @param {Number|String} ch4 Color channel value
  2231. *
  2232. * @function
  2233. * @returns {jsPDF}
  2234. * @methodOf jsPDF#
  2235. * @name setTextColor
  2236. */
  2237. API.setTextColor = function (ch1, ch2, ch3, ch4) {
  2238. var options = {
  2239. "ch1": ch1,
  2240. "ch2": ch2,
  2241. "ch3": ch3,
  2242. "ch4": ch4,
  2243. "pdfColorType": "text",
  2244. "precision": 3
  2245. };
  2246. textColor = generateColorString(options);
  2247. return this;
  2248. };
  2249. /**
  2250. * Initializes the default character set that the user wants to be global..
  2251. *
  2252. * @param {Number} charSpace
  2253. * @function
  2254. * @returns {jsPDF}
  2255. * @methodOf jsPDF#
  2256. * @name setCharSpace
  2257. */
  2258. API.setCharSpace = function (charSpace) {
  2259. activeCharSpace = charSpace;
  2260. return this;
  2261. };
  2262. /**
  2263. * Initializes the default character set that the user wants to be global..
  2264. *
  2265. * @param {Boolean} boolean
  2266. * @function
  2267. * @returns {jsPDF}
  2268. * @methodOf jsPDF#
  2269. * @name setR2L
  2270. */
  2271. API.setR2L = function (boolean) {
  2272. R2L = boolean;
  2273. return this;
  2274. };
  2275. /**
  2276. * Is an Object providing a mapping from human-readable to
  2277. * integer flag values designating the varieties of line cap
  2278. * and join styles.
  2279. *
  2280. * @returns {Object}
  2281. * @fieldOf jsPDF#
  2282. * @name CapJoinStyles
  2283. */
  2284. API.CapJoinStyles = {
  2285. 0: 0,
  2286. 'butt': 0,
  2287. 'but': 0,
  2288. 'miter': 0,
  2289. 1: 1,
  2290. 'round': 1,
  2291. 'rounded': 1,
  2292. 'circle': 1,
  2293. 2: 2,
  2294. 'projecting': 2,
  2295. 'project': 2,
  2296. 'square': 2,
  2297. 'bevel': 2
  2298. };
  2299. /**
  2300. * Sets the line cap styles
  2301. * See {jsPDF.CapJoinStyles} for variants
  2302. *
  2303. * @param {String|Number} style A string or number identifying the type of line cap
  2304. * @function
  2305. * @returns {jsPDF}
  2306. * @methodOf jsPDF#
  2307. * @name setLineCap
  2308. */
  2309. API.setLineCap = function (style) {
  2310. var id = this.CapJoinStyles[style];
  2311. if (id === undefined) {
  2312. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2313. }
  2314. lineCapID = id;
  2315. out(id + ' J');
  2316. return this;
  2317. };
  2318. /**
  2319. * Sets the line join styles
  2320. * See {jsPDF.CapJoinStyles} for variants
  2321. *
  2322. * @param {String|Number} style A string or number identifying the type of line join
  2323. * @function
  2324. * @returns {jsPDF}
  2325. * @methodOf jsPDF#
  2326. * @name setLineJoin
  2327. */
  2328. API.setLineJoin = function (style) {
  2329. var id = this.CapJoinStyles[style];
  2330. if (id === undefined) {
  2331. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2332. }
  2333. lineJoinID = id;
  2334. out(id + ' j');
  2335. return this;
  2336. };
  2337. // Output is both an internal (for plugins) and external function
  2338. API.output = _output;
  2339. /**
  2340. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  2341. * @param {String} filename The filename including extension.
  2342. *
  2343. * @function
  2344. * @returns {jsPDF}
  2345. * @methodOf jsPDF#
  2346. * @name save
  2347. */
  2348. API.save = function (filename) {
  2349. API.output('save', filename);
  2350. };
  2351. // applying plugins (more methods) ON TOP of built-in API.
  2352. // this is intentional as we allow plugins to override
  2353. // built-ins
  2354. for (var plugin in jsPDF.API) {
  2355. if (jsPDF.API.hasOwnProperty(plugin)) {
  2356. if (plugin === 'events' && jsPDF.API.events.length) {
  2357. (function (events, newEvents) {
  2358. // jsPDF.API.events is a JS Array of Arrays
  2359. // where each Array is a pair of event name, handler
  2360. // Events were added by plugins to the jsPDF instantiator.
  2361. // These are always added to the new instance and some ran
  2362. // during instantiation.
  2363. var eventname, handler_and_args, i;
  2364. for (i = newEvents.length - 1; i !== -1; i--) {
  2365. // subscribe takes 3 args: 'topic', function, runonce_flag
  2366. // if undefined, runonce is false.
  2367. // users can attach callback directly,
  2368. // or they can attach an array with [callback, runonce_flag]
  2369. // that's what the "apply" magic is for below.
  2370. eventname = newEvents[i][0];
  2371. handler_and_args = newEvents[i][1];
  2372. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  2373. }
  2374. })(events, jsPDF.API.events);
  2375. } else {
  2376. API[plugin] = jsPDF.API[plugin];
  2377. }
  2378. }
  2379. }
  2380. //////////////////////////////////////////////////////
  2381. // continuing initialization of jsPDF Document object
  2382. //////////////////////////////////////////////////////
  2383. // Add the first page automatically
  2384. addFonts();
  2385. activeFontKey = 'F1';
  2386. _addPage(format, orientation);
  2387. events.publish('initialized');
  2388. return API;
  2389. }
  2390. /**
  2391. * jsPDF.API is a STATIC property of jsPDF class.
  2392. * jsPDF.API is an object you can add methods and properties to.
  2393. * The methods / properties you add will show up in new jsPDF objects.
  2394. *
  2395. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  2396. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  2397. * Examples:
  2398. * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  2399. * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  2400. *
  2401. * @static
  2402. * @public
  2403. * @memberOf jsPDF
  2404. * @name API
  2405. *
  2406. * @example
  2407. * jsPDF.API.mymethod = function(){
  2408. * // 'this' will be ref to internal API object. see jsPDF source
  2409. * // , so you can refer to built-in methods like so:
  2410. * // this.line(....)
  2411. * // this.text(....)
  2412. * }
  2413. * var pdfdoc = new jsPDF()
  2414. * pdfdoc.mymethod() // <- !!!!!!
  2415. */
  2416. jsPDF.API = {
  2417. events: []
  2418. };
  2419. jsPDF.version = "0.0.0";
  2420. if (typeof define === 'function' && define.amd) {
  2421. define('jsPDF', function () {
  2422. return jsPDF;
  2423. });
  2424. } else if (typeof module !== 'undefined' && module.exports) {
  2425. module.exports = jsPDF;
  2426. module.exports.jsPDF = jsPDF;
  2427. } else {
  2428. global.jsPDF = jsPDF;
  2429. }
  2430. return jsPDF;
  2431. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')());
  2432. // `self` is undefined in Firefox for Android content script context
  2433. // while `this` is nsIContentFrameMessageManager
  2434. // with an attribute `content` that corresponds to the window
  2435. /**
  2436. * jsPDF AcroForm Plugin Copyright (c) 2016 Alexander Weidt,
  2437. * https://github.com/BiggA94
  2438. *
  2439. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  2440. */
  2441. (function (jsPDFAPI, globalObj) {
  2442. var scope;
  2443. var pageHeight;
  2444. var scaleFactor = 1;
  2445. var inherit = function inherit(child, parent) {
  2446. child.prototype = Object.create(parent.prototype);
  2447. child.prototype.constructor = child;
  2448. };
  2449. var scale = function scale(x) {
  2450. return x * (scaleFactor / 1); // 1 = (96 / 72)
  2451. };
  2452. var createFormXObject = function createFormXObject(formObject) {
  2453. var xobj = new AcroFormXObject();
  2454. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  2455. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  2456. xobj.BBox = [0, 0, width.toFixed(2), height.toFixed(2)];
  2457. return xobj;
  2458. };
  2459. var setBitPosition = function setBitPosition(variable, position, value) {
  2460. variable = variable || 0;
  2461. value = value || 1;
  2462. var bitMask = 1;
  2463. bitMask = bitMask << position - 1;
  2464. if (value == 1) {
  2465. // Set the Bit to 1
  2466. var variable = variable | bitMask;
  2467. } else {
  2468. // Set the Bit to 0
  2469. var variable = variable & ~bitMask;
  2470. }
  2471. return variable;
  2472. };
  2473. /**
  2474. * Calculating the Ff entry:
  2475. *
  2476. * The Ff entry contains flags, that have to be set bitwise In the Following
  2477. * the number in the Comment is the BitPosition
  2478. */
  2479. var calculateFlagsOnOptions = function calculateFlagsOnOptions(flags, opts, PDFVersion) {
  2480. var PDFVersion = PDFVersion || 1.3;
  2481. var flags = flags || 0;
  2482. // 1, readOnly
  2483. if (opts.readOnly == true) {
  2484. flags = setBitPosition(flags, 1);
  2485. }
  2486. // 2, required
  2487. if (opts.required == true) {
  2488. flags = setBitPosition(flags, 2);
  2489. }
  2490. // 4, noExport
  2491. if (opts.noExport == true) {
  2492. flags = setBitPosition(flags, 3);
  2493. }
  2494. // 13, multiline
  2495. if (opts.multiline == true) {
  2496. flags = setBitPosition(flags, 13);
  2497. }
  2498. // 14, Password
  2499. if (opts.password) {
  2500. flags = setBitPosition(flags, 14);
  2501. }
  2502. // 15, NoToggleToOff (Radio buttons only
  2503. if (opts.noToggleToOff) {
  2504. flags = setBitPosition(flags, 15);
  2505. }
  2506. // 16, Radio
  2507. if (opts.radio) {
  2508. flags = setBitPosition(flags, 16);
  2509. }
  2510. // 17, Pushbutton
  2511. if (opts.pushbutton) {
  2512. flags = setBitPosition(flags, 17);
  2513. }
  2514. // 18, Combo (If not set, the choiceField is a listBox!!)
  2515. if (opts.combo) {
  2516. flags = setBitPosition(flags, 18);
  2517. }
  2518. // 19, Edit
  2519. if (opts.edit) {
  2520. flags = setBitPosition(flags, 19);
  2521. }
  2522. // 20, Sort
  2523. if (opts.sort) {
  2524. flags = setBitPosition(flags, 20);
  2525. }
  2526. // 21, FileSelect, PDF 1.4...
  2527. if (opts.fileSelect && PDFVersion >= 1.4) {
  2528. flags = setBitPosition(flags, 21);
  2529. }
  2530. // 22, MultiSelect (PDF 1.4)
  2531. if (opts.multiSelect && PDFVersion >= 1.4) {
  2532. flags = setBitPosition(flags, 22);
  2533. }
  2534. // 23, DoNotSpellCheck (PDF 1.4)
  2535. if (opts.doNotSpellCheck && PDFVersion >= 1.4) {
  2536. flags = setBitPosition(flags, 23);
  2537. }
  2538. // 24, DoNotScroll (PDF 1.4)
  2539. if (opts.doNotScroll == true && PDFVersion >= 1.4) {
  2540. flags = setBitPosition(flags, 24);
  2541. }
  2542. // 25, RichText (PDF 1.4)
  2543. if (opts.richText && PDFVersion >= 1.4) {
  2544. flags = setBitPosition(flags, 25);
  2545. }
  2546. return flags;
  2547. };
  2548. var calculateCoordinates = function calculateCoordinates(args) {
  2549. var x = args[0];
  2550. var y = args[1];
  2551. var w = args[2];
  2552. var h = args[3];
  2553. var coordinates = {};
  2554. if (Array.isArray(x)) {
  2555. x[0] = scale(x[0]);
  2556. x[1] = scale(x[1]);
  2557. x[2] = scale(x[2]);
  2558. x[3] = scale(x[3]);
  2559. } else {
  2560. x = scale(x);
  2561. y = scale(y);
  2562. w = scale(w);
  2563. h = scale(h);
  2564. }
  2565. coordinates.lowerLeft_X = x || 0;
  2566. coordinates.lowerLeft_Y = scale(pageHeight) - y - h || 0;
  2567. coordinates.upperRight_X = x + w || 0;
  2568. coordinates.upperRight_Y = scale(pageHeight) - y || 0;
  2569. return [coordinates.lowerLeft_X.toFixed(2), coordinates.lowerLeft_Y.toFixed(2), coordinates.upperRight_X.toFixed(2), coordinates.upperRight_Y.toFixed(2)];
  2570. };
  2571. var calculateAppearanceStream = function calculateAppearanceStream(formObject) {
  2572. if (formObject.appearanceStreamContent) {
  2573. // If appearanceStream is already set, use it
  2574. return formObject.appearanceStreamContent;
  2575. }
  2576. if (!formObject.V && !formObject.DV) {
  2577. return;
  2578. }
  2579. // else calculate it
  2580. var stream = [];
  2581. var text = formObject.V || formObject.DV;
  2582. var calcRes = calculateX(formObject, text);
  2583. stream.push('/Tx BMC');
  2584. stream.push('q');
  2585. stream.push('/F1 ' + calcRes.fontSize.toFixed(2) + ' Tf');
  2586. stream.push('1 0 0 1 0 0 Tm'); // Text Matrix
  2587. stream.push('BT'); // Begin Text
  2588. stream.push(calcRes.text);
  2589. stream.push('ET'); // End Text
  2590. stream.push('Q');
  2591. stream.push('EMC');
  2592. var appearanceStreamContent = new createFormXObject(formObject);
  2593. appearanceStreamContent.stream = stream.join("\n");
  2594. return appearanceStreamContent;
  2595. };
  2596. var calculateX = function calculateX(formObject, text, font, maxFontSize) {
  2597. var maxFontSize = maxFontSize || 12;
  2598. var font = font || "helvetica";
  2599. var returnValue = {
  2600. text: "",
  2601. fontSize: ""
  2602. };
  2603. // Remove Brackets
  2604. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  2605. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
  2606. // split into array of words
  2607. var textSplit = text.split(' ');
  2608. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  2609. var lineSpacing = 2;
  2610. var borderPadding = 2;
  2611. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  2612. height = height < 0 ? -height : height;
  2613. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  2614. width = width < 0 ? -width : width;
  2615. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  2616. if (i + 1 < textSplit.length) {
  2617. var tmp = lastLine + " " + textSplit[i + 1];
  2618. var TextWidth = calculateFontSpace(tmp, fontSize + "px", font).width;
  2619. var FieldWidth = width - 2 * borderPadding;
  2620. return TextWidth <= FieldWidth;
  2621. } else {
  2622. return false;
  2623. }
  2624. };
  2625. fontSize++;
  2626. FontSize: while (true) {
  2627. var text = "";
  2628. fontSize--;
  2629. var textHeight = calculateFontSpace("3", fontSize + "px", font).height;
  2630. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  2631. startY += lineSpacing;
  2632. var startX = -borderPadding;
  2633. var lastY = startY;
  2634. var firstWordInLine = 0,
  2635. lastWordInLine = 0;
  2636. var lastLength = 0;
  2637. if (fontSize <= 0) {
  2638. // In case, the Text doesn't fit at all
  2639. fontSize = 12;
  2640. text = "(...) Tj\n";
  2641. text += "% Width of Text: " + calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
  2642. break;
  2643. }
  2644. lastLength = calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
  2645. var lastLine = "";
  2646. var lineCount = 0;
  2647. Line: for (var i in textSplit) {
  2648. if (textSplit.hasOwnProperty(i)) {
  2649. lastLine += textSplit[i] + " ";
  2650. // Remove last blank
  2651. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  2652. var key = parseInt(i);
  2653. lastLength = calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
  2654. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  2655. var isLastWord = i >= textSplit.length - 1;
  2656. if (nextLineIsSmaller && !isLastWord) {
  2657. lastLine += " ";
  2658. continue; // Line
  2659. } else if (!nextLineIsSmaller && !isLastWord) {
  2660. if (!formObject.multiline) {
  2661. continue FontSize;
  2662. } else {
  2663. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  2664. // If the Text is higher than the
  2665. // FieldObject
  2666. continue FontSize;
  2667. }
  2668. lastWordInLine = key;
  2669. // go on
  2670. }
  2671. } else if (isLastWord) {
  2672. lastWordInLine = key;
  2673. } else {
  2674. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  2675. // If the Text is higher than the FieldObject
  2676. continue FontSize;
  2677. }
  2678. }
  2679. var line = '';
  2680. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  2681. line += textSplit[x] + ' ';
  2682. }
  2683. // Remove last blank
  2684. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
  2685. // lastLength -= blankSpace.width;
  2686. lastLength = calculateFontSpace(line, fontSize + "px", font).width;
  2687. // Calculate startX
  2688. switch (formObject.Q) {
  2689. case 2:
  2690. // Right justified
  2691. startX = width - lastLength - borderPadding;
  2692. break;
  2693. case 1:
  2694. // Q = 1 := Text-Alignment: Center
  2695. startX = (width - lastLength) / 2;
  2696. break;
  2697. case 0:
  2698. default:
  2699. startX = borderPadding;
  2700. break;
  2701. }
  2702. text += startX.toFixed(2) + ' ' + lastY.toFixed(2) + ' Td\n';
  2703. text += '(' + line + ') Tj\n';
  2704. // reset X in PDF
  2705. text += -startX.toFixed(2) + ' 0 Td\n';
  2706. // After a Line, adjust y position
  2707. lastY = -(fontSize + lineSpacing);
  2708. // Reset for next iteration step
  2709. lastLength = 0;
  2710. firstWordInLine = lastWordInLine + 1;
  2711. lineCount++;
  2712. lastLine = "";
  2713. continue Line;
  2714. }
  2715. }
  2716. break;
  2717. }
  2718. returnValue.text = text;
  2719. returnValue.fontSize = fontSize;
  2720. return returnValue;
  2721. };
  2722. /**
  2723. * small workaround for calculating the TextMetric approximately
  2724. *
  2725. * @param text
  2726. * @param fontsize
  2727. * @returns {TextMetrics} (Has Height and Width)
  2728. */
  2729. var calculateFontSpace = function calculateFontSpace(text, fontSize, fontType) {
  2730. fontType = fontType || "helvetica";
  2731. var font = scope.internal.getFont(fontType);
  2732. var width = scope.getStringUnitWidth(text, { font: font, fontSize: parseFloat(fontSize), charSpace: 0 }) * parseFloat(fontSize);
  2733. var height = scope.getStringUnitWidth("3", { font: font, fontSize: parseFloat(fontSize), charSpace: 0 }) * parseFloat(fontSize) * 1.5;
  2734. var result = { height: height, width: width };
  2735. return result;
  2736. };
  2737. var acroformPluginTemplate = {
  2738. fields: [],
  2739. xForms: [],
  2740. /**
  2741. * acroFormDictionaryRoot contains information about the AcroForm
  2742. * Dictionary 0: The Event-Token, the AcroFormDictionaryCallback has
  2743. * 1: The Object ID of the Root
  2744. */
  2745. acroFormDictionaryRoot: null,
  2746. /**
  2747. * After the PDF gets evaluated, the reference to the root has to be
  2748. * reset, this indicates, whether the root has already been printed
  2749. * out
  2750. */
  2751. printedOut: false,
  2752. internal: null,
  2753. isInitialized: false
  2754. };
  2755. var annotReferenceCallback = function annotReferenceCallback() {
  2756. var fields = scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields;
  2757. for (var i in fields) {
  2758. if (fields.hasOwnProperty(i)) {
  2759. var formObject = fields[i];
  2760. // add Annot Reference!
  2761. if (formObject.hasAnnotation) {
  2762. // If theres an Annotation Widget in the Form Object, put the
  2763. // Reference in the /Annot array
  2764. createAnnotationReference.call(scope, formObject);
  2765. }
  2766. }
  2767. }
  2768. };
  2769. var putForm = function putForm(formObject) {
  2770. if (scope.internal.acroformPlugin.printedOut) {
  2771. scope.internal.acroformPlugin.printedOut = false;
  2772. scope.internal.acroformPlugin.acroFormDictionaryRoot = null;
  2773. }
  2774. if (!scope.internal.acroformPlugin.acroFormDictionaryRoot) {
  2775. initializeAcroForm.call(scope);
  2776. }
  2777. scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  2778. };
  2779. /**
  2780. * Create the Reference to the widgetAnnotation, so that it gets referenced
  2781. * in the Annot[] int the+ (Requires the Annotation Plugin)
  2782. */
  2783. var createAnnotationReference = function createAnnotationReference(object) {
  2784. var options = {
  2785. type: 'reference',
  2786. object: object
  2787. };
  2788. scope.annotationPlugin.annotations[scope.internal.getPageInfo(object.page).pageNumber].push(options);
  2789. };
  2790. // Callbacks
  2791. var putCatalogCallback = function putCatalogCallback() {
  2792. // Put reference to AcroForm to DocumentCatalog
  2793. if (typeof scope.internal.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  2794. // for safety, shouldn't normally be the case
  2795. scope.internal.write('/AcroForm ' + scope.internal.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  2796. } else {
  2797. console.log('Root missing...');
  2798. }
  2799. };
  2800. /**
  2801. * Adds /Acroform X 0 R to Document Catalog, and creates the AcroForm
  2802. * Dictionary
  2803. */
  2804. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  2805. // Remove event
  2806. scope.internal.events.unsubscribe(scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID);
  2807. delete scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID;
  2808. scope.internal.acroformPlugin.printedOut = true;
  2809. };
  2810. /**
  2811. * Creates the single Fields and writes them into the Document
  2812. *
  2813. * If fieldArray is set, use the fields that are inside it instead of the
  2814. * fields from the AcroRoot (for the FormXObjects...)
  2815. */
  2816. var createFieldCallback = function createFieldCallback(fieldArray) {
  2817. var standardFields = !fieldArray;
  2818. if (!fieldArray) {
  2819. // in case there is no fieldArray specified, we want to print out
  2820. // the Fields of the AcroForm
  2821. // Print out Root
  2822. scope.internal.newObjectDeferredBegin(scope.internal.acroformPlugin.acroFormDictionaryRoot.objId);
  2823. scope.internal.out(scope.internal.acroformPlugin.acroFormDictionaryRoot.getString());
  2824. }
  2825. var fieldArray = fieldArray || scope.internal.acroformPlugin.acroFormDictionaryRoot.Kids;
  2826. for (var i in fieldArray) {
  2827. if (fieldArray.hasOwnProperty(i)) {
  2828. var form = fieldArray[i];
  2829. var oldRect = form.Rect;
  2830. if (form.Rect) {
  2831. form.Rect = calculateCoordinates.call(this, form.Rect);
  2832. }
  2833. // Start Writing the Object
  2834. scope.internal.newObjectDeferredBegin(form.objId);
  2835. var content = form.objId + " 0 obj\n<<\n";
  2836. if ((typeof form === 'undefined' ? 'undefined' : _typeof(form)) === "object" && typeof form.getContent === "function") {
  2837. content += form.getContent();
  2838. }
  2839. form.Rect = oldRect;
  2840. if (form.hasAppearanceStream && !form.appearanceStreamContent) {
  2841. // Calculate Appearance
  2842. var appearance = calculateAppearanceStream.call(this, form);
  2843. content += "/AP << /N " + appearance + " >>\n";
  2844. scope.internal.acroformPlugin.xForms.push(appearance);
  2845. }
  2846. // Assume AppearanceStreamContent is a Array with N,R,D (at least
  2847. // one of them!)
  2848. if (form.appearanceStreamContent) {
  2849. content += "/AP << ";
  2850. // Iterate over N,R and D
  2851. for (var k in form.appearanceStreamContent) {
  2852. if (form.appearanceStreamContent.hasOwnProperty(k)) {
  2853. var value = form.appearanceStreamContent[k];
  2854. content += "/" + k + " ";
  2855. content += "<< ";
  2856. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  2857. // appearanceStream is an Array or Object!
  2858. for (var i in value) {
  2859. if (value.hasOwnProperty(i)) {
  2860. var obj = value[i];
  2861. if (typeof obj === 'function') {
  2862. // if Function is referenced, call it in order
  2863. // to get the FormXObject
  2864. obj = obj.call(this, form);
  2865. }
  2866. content += "/" + i + " " + obj + " ";
  2867. // In case the XForm is already used, e.g. OffState
  2868. // of CheckBoxes, don't add it
  2869. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  2870. }
  2871. }
  2872. } else {
  2873. var obj = value;
  2874. if (typeof obj === 'function') {
  2875. // if Function is referenced, call it in order to
  2876. // get the FormXObject
  2877. obj = obj.call(this, form);
  2878. }
  2879. content += "/" + i + " " + obj + " \n";
  2880. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  2881. }
  2882. content += " >>\n";
  2883. }
  2884. }
  2885. // appearance stream is a normal Object..
  2886. content += ">>\n";
  2887. }
  2888. content += ">>\nendobj\n";
  2889. scope.internal.out(content);
  2890. }
  2891. }
  2892. if (standardFields) {
  2893. createXFormObjectCallback.call(this, scope.internal.acroformPlugin.xForms);
  2894. }
  2895. };
  2896. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  2897. for (var i in fieldArray) {
  2898. if (fieldArray.hasOwnProperty(i)) {
  2899. var key = i;
  2900. var form = fieldArray[i];
  2901. // Start Writing the Object
  2902. scope.internal.newObjectDeferredBegin(form && form.objId);
  2903. var content = "";
  2904. if ((typeof form === 'undefined' ? 'undefined' : _typeof(form)) === "object" && typeof form.getString === "function") {
  2905. content = form.getString();
  2906. }
  2907. scope.internal.out(content);
  2908. delete fieldArray[key];
  2909. }
  2910. }
  2911. };
  2912. var initializeAcroForm = function initializeAcroForm() {
  2913. if (this.internal !== undefined && (this.internal.acroformPlugin === undefined || this.internal.acroformPlugin.isInitialized === false)) {
  2914. scope = this;
  2915. AcroFormField.FieldNum = 0;
  2916. this.internal.acroformPlugin = JSON.parse(JSON.stringify(acroformPluginTemplate));
  2917. if (this.internal.acroformPlugin.acroFormDictionaryRoot) {
  2918. // return;
  2919. throw new Error("Exception while creating AcroformDictionary");
  2920. }
  2921. scaleFactor = scope.internal.scaleFactor;
  2922. pageHeight = scope.internal.pageSize.getHeight();
  2923. // The Object Number of the AcroForm Dictionary
  2924. scope.internal.acroformPlugin.acroFormDictionaryRoot = new AcroFormDictionary();
  2925. // add Callback for creating the AcroForm Dictionary
  2926. scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID = scope.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  2927. scope.internal.events.subscribe('buildDocument', annotReferenceCallback); // buildDocument
  2928. // Register event, that is triggered when the DocumentCatalog is
  2929. // written, in order to add /AcroForm
  2930. scope.internal.events.subscribe('putCatalog', putCatalogCallback);
  2931. // Register event, that creates all Fields
  2932. scope.internal.events.subscribe('postPutPages', createFieldCallback);
  2933. scope.internal.acroformPlugin.isInitialized = true;
  2934. }
  2935. };
  2936. var arrayToPdfArray = function arrayToPdfArray(array) {
  2937. if (Array.isArray(array)) {
  2938. var content = ' [';
  2939. for (var i in array) {
  2940. if (array.hasOwnProperty(i)) {
  2941. var element = array[i].toString();
  2942. content += element;
  2943. content += i < array.length - 1 ? ' ' : '';
  2944. }
  2945. }
  2946. content += ']';
  2947. return content;
  2948. }
  2949. };
  2950. var toPdfString = function toPdfString(string) {
  2951. string = string || "";
  2952. // put Bracket at the Beginning of the String
  2953. if (string.indexOf('(') !== 0) {
  2954. string = '(' + string;
  2955. }
  2956. if (string.substring(string.length - 1) != ')') {
  2957. string += ')';
  2958. }
  2959. return string;
  2960. };
  2961. // ##########################
  2962. // Classes
  2963. // ##########################
  2964. var AcroFormPDFObject = function AcroFormPDFObject() {
  2965. // The Object ID in the PDF Object Model
  2966. // todo
  2967. var _objId;
  2968. Object.defineProperty(this, 'objId', {
  2969. get: function get$$1() {
  2970. if (!_objId) {
  2971. _objId = scope.internal.newObjectDeferred();
  2972. }
  2973. if (!_objId) {
  2974. console.log("Couldn't create Object ID");
  2975. }
  2976. return _objId;
  2977. },
  2978. configurable: false
  2979. });
  2980. };
  2981. AcroFormPDFObject.prototype.toString = function () {
  2982. return this.objId + " 0 R";
  2983. };
  2984. AcroFormPDFObject.prototype.getString = function () {
  2985. var res = this.objId + " 0 obj\n<<";
  2986. var content = this.getContent();
  2987. res += content + ">>\n";
  2988. if (this.stream) {
  2989. res += "stream\n";
  2990. res += this.stream;
  2991. res += "\nendstream\n";
  2992. }
  2993. res += "endobj\n";
  2994. return res;
  2995. };
  2996. AcroFormPDFObject.prototype.getContent = function () {
  2997. /**
  2998. * Prints out all enumerable Variables from the Object
  2999. *
  3000. * @param fieldObject
  3001. * @returns {string}
  3002. */
  3003. var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
  3004. var content = '';
  3005. var keys = Object.keys(fieldObject).filter(function (key) {
  3006. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  3007. });
  3008. for (var i in keys) {
  3009. if (keys.hasOwnProperty(i)) {
  3010. var key = keys[i];
  3011. var value = fieldObject[key];
  3012. /*
  3013. * if (key == 'Rect' && value) { value =
  3014. * AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal,
  3015. * value); }
  3016. */
  3017. if (value) {
  3018. if (Array.isArray(value)) {
  3019. content += '/' + key + ' ' + arrayToPdfArray(value) + "\n";
  3020. } else if (value instanceof AcroFormPDFObject) {
  3021. // In case it is a reference to another PDFObject,
  3022. // take the referennce number
  3023. content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
  3024. } else {
  3025. content += '/' + key + ' ' + value + '\n';
  3026. }
  3027. }
  3028. }
  3029. }
  3030. return content;
  3031. };
  3032. var object = "";
  3033. object += createContentFromFieldObject(this);
  3034. return object;
  3035. };
  3036. var AcroFormXObject = function AcroFormXObject() {
  3037. AcroFormPDFObject.call(this);
  3038. this.Type = "/XObject";
  3039. this.Subtype = "/Form";
  3040. this.FormType = 1;
  3041. this.BBox;
  3042. this.Matrix;
  3043. this.Resources = "2 0 R";
  3044. this.PieceInfo;
  3045. var _stream;
  3046. Object.defineProperty(this, 'Length', {
  3047. enumerable: true,
  3048. get: function get$$1() {
  3049. return _stream !== undefined ? _stream.length : 0;
  3050. }
  3051. });
  3052. Object.defineProperty(this, 'stream', {
  3053. enumerable: false,
  3054. set: function set$$1(val) {
  3055. _stream = val.trim();
  3056. },
  3057. get: function get$$1() {
  3058. if (_stream) {
  3059. return _stream;
  3060. } else {
  3061. return null;
  3062. }
  3063. }
  3064. });
  3065. };
  3066. inherit(AcroFormXObject, AcroFormPDFObject);
  3067. // ##### The Objects, the User can Create:
  3068. var AcroFormDictionary = function AcroFormDictionary() {
  3069. AcroFormPDFObject.call(this);
  3070. var _Kids = [];
  3071. Object.defineProperty(this, 'Kids', {
  3072. enumerable: false,
  3073. configurable: true,
  3074. get: function get$$1() {
  3075. if (_Kids.length > 0) {
  3076. return _Kids;
  3077. } else {
  3078. return;
  3079. }
  3080. }
  3081. });
  3082. Object.defineProperty(this, 'Fields', {
  3083. enumerable: true,
  3084. configurable: true,
  3085. get: function get$$1() {
  3086. return _Kids;
  3087. }
  3088. });
  3089. // Default Appearance
  3090. this.DA;
  3091. };
  3092. inherit(AcroFormDictionary, AcroFormPDFObject);
  3093. // The Field Object contains the Variables, that every Field needs
  3094. // Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
  3095. var AcroFormField = function AcroFormField() {
  3096. AcroFormPDFObject.call(this);
  3097. var _Rect;
  3098. Object.defineProperty(this, 'Rect', {
  3099. enumerable: true,
  3100. configurable: false,
  3101. get: function get$$1() {
  3102. if (!_Rect) {
  3103. return;
  3104. }
  3105. var tmp = _Rect;
  3106. // var calculatedRes =
  3107. // AcroForm.internal.calculateCoordinates(_Rect); // do
  3108. // later!
  3109. return tmp;
  3110. },
  3111. set: function set$$1(val) {
  3112. _Rect = val;
  3113. }
  3114. });
  3115. var _FT = "";
  3116. Object.defineProperty(this, 'FT', {
  3117. enumerable: true,
  3118. set: function set$$1(val) {
  3119. _FT = val;
  3120. },
  3121. get: function get$$1() {
  3122. return _FT;
  3123. }
  3124. });
  3125. var _F = 4;
  3126. Object.defineProperty(this, 'F', {
  3127. enumerable: true,
  3128. set: function set$$1(val) {
  3129. _F = val;
  3130. },
  3131. get: function get$$1() {
  3132. return _F;
  3133. }
  3134. });
  3135. /**
  3136. * The Partial name of the Field Object. It has to be unique.
  3137. */
  3138. var _T;
  3139. Object.defineProperty(this, 'T', {
  3140. enumerable: true,
  3141. configurable: false,
  3142. set: function set$$1(val) {
  3143. _T = val;
  3144. },
  3145. get: function get$$1() {
  3146. if (!_T || _T.length < 1) {
  3147. if (this instanceof AcroFormChildClass) {
  3148. // In case of a Child from a Radio´Group, you don't
  3149. // need a FieldName!!!
  3150. return;
  3151. }
  3152. return "(FieldObject" + AcroFormField.FieldNum++ + ")";
  3153. }
  3154. if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
  3155. return _T;
  3156. }
  3157. return "(" + _T + ")";
  3158. }
  3159. });
  3160. var _DA;
  3161. // Defines the default appearance (Needed for variable Text)
  3162. Object.defineProperty(this, 'DA', {
  3163. enumerable: true,
  3164. get: function get$$1() {
  3165. if (!_DA) {
  3166. return;
  3167. }
  3168. return '(' + _DA + ')';
  3169. },
  3170. set: function set$$1(val) {
  3171. _DA = val;
  3172. }
  3173. });
  3174. var _DV;
  3175. // Defines the default value
  3176. Object.defineProperty(this, 'DV', {
  3177. enumerable: true,
  3178. configurable: true,
  3179. get: function get$$1() {
  3180. if (!_DV) {
  3181. return;
  3182. }
  3183. return _DV;
  3184. },
  3185. set: function set$$1(val) {
  3186. _DV = val;
  3187. }
  3188. });
  3189. var _V;
  3190. // Defines the default value
  3191. Object.defineProperty(this, 'V', {
  3192. enumerable: true,
  3193. configurable: true,
  3194. get: function get$$1() {
  3195. if (!_V) {
  3196. return;
  3197. }
  3198. return _V;
  3199. },
  3200. set: function set$$1(val) {
  3201. _V = val;
  3202. }
  3203. });
  3204. // this.Type = "/Annot";
  3205. // this.Subtype = "/Widget";
  3206. Object.defineProperty(this, 'Type', {
  3207. enumerable: true,
  3208. get: function get$$1() {
  3209. return this.hasAnnotation ? "/Annot" : null;
  3210. }
  3211. });
  3212. Object.defineProperty(this, 'Subtype', {
  3213. enumerable: true,
  3214. get: function get$$1() {
  3215. return this.hasAnnotation ? "/Widget" : null;
  3216. }
  3217. });
  3218. /**
  3219. *
  3220. * @type {Array}
  3221. */
  3222. this.BG;
  3223. Object.defineProperty(this, 'hasAnnotation', {
  3224. enumerable: false,
  3225. get: function get$$1() {
  3226. if (this.Rect || this.BC || this.BG) {
  3227. return true;
  3228. }
  3229. return false;
  3230. }
  3231. });
  3232. Object.defineProperty(this, 'hasAppearanceStream', {
  3233. enumerable: false,
  3234. configurable: true,
  3235. writable: true
  3236. });
  3237. Object.defineProperty(this, 'page', {
  3238. enumerable: false,
  3239. configurable: true,
  3240. writable: true
  3241. });
  3242. };
  3243. inherit(AcroFormField, AcroFormPDFObject);
  3244. var AcroFormChoiceField = function AcroFormChoiceField() {
  3245. AcroFormField.call(this);
  3246. // Field Type = Choice Field
  3247. this.FT = "/Ch";
  3248. // options
  3249. this.Opt = [];
  3250. this.V = '()';
  3251. // Top Index
  3252. this.TI = 0;
  3253. /**
  3254. * Defines, whether the
  3255. *
  3256. * @type {boolean}
  3257. */
  3258. var _combo = false;
  3259. Object.defineProperty(this, 'combo', {
  3260. enumerable: false,
  3261. get: function get$$1() {
  3262. return _combo;
  3263. },
  3264. set: function set$$1(val) {
  3265. _combo = val;
  3266. }
  3267. });
  3268. /**
  3269. * Defines, whether the Choice Field is an Edit Field. An Edit Field
  3270. * is automatically an Combo Field.
  3271. */
  3272. Object.defineProperty(this, 'edit', {
  3273. enumerable: true,
  3274. set: function set$$1(val) {
  3275. if (val == true) {
  3276. this._edit = true;
  3277. // ComboBox has to be true
  3278. this.combo = true;
  3279. } else {
  3280. this._edit = false;
  3281. }
  3282. },
  3283. get: function get$$1() {
  3284. if (!this._edit) {
  3285. return false;
  3286. }
  3287. return this._edit;
  3288. },
  3289. configurable: false
  3290. });
  3291. this.hasAppearanceStream = true;
  3292. };
  3293. inherit(AcroFormChoiceField, AcroFormField);
  3294. var AcroFormListBox = function AcroFormListBox() {
  3295. AcroFormChoiceField.call(this);
  3296. this.combo = false;
  3297. };
  3298. inherit(AcroFormListBox, AcroFormChoiceField);
  3299. var AcroFormComboBox = function AcroFormComboBox() {
  3300. AcroFormListBox.call(this);
  3301. this.combo = true;
  3302. };
  3303. inherit(AcroFormComboBox, AcroFormListBox);
  3304. var AcroFormEditBox = function AcroFormEditBox() {
  3305. AcroFormComboBox.call(this);
  3306. this.edit = true;
  3307. };
  3308. inherit(AcroFormEditBox, AcroFormComboBox);
  3309. var AcroFormButton = function AcroFormButton() {
  3310. AcroFormField.call(this);
  3311. this.FT = "/Btn";
  3312. // this.hasAnnotation = true;
  3313. };
  3314. inherit(AcroFormButton, AcroFormField);
  3315. var AcroFormPushButton = function AcroFormPushButton() {
  3316. AcroFormButton.call(this);
  3317. var _pushbutton = true;
  3318. Object.defineProperty(this, 'pushbutton', {
  3319. enumerable: false,
  3320. get: function get$$1() {
  3321. return _pushbutton;
  3322. },
  3323. set: function set$$1(val) {
  3324. _pushbutton = val;
  3325. }
  3326. });
  3327. };
  3328. inherit(AcroFormPushButton, AcroFormButton);
  3329. var AcroFormRadioButton = function AcroFormRadioButton() {
  3330. AcroFormButton.call(this);
  3331. var _radio = true;
  3332. Object.defineProperty(this, 'radio', {
  3333. enumerable: false,
  3334. get: function get$$1() {
  3335. return _radio;
  3336. },
  3337. set: function set$$1(val) {
  3338. _radio = val;
  3339. }
  3340. });
  3341. var _Kids = [];
  3342. Object.defineProperty(this, 'Kids', {
  3343. enumerable: true,
  3344. get: function get$$1() {
  3345. if (_Kids.length > 0) {
  3346. return _Kids;
  3347. }
  3348. }
  3349. });
  3350. Object.defineProperty(this, '__Kids', {
  3351. get: function get$$1() {
  3352. return _Kids;
  3353. }
  3354. });
  3355. var _noToggleToOff;
  3356. Object.defineProperty(this, 'noToggleToOff', {
  3357. enumerable: false,
  3358. get: function get$$1() {
  3359. return _noToggleToOff;
  3360. },
  3361. set: function set$$1(val) {
  3362. _noToggleToOff = val;
  3363. }
  3364. });
  3365. // this.hasAnnotation = false;
  3366. };
  3367. inherit(AcroFormRadioButton, AcroFormButton);
  3368. /*
  3369. * The Child classs of a RadioButton (the radioGroup) -> The single
  3370. * Buttons
  3371. */
  3372. var AcroFormChildClass = function AcroFormChildClass(parent, name) {
  3373. AcroFormField.call(this);
  3374. this.Parent = parent;
  3375. // todo: set AppearanceType as variable that can be set from the
  3376. // outside...
  3377. this._AppearanceType = AcroFormAppearance.RadioButton.Circle;
  3378. // The Default appearanceType is the Circle
  3379. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  3380. // Set Print in the Annot Flag
  3381. this.F = setBitPosition(this.F, 3, 1);
  3382. // Set AppearanceCharacteristicsDictionary with default appearance
  3383. // if field is not interacting with user
  3384. this.MK = this._AppearanceType.createMK();
  3385. // (8) -> Cross, (1)-> Circle, ()-> nothing
  3386. // Default Appearance is Off
  3387. this.AS = "/Off"; // + name;
  3388. this._Name = name;
  3389. };
  3390. inherit(AcroFormChildClass, AcroFormField);
  3391. AcroFormRadioButton.prototype.setAppearance = function (appearance) {
  3392. if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
  3393. console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  3394. return;
  3395. }
  3396. for (var i in this.__Kids) {
  3397. if (this.__Kids.hasOwnProperty(i)) {
  3398. var child = this.__Kids[i];
  3399. child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
  3400. child.MK = appearance.createMK();
  3401. }
  3402. }
  3403. };
  3404. AcroFormRadioButton.prototype.createOption = function (name) {
  3405. var parent = this;
  3406. var kidCount = this.__Kids.length;
  3407. // Create new Child for RadioGroup
  3408. var child = new AcroFormChildClass(parent, name);
  3409. // Add to Parent
  3410. this.__Kids.push(child);
  3411. jsPDFAPI.addField(child);
  3412. return child;
  3413. };
  3414. var AcroFormCheckBox = function AcroFormCheckBox() {
  3415. AcroFormButton.call(this);
  3416. this.appearanceStreamContent = AcroFormAppearance.CheckBox.createAppearanceStream();
  3417. this.MK = AcroFormAppearance.CheckBox.createMK();
  3418. this.AS = "/On";
  3419. this.V = "/On";
  3420. };
  3421. inherit(AcroFormCheckBox, AcroFormButton);
  3422. var AcroFormTextField = function AcroFormTextField() {
  3423. AcroFormField.call(this);
  3424. this.DA = AcroFormAppearance.createDefaultAppearanceStream();
  3425. this.F = 4;
  3426. var _V;
  3427. Object.defineProperty(this, 'V', {
  3428. get: function get$$1() {
  3429. if (_V) {
  3430. return toPdfString(_V);
  3431. } else {
  3432. return _V;
  3433. }
  3434. },
  3435. enumerable: true,
  3436. set: function set$$1(val) {
  3437. _V = val;
  3438. }
  3439. });
  3440. var _DV;
  3441. Object.defineProperty(this, 'DV', {
  3442. get: function get$$1() {
  3443. if (_DV) {
  3444. return toPdfString(_DV);
  3445. } else {
  3446. return _DV;
  3447. }
  3448. },
  3449. enumerable: true,
  3450. set: function set$$1(val) {
  3451. _DV = val;
  3452. }
  3453. });
  3454. var _multiline = false;
  3455. Object.defineProperty(this, 'multiline', {
  3456. enumerable: false,
  3457. get: function get$$1() {
  3458. return _multiline;
  3459. },
  3460. set: function set$$1(val) {
  3461. _multiline = val;
  3462. }
  3463. });
  3464. /**
  3465. * For PDF 1.4
  3466. *
  3467. * @type {boolean}
  3468. */
  3469. var _fileSelect = false;
  3470. Object.defineProperty(this, 'fileSelect', {
  3471. enumerable: false,
  3472. get: function get$$1() {
  3473. return _fileSelect;
  3474. },
  3475. set: function set$$1(val) {
  3476. _fileSelect = val;
  3477. }
  3478. });
  3479. /**
  3480. * For PDF 1.4
  3481. *
  3482. * @type {boolean}
  3483. */
  3484. var _doNotSpellCheck = false;
  3485. Object.defineProperty(this, 'doNotSpellCheck', {
  3486. enumerable: false,
  3487. get: function get$$1() {
  3488. return _doNotSpellCheck;
  3489. },
  3490. set: function set$$1(val) {
  3491. _doNotSpellCheck = val;
  3492. }
  3493. });
  3494. /**
  3495. * For PDF 1.4
  3496. *
  3497. * @type {boolean}
  3498. */
  3499. var _doNotScroll = false;
  3500. Object.defineProperty(this, 'doNotScroll', {
  3501. enumerable: false,
  3502. get: function get$$1() {
  3503. return _doNotScroll;
  3504. },
  3505. set: function set$$1(val) {
  3506. _doNotScroll = val;
  3507. }
  3508. });
  3509. var _MaxLen = false;
  3510. Object.defineProperty(this, 'MaxLen', {
  3511. enumerable: true,
  3512. get: function get$$1() {
  3513. return _MaxLen;
  3514. },
  3515. set: function set$$1(val) {
  3516. _MaxLen = val;
  3517. }
  3518. });
  3519. Object.defineProperty(this, 'hasAppearanceStream', {
  3520. enumerable: false,
  3521. get: function get$$1() {
  3522. return this.V || this.DV;
  3523. }
  3524. });
  3525. };
  3526. inherit(AcroFormTextField, AcroFormField);
  3527. var AcroFormPasswordField = function AcroFormPasswordField() {
  3528. AcroFormTextField.call(this);
  3529. var _password = true;
  3530. Object.defineProperty(this, 'password', {
  3531. enumerable: false,
  3532. get: function get$$1() {
  3533. return _password;
  3534. },
  3535. set: function set$$1(val) {
  3536. _password = val;
  3537. }
  3538. });
  3539. };
  3540. inherit(AcroFormPasswordField, AcroFormTextField);
  3541. // Contains Methods for creating standard appearances
  3542. var AcroFormAppearance = {
  3543. CheckBox: {
  3544. createAppearanceStream: function createAppearanceStream() {
  3545. var appearance = {
  3546. N: {
  3547. On: AcroFormAppearance.CheckBox.YesNormal
  3548. },
  3549. D: {
  3550. On: AcroFormAppearance.CheckBox.YesPushDown,
  3551. Off: AcroFormAppearance.CheckBox.OffPushDown
  3552. }
  3553. };
  3554. return appearance;
  3555. },
  3556. /**
  3557. * If any other icons are needed, the number between the
  3558. * brackets can be changed
  3559. *
  3560. * @returns {string}
  3561. */
  3562. createMK: function createMK() {
  3563. return "<< /CA (3)>>";
  3564. },
  3565. /**
  3566. * Returns the standard On Appearance for a CheckBox
  3567. *
  3568. * @returns {AcroFormXObject}
  3569. */
  3570. YesPushDown: function YesPushDown(formObject) {
  3571. var xobj = createFormXObject(formObject);
  3572. var stream = [];
  3573. var zapfDingbatsId = scope.internal.getFont("zapfdingbats", "normal").id;
  3574. formObject.Q = 1; // set text-alignment as centered
  3575. var calcRes = calculateX(formObject, "3", "ZapfDingbats", 50);
  3576. stream.push("0.749023 g");
  3577. stream.push("0 0 " + AcroFormAppearance.internal.getWidth(formObject).toFixed(2) + " " + AcroFormAppearance.internal.getHeight(formObject).toFixed(2) + " re");
  3578. stream.push("f");
  3579. stream.push("BMC");
  3580. stream.push("q");
  3581. stream.push("0 0 1 rg");
  3582. stream.push("/" + zapfDingbatsId + " " + calcRes.fontSize.toFixed(2) + " Tf 0 g");
  3583. stream.push("BT");
  3584. stream.push(calcRes.text);
  3585. stream.push("ET");
  3586. stream.push("Q");
  3587. stream.push("EMC");
  3588. xobj.stream = stream.join("\n");
  3589. return xobj;
  3590. },
  3591. YesNormal: function YesNormal(formObject) {
  3592. var xobj = createFormXObject(formObject);
  3593. var zapfDingbatsId = scope.internal.getFont("zapfdingbats", "normal").id;
  3594. var stream = [];
  3595. formObject.Q = 1; // set text-alignment as centered
  3596. var height = AcroFormAppearance.internal.getHeight(formObject);
  3597. var width = AcroFormAppearance.internal.getWidth(formObject);
  3598. var calcRes = calculateX(formObject, "3", "ZapfDingbats", height * 0.9);
  3599. stream.push("1 g");
  3600. stream.push("0 0 " + width.toFixed(2) + " " + height.toFixed(2) + " re");
  3601. stream.push("f");
  3602. stream.push("q");
  3603. stream.push("0 0 1 rg");
  3604. stream.push("0 0 " + (width - 1).toFixed(2) + " " + (height - 1).toFixed(2) + " re");
  3605. stream.push("W");
  3606. stream.push("n");
  3607. stream.push("0 g");
  3608. stream.push("BT");
  3609. stream.push("/" + zapfDingbatsId + " " + calcRes.fontSize.toFixed(2) + " Tf 0 g");
  3610. stream.push(calcRes.text);
  3611. stream.push("ET");
  3612. stream.push("Q");
  3613. xobj.stream = stream.join("\n");
  3614. return xobj;
  3615. },
  3616. /**
  3617. * Returns the standard Off Appearance for a CheckBox
  3618. *
  3619. * @returns {AcroFormXObject}
  3620. */
  3621. OffPushDown: function OffPushDown(formObject) {
  3622. var xobj = createFormXObject(formObject);
  3623. var stream = [];
  3624. stream.push("0.749023 g");
  3625. stream.push("0 0 " + AcroFormAppearance.internal.getWidth(formObject).toFixed(2) + " " + AcroFormAppearance.internal.getHeight(formObject).toFixed(2) + " re");
  3626. stream.push("f");
  3627. xobj.stream = stream.join("\n");
  3628. return xobj;
  3629. }
  3630. },
  3631. RadioButton: {
  3632. Circle: {
  3633. createAppearanceStream: function createAppearanceStream(name) {
  3634. var appearanceStreamContent = {
  3635. D: {
  3636. 'Off': AcroFormAppearance.RadioButton.Circle.OffPushDown
  3637. },
  3638. N: {}
  3639. };
  3640. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Circle.YesNormal;
  3641. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Circle.YesPushDown;
  3642. return appearanceStreamContent;
  3643. },
  3644. createMK: function createMK() {
  3645. return "<< /CA (l)>>";
  3646. },
  3647. YesNormal: function YesNormal(formObject) {
  3648. var xobj = createFormXObject(formObject);
  3649. var stream = [];
  3650. // Make the Radius of the Circle relative to min(height,
  3651. // width) of formObject
  3652. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4;
  3653. // The Borderpadding...
  3654. DotRadius *= 0.9;
  3655. var c = AcroFormAppearance.internal.Bezier_C;
  3656. /*
  3657. * The Following is a Circle created with Bezier-Curves.
  3658. */
  3659. stream.push("q");
  3660. stream.push("1 0 0 1 " + AcroFormAppearance.internal.getWidth(formObject) / 2 + " " + AcroFormAppearance.internal.getHeight(formObject) / 2 + " cm");
  3661. stream.push(DotRadius + " 0 m");
  3662. stream.push(DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c");
  3663. stream.push("-" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c");
  3664. stream.push("-" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c");
  3665. stream.push(DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c");
  3666. stream.push("f");
  3667. stream.push("Q");
  3668. xobj.stream = stream.join("\n");
  3669. return xobj;
  3670. },
  3671. YesPushDown: function YesPushDown(formObject) {
  3672. var xobj = createFormXObject(formObject);
  3673. var stream = [];
  3674. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4;
  3675. // The Borderpadding...
  3676. DotRadius *= 0.9;
  3677. // Save results for later use; no need to waste
  3678. // processor ticks on doing math
  3679. var k = DotRadius * 2;
  3680. // var c = AcroFormAppearance.internal.Bezier_C;
  3681. var kc = k * AcroFormAppearance.internal.Bezier_C;
  3682. var dc = DotRadius * AcroFormAppearance.internal.Bezier_C;
  3683. stream.push("0.749023 g");
  3684. stream.push("q");
  3685. stream.push("1 0 0 1 " + (AcroFormAppearance.internal.getWidth(formObject) / 2).toFixed(2) + " " + (AcroFormAppearance.internal.getHeight(formObject) / 2).toFixed(2) + " cm");
  3686. stream.push(k + " 0 m");
  3687. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  3688. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  3689. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  3690. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  3691. stream.push("f");
  3692. stream.push("Q");
  3693. stream.push("0 g");
  3694. stream.push("q");
  3695. stream.push("1 0 0 1 " + (AcroFormAppearance.internal.getWidth(formObject) / 2).toFixed(2) + " " + (AcroFormAppearance.internal.getHeight(formObject) / 2).toFixed(2) + " cm");
  3696. stream.push(DotRadius + " 0 m");
  3697. stream.push("" + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c");
  3698. stream.push("-" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c");
  3699. stream.push("-" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c");
  3700. stream.push(dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c");
  3701. stream.push("f");
  3702. stream.push("Q");
  3703. xobj.stream = stream.join("\n");
  3704. return xobj;
  3705. },
  3706. OffPushDown: function OffPushDown(formObject) {
  3707. var xobj = createFormXObject(formObject);
  3708. var stream = [];
  3709. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4;
  3710. // The Borderpadding...
  3711. DotRadius *= 0.9;
  3712. // Save results for later use; no need to waste
  3713. // processor ticks on doing math
  3714. var k = DotRadius * 2;
  3715. // var c = AcroFormAppearance.internal.Bezier_C;
  3716. var kc = k * AcroFormAppearance.internal.Bezier_C;
  3717. stream.push("0.749023 g");
  3718. stream.push("q");
  3719. stream.push("1 0 0 1 " + (AcroFormAppearance.internal.getWidth(formObject) / 2).toFixed(2) + " " + (AcroFormAppearance.internal.getHeight(formObject) / 2).toFixed(2) + " cm");
  3720. stream.push(k + " 0 m");
  3721. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  3722. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  3723. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  3724. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  3725. stream.push("f");
  3726. stream.push("Q");
  3727. xobj.stream = stream.join("\n");
  3728. return xobj;
  3729. }
  3730. },
  3731. Cross: {
  3732. /**
  3733. * Creates the Actual AppearanceDictionary-References
  3734. *
  3735. * @param name
  3736. * @returns
  3737. */
  3738. createAppearanceStream: function createAppearanceStream(name) {
  3739. var appearanceStreamContent = {
  3740. D: {
  3741. 'Off': AcroFormAppearance.RadioButton.Cross.OffPushDown
  3742. },
  3743. N: {}
  3744. };
  3745. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Cross.YesNormal;
  3746. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Cross.YesPushDown;
  3747. return appearanceStreamContent;
  3748. },
  3749. createMK: function createMK() {
  3750. return "<< /CA (8)>>";
  3751. },
  3752. YesNormal: function YesNormal(formObject) {
  3753. var xobj = createFormXObject(formObject);
  3754. var stream = [];
  3755. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  3756. stream.push("q");
  3757. stream.push("1 1 " + (AcroFormAppearance.internal.getWidth(formObject) - 2).toFixed(2) + " " + (AcroFormAppearance.internal.getHeight(formObject) - 2).toFixed(2) + " re");
  3758. stream.push("W");
  3759. stream.push("n");
  3760. stream.push(cross.x1.x.toFixed(2) + " " + cross.x1.y.toFixed(2) + " m");
  3761. stream.push(cross.x2.x.toFixed(2) + " " + cross.x2.y.toFixed(2) + " l");
  3762. stream.push(cross.x4.x.toFixed(2) + " " + cross.x4.y.toFixed(2) + " m");
  3763. stream.push(cross.x3.x.toFixed(2) + " " + cross.x3.y.toFixed(2) + " l");
  3764. stream.push("s");
  3765. stream.push("Q");
  3766. xobj.stream = stream.join("\n");
  3767. return xobj;
  3768. },
  3769. YesPushDown: function YesPushDown(formObject) {
  3770. var xobj = createFormXObject(formObject);
  3771. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  3772. var stream = [];
  3773. stream.push("0.749023 g");
  3774. stream.push("0 0 " + AcroFormAppearance.internal.getWidth(formObject).toFixed(2) + " " + AcroFormAppearance.internal.getHeight(formObject).toFixed(2) + " re");
  3775. stream.push("f");
  3776. stream.push("q");
  3777. stream.push("1 1 " + (AcroFormAppearance.internal.getWidth(formObject) - 2).toFixed(2) + " " + (AcroFormAppearance.internal.getHeight(formObject) - 2).toFixed(2) + " re");
  3778. stream.push("W");
  3779. stream.push("n");
  3780. stream.push(cross.x1.x.toFixed(2) + " " + cross.x1.y.toFixed(2) + " m");
  3781. stream.push(cross.x2.x.toFixed(2) + " " + cross.x2.y.toFixed(2) + " l");
  3782. stream.push(cross.x4.x.toFixed(2) + " " + cross.x4.y.toFixed(2) + " m");
  3783. stream.push(cross.x3.x.toFixed(2) + " " + cross.x3.y.toFixed(2) + " l");
  3784. stream.push("s");
  3785. stream.push("Q");
  3786. xobj.stream = stream.join("\n");
  3787. return xobj;
  3788. },
  3789. OffPushDown: function OffPushDown(formObject) {
  3790. var xobj = createFormXObject(formObject);
  3791. var stream = [];
  3792. stream.push("0.749023 g");
  3793. stream.push("0 0 " + AcroFormAppearance.internal.getWidth(formObject).toFixed(2) + " " + AcroFormAppearance.internal.getHeight(formObject).toFixed(2) + " re");
  3794. stream.push("f");
  3795. xobj.stream = stream.join("\n");
  3796. return xobj;
  3797. }
  3798. }
  3799. },
  3800. /**
  3801. * Returns the standard Appearance
  3802. *
  3803. * @returns {AcroFormXObject}
  3804. */
  3805. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  3806. // Set Helvetica to Standard Font (size: auto)
  3807. // Color: Black
  3808. return "/F1 0 Tf 0 g";
  3809. }
  3810. };
  3811. AcroFormAppearance.internal = {
  3812. Bezier_C: 0.551915024494,
  3813. calculateCross: function calculateCross(formObject) {
  3814. var min = function min(x, y) {
  3815. return x > y ? y : x;
  3816. };
  3817. var width = AcroFormAppearance.internal.getWidth(formObject);
  3818. var height = AcroFormAppearance.internal.getHeight(formObject);
  3819. var a = min(width, height);
  3820. var cross = {
  3821. x1: { // upperLeft
  3822. x: (width - a) / 2,
  3823. y: (height - a) / 2 + a // height - borderPadding
  3824. },
  3825. x2: { // lowerRight
  3826. x: (width - a) / 2 + a,
  3827. y: (height - a) / 2 // borderPadding
  3828. },
  3829. x3: { // lowerLeft
  3830. x: (width - a) / 2,
  3831. y: (height - a) / 2 // borderPadding
  3832. },
  3833. x4: { // upperRight
  3834. x: (width - a) / 2 + a,
  3835. y: (height - a) / 2 + a // height - borderPadding
  3836. }
  3837. };
  3838. return cross;
  3839. }
  3840. };
  3841. AcroFormAppearance.internal.getWidth = function (formObject) {
  3842. var result = 0;
  3843. if ((typeof formObject === 'undefined' ? 'undefined' : _typeof(formObject)) === "object") {
  3844. result = scale(formObject.Rect[2]); // (formObject.Rect[2] -
  3845. // formObject.Rect[0]) || 0;
  3846. }
  3847. return result;
  3848. };
  3849. AcroFormAppearance.internal.getHeight = function (formObject) {
  3850. var result = 0;
  3851. if ((typeof formObject === 'undefined' ? 'undefined' : _typeof(formObject)) === "object") {
  3852. result = scale(formObject.Rect[3]); // (formObject.Rect[1] -
  3853. // formObject.Rect[3]) || 0;
  3854. }
  3855. return result;
  3856. };
  3857. // Public:
  3858. jsPDFAPI.addField = function (fieldObject) {
  3859. initializeAcroForm.call(this);
  3860. // var opt = parseOptions(fieldObject);
  3861. if (fieldObject instanceof AcroFormTextField) {
  3862. this.addTextField.call(this, fieldObject);
  3863. } else if (fieldObject instanceof AcroFormChoiceField) {
  3864. this.addChoiceField.call(this, fieldObject);
  3865. } else if (fieldObject instanceof AcroFormButton) {
  3866. this.addButton.call(this, fieldObject);
  3867. } else if (fieldObject instanceof AcroFormChildClass) {
  3868. putForm.call(this, fieldObject);
  3869. } else if (fieldObject) {
  3870. // try to put..
  3871. putForm.call(this, fieldObject);
  3872. }
  3873. fieldObject.page = scope.internal.getCurrentPageInfo().pageNumber;
  3874. return this;
  3875. };
  3876. /**
  3877. * Button FT = Btn
  3878. */
  3879. jsPDFAPI.addButton = function (opts) {
  3880. initializeAcroForm.call(this);
  3881. var options = opts || new AcroFormField();
  3882. options.FT = '/Btn';
  3883. options.Ff = calculateFlagsOnOptions(options.Ff, opts, scope.internal.getPDFVersion());
  3884. putForm.call(this, options);
  3885. };
  3886. jsPDFAPI.addTextField = function (opts) {
  3887. initializeAcroForm.call(this);
  3888. var options = opts || new AcroFormField();
  3889. options.FT = '/Tx';
  3890. options.Ff = calculateFlagsOnOptions(options.Ff, opts, scope.internal.getPDFVersion());
  3891. // Add field
  3892. putForm.call(this, options);
  3893. };
  3894. jsPDFAPI.addChoiceField = function (opts) {
  3895. initializeAcroForm.call(this);
  3896. var options = opts || new AcroFormField();
  3897. options.FT = '/Ch';
  3898. options.Ff = calculateFlagsOnOptions(options.Ff, opts, scope.internal.getPDFVersion());
  3899. // options.hasAnnotation = true;
  3900. // Add field
  3901. putForm.call(this, options);
  3902. };
  3903. if ((typeof globalObj === 'undefined' ? 'undefined' : _typeof(globalObj)) == "object") {
  3904. globalObj["ChoiceField"] = AcroFormChoiceField;
  3905. globalObj["ListBox"] = AcroFormListBox;
  3906. globalObj["ComboBox"] = AcroFormComboBox;
  3907. globalObj["EditBox"] = AcroFormEditBox;
  3908. globalObj["Button"] = AcroFormButton;
  3909. globalObj["PushButton"] = AcroFormPushButton;
  3910. globalObj["RadioButton"] = AcroFormRadioButton;
  3911. globalObj["CheckBox"] = AcroFormCheckBox;
  3912. globalObj["TextField"] = AcroFormTextField;
  3913. globalObj["PasswordField"] = AcroFormPasswordField;
  3914. // backwardsCompatibility
  3915. globalObj["AcroForm"] = { Appearance: AcroFormAppearance };
  3916. }
  3917. jsPDFAPI.AcroFormChoiceField = AcroFormChoiceField;
  3918. jsPDFAPI.AcroFormListBox = AcroFormListBox;
  3919. jsPDFAPI.AcroFormComboBox = AcroFormComboBox;
  3920. jsPDFAPI.AcroFormEditBox = AcroFormEditBox;
  3921. jsPDFAPI.AcroFormButton = AcroFormButton;
  3922. jsPDFAPI.AcroFormPushButton = AcroFormPushButton;
  3923. jsPDFAPI.AcroFormRadioButton = AcroFormRadioButton;
  3924. jsPDFAPI.AcroFormCheckBox = AcroFormCheckBox;
  3925. jsPDFAPI.AcroFormTextField = AcroFormTextField;
  3926. jsPDFAPI.AcroFormPasswordField = AcroFormPasswordField;
  3927. jsPDFAPI.AcroFormAppearance = AcroFormAppearance;
  3928. jsPDFAPI.AcroForm = {
  3929. ChoiceField: AcroFormChoiceField,
  3930. ListBox: AcroFormListBox,
  3931. ComboBox: AcroFormComboBox,
  3932. EditBox: AcroFormEditBox,
  3933. Button: AcroFormButton,
  3934. PushButton: AcroFormPushButton,
  3935. RadioButton: AcroFormRadioButton,
  3936. CheckBox: AcroFormCheckBox,
  3937. TextField: AcroFormTextField,
  3938. PasswordField: AcroFormPasswordField,
  3939. Appearance: AcroFormAppearance
  3940. };
  3941. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  3942. /**
  3943. * jsPDF addHTML PlugIn
  3944. * Copyright (c) 2014 Diego Casorran
  3945. *
  3946. * Licensed under the MIT License.
  3947. * http://opensource.org/licenses/mit-license
  3948. */
  3949. (function (jsPDFAPI) {
  3950. /**
  3951. * Renders an HTML element to canvas object which added to the PDF
  3952. *
  3953. * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
  3954. * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
  3955. *
  3956. * @returns {jsPDF}
  3957. * @name addHTML
  3958. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  3959. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  3960. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  3961. * @param options {Object} Additional options, check the code below.
  3962. * @param callback {Function} to call when the rendering has finished.
  3963. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  3964. * case the image is positioned at 0x0 covering the whole PDF document
  3965. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  3966. * @deprecated This is being replace with a vector-supporting API. See
  3967. * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
  3968. */
  3969. jsPDFAPI.addHTML = function (element, x, y, options, callback) {
  3970. 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');
  3971. if (typeof x !== 'number') {
  3972. options = x;
  3973. callback = y;
  3974. }
  3975. if (typeof options === 'function') {
  3976. callback = options;
  3977. options = null;
  3978. }
  3979. if (typeof callback !== 'function') {
  3980. callback = function callback() {};
  3981. }
  3982. var I = this.internal,
  3983. K = I.scaleFactor,
  3984. W = I.pageSize.getWidth(),
  3985. H = I.pageSize.getHeight();
  3986. options = options || {};
  3987. options.onrendered = function (obj) {
  3988. x = parseInt(x) || 0;
  3989. y = parseInt(y) || 0;
  3990. var dim = options.dim || {};
  3991. var margin = Object.assign({ top: 0, right: 0, bottom: 0, left: 0, useFor: 'content' }, options.margin);
  3992. var h = dim.h || Math.min(H, obj.height / K);
  3993. var w = dim.w || Math.min(W, obj.width / K) - x;
  3994. var format = options.format || 'JPEG';
  3995. var imageCompression = options.imageCompression || 'SLOW';
  3996. var notFittingHeight = obj.height > H - margin.top - margin.bottom;
  3997. if (notFittingHeight && options.pagesplit) {
  3998. var cropArea = function cropArea(parmObj, parmX, parmY, parmWidth, parmHeight) {
  3999. var canvas = document.createElement('canvas');
  4000. canvas.height = parmHeight;
  4001. canvas.width = parmWidth;
  4002. var ctx = canvas.getContext('2d');
  4003. ctx.mozImageSmoothingEnabled = false;
  4004. ctx.webkitImageSmoothingEnabled = false;
  4005. ctx.msImageSmoothingEnabled = false;
  4006. ctx.imageSmoothingEnabled = false;
  4007. ctx.fillStyle = options.backgroundColor || '#ffffff';
  4008. ctx.fillRect(0, 0, parmWidth, parmHeight);
  4009. ctx.drawImage(parmObj, parmX, parmY, parmWidth, parmHeight, 0, 0, parmWidth, parmHeight);
  4010. return canvas;
  4011. };
  4012. var crop = function () {
  4013. var cy = 0;
  4014. var cx = 0;
  4015. var position = {};
  4016. var isOverWide = false;
  4017. var width;
  4018. var height;
  4019. while (1) {
  4020. cx = 0;
  4021. position.top = cy !== 0 ? margin.top : y;
  4022. position.left = cy !== 0 ? margin.left : x;
  4023. isOverWide = (W - margin.left - margin.right) * K < obj.width;
  4024. if (margin.useFor === "content") {
  4025. if (cy === 0) {
  4026. width = Math.min((W - margin.left) * K, obj.width);
  4027. height = Math.min((H - margin.top) * K, obj.height - cy);
  4028. } else {
  4029. width = Math.min(W * K, obj.width);
  4030. height = Math.min(H * K, obj.height - cy);
  4031. position.top = 0;
  4032. }
  4033. } else {
  4034. width = Math.min((W - margin.left - margin.right) * K, obj.width);
  4035. height = Math.min((H - margin.bottom - margin.top) * K, obj.height - cy);
  4036. }
  4037. if (isOverWide) {
  4038. while (1) {
  4039. if (margin.useFor === "content") {
  4040. if (cx === 0) {
  4041. width = Math.min((W - margin.left) * K, obj.width);
  4042. } else {
  4043. width = Math.min(W * K, obj.width - cx);
  4044. position.left = 0;
  4045. }
  4046. }
  4047. var canvas = cropArea(obj, cx, cy, width, height);
  4048. var args = [canvas, position.left, position.top, canvas.width / K, canvas.height / K, format, null, imageCompression];
  4049. this.addImage.apply(this, args);
  4050. cx += width;
  4051. if (cx >= obj.width) {
  4052. break;
  4053. }
  4054. this.addPage();
  4055. }
  4056. } else {
  4057. var canvas = cropArea(obj, 0, cy, width, height);
  4058. var args = [canvas, position.left, position.top, canvas.width / K, canvas.height / K, format, null, imageCompression];
  4059. this.addImage.apply(this, args);
  4060. }
  4061. cy += height;
  4062. if (cy >= obj.height) {
  4063. break;
  4064. }
  4065. this.addPage();
  4066. }
  4067. callback(w, cy, null, args);
  4068. }.bind(this);
  4069. if (obj.nodeName === 'CANVAS') {
  4070. var img = new Image();
  4071. img.onload = crop;
  4072. img.src = obj.toDataURL("image/png");
  4073. obj = img;
  4074. } else {
  4075. crop();
  4076. }
  4077. } else {
  4078. var alias = Math.random().toString(35);
  4079. var args = [obj, x, y, w, h, format, alias, imageCompression];
  4080. this.addImage.apply(this, args);
  4081. callback(w, h, alias, args);
  4082. }
  4083. }.bind(this);
  4084. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  4085. return html2canvas(element, options);
  4086. }
  4087. if (typeof rasterizeHTML !== 'undefined') {
  4088. var meth = 'drawDocument';
  4089. if (typeof element === 'string') {
  4090. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  4091. }
  4092. options.width = options.width || W * K;
  4093. return rasterizeHTML[meth](element, void 0, options).then(function (r) {
  4094. options.onrendered(r.image);
  4095. }, function (e) {
  4096. callback(null, e);
  4097. });
  4098. }
  4099. return null;
  4100. };
  4101. })(jsPDF.API);
  4102. /** @preserve
  4103. * jsPDF addImage plugin
  4104. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  4105. * 2013 Chris Dowling, https://github.com/gingerchris
  4106. * 2013 Trinh Ho, https://github.com/ineedfat
  4107. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  4108. * 2013 Norah Smith, https://github.com/burnburnrocket
  4109. * 2014 Diego Casorran, https://github.com/diegocr
  4110. * 2014 James Robb, https://github.com/jamesbrobb
  4111. *
  4112. *
  4113. */
  4114. (function (jsPDFAPI) {
  4115. var namespace = 'addImage_';
  4116. var imageFileTypeHeaders = {
  4117. PNG: [[0x89, 0x50, 0x4e, 0x47]],
  4118. TIFF: [[0x4D, 0x4D, 0x00, 0x2A], //Motorola
  4119. [0x49, 0x49, 0x2A, 0x00] //Intel
  4120. ],
  4121. JPEG: [[0xFF, 0xD8, 0xFF, 0xE0, undefined, undefined, 0x4A, 0x46, 0x49, 0x46, 0x00], //JFIF
  4122. [0xFF, 0xD8, 0xFF, 0xE1, undefined, undefined, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00] //Exif
  4123. ],
  4124. JPEG2000: [[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20]],
  4125. GIF87a: [[0x47, 0x49, 0x46, 0x38, 0x37, 0x61]],
  4126. GIF89a: [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61]],
  4127. BMP: [[0x42, 0x4D], //BM - Windows 3.1x, 95, NT, ... etc.
  4128. [0x42, 0x41], //BA - OS/2 struct bitmap array
  4129. [0x43, 0x49], //CI - OS/2 struct color icon
  4130. [0x43, 0x50], //CP - OS/2 const color pointer
  4131. [0x49, 0x43], //IC - OS/2 struct icon
  4132. [0x50, 0x54] //PT - OS/2 pointer
  4133. ]
  4134. /**
  4135. * Recognize filetype of Image by magic-bytes
  4136. *
  4137. * https://en.wikipedia.org/wiki/List_of_file_signatures
  4138. *
  4139. * @name getImageFileTypeByImageData
  4140. * @public
  4141. * @function
  4142. * @param {String} imageData as base64 encoded DataUrl
  4143. * @param {String} format of file if filetype-recognition fails, e.g. 'JPEG'
  4144. *
  4145. * @returns {String} filetype of Image
  4146. * @methodOf jsPDF#
  4147. */
  4148. };jsPDFAPI.getImageFileTypeByImageData = function (imageData, fallbackFormat) {
  4149. fallbackFormat = fallbackFormat || 'UNKNOWN';
  4150. var i;
  4151. var j;
  4152. var result = 'UNKNOWN';
  4153. var headerSchemata;
  4154. var compareResult;
  4155. var fileType;
  4156. for (fileType in imageFileTypeHeaders) {
  4157. headerSchemata = imageFileTypeHeaders[fileType];
  4158. for (i = 0; i < headerSchemata.length; i += 1) {
  4159. compareResult = true;
  4160. for (j = 0; j < headerSchemata[i].length; j += 1) {
  4161. if (headerSchemata[i][j] === undefined) {
  4162. continue;
  4163. }
  4164. if (headerSchemata[i][j] !== imageData.charCodeAt(j)) {
  4165. compareResult = false;
  4166. break;
  4167. }
  4168. }
  4169. if (compareResult === true) {
  4170. result = fileType;
  4171. break;
  4172. }
  4173. }
  4174. }
  4175. if (result === 'UNKNOWN' && fallbackFormat !== 'UNKNOWN') {
  4176. console.warn('FileType of Image not recognized. Processing image as "' + fallbackFormat + '".');
  4177. result = fallbackFormat;
  4178. }
  4179. return result;
  4180. };
  4181. // Image functionality ported from pdf.js
  4182. var putImage = function putImage(img) {
  4183. var objectNumber = this.internal.newObject(),
  4184. out = this.internal.write,
  4185. putStream = this.internal.putStream;
  4186. img['n'] = objectNumber;
  4187. out('<</Type /XObject');
  4188. out('/Subtype /Image');
  4189. out('/Width ' + img['w']);
  4190. out('/Height ' + img['h']);
  4191. if (img['cs'] === this.color_spaces.INDEXED) {
  4192. out('/ColorSpace [/Indexed /DeviceRGB '
  4193. // if an indexed png defines more than one colour with transparency, we've created a smask
  4194. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
  4195. } else {
  4196. out('/ColorSpace /' + img['cs']);
  4197. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  4198. out('/Decode [1 0 1 0 1 0 1 0]');
  4199. }
  4200. }
  4201. out('/BitsPerComponent ' + img['bpc']);
  4202. if ('f' in img) {
  4203. out('/Filter /' + img['f']);
  4204. }
  4205. if ('dp' in img) {
  4206. out('/DecodeParms <<' + img['dp'] + '>>');
  4207. }
  4208. if ('trns' in img && img['trns'].constructor == Array) {
  4209. var trns = '',
  4210. i = 0,
  4211. len = img['trns'].length;
  4212. for (; i < len; i++) {
  4213. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  4214. }out('/Mask [' + trns + ']');
  4215. }
  4216. if ('smask' in img) {
  4217. out('/SMask ' + (objectNumber + 1) + ' 0 R');
  4218. }
  4219. out('/Length ' + img['data'].length + '>>');
  4220. putStream(img['data']);
  4221. out('endobj');
  4222. // Soft mask
  4223. if ('smask' in img) {
  4224. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  4225. var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
  4226. if ('f' in img) smask.f = img['f'];
  4227. putImage.call(this, smask);
  4228. }
  4229. //Palette
  4230. if (img['cs'] === this.color_spaces.INDEXED) {
  4231. this.internal.newObject();
  4232. //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  4233. //putStream(zlib.compress(img['pal']));
  4234. out('<< /Length ' + img['pal'].length + '>>');
  4235. putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
  4236. out('endobj');
  4237. }
  4238. },
  4239. putResourcesCallback = function putResourcesCallback() {
  4240. var images = this.internal.collections[namespace + 'images'];
  4241. for (var i in images) {
  4242. putImage.call(this, images[i]);
  4243. }
  4244. },
  4245. putXObjectsDictCallback = function putXObjectsDictCallback() {
  4246. var images = this.internal.collections[namespace + 'images'],
  4247. out = this.internal.write,
  4248. image;
  4249. for (var i in images) {
  4250. image = images[i];
  4251. out('/I' + image['i'], image['n'], '0', 'R');
  4252. }
  4253. },
  4254. checkCompressValue = function checkCompressValue(value) {
  4255. if (value && typeof value === 'string') value = value.toUpperCase();
  4256. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  4257. },
  4258. getImages = function getImages() {
  4259. var images = this.internal.collections[namespace + 'images'];
  4260. //first run, so initialise stuff
  4261. if (!images) {
  4262. this.internal.collections[namespace + 'images'] = images = {};
  4263. this.internal.events.subscribe('putResources', putResourcesCallback);
  4264. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  4265. }
  4266. return images;
  4267. },
  4268. getImageIndex = function getImageIndex(images) {
  4269. var imageIndex = 0;
  4270. if (images) {
  4271. // this is NOT the first time this method is ran on this instance of jsPDF object.
  4272. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  4273. var i = 0;
  4274. for (var e in o) {
  4275. if (o.hasOwnProperty(e)) {
  4276. i++;
  4277. }
  4278. }
  4279. return i;
  4280. }(images);
  4281. }
  4282. return imageIndex;
  4283. },
  4284. notDefined = function notDefined(value) {
  4285. return typeof value === 'undefined' || value === null || value.length === 0;
  4286. },
  4287. generateAliasFromData = function generateAliasFromData(data) {
  4288. return typeof data === 'string' && jsPDFAPI.sHashCode(data);
  4289. },
  4290. isImageTypeSupported = function isImageTypeSupported(type) {
  4291. return typeof jsPDFAPI["process" + type.toUpperCase()] === "function";
  4292. },
  4293. isDOMElement = function isDOMElement(object) {
  4294. return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
  4295. },
  4296. createDataURIFromElement = function createDataURIFromElement(element, format) {
  4297. //if element is an image which uses data url definition, just return the dataurl
  4298. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  4299. var src = '' + element.getAttribute('src');
  4300. if (src.indexOf('data:image/') === 0) return src;
  4301. // only if the user doesn't care about a format
  4302. if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
  4303. }
  4304. if (element.nodeName === 'CANVAS') {
  4305. var canvas = element;
  4306. } else {
  4307. var canvas = document.createElement('canvas');
  4308. canvas.width = element.clientWidth || element.width;
  4309. canvas.height = element.clientHeight || element.height;
  4310. var ctx = canvas.getContext('2d');
  4311. if (!ctx) {
  4312. throw 'addImage requires canvas to be supported by browser.';
  4313. }
  4314. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  4315. }
  4316. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  4317. },
  4318. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  4319. var cached_info;
  4320. if (images) {
  4321. for (var e in images) {
  4322. if (alias === images[e].alias) {
  4323. cached_info = images[e];
  4324. break;
  4325. }
  4326. }
  4327. }
  4328. return cached_info;
  4329. },
  4330. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  4331. if (!w && !h) {
  4332. w = -96;
  4333. h = -96;
  4334. }
  4335. if (w < 0) {
  4336. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  4337. }
  4338. if (h < 0) {
  4339. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  4340. }
  4341. if (w === 0) {
  4342. w = h * info['w'] / info['h'];
  4343. }
  4344. if (h === 0) {
  4345. h = w * info['h'] / info['w'];
  4346. }
  4347. return [w, h];
  4348. },
  4349. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images, rotation) {
  4350. var dims = determineWidthAndHeight.call(this, w, h, info),
  4351. coord = this.internal.getCoordinateString,
  4352. vcoord = this.internal.getVerticalCoordinateString;
  4353. w = dims[0];
  4354. h = dims[1];
  4355. images[index] = info;
  4356. if (rotation) {
  4357. rotation *= Math.PI / 180;
  4358. var c = Math.cos(rotation);
  4359. var s = Math.sin(rotation);
  4360. //like in pdf Reference do it 4 digits instead of 2
  4361. var f4 = function f4(number) {
  4362. return number.toFixed(4);
  4363. };
  4364. var rotationTransformationMatrix = [f4(c), f4(s), f4(s * -1), f4(c), 0, 0, 'cm'];
  4365. }
  4366. this.internal.write('q'); //Save graphics state
  4367. if (rotation) {
  4368. this.internal.write([1, '0', '0', 1, coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate
  4369. this.internal.write(rotationTransformationMatrix.join(' ')); //Rotate
  4370. this.internal.write([coord(w), '0', '0', coord(h), '0', '0', 'cm'].join(' ')); //Scale
  4371. } else {
  4372. this.internal.write([coord(w), '0', '0', coord(h), coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate and Scale
  4373. }
  4374. this.internal.write('/I' + info['i'] + ' Do'); //Paint Image
  4375. this.internal.write('Q'); //Restore graphics state
  4376. };
  4377. /**
  4378. * COLOR SPACES
  4379. */
  4380. jsPDFAPI.color_spaces = {
  4381. DEVICE_RGB: 'DeviceRGB',
  4382. DEVICE_GRAY: 'DeviceGray',
  4383. DEVICE_CMYK: 'DeviceCMYK',
  4384. CAL_GREY: 'CalGray',
  4385. CAL_RGB: 'CalRGB',
  4386. LAB: 'Lab',
  4387. ICC_BASED: 'ICCBased',
  4388. INDEXED: 'Indexed',
  4389. PATTERN: 'Pattern',
  4390. SEPARATION: 'Separation',
  4391. DEVICE_N: 'DeviceN'
  4392. };
  4393. /**
  4394. * DECODE METHODS
  4395. */
  4396. jsPDFAPI.decode = {
  4397. DCT_DECODE: 'DCTDecode',
  4398. FLATE_DECODE: 'FlateDecode',
  4399. LZW_DECODE: 'LZWDecode',
  4400. JPX_DECODE: 'JPXDecode',
  4401. JBIG2_DECODE: 'JBIG2Decode',
  4402. ASCII85_DECODE: 'ASCII85Decode',
  4403. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  4404. RUN_LENGTH_DECODE: 'RunLengthDecode',
  4405. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  4406. };
  4407. /**
  4408. * IMAGE COMPRESSION TYPES
  4409. */
  4410. jsPDFAPI.image_compression = {
  4411. NONE: 'NONE',
  4412. FAST: 'FAST',
  4413. MEDIUM: 'MEDIUM',
  4414. SLOW: 'SLOW'
  4415. };
  4416. jsPDFAPI.sHashCode = function (str) {
  4417. str = str || "";
  4418. return Array.prototype.reduce && str.split("").reduce(function (a, b) {
  4419. a = (a << 5) - a + b.charCodeAt(0);return a & a;
  4420. }, 0);
  4421. };
  4422. jsPDFAPI.isString = function (object) {
  4423. return typeof object === 'string';
  4424. };
  4425. /**
  4426. * Validates if given String is a valid Base64-String
  4427. *
  4428. * @name validateStringAsBase64
  4429. * @public
  4430. * @function
  4431. * @param {String} possible Base64-String
  4432. *
  4433. * @returns {boolean}
  4434. * @methodOf jsPDF#
  4435. */
  4436. jsPDFAPI.validateStringAsBase64 = function (possibleBase64String) {
  4437. possibleBase64String = possibleBase64String || '';
  4438. var result = true;
  4439. if (possibleBase64String.length % 4 !== 0) {
  4440. result = false;
  4441. }
  4442. if (/[A-Za-z0-9\/]+/.test(possibleBase64String.substr(0, possibleBase64String.length - 2)) === false) {
  4443. result = false;
  4444. }
  4445. if (/[A-Za-z0-9\/][A-Za-z0-9+\/]|[A-Za-z0-9+\/]=|==/.test(possibleBase64String.substr(-2)) === false) {
  4446. result = false;
  4447. }
  4448. return result;
  4449. };
  4450. /**
  4451. * Strips out and returns info from a valid base64 data URI
  4452. * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  4453. * @returns an Array containing the following
  4454. * [0] the complete data URI
  4455. * [1] <MIME-type>
  4456. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  4457. * [4] <data>
  4458. */
  4459. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  4460. return (/^data:([\w]+?\/([\w]+?));base64,(.+)$/g.exec(dataURI)
  4461. );
  4462. };
  4463. /**
  4464. * Check to see if ArrayBuffer is supported
  4465. *
  4466. * @returns {boolean}
  4467. * @methodOf jsPDF#
  4468. */
  4469. jsPDFAPI.supportsArrayBuffer = function () {
  4470. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  4471. };
  4472. /**
  4473. * Tests supplied object to determine if ArrayBuffer
  4474. * @param {Object[object]}
  4475. *
  4476. * @returns {boolean}
  4477. * @methodOf jsPDF#
  4478. */
  4479. jsPDFAPI.isArrayBuffer = function (object) {
  4480. if (!this.supportsArrayBuffer()) return false;
  4481. return object instanceof ArrayBuffer;
  4482. };
  4483. /**
  4484. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  4485. * @param {Object[object]}
  4486. */
  4487. jsPDFAPI.isArrayBufferView = function (object) {
  4488. if (!this.supportsArrayBuffer()) return false;
  4489. if (typeof Uint32Array === 'undefined') return false;
  4490. 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;
  4491. };
  4492. /**
  4493. * Convert the Buffer to a Binary String
  4494. *
  4495. * @name binaryStringToUint8Array
  4496. * @public
  4497. * @function
  4498. * @param {ArrayBuffer} BinaryString with ImageData
  4499. *
  4500. * @returns {Uint8Array}
  4501. */
  4502. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  4503. /*
  4504. * not sure how efficient this will be will bigger files. Is there a native method?
  4505. */
  4506. var len = binary_string.length;
  4507. var bytes = new Uint8Array(len);
  4508. for (var i = 0; i < len; i++) {
  4509. bytes[i] = binary_string.charCodeAt(i);
  4510. }
  4511. return bytes;
  4512. };
  4513. /**
  4514. * Convert the Buffer to a Binary String
  4515. *
  4516. * @name arrayBufferToBinaryString
  4517. * @public
  4518. * @function
  4519. * @param {ArrayBuffer} ArrayBuffer with ImageData
  4520. *
  4521. * @returns {String}
  4522. */
  4523. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  4524. if (typeof atob === "function") {
  4525. return atob(this.arrayBufferToBase64(buffer));
  4526. }
  4527. if (typeof TextDecoder === "function") {
  4528. var decoder = new TextDecoder('ascii');
  4529. // test if the encoding is supported
  4530. if (decoder.encoding === 'ascii') {
  4531. return decoder.decode(buffer);
  4532. }
  4533. }
  4534. //Fallback-solution
  4535. var data = this.isArrayBuffer(buffer) ? buffer : new Uint8Array(buffer);
  4536. var chunkSizeForSlice = 0x5000;
  4537. var binary_string = '';
  4538. var slicesCount = Math.ceil(data.byteLength / chunkSizeForSlice);
  4539. for (var i = 0; i < slicesCount; i++) {
  4540. binary_string += String.fromCharCode.apply(null, data.slice(i * chunkSizeForSlice, i * chunkSizeForSlice + chunkSizeForSlice));
  4541. }
  4542. return binary_string;
  4543. };
  4544. /**
  4545. * Converts an ArrayBuffer directly to base64
  4546. *
  4547. * Taken from http://jsperf.com/encoding-xhr-image-data/31
  4548. *
  4549. * Need to test if this is a better solution for larger files
  4550. *
  4551. * @name arrayBufferToBase64
  4552. * @public
  4553. * @function
  4554. *
  4555. * @returns {String}
  4556. */
  4557. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  4558. var base64 = '';
  4559. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  4560. var bytes = new Uint8Array(arrayBuffer);
  4561. var byteLength = bytes.byteLength;
  4562. var byteRemainder = byteLength % 3;
  4563. var mainLength = byteLength - byteRemainder;
  4564. var a, b, c, d;
  4565. var chunk;
  4566. // Main loop deals with bytes in chunks of 3
  4567. for (var i = 0; i < mainLength; i = i + 3) {
  4568. // Combine the three bytes into a single integer
  4569. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
  4570. // Use bitmasks to extract 6-bit segments from the triplet
  4571. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  4572. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  4573. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  4574. d = chunk & 63; // 63 = 2^6 - 1
  4575. // Convert the raw binary segments to the appropriate ASCII encoding
  4576. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  4577. }
  4578. // Deal with the remaining bytes and padding
  4579. if (byteRemainder == 1) {
  4580. chunk = bytes[mainLength];
  4581. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  4582. // Set the 4 least significant bits to zero
  4583. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  4584. base64 += encodings[a] + encodings[b] + '==';
  4585. } else if (byteRemainder == 2) {
  4586. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  4587. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  4588. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  4589. // Set the 2 least significant bits to zero
  4590. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  4591. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  4592. }
  4593. return base64;
  4594. };
  4595. /**
  4596. * Converts an ArrayBuffer directly to base64
  4597. *
  4598. * Taken from http://jsperf.com/encoding-xhr-image-data/31
  4599. *
  4600. * Need to test if this is a better solution for larger files
  4601. *
  4602. * @public
  4603. * @function
  4604. *
  4605. * @returns {String}
  4606. */
  4607. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  4608. var info = {
  4609. alias: alias,
  4610. w: wd,
  4611. h: ht,
  4612. cs: cs,
  4613. bpc: bpc,
  4614. i: imageIndex,
  4615. data: data
  4616. // n: objectNumber will be added by putImage code
  4617. };
  4618. if (f) info.f = f;
  4619. if (dp) info.dp = dp;
  4620. if (trns) info.trns = trns;
  4621. if (pal) info.pal = pal;
  4622. if (smask) info.smask = smask;
  4623. if (p) info.p = p; // predictor parameter for PNG compression
  4624. return info;
  4625. };
  4626. /**
  4627. * Adds an Image to the PDF.
  4628. *
  4629. * @name addImage
  4630. * @public
  4631. * @function
  4632. * @param {String/Image-Element/Canvas-Element/Uint8Array} imageData as base64 encoded DataUrl or Image-HTMLElement or Canvas-HTMLElement
  4633. * @param {String} format of file if filetype-recognition fails, e.g. 'JPEG'
  4634. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  4635. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  4636. * @param {Number} width of the image (in units declared at inception of PDF document)
  4637. * @param {Number} height of the Image (in units declared at inception of PDF document)
  4638. * @param {String} alias of the image (if used multiple times)
  4639. * @param {String} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  4640. * @param {Number} rotation of the image in degrees (0-359)
  4641. *
  4642. * @returns jsPDF
  4643. * @methodOf jsPDF#
  4644. */
  4645. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  4646. var tmpImageData = '';
  4647. if (typeof format !== 'string') {
  4648. var tmp = h;
  4649. h = w;
  4650. w = y;
  4651. y = x;
  4652. x = format;
  4653. format = tmp;
  4654. }
  4655. if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  4656. var options = imageData;
  4657. imageData = options.imageData;
  4658. format = options.format || format;
  4659. x = options.x || x || 0;
  4660. y = options.y || y || 0;
  4661. w = options.w || w;
  4662. h = options.h || h;
  4663. alias = options.alias || alias;
  4664. compression = options.compression || compression;
  4665. rotation = options.rotation || options.angle || rotation;
  4666. }
  4667. if (isNaN(x) || isNaN(y)) {
  4668. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  4669. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  4670. }
  4671. var images = getImages.call(this),
  4672. info;
  4673. if (!(info = checkImagesForAlias(imageData, images))) {
  4674. var dataAsBinaryString;
  4675. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format);
  4676. if (notDefined(alias)) alias = generateAliasFromData(imageData);
  4677. if (!(info = checkImagesForAlias(alias, images))) {
  4678. if (this.isString(imageData)) {
  4679. tmpImageData = this.convertStringToImageData(imageData);
  4680. if (tmpImageData !== '') {
  4681. imageData = tmpImageData;
  4682. } else {
  4683. tmpImageData = this.loadImageFile(imageData);
  4684. if (tmpImageData !== undefined) {
  4685. imageData = tmpImageData;
  4686. }
  4687. }
  4688. }
  4689. format = this.getImageFileTypeByImageData(imageData, format);
  4690. if (!isImageTypeSupported(format)) throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  4691. /**
  4692. * need to test if it's more efficient to convert all binary strings
  4693. * to TypedArray - or should we just leave and process as string?
  4694. */
  4695. if (this.supportsArrayBuffer()) {
  4696. // no need to convert if imageData is already uint8array
  4697. if (!(imageData instanceof Uint8Array)) {
  4698. dataAsBinaryString = imageData;
  4699. imageData = this.binaryStringToUint8Array(imageData);
  4700. }
  4701. }
  4702. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  4703. if (!info) throw new Error('An unkwown error occurred whilst processing the image');
  4704. }
  4705. }
  4706. writeImageToPDF.call(this, x, y, w, h, info, info.i, images, rotation);
  4707. return this;
  4708. };
  4709. jsPDFAPI.convertStringToImageData = function (stringData) {
  4710. var base64Info;
  4711. var imageData = '';
  4712. if (this.isString(stringData)) {
  4713. var base64Info = this.extractInfoFromBase64DataURI(stringData);
  4714. if (base64Info !== null) {
  4715. if (jsPDFAPI.validateStringAsBase64(base64Info[3])) {
  4716. imageData = atob(base64Info[3]); //convert to binary string
  4717. }
  4718. } else if (jsPDFAPI.validateStringAsBase64(stringData)) {
  4719. imageData = atob(stringData);
  4720. }
  4721. }
  4722. return imageData;
  4723. };
  4724. /**
  4725. * JPEG SUPPORT
  4726. **/
  4727. //takes a string imgData containing the raw bytes of
  4728. //a jpeg image and returns [width, height]
  4729. //Algorithm from: http://www.64lines.com/jpeg-width-height
  4730. var getJpegSize = function getJpegSize(imgData) {
  4731. var width, height, numcomponents;
  4732. // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  4733. 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) {
  4734. throw new Error('getJpegSize requires a binary string jpeg file');
  4735. }
  4736. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  4737. var i = 4,
  4738. len = imgData.length;
  4739. while (i < len) {
  4740. i += blockLength;
  4741. if (imgData.charCodeAt(i) !== 0xff) {
  4742. throw new Error('getJpegSize could not find the size of the image');
  4743. }
  4744. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  4745. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  4746. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  4747. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  4748. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  4749. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  4750. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  4751. imgData.charCodeAt(i + 1) === 0xc7) {
  4752. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  4753. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  4754. numcomponents = imgData.charCodeAt(i + 9);
  4755. return [width, height, numcomponents];
  4756. } else {
  4757. i += 2;
  4758. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  4759. }
  4760. }
  4761. },
  4762. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  4763. var hdr = data[0] << 8 | data[1];
  4764. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  4765. var len = data.length,
  4766. block = (data[4] << 8) + data[5],
  4767. pos = 4,
  4768. bytes,
  4769. width,
  4770. height,
  4771. numcomponents;
  4772. while (pos < len) {
  4773. pos += block;
  4774. bytes = readBytes(data, pos);
  4775. block = (bytes[2] << 8) + bytes[3];
  4776. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  4777. bytes = readBytes(data, pos + 5);
  4778. width = (bytes[2] << 8) + bytes[3];
  4779. height = (bytes[0] << 8) + bytes[1];
  4780. numcomponents = bytes[4];
  4781. return { width: width, height: height, numcomponents: numcomponents };
  4782. }
  4783. pos += 2;
  4784. }
  4785. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  4786. },
  4787. readBytes = function readBytes(data, offset) {
  4788. return data.subarray(offset, offset + 5);
  4789. };
  4790. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString, colorSpace) {
  4791. var filter = this.decode.DCT_DECODE,
  4792. bpc = 8,
  4793. dims;
  4794. if (!this.isString(data) && !this.isArrayBuffer(data) && !this.isArrayBufferView(data)) {
  4795. return null;
  4796. }
  4797. if (this.isString(data)) {
  4798. dims = getJpegSize(data);
  4799. }
  4800. if (this.isArrayBuffer(data)) {
  4801. data = new Uint8Array(data);
  4802. }
  4803. if (this.isArrayBufferView(data)) {
  4804. dims = getJpegSizeFromBytes(data);
  4805. // if we already have a stored binary string rep use that
  4806. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  4807. }
  4808. if (colorSpace === undefined) {
  4809. switch (dims.numcomponents) {
  4810. case 1:
  4811. colorSpace = this.color_spaces.DEVICE_GRAY;
  4812. break;
  4813. case 4:
  4814. colorSpace = this.color_spaces.DEVICE_CMYK;
  4815. break;
  4816. default:
  4817. case 3:
  4818. colorSpace = this.color_spaces.DEVICE_RGB;
  4819. break;
  4820. }
  4821. }
  4822. return this.createImageInfo(data, dims.width, dims.height, colorSpace, bpc, filter, index, alias);
  4823. };
  4824. jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
  4825. return this.processJPEG.apply(this, arguments);
  4826. };
  4827. jsPDFAPI.loadImageFile = function (path, sync, callback) {
  4828. sync = sync || true;
  4829. callback = callback || function () {};
  4830. var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
  4831. var xhrMethod = function xhrMethod(url, sync, callback) {
  4832. var req = new XMLHttpRequest();
  4833. var byteArray = [];
  4834. var i = 0;
  4835. var sanitizeUnicode = function sanitizeUnicode(data) {
  4836. var dataLength = data.length;
  4837. var StringFromCharCode = String.fromCharCode;
  4838. //Transform Unicode to ASCII
  4839. for (i = 0; i < dataLength; i += 1) {
  4840. byteArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff));
  4841. }
  4842. return byteArray.join("");
  4843. };
  4844. req.open('GET', url, !sync);
  4845. // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  4846. req.overrideMimeType('text\/plain; charset=x-user-defined');
  4847. if (sync === false) {
  4848. req.onload = function () {
  4849. return sanitizeUnicode(this.responseText);
  4850. };
  4851. }
  4852. req.send(null);
  4853. if (req.status !== 200) {
  4854. console.warn('Unable to load file "' + url + '"');
  4855. return;
  4856. }
  4857. if (sync) {
  4858. return sanitizeUnicode(req.responseText);
  4859. }
  4860. };
  4861. //we have a browser and probably no CORS-Problem
  4862. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== undefined && (typeof location === 'undefined' ? 'undefined' : _typeof(location)) === "object" && location.protocol.substr(0, 4) === "http") {
  4863. return xhrMethod(path, sync, callback);
  4864. }
  4865. };
  4866. jsPDFAPI.getImageProperties = function (imageData) {
  4867. var info;
  4868. var tmpImageData = '';
  4869. var format;
  4870. if (isDOMElement(imageData)) {
  4871. imageData = createDataURIFromElement(imageData);
  4872. }
  4873. if (this.isString(imageData)) {
  4874. tmpImageData = this.convertStringToImageData(imageData);
  4875. if (tmpImageData !== '') {
  4876. imageData = tmpImageData;
  4877. } else {
  4878. tmpImageData = this.loadImageFile(imageData);
  4879. if (tmpImageData !== undefined) {
  4880. imageData = tmpImageData;
  4881. }
  4882. }
  4883. }
  4884. format = this.getImageFileTypeByImageData(imageData);
  4885. if (!isImageTypeSupported(format)) throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  4886. /**
  4887. * need to test if it's more efficient to convert all binary strings
  4888. * to TypedArray - or should we just leave and process as string?
  4889. */
  4890. if (this.supportsArrayBuffer()) {
  4891. // no need to convert if imageData is already uint8array
  4892. if (!(imageData instanceof Uint8Array)) {
  4893. imageData = this.binaryStringToUint8Array(imageData);
  4894. }
  4895. }
  4896. info = this['process' + format.toUpperCase()](imageData);
  4897. if (!info) {
  4898. throw new Error('An unkwown error occurred whilst processing the image');
  4899. }
  4900. return {
  4901. fileType: format,
  4902. width: info.w,
  4903. height: info.h,
  4904. colorSpace: info.cs,
  4905. compressionMode: info.f,
  4906. bitsPerComponent: info.bpc
  4907. };
  4908. };
  4909. })(jsPDF.API);
  4910. /**
  4911. * jsPDF Annotations PlugIn
  4912. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  4913. *
  4914. * Licensed under the MIT License.
  4915. * http://opensource.org/licenses/mit-license
  4916. */
  4917. /**
  4918. * There are many types of annotations in a PDF document. Annotations are placed
  4919. * on a page at a particular location. They are not 'attached' to an object.
  4920. * <br />
  4921. * This plugin current supports <br />
  4922. * <li> Goto Page (set pageNumber and top in options)
  4923. * <li> Goto Name (set name and top in options)
  4924. * <li> Goto URL (set url in options)
  4925. * <p>
  4926. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  4927. * (set magFactor in options). XYZ is the default.
  4928. * </p>
  4929. * <p>
  4930. * Links, Text, Popup, and FreeText are supported.
  4931. * </p>
  4932. * <p>
  4933. * Options In PDF spec Not Implemented Yet
  4934. * <li> link border
  4935. * <li> named target
  4936. * <li> page coordinates
  4937. * <li> destination page scaling and layout
  4938. * <li> actions other than URL and GotoPage
  4939. * <li> background / hover actions
  4940. * </p>
  4941. */
  4942. /*
  4943. Destination Magnification Factors
  4944. See PDF 1.3 Page 386 for meanings and options
  4945. [supported]
  4946. XYZ (options; left top zoom)
  4947. Fit (no options)
  4948. FitH (options: top)
  4949. FitV (options: left)
  4950. [not supported]
  4951. FitR
  4952. FitB
  4953. FitBH
  4954. FitBV
  4955. */
  4956. (function (jsPDFAPI) {
  4957. var annotationPlugin = {
  4958. /**
  4959. * An array of arrays, indexed by <em>pageNumber</em>.
  4960. */
  4961. annotations: [],
  4962. f2: function f2(number) {
  4963. return number.toFixed(2);
  4964. },
  4965. notEmpty: function notEmpty(obj) {
  4966. if (typeof obj != 'undefined') {
  4967. if (obj != '') {
  4968. return true;
  4969. }
  4970. }
  4971. }
  4972. };
  4973. jsPDF.API.annotationPlugin = annotationPlugin;
  4974. jsPDF.API.events.push(['addPage', function (info) {
  4975. this.annotationPlugin.annotations[info.pageNumber] = [];
  4976. }]);
  4977. jsPDFAPI.events.push(['putPage', function (info) {
  4978. //TODO store annotations in pageContext so reorder/remove will not affect them.
  4979. var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
  4980. var found = false;
  4981. for (var a = 0; a < pageAnnos.length && !found; a++) {
  4982. var anno = pageAnnos[a];
  4983. switch (anno.type) {
  4984. case 'link':
  4985. if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
  4986. found = true;
  4987. break;
  4988. }
  4989. case 'reference':
  4990. case 'text':
  4991. case 'freetext':
  4992. found = true;
  4993. break;
  4994. }
  4995. }
  4996. if (found == false) {
  4997. return;
  4998. }
  4999. this.internal.write("/Annots [");
  5000. var f2 = this.annotationPlugin.f2;
  5001. var k = this.internal.scaleFactor;
  5002. var pageHeight = this.internal.pageSize.getHeight();
  5003. var pageInfo = this.internal.getPageInfo(info.pageNumber);
  5004. for (var a = 0; a < pageAnnos.length; a++) {
  5005. var anno = pageAnnos[a];
  5006. switch (anno.type) {
  5007. case 'reference':
  5008. // References to Widget Anotations (for AcroForm Fields)
  5009. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  5010. break;
  5011. case 'text':
  5012. // Create a an object for both the text and the popup
  5013. var objText = this.internal.newAdditionalObject();
  5014. var objPopup = this.internal.newAdditionalObject();
  5015. var title = anno.title || 'Note';
  5016. 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) + "] ";
  5017. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  5018. line += ' /Popup ' + objPopup.objId + " 0 R";
  5019. line += ' /P ' + pageInfo.objId + " 0 R";
  5020. line += ' /T (' + title + ') >>';
  5021. objText.content = line;
  5022. var parent = objText.objId + ' 0 R';
  5023. var popoff = 30;
  5024. 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) + "] ";
  5025. //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) + "] ";
  5026. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  5027. if (anno.open) {
  5028. line += ' /Open true';
  5029. }
  5030. line += ' >>';
  5031. objPopup.content = line;
  5032. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  5033. break;
  5034. case 'freetext':
  5035. 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) + "] ";
  5036. var color = anno.color || '#000000';
  5037. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  5038. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  5039. line += ' /Border [0 0 0]';
  5040. line += ' >>';
  5041. this.internal.write(line);
  5042. break;
  5043. case 'link':
  5044. if (anno.options.name) {
  5045. var loc = this.annotations._nameMap[anno.options.name];
  5046. anno.options.pageNumber = loc.page;
  5047. anno.options.top = loc.y;
  5048. } else {
  5049. if (!anno.options.top) {
  5050. anno.options.top = 0;
  5051. }
  5052. }
  5053. 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) + "] ";
  5054. var line = '';
  5055. if (anno.options.url) {
  5056. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  5057. } else if (anno.options.pageNumber) {
  5058. // first page is 0
  5059. var info = this.internal.getPageInfo(anno.options.pageNumber);
  5060. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  5061. anno.options.magFactor = anno.options.magFactor || "XYZ";
  5062. switch (anno.options.magFactor) {
  5063. case 'Fit':
  5064. line += ' /Fit]';
  5065. break;
  5066. case 'FitH':
  5067. //anno.options.top = anno.options.top || f2(pageHeight * k);
  5068. line += ' /FitH ' + anno.options.top + ']';
  5069. break;
  5070. case 'FitV':
  5071. anno.options.left = anno.options.left || 0;
  5072. line += ' /FitV ' + anno.options.left + ']';
  5073. break;
  5074. case 'XYZ':
  5075. default:
  5076. var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
  5077. anno.options.left = anno.options.left || 0;
  5078. // 0 or null zoom will not change zoom factor
  5079. if (typeof anno.options.zoom === 'undefined') {
  5080. anno.options.zoom = 0;
  5081. }
  5082. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  5083. break;
  5084. }
  5085. }
  5086. if (line != '') {
  5087. line += " >>";
  5088. this.internal.write(line);
  5089. }
  5090. break;
  5091. }
  5092. }
  5093. this.internal.write("]");
  5094. }]);
  5095. jsPDFAPI.createAnnotation = function (options) {
  5096. switch (options.type) {
  5097. case 'link':
  5098. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  5099. break;
  5100. case 'text':
  5101. case 'freetext':
  5102. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
  5103. break;
  5104. }
  5105. };
  5106. /**
  5107. * valid options
  5108. * <li> pageNumber or url [required]
  5109. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  5110. */
  5111. jsPDFAPI.link = function (x, y, w, h, options) {
  5112. this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
  5113. x: x,
  5114. y: y,
  5115. w: w,
  5116. h: h,
  5117. options: options,
  5118. type: 'link'
  5119. });
  5120. };
  5121. /**
  5122. * Currently only supports single line text.
  5123. * Returns the width of the text/link
  5124. */
  5125. jsPDFAPI.textWithLink = function (text, x, y, options) {
  5126. var width = this.getTextWidth(text);
  5127. var height = this.internal.getLineHeight() / this.internal.scaleFactor;
  5128. this.text(text, x, y);
  5129. //TODO We really need the text baseline height to do this correctly.
  5130. // Or ability to draw text on top, bottom, center, or baseline.
  5131. y += height * .2;
  5132. this.link(x, y - height, width, height, options);
  5133. return width;
  5134. };
  5135. //TODO move into external library
  5136. jsPDFAPI.getTextWidth = function (text) {
  5137. var fontSize = this.internal.getFontSize();
  5138. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  5139. return txtWidth;
  5140. };
  5141. //TODO move into external library
  5142. jsPDFAPI.getLineHeight = function () {
  5143. return this.internal.getLineHeight();
  5144. };
  5145. return this;
  5146. })(jsPDF.API);
  5147. (function (jsPDFAPI) {
  5148. var arLangCodes = {
  5149. "ar": "Arabic (Standard)",
  5150. "ar-DZ": "Arabic (Algeria)",
  5151. "ar-BH": "Arabic (Bahrain)",
  5152. "ar-EG": "Arabic (Egypt)",
  5153. "ar-IQ": "Arabic (Iraq)",
  5154. "ar-JO": "Arabic (Jordan)",
  5155. "ar-KW": "Arabic (Kuwait)",
  5156. "ar-LB": "Arabic (Lebanon)",
  5157. "ar-LY": "Arabic (Libya)",
  5158. "ar-MA": "Arabic (Morocco)",
  5159. "ar-OM": "Arabic (Oman)",
  5160. "ar-QA": "Arabic (Qatar)",
  5161. "ar-SA": "Arabic (Saudi Arabia)",
  5162. "ar-SY": "Arabic (Syria)",
  5163. "ar-TN": "Arabic (Tunisia)",
  5164. "ar-AE": "Arabic (U.A.E.)",
  5165. "ar-YE": "Arabic (Yemen)",
  5166. "fa": "Persian",
  5167. "fa-IR": "Persian/Iran",
  5168. "ur": "Urdu"
  5169. };
  5170. var arLangCodesKeys = Object.keys(arLangCodes);
  5171. /**
  5172. * Arabic shape substitutions: char code => (isolated, final, initial, medial).
  5173. */
  5174. var arabicSubst = {
  5175. 1569: [65152],
  5176. 1570: [65153, 65154, 65153, 65154],
  5177. 1571: [65155, 65156, 65155, 65156],
  5178. 1572: [65157, 65158],
  5179. 1573: [65159, 65160, 65159, 65160],
  5180. 1574: [65161, 65162, 65163, 65164],
  5181. 1575: [65165, 65166, 65165, 65166],
  5182. 1576: [65167, 65168, 65169, 65170],
  5183. 1577: [65171, 65172],
  5184. 1578: [65173, 65174, 65175, 65176],
  5185. 1579: [65177, 65178, 65179, 65180],
  5186. 1580: [65181, 65182, 65183, 65184],
  5187. 1581: [65185, 65186, 65187, 65188],
  5188. 1582: [65189, 65190, 65191, 65192],
  5189. 1583: [65193, 65194, 65193],
  5190. 1584: [65195, 65196, 65195],
  5191. 1585: [65197, 65198, 65197],
  5192. 1586: [65199, 65200, 65199],
  5193. 1587: [65201, 65202, 65203, 65204],
  5194. 1588: [65205, 65206, 65207, 65208],
  5195. 1589: [65209, 65210, 65211, 65212],
  5196. 1590: [65213, 65214, 65215, 65216],
  5197. 1591: [65217, 65218, 65219, 65220],
  5198. 1592: [65221, 65222, 65223, 65224],
  5199. 1593: [65225, 65226, 65227, 65228],
  5200. 1594: [65229, 65230, 65231, 65232],
  5201. 1601: [65233, 65234, 65235, 65236],
  5202. 1602: [65237, 65238, 65239, 65240],
  5203. 1603: [65241, 65242, 65243, 65244],
  5204. 1604: [65245, 65246, 65247, 65248],
  5205. 1605: [65249, 65250, 65251, 65252],
  5206. 1606: [65253, 65254, 65255, 65256],
  5207. 1607: [65257, 65258, 65259, 65260],
  5208. 1608: [65261, 65262, 65261],
  5209. 1609: [65263, 65264, 64488, 64489],
  5210. 1610: [65265, 65266, 65267, 65268],
  5211. 1649: [64336, 64337],
  5212. 1655: [64477],
  5213. 1657: [64358, 64359, 64360, 64361],
  5214. 1658: [64350, 64351, 64352, 64353],
  5215. 1659: [64338, 64339, 64340, 64341],
  5216. 1662: [64342, 64343, 64344, 64345],
  5217. 1663: [64354, 64355, 64356, 64357],
  5218. 1664: [64346, 64347, 64348, 64349],
  5219. 1667: [64374, 64375, 64376, 64377],
  5220. 1668: [64370, 64371, 64372, 64373],
  5221. 1670: [64378, 64379, 64380, 64381],
  5222. 1671: [64382, 64383, 64384, 64385],
  5223. 1672: [64392, 64393],
  5224. 1676: [64388, 64389],
  5225. 1677: [64386, 64387],
  5226. 1678: [64390, 64391],
  5227. 1681: [64396, 64397],
  5228. 1688: [64394, 64395, 64394],
  5229. 1700: [64362, 64363, 64364, 64365],
  5230. 1702: [64366, 64367, 64368, 64369],
  5231. 1705: [64398, 64399, 64400, 64401],
  5232. 1709: [64467, 64468, 64469, 64470],
  5233. 1711: [64402, 64403, 64404, 64405],
  5234. 1713: [64410, 64411, 64412, 64413],
  5235. 1715: [64406, 64407, 64408, 64409],
  5236. 1722: [64414, 64415],
  5237. 1723: [64416, 64417, 64418, 64419],
  5238. 1726: [64426, 64427, 64428, 64429],
  5239. 1728: [64420, 64421],
  5240. 1729: [64422, 64423, 64424, 64425],
  5241. 1733: [64480, 64481],
  5242. 1734: [64473, 64474],
  5243. 1735: [64471, 64472],
  5244. 1736: [64475, 64476],
  5245. 1737: [64482, 64483],
  5246. 1739: [64478, 64479],
  5247. 1740: [64508, 64509, 64510, 64511],
  5248. 1744: [64484, 64485, 64486, 64487],
  5249. 1746: [64430, 64431],
  5250. 1747: [64432, 64433]
  5251. };
  5252. var arabiclaasubst = {
  5253. 1570: [65269, 65270, 65269, 65270],
  5254. 1571: [65271, 65272, 65271, 65272],
  5255. 1573: [65273, 65274, 65273, 65274],
  5256. 1575: [65275, 65276, 65275, 65276]
  5257. };
  5258. var arabicorigsubst = {
  5259. 1570: [65153, 65154, 65153, 65154],
  5260. 1571: [65155, 65156, 65155, 65156],
  5261. 1573: [65159, 65160, 65159, 65160],
  5262. 1575: [65165, 65166, 65165, 65166]
  5263. };
  5264. var arabic_diacritics = {
  5265. 1612: 64606, // Shadda + Dammatan
  5266. 1613: 64607, // Shadda + Kasratan
  5267. 1614: 64608, // Shadda + Fatha
  5268. 1615: 64609, // Shadda + Damma
  5269. 1616: 64610 // Shadda + Kasra
  5270. };
  5271. var alfletter = [1570, 1571, 1573, 1575];
  5272. var endedletter = [1569, 1570, 1571, 1572, 1573, 1575, 1577, 1583, 1584, 1585, 1586, 1608, 1688];
  5273. var isolatedForm = 0;
  5274. var finalForm = 1;
  5275. var initialForm = 2;
  5276. var medialForm = 3;
  5277. //private
  5278. function isArabicLetter(letter) {
  5279. return letter !== undefined && arabicSubst[letter.charCodeAt(0)] !== undefined;
  5280. }
  5281. function isArabicEndLetter(letter) {
  5282. return letter !== undefined && endedletter.indexOf(letter.charCodeAt(0)) >= 0;
  5283. }
  5284. function isArabicAlfLetter(letter) {
  5285. return letter !== undefined && alfletter.indexOf(letter.charCodeAt(0)) >= 0;
  5286. }
  5287. function arabicLetterHasFinalForm(letter) {
  5288. return isArabicLetter(letter) && arabicSubst[letter.charCodeAt(0)].length >= 2;
  5289. }
  5290. function arabicLetterHasMedialForm(letter) {
  5291. return isArabicLetter(letter) && arabicSubst[letter.charCodeAt(0)].length == 4;
  5292. }
  5293. function isArabicDiacritic(letter) {
  5294. return letter !== undefined && arabic_diacritics[letter.charCodeAt(0)] !== undefined;
  5295. }
  5296. function getCorrectForm(currentChar, beforeChar, nextChar, arabicSubstition) {
  5297. if (!isArabicLetter(currentChar)) {
  5298. return -1;
  5299. }
  5300. arabicSubstition = arabicSubstition || {};
  5301. arabicSubst = Object.assign(arabicSubst, arabicSubstition);
  5302. if (!arabicLetterHasFinalForm(currentChar) || !isArabicLetter(beforeChar) && !isArabicLetter(nextChar) || !isArabicLetter(nextChar) && isArabicEndLetter(beforeChar) || isArabicEndLetter(currentChar) && !isArabicLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicAlfLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicEndLetter(beforeChar)) {
  5303. arabicSubst = Object.assign(arabicSubst, arabicorigsubst);
  5304. return isolatedForm;
  5305. }
  5306. if (arabicLetterHasMedialForm(currentChar) && isArabicLetter(beforeChar) && !isArabicEndLetter(beforeChar) && isArabicLetter(nextChar) && arabicLetterHasFinalForm(nextChar)) {
  5307. arabicSubst = Object.assign(arabicSubst, arabicorigsubst);
  5308. return medialForm;
  5309. }
  5310. if (isArabicEndLetter(currentChar) || !isArabicLetter(nextChar)) {
  5311. arabicSubst = Object.assign(arabicSubst, arabicorigsubst);
  5312. return finalForm;
  5313. }
  5314. arabicSubst = Object.assign(arabicSubst, arabicorigsubst);
  5315. return initialForm;
  5316. }
  5317. var commonSubstition = function commonSubstition(character) {
  5318. var replacementTable = {
  5319. '(': ')',
  5320. ')': '('
  5321. };
  5322. return replacementTable[character] || character;
  5323. };
  5324. var processArabic = jsPDFAPI.processArabic = function (text, reverse) {
  5325. text = text || "";
  5326. reverse = reverse || false;
  5327. var result = "";
  5328. var i = 0;
  5329. var position = 0;
  5330. var currentLetter = "";
  5331. var prevLetter = "";
  5332. var nextLetter = "";
  5333. var resultingLetter;
  5334. var localPrevLetter;
  5335. var localCurrentLetter;
  5336. var localNextLetter;
  5337. for (i = 0; i < text.length; i += 1) {
  5338. currentLetter = text[i];
  5339. prevLetter = text[i - 1];
  5340. nextLetter = text[i + 1];
  5341. if (!isArabicLetter(currentLetter)) {
  5342. result += reverse ? commonSubstition(currentLetter) : currentLetter;
  5343. } else {
  5344. if (prevLetter !== undefined && prevLetter.charCodeAt(0) === 1604 && isArabicAlfLetter(currentLetter)) {
  5345. localPrevLetter = text[i - 2];
  5346. localCurrentLetter = currentLetter;
  5347. localNextLetter = text[i + 1];
  5348. position = getCorrectForm(localCurrentLetter, localPrevLetter, localNextLetter, arabiclaasubst);
  5349. resultingLetter = String.fromCharCode(arabiclaasubst[currentLetter.charCodeAt(0)][position]);
  5350. result = result.substr(0, result.length - 1) + resultingLetter;
  5351. } else if (prevLetter !== undefined && prevLetter.charCodeAt(0) === 1617 && isArabicDiacritic(currentLetter)) {
  5352. localPrevLetter = text[i - 2];
  5353. localCurrentLetter = currentLetter;
  5354. localNextLetter = text[i + 1];
  5355. position = getCorrectForm(localCurrentLetter, localPrevLetter, localNextLetter, arabicorigsubst);
  5356. resultingLetter = String.fromCharCode(arabic_diacritics[currentLetter.charCodeAt(0)][position]);
  5357. result = result.substr(0, result.length - 1) + resultingLetter;
  5358. } else {
  5359. position = getCorrectForm(currentLetter, prevLetter, nextLetter, arabicorigsubst);
  5360. result += String.fromCharCode(arabicSubst[currentLetter.charCodeAt(0)][position]);
  5361. }
  5362. }
  5363. }
  5364. return reverse ? result.split("").reverse().join("") : result;
  5365. };
  5366. var arabicParserFunction = function arabicParserFunction(args) {
  5367. var text = args.text;
  5368. var x = args.x;
  5369. var y = args.y;
  5370. var options = args.options || {};
  5371. var mutex = args.mutex || {};
  5372. var lang = options.lang;
  5373. var tmpText = [];
  5374. if (arLangCodesKeys.indexOf(lang) >= 0) {
  5375. if (Object.prototype.toString.call(text) === '[object Array]') {
  5376. var i = 0;
  5377. tmpText = [];
  5378. for (i = 0; i < text.length; i += 1) {
  5379. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  5380. tmpText.push([processArabic(text[i][0], true), text[i][1], text[i][2]]);
  5381. } else {
  5382. tmpText.push([processArabic(text[i], true)]);
  5383. }
  5384. }
  5385. args.text = tmpText;
  5386. } else {
  5387. args.text = processArabic(text, true);
  5388. }
  5389. //force charSpace if not given.
  5390. if (options.charSpace === undefined) {
  5391. args.options.charSpace = 0;
  5392. }
  5393. //if R2L is true, set it false.
  5394. if (options.R2L === true) {
  5395. args.options.R2L = false;
  5396. }
  5397. }
  5398. };
  5399. jsPDFAPI.events.push(['preProcessText', arabicParserFunction]);
  5400. })(jsPDF.API);
  5401. /**
  5402. * jsPDF Autoprint Plugin
  5403. *
  5404. * Licensed under the MIT License.
  5405. * http://opensource.org/licenses/mit-license
  5406. */
  5407. /**
  5408. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  5409. * Reader.
  5410. *
  5411. * @returns {jsPDF}
  5412. * @name autoPrint
  5413. * @example
  5414. * var doc = new jsPDF()
  5415. * doc.text(10, 10, 'This is a test')
  5416. * doc.autoPrint()
  5417. * doc.save('autoprint.pdf')
  5418. */
  5419. (function (jsPDFAPI) {
  5420. jsPDFAPI.autoPrint = function (options) {
  5421. var refAutoPrintTag;
  5422. options = options || {};
  5423. options.variant = options.variant || 'non-conform';
  5424. switch (options.variant) {
  5425. case 'javascript':
  5426. //https://github.com/Rob--W/pdf.js/commit/c676ecb5a0f54677b9f3340c3ef2cf42225453bb
  5427. this.addJS('print({});');
  5428. break;
  5429. case 'non-conform':
  5430. default:
  5431. this.internal.events.subscribe('postPutResources', function () {
  5432. refAutoPrintTag = this.internal.newObject();
  5433. this.internal.out("<<");
  5434. this.internal.out("/S /Named");
  5435. this.internal.out("/Type /Action");
  5436. this.internal.out("/N /Print");
  5437. this.internal.out(">>");
  5438. this.internal.out("endobj");
  5439. });
  5440. this.internal.events.subscribe("putCatalog", function () {
  5441. this.internal.out("/OpenAction " + refAutoPrintTag + " 0 R");
  5442. });
  5443. break;
  5444. }
  5445. return this;
  5446. };
  5447. })(jsPDF.API);
  5448. /**
  5449. * jsPDF Canvas PlugIn
  5450. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  5451. *
  5452. * Licensed under the MIT License.
  5453. * http://opensource.org/licenses/mit-license
  5454. */
  5455. /**
  5456. * This plugin mimics the HTML5 Canvas
  5457. *
  5458. * The goal is to provide a way for current canvas users to print directly to a PDF.
  5459. */
  5460. (function (jsPDFAPI) {
  5461. jsPDFAPI.events.push(['initialized', function () {
  5462. this.canvas.pdf = this;
  5463. }]);
  5464. jsPDFAPI.canvas = {
  5465. getContext: function getContext(name) {
  5466. this.pdf.context2d._canvas = this;
  5467. return this.pdf.context2d;
  5468. },
  5469. childNodes: []
  5470. };
  5471. Object.defineProperty(jsPDFAPI.canvas, 'width', {
  5472. get: function get() {
  5473. return this._width;
  5474. },
  5475. set: function set(value) {
  5476. this._width = value;
  5477. this.getContext('2d').pageWrapX = value + 1;
  5478. }
  5479. });
  5480. Object.defineProperty(jsPDFAPI.canvas, 'height', {
  5481. get: function get() {
  5482. return this._height;
  5483. },
  5484. set: function set(value) {
  5485. this._height = value;
  5486. this.getContext('2d').pageWrapY = value + 1;
  5487. }
  5488. });
  5489. return this;
  5490. })(jsPDF.API);
  5491. /** ====================================================================
  5492. * jsPDF Cell plugin
  5493. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  5494. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  5495. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  5496. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  5497. * 2014 James Hall, james@parall.ax
  5498. * 2014 Diego Casorran, https://github.com/diegocr
  5499. *
  5500. *
  5501. * ====================================================================
  5502. */
  5503. (function (jsPDFAPI) {
  5504. /*jslint browser:true */
  5505. /*global document: false, jsPDF */
  5506. var fontName,
  5507. fontSize,
  5508. fontStyle,
  5509. padding = 3,
  5510. margin = 13,
  5511. headerFunction,
  5512. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
  5513. pages = 1,
  5514. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  5515. lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
  5516. },
  5517. getLastCellPosition = function getLastCellPosition() {
  5518. return lastCellPos;
  5519. },
  5520. NO_MARGINS = { left: 0, top: 0, bottom: 0 };
  5521. jsPDFAPI.setHeaderFunction = function (func) {
  5522. headerFunction = func;
  5523. };
  5524. jsPDFAPI.getTextDimensions = function (txt) {
  5525. fontName = this.internal.getFont().fontName;
  5526. fontSize = this.table_font_size || this.internal.getFontSize();
  5527. fontStyle = this.internal.getFont().fontStyle;
  5528. // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
  5529. var px2pt = 0.264583 * 72 / 25.4,
  5530. dimensions,
  5531. text;
  5532. text = document.createElement('font');
  5533. text.id = "jsPDFCell";
  5534. try {
  5535. text.style.fontStyle = fontStyle;
  5536. } catch (e) {
  5537. text.style.fontWeight = fontStyle;
  5538. }
  5539. text.style.fontSize = fontSize + 'pt';
  5540. text.style.fontFamily = fontName;
  5541. try {
  5542. text.textContent = txt;
  5543. } catch (e) {
  5544. text.innerText = txt;
  5545. }
  5546. document.body.appendChild(text);
  5547. dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
  5548. document.body.removeChild(text);
  5549. return dimensions;
  5550. };
  5551. jsPDFAPI.cellAddPage = function () {
  5552. var margins = this.margins || NO_MARGINS;
  5553. this.addPage();
  5554. setLastCellPosition(margins.left, margins.top, undefined, undefined);
  5555. //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  5556. pages += 1;
  5557. };
  5558. jsPDFAPI.cellInitialize = function () {
  5559. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
  5560. pages = 1;
  5561. };
  5562. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  5563. var curCell = getLastCellPosition();
  5564. var pgAdded = false;
  5565. // If this is not the first cell, we must change its position
  5566. if (curCell.ln !== undefined) {
  5567. if (curCell.ln === ln) {
  5568. //Same line
  5569. x = curCell.x + curCell.w;
  5570. y = curCell.y;
  5571. } else {
  5572. //New line
  5573. var margins = this.margins || NO_MARGINS;
  5574. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.getHeight() - margins.bottom) {
  5575. this.cellAddPage();
  5576. pgAdded = true;
  5577. if (this.printHeaders && this.tableHeaderRow) {
  5578. this.printHeaderRow(ln, true);
  5579. }
  5580. }
  5581. //We ignore the passed y: the lines may have different heights
  5582. y = getLastCellPosition().y + getLastCellPosition().h;
  5583. if (pgAdded) y = margin + 10;
  5584. }
  5585. }
  5586. if (txt[0] !== undefined) {
  5587. if (this.printingHeaderRow) {
  5588. this.rect(x, y, w, h, 'FD');
  5589. } else {
  5590. this.rect(x, y, w, h);
  5591. }
  5592. if (align === 'right') {
  5593. if (!(txt instanceof Array)) {
  5594. txt = [txt];
  5595. }
  5596. for (var i = 0; i < txt.length; i++) {
  5597. var currentLine = txt[i];
  5598. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
  5599. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  5600. }
  5601. } else {
  5602. this.text(txt, x + padding, y + this.internal.getLineHeight());
  5603. }
  5604. }
  5605. setLastCellPosition(x, y, w, h, ln);
  5606. return this;
  5607. };
  5608. /**
  5609. * Return the maximum value from an array
  5610. * @param array
  5611. * @param comparisonFn
  5612. * @returns {*}
  5613. */
  5614. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  5615. var max = array[0],
  5616. i,
  5617. ln,
  5618. item;
  5619. for (i = 0, ln = array.length; i < ln; i += 1) {
  5620. item = array[i];
  5621. if (comparisonFn) {
  5622. if (comparisonFn(max, item) === -1) {
  5623. max = item;
  5624. }
  5625. } else {
  5626. if (item > max) {
  5627. max = item;
  5628. }
  5629. }
  5630. }
  5631. return max;
  5632. };
  5633. /**
  5634. * Create a table from a set of data.
  5635. * @param {Integer} [x] : left-position for top-left corner of table
  5636. * @param {Integer} [y] top-position for top-left corner of table
  5637. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  5638. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  5639. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  5640. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  5641. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  5642. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  5643. */
  5644. jsPDFAPI.table = function (x, y, data, headers, config) {
  5645. if (!data) {
  5646. throw 'No data for PDF table';
  5647. }
  5648. var headerNames = [],
  5649. headerPrompts = [],
  5650. header,
  5651. i,
  5652. ln,
  5653. cln,
  5654. columnMatrix = {},
  5655. columnWidths = {},
  5656. columnData,
  5657. column,
  5658. columnMinWidths = [],
  5659. j,
  5660. tableHeaderConfigs = [],
  5661. model,
  5662. jln,
  5663. func,
  5664. //set up defaults. If a value is provided in config, defaults will be overwritten:
  5665. autoSize = false,
  5666. printHeaders = true,
  5667. fontSize = 12,
  5668. margins = NO_MARGINS;
  5669. margins.width = this.internal.pageSize.getWidth();
  5670. if (config) {
  5671. //override config defaults if the user has specified non-default behavior:
  5672. if (config.autoSize === true) {
  5673. autoSize = true;
  5674. }
  5675. if (config.printHeaders === false) {
  5676. printHeaders = false;
  5677. }
  5678. if (config.fontSize) {
  5679. fontSize = config.fontSize;
  5680. }
  5681. if (config.css && typeof config.css['font-size'] !== "undefined") {
  5682. fontSize = config.css['font-size'] * 16;
  5683. }
  5684. if (config.margins) {
  5685. margins = config.margins;
  5686. }
  5687. }
  5688. /**
  5689. * @property {Number} lnMod
  5690. * Keep track of the current line number modifier used when creating cells
  5691. */
  5692. this.lnMod = 0;
  5693. lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
  5694. this.printHeaders = printHeaders;
  5695. this.margins = margins;
  5696. this.setFontSize(fontSize);
  5697. this.table_font_size = fontSize;
  5698. // Set header values
  5699. if (headers === undefined || headers === null) {
  5700. // No headers defined so we derive from data
  5701. headerNames = Object.keys(data[0]);
  5702. } else if (headers[0] && typeof headers[0] !== 'string') {
  5703. var px2pt = 0.264583 * 72 / 25.4;
  5704. // Split header configs into names and prompts
  5705. for (i = 0, ln = headers.length; i < ln; i += 1) {
  5706. header = headers[i];
  5707. headerNames.push(header.name);
  5708. headerPrompts.push(header.prompt);
  5709. columnWidths[header.name] = header.width * px2pt;
  5710. }
  5711. } else {
  5712. headerNames = headers;
  5713. }
  5714. if (autoSize) {
  5715. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  5716. func = function func(rec) {
  5717. return rec[header];
  5718. };
  5719. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  5720. header = headerNames[i];
  5721. columnMatrix[header] = data.map(func);
  5722. // get header width
  5723. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
  5724. column = columnMatrix[header];
  5725. // get cell widths
  5726. for (j = 0, cln = column.length; j < cln; j += 1) {
  5727. columnData = column[j];
  5728. columnMinWidths.push(this.getTextDimensions(columnData).w);
  5729. }
  5730. // get final column width
  5731. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
  5732. //have to reset
  5733. columnMinWidths = [];
  5734. }
  5735. }
  5736. // -- Construct the table
  5737. if (printHeaders) {
  5738. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
  5739. // Construct the header row
  5740. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  5741. header = headerNames[i];
  5742. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  5743. }
  5744. // Store the table header config
  5745. this.setTableHeaderRow(tableHeaderConfigs);
  5746. // Print the header for the start of the table
  5747. this.printHeaderRow(1, false);
  5748. }
  5749. // Construct the data rows
  5750. for (i = 0, ln = data.length; i < ln; i += 1) {
  5751. var lineHeight;
  5752. model = data[i];
  5753. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  5754. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  5755. header = headerNames[j];
  5756. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  5757. }
  5758. }
  5759. this.lastCellPos = lastCellPos;
  5760. this.table_x = x;
  5761. this.table_y = y;
  5762. return this;
  5763. };
  5764. /**
  5765. * Calculate the height for containing the highest column
  5766. * @param {String[]} headerNames is the header, used as keys to the data
  5767. * @param {Integer[]} columnWidths is size of each column
  5768. * @param {Object[]} model is the line of data we want to calculate the height of
  5769. */
  5770. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  5771. var header,
  5772. lineHeight = 0;
  5773. for (var j = 0; j < headerNames.length; j++) {
  5774. header = headerNames[j];
  5775. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  5776. var h = this.internal.getLineHeight() * model[header].length + padding;
  5777. if (h > lineHeight) lineHeight = h;
  5778. }
  5779. return lineHeight;
  5780. };
  5781. /**
  5782. * Store the config for outputting a table header
  5783. * @param {Object[]} config
  5784. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  5785. * except the ln parameter is excluded
  5786. */
  5787. jsPDFAPI.setTableHeaderRow = function (config) {
  5788. this.tableHeaderRow = config;
  5789. };
  5790. /**
  5791. * Output the store header row
  5792. * @param lineNumber The line number to output the header at
  5793. */
  5794. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  5795. if (!this.tableHeaderRow) {
  5796. throw 'Property tableHeaderRow does not exist.';
  5797. }
  5798. var tableHeaderCell, tmpArray, i, ln;
  5799. this.printingHeaderRow = true;
  5800. if (headerFunction !== undefined) {
  5801. var position = headerFunction(this, pages);
  5802. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  5803. }
  5804. this.setFontStyle('bold');
  5805. var tempHeaderConf = [];
  5806. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  5807. this.setFillColor(200, 200, 200);
  5808. tableHeaderCell = this.tableHeaderRow[i];
  5809. if (new_page) {
  5810. this.margins.top = margin;
  5811. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  5812. tempHeaderConf.push(tableHeaderCell);
  5813. }
  5814. tmpArray = [].concat(tableHeaderCell);
  5815. this.cell.apply(this, tmpArray.concat(lineNumber));
  5816. }
  5817. if (tempHeaderConf.length > 0) {
  5818. this.setTableHeaderRow(tempHeaderConf);
  5819. }
  5820. this.setFontStyle('normal');
  5821. this.printingHeaderRow = false;
  5822. };
  5823. })(jsPDF.API);
  5824. /**
  5825. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  5826. *
  5827. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  5828. */
  5829. /**
  5830. * This plugin mimics the HTML5 Canvas's context2d.
  5831. *
  5832. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  5833. */
  5834. /**
  5835. * TODO implement stroke opacity (refactor from fill() method )
  5836. * TODO transform angle and radii parameters
  5837. */
  5838. /**
  5839. * require('jspdf.js'); require('lib/css_colors.js');
  5840. */
  5841. (function (jsPDFAPI) {
  5842. jsPDFAPI.events.push(['initialized', function () {
  5843. this.context2d.pdf = this;
  5844. this.context2d.internal.pdf = this;
  5845. this.context2d.ctx = new context();
  5846. this.context2d.ctxStack = [];
  5847. this.context2d.path = [];
  5848. }]);
  5849. jsPDFAPI.context2d = {
  5850. pageWrapXEnabled: false,
  5851. pageWrapYEnabled: false,
  5852. pageWrapX: 9999999,
  5853. pageWrapY: 9999999,
  5854. ctx: new context(),
  5855. f2: function f2(number) {
  5856. return number.toFixed(2);
  5857. },
  5858. fillRect: function fillRect(x, y, w, h) {
  5859. if (this._isFillTransparent()) {
  5860. return;
  5861. }
  5862. x = this._wrapX(x);
  5863. y = this._wrapY(y);
  5864. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5865. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5866. },
  5867. strokeRect: function strokeRect(x, y, w, h) {
  5868. if (this._isStrokeTransparent()) {
  5869. return;
  5870. }
  5871. x = this._wrapX(x);
  5872. y = this._wrapY(y);
  5873. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5874. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
  5875. },
  5876. /**
  5877. * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  5878. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  5879. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  5880. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  5881. * @param x
  5882. * @param y
  5883. * @param w
  5884. * @param h
  5885. */
  5886. clearRect: function clearRect(x, y, w, h) {
  5887. if (this.ctx.ignoreClearRect) {
  5888. return;
  5889. }
  5890. x = this._wrapX(x);
  5891. y = this._wrapY(y);
  5892. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  5893. this.save();
  5894. this.setFillStyle('#ffffff');
  5895. //TODO This is hack to fill with white.
  5896. this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
  5897. this.restore();
  5898. },
  5899. save: function save() {
  5900. this.ctx._fontSize = this.pdf.internal.getFontSize();
  5901. var ctx = new context();
  5902. ctx.copy(this.ctx);
  5903. this.ctxStack.push(this.ctx);
  5904. this.ctx = ctx;
  5905. },
  5906. restore: function restore() {
  5907. this.ctx = this.ctxStack.pop();
  5908. this.setFillStyle(this.ctx.fillStyle);
  5909. this.setStrokeStyle(this.ctx.strokeStyle);
  5910. this.setFont(this.ctx.font);
  5911. this.pdf.setFontSize(this.ctx._fontSize);
  5912. this.setLineCap(this.ctx.lineCap);
  5913. this.setLineWidth(this.ctx.lineWidth);
  5914. this.setLineJoin(this.ctx.lineJoin);
  5915. },
  5916. rect: function rect(x, y, w, h) {
  5917. this.moveTo(x, y);
  5918. this.lineTo(x + w, y);
  5919. this.lineTo(x + w, y + h);
  5920. this.lineTo(x, y + h);
  5921. this.lineTo(x, y); //TODO not needed
  5922. this.closePath();
  5923. },
  5924. beginPath: function beginPath() {
  5925. this.path = [];
  5926. },
  5927. closePath: function closePath() {
  5928. this.path.push({
  5929. type: 'close'
  5930. });
  5931. },
  5932. _getRGBA: function _getRGBA(style) {
  5933. // get the decimal values of r, g, and b;
  5934. var r, g, b, a;
  5935. var rgbColor = new RGBColor(style);
  5936. if (!style) {
  5937. return { r: 0, g: 0, b: 0, a: 0, style: style };
  5938. }
  5939. if (this.internal.rxTransparent.test(style)) {
  5940. r = 0;
  5941. g = 0;
  5942. b = 0;
  5943. a = 0;
  5944. } else {
  5945. var m = this.internal.rxRgb.exec(style);
  5946. if (m != null) {
  5947. r = parseInt(m[1]);
  5948. g = parseInt(m[2]);
  5949. b = parseInt(m[3]);
  5950. a = 1;
  5951. } else {
  5952. m = this.internal.rxRgba.exec(style);
  5953. if (m != null) {
  5954. r = parseInt(m[1]);
  5955. g = parseInt(m[2]);
  5956. b = parseInt(m[3]);
  5957. a = parseFloat(m[4]);
  5958. } else {
  5959. a = 1;
  5960. if (style.charAt(0) != '#') {
  5961. if (rgbColor.ok) {
  5962. style = rgbColor.toHex();
  5963. } else {
  5964. style = '#000000';
  5965. }
  5966. }
  5967. if (style.length === 4) {
  5968. r = style.substring(1, 2);
  5969. r += r;
  5970. g = style.substring(2, 3);
  5971. g += g;
  5972. b = style.substring(3, 4);
  5973. b += b;
  5974. } else {
  5975. r = style.substring(1, 3);
  5976. g = style.substring(3, 5);
  5977. b = style.substring(5, 7);
  5978. }
  5979. r = parseInt(r, 16);
  5980. g = parseInt(g, 16);
  5981. b = parseInt(b, 16);
  5982. }
  5983. }
  5984. }
  5985. return { r: r, g: g, b: b, a: a, style: style };
  5986. },
  5987. setFillStyle: function setFillStyle(style) {
  5988. var rgba = this._getRGBA(style);
  5989. this.ctx.fillStyle = style;
  5990. this.ctx._isFillTransparent = rgba.a === 0;
  5991. this.ctx._fillOpacity = rgba.a;
  5992. this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, {
  5993. a: rgba.a
  5994. });
  5995. this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, {
  5996. a: rgba.a
  5997. });
  5998. },
  5999. setStrokeStyle: function setStrokeStyle(style) {
  6000. var rgba = this._getRGBA(style);
  6001. this.ctx.strokeStyle = rgba.style;
  6002. this.ctx._isStrokeTransparent = rgba.a === 0;
  6003. this.ctx._strokeOpacity = rgba.a;
  6004. //TODO jsPDF to handle rgba
  6005. if (rgba.a === 0) {
  6006. this.pdf.setDrawColor(255, 255, 255);
  6007. } else if (rgba.a === 1) {
  6008. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  6009. } else {
  6010. //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
  6011. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  6012. }
  6013. },
  6014. fillText: function fillText(text, x, y, maxWidth) {
  6015. if (this._isFillTransparent()) {
  6016. return;
  6017. }
  6018. x = this._wrapX(x);
  6019. y = this._wrapY(y);
  6020. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6021. x = xpt[0];
  6022. y = xpt[1];
  6023. var rads = this._matrix_rotation(this.ctx._transform);
  6024. var degs = rads * 57.2958;
  6025. //TODO only push the clip if it has not been applied to the current PDF context
  6026. if (this.ctx._clip_path.length > 0) {
  6027. var lines;
  6028. if (window.outIntercept) {
  6029. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  6030. } else {
  6031. lines = this.internal.getCurrentPage();
  6032. }
  6033. lines.push("q");
  6034. var origPath = this.path;
  6035. this.path = this.ctx._clip_path;
  6036. this.ctx._clip_path = [];
  6037. this._fill(null, true);
  6038. this.ctx._clip_path = this.path;
  6039. this.path = origPath;
  6040. }
  6041. // We only use X axis as scale hint
  6042. var scale = 1;
  6043. try {
  6044. scale = this._matrix_decompose(this._getTransform()).scale[0];
  6045. } catch (e) {
  6046. console.warn(e);
  6047. }
  6048. // In some cases the transform was very small (5.715760606202283e-17). Most likely a canvg rounding error.
  6049. if (scale < 0.01) {
  6050. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  6051. } else {
  6052. var oldSize = this.pdf.internal.getFontSize();
  6053. this.pdf.setFontSize(oldSize * scale);
  6054. this.pdf.text(text, x, this._getBaseline(y), null, degs);
  6055. this.pdf.setFontSize(oldSize);
  6056. }
  6057. if (this.ctx._clip_path.length > 0) {
  6058. lines.push('Q');
  6059. }
  6060. },
  6061. strokeText: function strokeText(text, x, y, maxWidth) {
  6062. if (this._isStrokeTransparent()) {
  6063. return;
  6064. }
  6065. x = this._wrapX(x);
  6066. y = this._wrapY(y);
  6067. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6068. x = xpt[0];
  6069. y = xpt[1];
  6070. var rads = this._matrix_rotation(this.ctx._transform);
  6071. var degs = rads * 57.2958;
  6072. //TODO only push the clip if it has not been applied to the current PDF context
  6073. if (this.ctx._clip_path.length > 0) {
  6074. var lines;
  6075. if (window.outIntercept) {
  6076. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  6077. } else {
  6078. lines = this.internal.getCurrentPage();
  6079. }
  6080. lines.push("q");
  6081. var origPath = this.path;
  6082. this.path = this.ctx._clip_path;
  6083. this.ctx._clip_path = [];
  6084. this._fill(null, true);
  6085. this.ctx._clip_path = this.path;
  6086. this.path = origPath;
  6087. }
  6088. var scale = 1;
  6089. // We only use the X axis as scale hint
  6090. try {
  6091. scale = this._matrix_decompose(this._getTransform()).scale[0];
  6092. } catch (e) {
  6093. console.warn(e);
  6094. }
  6095. if (scale === 1) {
  6096. this.pdf.text(text, x, this._getBaseline(y), {
  6097. stroke: true
  6098. }, degs);
  6099. } else {
  6100. var oldSize = this.pdf.internal.getFontSize();
  6101. this.pdf.setFontSize(oldSize * scale);
  6102. this.pdf.text(text, x, this._getBaseline(y), {
  6103. stroke: true
  6104. }, degs);
  6105. this.pdf.setFontSize(oldSize);
  6106. }
  6107. if (this.ctx._clip_path.length > 0) {
  6108. lines.push('Q');
  6109. }
  6110. },
  6111. setFont: function setFont(font) {
  6112. this.ctx.font = font;
  6113. //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
  6114. var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
  6115. m = rx.exec(font);
  6116. if (m != null) {
  6117. var fontStyle = m[1];
  6118. var fontVariant = m[2];
  6119. var fontWeight = m[3];
  6120. var fontSize = m[4];
  6121. var fontSizeUnit = m[5];
  6122. var fontFamily = m[6];
  6123. if ('px' === fontSizeUnit) {
  6124. fontSize = Math.floor(parseFloat(fontSize));
  6125. // fontSize = fontSize * 1.25;
  6126. } else if ('em' === fontSizeUnit) {
  6127. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  6128. } else {
  6129. fontSize = Math.floor(parseFloat(fontSize));
  6130. }
  6131. this.pdf.setFontSize(fontSize);
  6132. if (fontWeight === 'bold' || fontWeight === '700') {
  6133. this.pdf.setFontStyle('bold');
  6134. } else {
  6135. if (fontStyle === 'italic') {
  6136. this.pdf.setFontStyle('italic');
  6137. } else {
  6138. this.pdf.setFontStyle('normal');
  6139. }
  6140. }
  6141. var style;
  6142. if ('bold' === fontWeight || fontWeight === '700') {
  6143. style = fontStyle === 'italic' ? 'bolditalic' : 'bold';
  6144. } else if (fontStyle === 'italic') {
  6145. style = 'italic';
  6146. } else {
  6147. style = 'normal';
  6148. }
  6149. var parts = fontFamily.toLowerCase().split(/\s*,\s*/);
  6150. var jsPdfFontName = 'Times';
  6151. for (var i = 0; i < parts.length; i++) {
  6152. if (this.pdf.internal.getFont(parts[i], style, { noFallback: true, disableWarning: true }) !== undefined) {
  6153. jsPdfFontName = parts[i];
  6154. break;
  6155. } else if (style === 'bolditalic' && this.pdf.internal.getFont(parts[i], 'bold', { noFallback: true, disableWarning: true }) !== undefined) {
  6156. jsPdfFontName = parts[i];
  6157. style = 'bold';
  6158. } else if (this.pdf.internal.getFont(parts[i], 'normal', { noFallback: true, disableWarning: true }) !== undefined) {
  6159. jsPdfFontName = parts[i];
  6160. style = 'normal';
  6161. break;
  6162. }
  6163. }
  6164. this.pdf.setFont(jsPdfFontName, style);
  6165. } else {
  6166. var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
  6167. var m = rx.exec(font);
  6168. if (m != null) {
  6169. var size = m[1];
  6170. var unit = m[2];
  6171. var name = m[3];
  6172. var style = m[4];
  6173. if (!style) {
  6174. style = 'normal';
  6175. }
  6176. if ('em' === fontSizeUnit) {
  6177. size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  6178. } else {
  6179. size = Math.floor(parseFloat(size));
  6180. }
  6181. this.pdf.setFontSize(size);
  6182. this.pdf.setFont(name, style);
  6183. }
  6184. }
  6185. },
  6186. setTextBaseline: function setTextBaseline(baseline) {
  6187. this.ctx.textBaseline = baseline;
  6188. },
  6189. getTextBaseline: function getTextBaseline() {
  6190. return this.ctx.textBaseline;
  6191. },
  6192. //TODO implement textAlign
  6193. setTextAlign: function setTextAlign(align) {
  6194. this.ctx.textAlign = align;
  6195. },
  6196. getTextAlign: function getTextAlign() {
  6197. return this.ctx.textAlign;
  6198. },
  6199. setLineWidth: function setLineWidth(width) {
  6200. this.ctx.lineWidth = width;
  6201. this.pdf.setLineWidth(width);
  6202. },
  6203. setLineCap: function setLineCap(style) {
  6204. this.ctx.lineCap = style;
  6205. this.pdf.setLineCap(style);
  6206. },
  6207. setLineJoin: function setLineJoin(style) {
  6208. this.ctx.lineJoin = style;
  6209. this.pdf.setLineJoin(style);
  6210. },
  6211. moveTo: function moveTo(x, y) {
  6212. x = this._wrapX(x);
  6213. y = this._wrapY(y);
  6214. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6215. x = xpt[0];
  6216. y = xpt[1];
  6217. var obj = {
  6218. type: 'mt',
  6219. x: x,
  6220. y: y
  6221. };
  6222. this.path.push(obj);
  6223. },
  6224. _wrapX: function _wrapX(x) {
  6225. if (this.pageWrapXEnabled) {
  6226. return x % this.pageWrapX;
  6227. } else {
  6228. return x;
  6229. }
  6230. },
  6231. _wrapY: function _wrapY(y) {
  6232. if (this.pageWrapYEnabled) {
  6233. this._gotoPage(this._page(y));
  6234. return (y - this.lastBreak) % this.pageWrapY;
  6235. } else {
  6236. return y;
  6237. }
  6238. },
  6239. transform: function transform(a, b, c, d, e, f) {
  6240. this.ctx._transform = this._matrix_multiply(this.ctx._transform, [a, b, c, d, e, f]);
  6241. },
  6242. setTransform: function setTransform(a, b, c, d, e, f) {
  6243. this.ctx._transform = [a, b, c, d, e, f];
  6244. },
  6245. _getTransform: function _getTransform() {
  6246. return this.ctx._transform;
  6247. },
  6248. lastBreak: 0,
  6249. // Y Position of page breaks.
  6250. pageBreaks: [],
  6251. // returns: One-based Page Number
  6252. // Should only be used if pageWrapYEnabled is true
  6253. _page: function _page(y) {
  6254. if (this.pageWrapYEnabled) {
  6255. this.lastBreak = 0;
  6256. var manualBreaks = 0;
  6257. var autoBreaks = 0;
  6258. for (var i = 0; i < this.pageBreaks.length; i++) {
  6259. if (y >= this.pageBreaks[i]) {
  6260. manualBreaks++;
  6261. if (this.lastBreak === 0) {
  6262. autoBreaks++;
  6263. }
  6264. var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
  6265. this.lastBreak = this.pageBreaks[i];
  6266. var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
  6267. autoBreaks += pagesSinceLastBreak;
  6268. }
  6269. }
  6270. if (this.lastBreak === 0) {
  6271. var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
  6272. autoBreaks += pagesSinceLastBreak;
  6273. }
  6274. return autoBreaks + manualBreaks;
  6275. } else {
  6276. return this.pdf.internal.getCurrentPageInfo().pageNumber;
  6277. }
  6278. },
  6279. _gotoPage: function _gotoPage(pageOneBased) {
  6280. // This is a stub to be overriden if needed
  6281. },
  6282. lineTo: function lineTo(x, y) {
  6283. x = this._wrapX(x);
  6284. y = this._wrapY(y);
  6285. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6286. x = xpt[0];
  6287. y = xpt[1];
  6288. var obj = {
  6289. type: 'lt',
  6290. x: x,
  6291. y: y
  6292. };
  6293. this.path.push(obj);
  6294. },
  6295. bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
  6296. x1 = this._wrapX(x1);
  6297. y1 = this._wrapY(y1);
  6298. x2 = this._wrapX(x2);
  6299. y2 = this._wrapY(y2);
  6300. x = this._wrapX(x);
  6301. y = this._wrapY(y);
  6302. var xpt;
  6303. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6304. x = xpt[0];
  6305. y = xpt[1];
  6306. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  6307. x1 = xpt[0];
  6308. y1 = xpt[1];
  6309. xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
  6310. x2 = xpt[0];
  6311. y2 = xpt[1];
  6312. var obj = {
  6313. type: 'bct',
  6314. x1: x1,
  6315. y1: y1,
  6316. x2: x2,
  6317. y2: y2,
  6318. x: x,
  6319. y: y
  6320. };
  6321. this.path.push(obj);
  6322. },
  6323. quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
  6324. x1 = this._wrapX(x1);
  6325. y1 = this._wrapY(y1);
  6326. x = this._wrapX(x);
  6327. y = this._wrapY(y);
  6328. var xpt;
  6329. xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6330. x = xpt[0];
  6331. y = xpt[1];
  6332. xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
  6333. x1 = xpt[0];
  6334. y1 = xpt[1];
  6335. var obj = {
  6336. type: 'qct',
  6337. x1: x1,
  6338. y1: y1,
  6339. x: x,
  6340. y: y
  6341. };
  6342. this.path.push(obj);
  6343. },
  6344. arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
  6345. x = this._wrapX(x);
  6346. y = this._wrapY(y);
  6347. if (!this._matrix_is_identity(this.ctx._transform)) {
  6348. var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
  6349. x = xpt[0];
  6350. y = xpt[1];
  6351. var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
  6352. var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
  6353. radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
  6354. //TODO angles need to be transformed
  6355. }
  6356. var obj = {
  6357. type: 'arc',
  6358. x: x,
  6359. y: y,
  6360. radius: radius,
  6361. startAngle: startAngle,
  6362. endAngle: endAngle,
  6363. anticlockwise: anticlockwise
  6364. };
  6365. this.path.push(obj);
  6366. },
  6367. drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
  6368. if (x2 !== undefined) {
  6369. x = x2;
  6370. y = y2;
  6371. w = w2;
  6372. h = h2;
  6373. }
  6374. x = this._wrapX(x);
  6375. y = this._wrapY(y);
  6376. var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
  6377. var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
  6378. // TODO implement source clipping and image scaling
  6379. var format;
  6380. var rx = /data:image\/(\w+).*/i;
  6381. var m = rx.exec(img);
  6382. if (m != null) {
  6383. format = m[1];
  6384. } else {
  6385. // format = "jpeg";
  6386. format = "png";
  6387. }
  6388. this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
  6389. },
  6390. /**
  6391. * Multiply the first matrix by the second
  6392. * @param m1
  6393. * @param m2
  6394. * @returns {*[]}
  6395. * @private
  6396. */
  6397. _matrix_multiply: function _matrix_multiply(m2, m1) {
  6398. var sx = m1[0];
  6399. var shy = m1[1];
  6400. var shx = m1[2];
  6401. var sy = m1[3];
  6402. var tx = m1[4];
  6403. var ty = m1[5];
  6404. var t0 = sx * m2[0] + shy * m2[2];
  6405. var t2 = shx * m2[0] + sy * m2[2];
  6406. var t4 = tx * m2[0] + ty * m2[2] + m2[4];
  6407. shy = sx * m2[1] + shy * m2[3];
  6408. sy = shx * m2[1] + sy * m2[3];
  6409. ty = tx * m2[1] + ty * m2[3] + m2[5];
  6410. sx = t0;
  6411. shx = t2;
  6412. tx = t4;
  6413. return [sx, shy, shx, sy, tx, ty];
  6414. },
  6415. _matrix_rotation: function _matrix_rotation(m) {
  6416. return Math.atan2(m[2], m[0]);
  6417. },
  6418. _matrix_decompose: function _matrix_decompose(matrix) {
  6419. var a = matrix[0];
  6420. var b = matrix[1];
  6421. var c = matrix[2];
  6422. var d = matrix[3];
  6423. var scaleX = Math.sqrt(a * a + b * b);
  6424. a /= scaleX;
  6425. b /= scaleX;
  6426. var shear = a * c + b * d;
  6427. c -= a * shear;
  6428. d -= b * shear;
  6429. var scaleY = Math.sqrt(c * c + d * d);
  6430. c /= scaleY;
  6431. d /= scaleY;
  6432. shear /= scaleY;
  6433. if (a * d < b * c) {
  6434. a = -a;
  6435. b = -b;
  6436. shear = -shear;
  6437. scaleX = -scaleX;
  6438. }
  6439. return {
  6440. scale: [scaleX, 0, 0, scaleY, 0, 0],
  6441. translate: [1, 0, 0, 1, matrix[4], matrix[5]],
  6442. rotate: [a, b, -b, a, 0, 0],
  6443. skew: [1, 0, shear, 1, 0, 0]
  6444. };
  6445. },
  6446. _matrix_map_point: function _matrix_map_point(m1, pt) {
  6447. var sx = m1[0];
  6448. var shy = m1[1];
  6449. var shx = m1[2];
  6450. var sy = m1[3];
  6451. var tx = m1[4];
  6452. var ty = m1[5];
  6453. var px = pt[0];
  6454. var py = pt[1];
  6455. var x = px * sx + py * shx + tx;
  6456. var y = px * shy + py * sy + ty;
  6457. return [x, y];
  6458. },
  6459. _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
  6460. var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
  6461. return { x: xpt[0], y: xpt[1] };
  6462. },
  6463. _matrix_map_rect: function _matrix_map_rect(m1, rect) {
  6464. var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
  6465. var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
  6466. return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
  6467. },
  6468. _matrix_is_identity: function _matrix_is_identity(m1) {
  6469. if (m1[0] != 1) {
  6470. return false;
  6471. }
  6472. if (m1[1] != 0) {
  6473. return false;
  6474. }
  6475. if (m1[2] != 0) {
  6476. return false;
  6477. }
  6478. if (m1[3] != 1) {
  6479. return false;
  6480. }
  6481. if (m1[4] != 0) {
  6482. return false;
  6483. }
  6484. if (m1[5] != 0) {
  6485. return false;
  6486. }
  6487. return true;
  6488. },
  6489. rotate: function rotate(angle) {
  6490. var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
  6491. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  6492. },
  6493. scale: function scale(sx, sy) {
  6494. var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
  6495. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  6496. },
  6497. translate: function translate(x, y) {
  6498. var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
  6499. this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
  6500. },
  6501. stroke: function stroke() {
  6502. if (this.ctx._clip_path.length > 0) {
  6503. var lines;
  6504. if (window.outIntercept) {
  6505. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  6506. } else {
  6507. lines = this.internal.getCurrentPage();
  6508. }
  6509. lines.push("q");
  6510. var origPath = this.path;
  6511. this.path = this.ctx._clip_path;
  6512. this.ctx._clip_path = [];
  6513. this._stroke(true);
  6514. this.ctx._clip_path = this.path;
  6515. this.path = origPath;
  6516. this._stroke(false);
  6517. lines.push("Q");
  6518. } else {
  6519. this._stroke(false);
  6520. }
  6521. },
  6522. _stroke: function _stroke(isClip) {
  6523. if (!isClip && this._isStrokeTransparent()) {
  6524. return;
  6525. }
  6526. //TODO opacity
  6527. var moves = [];
  6528. var xPath = this.path;
  6529. for (var i = 0; i < xPath.length; i++) {
  6530. var pt = xPath[i];
  6531. switch (pt.type) {
  6532. case 'mt':
  6533. moves.push({ start: pt, deltas: [], abs: [] });
  6534. break;
  6535. case 'lt':
  6536. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  6537. moves[moves.length - 1].deltas.push(delta);
  6538. moves[moves.length - 1].abs.push(pt);
  6539. break;
  6540. case 'bct':
  6541. 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];
  6542. moves[moves.length - 1].deltas.push(delta);
  6543. break;
  6544. case 'qct':
  6545. // convert to bezier
  6546. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  6547. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  6548. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  6549. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  6550. var x3 = pt.x;
  6551. var y3 = pt.y;
  6552. 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];
  6553. moves[moves.length - 1].deltas.push(delta);
  6554. break;
  6555. case 'arc':
  6556. //TODO this was hack to avoid out-of-bounds issue
  6557. // No move-to before drawing the arc
  6558. if (moves.length == 0) {
  6559. moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
  6560. }
  6561. moves[moves.length - 1].arc = true;
  6562. if (Array.isArray(moves[moves.length - 1].abs)) {
  6563. moves[moves.length - 1].abs.push(pt);
  6564. }
  6565. break;
  6566. case 'close':
  6567. break;
  6568. }
  6569. }
  6570. for (var i = 0; i < moves.length; i++) {
  6571. var style;
  6572. if (i == moves.length - 1) {
  6573. style = 's';
  6574. } else {
  6575. style = null;
  6576. }
  6577. if (moves[i].arc) {
  6578. var arcs = moves[i].abs;
  6579. for (var ii = 0; ii < arcs.length; ii++) {
  6580. var arc = arcs[ii];
  6581. var start = arc.startAngle * 360 / (2 * Math.PI);
  6582. var end = arc.endAngle * 360 / (2 * Math.PI);
  6583. var x = arc.x;
  6584. var y = arc.y;
  6585. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
  6586. }
  6587. } else {
  6588. var x = moves[i].start.x;
  6589. var y = moves[i].start.y;
  6590. if (!isClip) {
  6591. this.pdf.lines(moves[i].deltas, x, y, null, style);
  6592. } else {
  6593. this.pdf.lines(moves[i].deltas, x, y, null, null);
  6594. this.pdf.clip_fixed();
  6595. }
  6596. }
  6597. }
  6598. },
  6599. _isFillTransparent: function _isFillTransparent() {
  6600. return this.ctx._isFillTransparent || this.globalAlpha == 0;
  6601. },
  6602. _isStrokeTransparent: function _isStrokeTransparent() {
  6603. return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
  6604. },
  6605. fill: function fill(fillRule) {
  6606. //evenodd or nonzero (default)
  6607. if (this.ctx._clip_path.length > 0) {
  6608. var lines;
  6609. if (window.outIntercept) {
  6610. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  6611. } else {
  6612. lines = this.internal.getCurrentPage();
  6613. }
  6614. lines.push("q");
  6615. var origPath = this.path;
  6616. this.path = this.ctx._clip_path;
  6617. this.ctx._clip_path = [];
  6618. this._fill(fillRule, true);
  6619. this.ctx._clip_path = this.path;
  6620. this.path = origPath;
  6621. this._fill(fillRule, false);
  6622. lines.push('Q');
  6623. } else {
  6624. this._fill(fillRule, false);
  6625. }
  6626. },
  6627. _fill: function _fill(fillRule, isClip) {
  6628. if (this._isFillTransparent()) {
  6629. return;
  6630. }
  6631. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  6632. var lines;
  6633. if (window.outIntercept) {
  6634. lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
  6635. } else {
  6636. lines = this.internal.getCurrentPage();
  6637. }
  6638. // if (this.ctx._clip_path.length > 0) {
  6639. // lines.push('q');
  6640. // var oldPath = this.path;
  6641. // this.path = this.ctx._clip_path;
  6642. // this.ctx._clip_path = [];
  6643. // this._fill(fillRule, true);
  6644. // this.ctx._clip_path = this.path;
  6645. // this.path = oldPath;
  6646. // lines.push('Q');
  6647. // }
  6648. var moves = [];
  6649. var outInterceptOld = window.outIntercept;
  6650. if (v2Support) {
  6651. // Blend and Mask
  6652. switch (this.ctx.globalCompositeOperation) {
  6653. case 'normal':
  6654. case 'source-over':
  6655. break;
  6656. case 'destination-in':
  6657. case 'destination-out':
  6658. //TODO this need to be added to the current group or page
  6659. // define a mask stream
  6660. var obj = this.pdf.internal.newStreamObject();
  6661. // define a mask state
  6662. var obj2 = this.pdf.internal.newObject2();
  6663. obj2.push('<</Type /ExtGState');
  6664. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  6665. obj2.push('>>');
  6666. // add mask to page resources
  6667. var gsName = 'MASK' + obj2.objId;
  6668. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  6669. var instruction = '/' + gsName + ' gs';
  6670. // add mask to page, group, or stream
  6671. lines.splice(0, 0, 'q');
  6672. lines.splice(1, 0, instruction);
  6673. lines.push('Q');
  6674. window.outIntercept = obj;
  6675. break;
  6676. default:
  6677. var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
  6678. if (dictionaryEntry) {
  6679. this.pdf.internal.out(dictionaryEntry + ' gs');
  6680. }
  6681. break;
  6682. }
  6683. }
  6684. var alpha = this.ctx.globalAlpha;
  6685. if (this.ctx._fillOpacity < 1) {
  6686. // TODO combine this with global opacity
  6687. alpha = this.ctx._fillOpacity;
  6688. }
  6689. //TODO check for an opacity graphics state that was already created
  6690. //TODO do not set opacity if current value is already active
  6691. if (v2Support) {
  6692. var objOpac = this.pdf.internal.newObject2();
  6693. objOpac.push('<</Type /ExtGState');
  6694. //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
  6695. //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
  6696. objOpac.push('/CA ' + alpha); // Stroke
  6697. objOpac.push('/ca ' + alpha); // Not Stroke
  6698. objOpac.push('>>');
  6699. var gsName = 'GS_O_' + objOpac.objId;
  6700. this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
  6701. this.pdf.internal.out('/' + gsName + ' gs');
  6702. }
  6703. var xPath = this.path;
  6704. for (var i = 0; i < xPath.length; i++) {
  6705. var pt = xPath[i];
  6706. switch (pt.type) {
  6707. case 'mt':
  6708. moves.push({ start: pt, deltas: [], abs: [] });
  6709. break;
  6710. case 'lt':
  6711. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  6712. moves[moves.length - 1].deltas.push(delta);
  6713. moves[moves.length - 1].abs.push(pt);
  6714. break;
  6715. case 'bct':
  6716. 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];
  6717. moves[moves.length - 1].deltas.push(delta);
  6718. break;
  6719. case 'qct':
  6720. // convert to bezier
  6721. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  6722. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  6723. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  6724. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  6725. var x3 = pt.x;
  6726. var y3 = pt.y;
  6727. 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];
  6728. moves[moves.length - 1].deltas.push(delta);
  6729. break;
  6730. case 'arc':
  6731. //TODO this was hack to avoid out-of-bounds issue when drawing circle
  6732. // No move-to before drawing the arc
  6733. if (moves.length === 0) {
  6734. moves.push({ deltas: [], abs: [] });
  6735. }
  6736. moves[moves.length - 1].arc = true;
  6737. if (Array.isArray(moves[moves.length - 1].abs)) {
  6738. moves[moves.length - 1].abs.push(pt);
  6739. }
  6740. break;
  6741. case 'close':
  6742. moves.push({ close: true });
  6743. break;
  6744. }
  6745. }
  6746. for (var i = 0; i < moves.length; i++) {
  6747. var style;
  6748. if (i == moves.length - 1) {
  6749. style = 'f';
  6750. if (fillRule === 'evenodd') {
  6751. style += '*';
  6752. }
  6753. } else {
  6754. style = null;
  6755. }
  6756. if (moves[i].close) {
  6757. this.pdf.internal.out('h');
  6758. if (style) {
  6759. // only fill at final path move
  6760. this.pdf.internal.out(style);
  6761. }
  6762. } else if (moves[i].arc) {
  6763. if (moves[i].start) {
  6764. this.internal.move2(this, moves[i].start.x, moves[i].start.y);
  6765. }
  6766. var arcs = moves[i].abs;
  6767. for (var ii = 0; ii < arcs.length; ii++) {
  6768. var arc = arcs[ii];
  6769. //TODO lines deltas were getting in here
  6770. if (typeof arc.startAngle !== 'undefined') {
  6771. var start = arc.startAngle * 360 / (2 * Math.PI);
  6772. var end = arc.endAngle * 360 / (2 * Math.PI);
  6773. var x = arc.x;
  6774. var y = arc.y;
  6775. if (ii === 0) {
  6776. this.internal.move2(this, x, y);
  6777. }
  6778. this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
  6779. if (ii === arcs.length - 1) {
  6780. // The original arc move did not occur because of the algorithm
  6781. if (moves[i].start) {
  6782. var x = moves[i].start.x;
  6783. var y = moves[i].start.y;
  6784. this.internal.line2(c2d, x, y);
  6785. }
  6786. }
  6787. } else {
  6788. this.internal.line2(c2d, arc.x, arc.y);
  6789. }
  6790. }
  6791. } else {
  6792. var x = moves[i].start.x;
  6793. var y = moves[i].start.y;
  6794. if (!isClip) {
  6795. this.pdf.lines(moves[i].deltas, x, y, null, style);
  6796. } else {
  6797. this.pdf.lines(moves[i].deltas, x, y, null, null);
  6798. this.pdf.clip_fixed();
  6799. }
  6800. }
  6801. }
  6802. window.outIntercept = outInterceptOld;
  6803. // if (this.ctx._clip_path.length > 0) {
  6804. // lines.push('Q');
  6805. // }
  6806. },
  6807. pushMask: function pushMask() {
  6808. var v2Support = typeof this.pdf.internal.newObject2 === 'function';
  6809. if (!v2Support) {
  6810. console.log('jsPDF v2 not enabled');
  6811. return;
  6812. }
  6813. // define a mask stream
  6814. var obj = this.pdf.internal.newStreamObject();
  6815. // define a mask state
  6816. var obj2 = this.pdf.internal.newObject2();
  6817. obj2.push('<</Type /ExtGState');
  6818. obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
  6819. obj2.push('>>');
  6820. // add mask to page resources
  6821. var gsName = 'MASK' + obj2.objId;
  6822. this.pdf.internal.addGraphicsState(gsName, obj2.objId);
  6823. var instruction = '/' + gsName + ' gs';
  6824. this.pdf.internal.out(instruction);
  6825. },
  6826. clip: function clip() {
  6827. //TODO do we reset the path, or just copy it?
  6828. if (this.ctx._clip_path.length > 0) {
  6829. for (var i = 0; i < this.path.length; i++) {
  6830. this.ctx._clip_path.push(this.path[i]);
  6831. }
  6832. } else {
  6833. this.ctx._clip_path = this.path;
  6834. }
  6835. this.path = [];
  6836. },
  6837. measureText: function measureText(text) {
  6838. var pdf = this.pdf;
  6839. return {
  6840. getWidth: function getWidth() {
  6841. var fontSize = pdf.internal.getFontSize();
  6842. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  6843. // Convert points to pixels
  6844. txtWidth *= 1.3333;
  6845. return txtWidth;
  6846. },
  6847. get width() {
  6848. return this.getWidth(text);
  6849. }
  6850. };
  6851. },
  6852. _getBaseline: function _getBaseline(y) {
  6853. var height = parseInt(this.pdf.internal.getFontSize());
  6854. // TODO Get descent from font descriptor
  6855. var descent = height * 0.25;
  6856. switch (this.ctx.textBaseline) {
  6857. case 'bottom':
  6858. return y - descent;
  6859. case 'top':
  6860. return y + height;
  6861. case 'hanging':
  6862. return y + height - descent;
  6863. case 'middle':
  6864. return y + height / 2 - descent;
  6865. case 'ideographic':
  6866. // TODO not implemented
  6867. return y;
  6868. case 'alphabetic':
  6869. default:
  6870. return y;
  6871. }
  6872. }
  6873. };
  6874. var c2d = jsPDFAPI.context2d;
  6875. // accessor methods
  6876. Object.defineProperty(c2d, 'fillStyle', {
  6877. set: function set(value) {
  6878. this.setFillStyle(value);
  6879. },
  6880. get: function get() {
  6881. return this.ctx.fillStyle;
  6882. }
  6883. });
  6884. Object.defineProperty(c2d, 'strokeStyle', {
  6885. set: function set(value) {
  6886. this.setStrokeStyle(value);
  6887. },
  6888. get: function get() {
  6889. return this.ctx.strokeStyle;
  6890. }
  6891. });
  6892. Object.defineProperty(c2d, 'lineWidth', {
  6893. set: function set(value) {
  6894. this.setLineWidth(value);
  6895. },
  6896. get: function get() {
  6897. return this.ctx.lineWidth;
  6898. }
  6899. });
  6900. Object.defineProperty(c2d, 'lineCap', {
  6901. set: function set(val) {
  6902. this.setLineCap(val);
  6903. },
  6904. get: function get() {
  6905. return this.ctx.lineCap;
  6906. }
  6907. });
  6908. Object.defineProperty(c2d, 'lineJoin', {
  6909. set: function set(val) {
  6910. this.setLineJoin(val);
  6911. },
  6912. get: function get() {
  6913. return this.ctx.lineJoin;
  6914. }
  6915. });
  6916. Object.defineProperty(c2d, 'miterLimit', {
  6917. set: function set(val) {
  6918. this.ctx.miterLimit = val;
  6919. },
  6920. get: function get() {
  6921. return this.ctx.miterLimit;
  6922. }
  6923. });
  6924. Object.defineProperty(c2d, 'textBaseline', {
  6925. set: function set(value) {
  6926. this.setTextBaseline(value);
  6927. },
  6928. get: function get() {
  6929. return this.getTextBaseline();
  6930. }
  6931. });
  6932. Object.defineProperty(c2d, 'textAlign', {
  6933. set: function set(value) {
  6934. this.setTextAlign(value);
  6935. },
  6936. get: function get() {
  6937. return this.getTextAlign();
  6938. }
  6939. });
  6940. Object.defineProperty(c2d, 'font', {
  6941. set: function set(value) {
  6942. this.setFont(value);
  6943. },
  6944. get: function get() {
  6945. return this.ctx.font;
  6946. }
  6947. });
  6948. Object.defineProperty(c2d, 'globalCompositeOperation', {
  6949. set: function set(value) {
  6950. this.ctx.globalCompositeOperation = value;
  6951. },
  6952. get: function get() {
  6953. return this.ctx.globalCompositeOperation;
  6954. }
  6955. });
  6956. Object.defineProperty(c2d, 'globalAlpha', {
  6957. set: function set(value) {
  6958. this.ctx.globalAlpha = value;
  6959. },
  6960. get: function get() {
  6961. return this.ctx.globalAlpha;
  6962. }
  6963. });
  6964. Object.defineProperty(c2d, 'canvas', {
  6965. get: function get() {
  6966. return { parentNode: false, style: false };
  6967. }
  6968. });
  6969. // Not HTML API
  6970. Object.defineProperty(c2d, 'ignoreClearRect', {
  6971. set: function set(value) {
  6972. this.ctx.ignoreClearRect = value;
  6973. },
  6974. get: function get() {
  6975. return this.ctx.ignoreClearRect;
  6976. }
  6977. });
  6978. // End Not HTML API
  6979. c2d.internal = {};
  6980. c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  6981. c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  6982. c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  6983. // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
  6984. c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
  6985. var k = this.pdf.internal.scaleFactor;
  6986. var pageHeight = this.pdf.internal.pageSize.getHeight();
  6987. var f2 = this.pdf.internal.f2;
  6988. var a1r = a1 * (Math.PI / 180);
  6989. var a2r = a2 * (Math.PI / 180);
  6990. var curves = this.createArc(r, a1r, a2r, anticlockwise);
  6991. for (var i = 0; i < curves.length; i++) {
  6992. var curve = curves[i];
  6993. if (i === 0) {
  6994. 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(' '));
  6995. } else {
  6996. 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(' '));
  6997. }
  6998. //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
  6999. c2d._lastPoint = { x: xc, y: yc };
  7000. // 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'
  7001. }
  7002. if (style !== null) {
  7003. this.pdf.internal.out(this.pdf.internal.getStyle(style));
  7004. }
  7005. };
  7006. /**
  7007. *
  7008. * @param x Edge point X
  7009. * @param y Edge point Y
  7010. * @param r Radius
  7011. * @param a1 start angle
  7012. * @param a2 end angle
  7013. * @param anticlockwise
  7014. * @param style
  7015. * @param isClip
  7016. */
  7017. c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
  7018. // we need to convert from cartesian to polar here methinks.
  7019. var centerX = x; // + r;
  7020. var centerY = y;
  7021. if (!isClip) {
  7022. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
  7023. } else {
  7024. this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
  7025. this.pdf.clip_fixed();
  7026. }
  7027. };
  7028. c2d.internal.move2 = function (c2d, x, y) {
  7029. var k = this.pdf.internal.scaleFactor;
  7030. var pageHeight = this.pdf.internal.pageSize.getHeight();
  7031. var f2 = this.pdf.internal.f2;
  7032. this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
  7033. c2d._lastPoint = { x: x, y: y };
  7034. };
  7035. c2d.internal.line2 = function (c2d, dx, dy) {
  7036. var k = this.pdf.internal.scaleFactor;
  7037. var pageHeight = this.pdf.internal.pageSize.getHeight();
  7038. var f2 = this.pdf.internal.f2;
  7039. //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
  7040. var pt = { x: dx, y: dy };
  7041. this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
  7042. //this.pdf.internal.out('f');
  7043. c2d._lastPoint = pt;
  7044. };
  7045. /**
  7046. * 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.
  7047. *
  7048. * 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.
  7049. */
  7050. c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
  7051. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
  7052. var twoPI = Math.PI * 2;
  7053. var piOverTwo = Math.PI / 2.0;
  7054. // normalize startAngle, endAngle to [0, 2PI]
  7055. var startAngleN = startAngle;
  7056. if (startAngleN < twoPI || startAngleN > twoPI) {
  7057. startAngleN = startAngleN % twoPI;
  7058. }
  7059. if (startAngleN < 0) {
  7060. startAngleN = twoPI + startAngleN;
  7061. }
  7062. while (startAngle > endAngle) {
  7063. startAngle = startAngle - twoPI;
  7064. }
  7065. var totalAngle = Math.abs(endAngle - startAngle);
  7066. if (totalAngle < twoPI) {
  7067. if (anticlockwise) {
  7068. totalAngle = twoPI - totalAngle;
  7069. }
  7070. }
  7071. // Compute the sequence of arc curves, up to PI/2 at a time.
  7072. var curves = [];
  7073. var sgn = anticlockwise ? -1 : +1;
  7074. var a1 = startAngleN;
  7075. for (; totalAngle > EPSILON;) {
  7076. var remain = sgn * Math.min(totalAngle, piOverTwo);
  7077. var a2 = a1 + remain;
  7078. curves.push(this.createSmallArc(radius, a1, a2));
  7079. totalAngle -= Math.abs(a2 - a1);
  7080. a1 = a2;
  7081. }
  7082. return curves;
  7083. };
  7084. c2d.internal.getCurrentPage = function () {
  7085. return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
  7086. };
  7087. /**
  7088. * 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.
  7089. *
  7090. * 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.
  7091. *
  7092. * 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.
  7093. */
  7094. c2d.internal.createSmallArc = function (r, a1, a2) {
  7095. // Compute all four points for an arc that subtends the same total angle
  7096. // but is centered on the X-axis
  7097. var a = (a2 - a1) / 2.0;
  7098. var x4 = r * Math.cos(a);
  7099. var y4 = r * Math.sin(a);
  7100. var x1 = x4;
  7101. var y1 = -y4;
  7102. var q1 = x1 * x1 + y1 * y1;
  7103. var q2 = q1 + x1 * x4 + y1 * y4;
  7104. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  7105. var x2 = x1 - k2 * y1;
  7106. var y2 = y1 + k2 * x1;
  7107. var x3 = x2;
  7108. var y3 = -y2;
  7109. // Find the arc points' actual locations by computing x1,y1 and x4,y4
  7110. // and rotating the control points by a + a1
  7111. var ar = a + a1;
  7112. var cos_ar = Math.cos(ar);
  7113. var sin_ar = Math.sin(ar);
  7114. return {
  7115. x1: r * Math.cos(a1),
  7116. y1: r * Math.sin(a1),
  7117. x2: x2 * cos_ar - y2 * sin_ar,
  7118. y2: x2 * sin_ar + y2 * cos_ar,
  7119. x3: x3 * cos_ar - y3 * sin_ar,
  7120. y3: x3 * sin_ar + y3 * cos_ar,
  7121. x4: r * Math.cos(a2),
  7122. y4: r * Math.sin(a2)
  7123. };
  7124. };
  7125. function context() {
  7126. this._isStrokeTransparent = false;
  7127. this._strokeOpacity = 1;
  7128. this.strokeStyle = '#000000';
  7129. this.fillStyle = '#000000';
  7130. this._isFillTransparent = false;
  7131. this._fillOpacity = 1;
  7132. this.font = "12pt times";
  7133. this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
  7134. this.textAlign = 'start';
  7135. this.lineWidth = 1;
  7136. this.lineJoin = 'miter'; // round, bevel, miter
  7137. this.lineCap = 'butt'; // butt, round, square
  7138. this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
  7139. this.globalCompositeOperation = 'normal';
  7140. this.globalAlpha = 1.0;
  7141. this._clip_path = [];
  7142. // TODO miter limit //default 10
  7143. // Not HTML API
  7144. this.ignoreClearRect = false;
  7145. this.copy = function (ctx) {
  7146. this._isStrokeTransparent = ctx._isStrokeTransparent;
  7147. this._strokeOpacity = ctx._strokeOpacity;
  7148. this.strokeStyle = ctx.strokeStyle;
  7149. this._isFillTransparent = ctx._isFillTransparent;
  7150. this._fillOpacity = ctx._fillOpacity;
  7151. this.fillStyle = ctx.fillStyle;
  7152. this.font = ctx.font;
  7153. this.lineWidth = ctx.lineWidth;
  7154. this.lineJoin = ctx.lineJoin;
  7155. this.lineCap = ctx.lineCap;
  7156. this.textBaseline = ctx.textBaseline;
  7157. this.textAlign = ctx.textAlign;
  7158. this._fontSize = ctx._fontSize;
  7159. this._transform = ctx._transform.slice(0);
  7160. this.globalCompositeOperation = ctx.globalCompositeOperation;
  7161. this.globalAlpha = ctx.globalAlpha;
  7162. this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
  7163. // Not HTML API
  7164. this.ignoreClearRect = ctx.ignoreClearRect;
  7165. };
  7166. }
  7167. return this;
  7168. })(jsPDF.API, typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')());
  7169. /** @preserve
  7170. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  7171. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  7172. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  7173. * 2014 Diego Casorran, https://github.com/diegocr
  7174. * 2014 Daniel Husar, https://github.com/danielhusar
  7175. * 2014 Wolfgang Gassler, https://github.com/woolfg
  7176. * 2014 Steven Spungin, https://github.com/flamenco
  7177. *
  7178. *
  7179. * ====================================================================
  7180. */
  7181. (function (jsPDFAPI) {
  7182. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  7183. clone = function () {
  7184. return function (obj) {
  7185. Clone.prototype = obj;
  7186. return new Clone();
  7187. };
  7188. function Clone() {}
  7189. }();
  7190. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  7191. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  7192. i = 0;
  7193. l = array.length;
  7194. fragment = void 0;
  7195. lTrimmed = false;
  7196. rTrimmed = false;
  7197. while (!lTrimmed && i !== l) {
  7198. fragment = array[i] = array[i].trimLeft();
  7199. if (fragment) {
  7200. lTrimmed = true;
  7201. }
  7202. i++;
  7203. }
  7204. i = l - 1;
  7205. while (l && !rTrimmed && i !== -1) {
  7206. fragment = array[i] = array[i].trimRight();
  7207. if (fragment) {
  7208. rTrimmed = true;
  7209. }
  7210. i--;
  7211. }
  7212. r = /\s+$/g;
  7213. trailingSpace = true;
  7214. i = 0;
  7215. while (i !== l) {
  7216. // Leave the line breaks intact
  7217. if (array[i] != "\u2028") {
  7218. fragment = array[i].replace(/\s+/g, " ");
  7219. if (trailingSpace) {
  7220. fragment = fragment.trimLeft();
  7221. }
  7222. if (fragment) {
  7223. trailingSpace = r.test(fragment);
  7224. }
  7225. array[i] = fragment;
  7226. }
  7227. i++;
  7228. }
  7229. return array;
  7230. };
  7231. Renderer = function Renderer(pdf, x, y, settings) {
  7232. this.pdf = pdf;
  7233. this.x = x;
  7234. this.y = y;
  7235. this.settings = settings;
  7236. //list of functions which are called after each element-rendering process
  7237. this.watchFunctions = [];
  7238. this.init();
  7239. return this;
  7240. };
  7241. ResolveFont = function ResolveFont(css_font_family_string) {
  7242. var name, part, parts;
  7243. name = void 0;
  7244. parts = css_font_family_string.split(",");
  7245. part = parts.shift();
  7246. while (!name && part) {
  7247. name = FontNameDB[part.trim().toLowerCase()];
  7248. part = parts.shift();
  7249. }
  7250. return name;
  7251. };
  7252. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  7253. //IE8 issues
  7254. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  7255. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  7256. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  7257. }
  7258. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  7259. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  7260. }
  7261. var normal, undef, value;
  7262. undef = void 0;
  7263. normal = 16.00;
  7264. value = UnitedNumberMap[css_line_height_string];
  7265. if (value) {
  7266. return value;
  7267. }
  7268. value = {
  7269. "xx-small": 9,
  7270. "x-small": 11,
  7271. small: 13,
  7272. medium: 16,
  7273. large: 19,
  7274. "x-large": 23,
  7275. "xx-large": 28,
  7276. auto: 0
  7277. }[css_line_height_string];
  7278. if (value !== undef) {
  7279. return UnitedNumberMap[css_line_height_string] = value / normal;
  7280. }
  7281. if (value = parseFloat(css_line_height_string)) {
  7282. return UnitedNumberMap[css_line_height_string] = value / normal;
  7283. }
  7284. value = css_line_height_string.match(/([\d\.]+)(px)/);
  7285. if (Array.isArray(value) && value.length === 3) {
  7286. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  7287. }
  7288. return UnitedNumberMap[css_line_height_string] = 1;
  7289. };
  7290. GetCSS = function GetCSS(element) {
  7291. var css, tmp, computedCSSElement;
  7292. computedCSSElement = function (el) {
  7293. var compCSS;
  7294. compCSS = function (el) {
  7295. if (document.defaultView && document.defaultView.getComputedStyle) {
  7296. return document.defaultView.getComputedStyle(el, null);
  7297. } else if (el.currentStyle) {
  7298. return el.currentStyle;
  7299. } else {
  7300. return el.style;
  7301. }
  7302. }(el);
  7303. return function (prop) {
  7304. prop = prop.replace(/-\D/g, function (match) {
  7305. return match.charAt(1).toUpperCase();
  7306. });
  7307. return compCSS[prop];
  7308. };
  7309. }(element);
  7310. css = {};
  7311. tmp = void 0;
  7312. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  7313. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  7314. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  7315. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  7316. if (tmp === "bold") {
  7317. if (css["font-style"] === "normal") {
  7318. css["font-style"] = tmp;
  7319. } else {
  7320. css["font-style"] = tmp + css["font-style"];
  7321. }
  7322. }
  7323. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  7324. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  7325. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  7326. tmp = css["display"] === "block";
  7327. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  7328. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  7329. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  7330. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  7331. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  7332. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  7333. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  7334. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  7335. css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
  7336. //float and clearing of floats
  7337. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  7338. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  7339. css["color"] = computedCSSElement("color");
  7340. return css;
  7341. };
  7342. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  7343. var handlers, i, isHandledElsewhere, l, classNames;
  7344. isHandledElsewhere = false;
  7345. i = void 0;
  7346. l = void 0;
  7347. handlers = elementHandlers["#" + element.id];
  7348. if (handlers) {
  7349. if (typeof handlers === "function") {
  7350. isHandledElsewhere = handlers(element, renderer);
  7351. } else {
  7352. i = 0;
  7353. l = handlers.length;
  7354. while (!isHandledElsewhere && i !== l) {
  7355. isHandledElsewhere = handlers[i](element, renderer);
  7356. i++;
  7357. }
  7358. }
  7359. }
  7360. handlers = elementHandlers[element.nodeName];
  7361. if (!isHandledElsewhere && handlers) {
  7362. if (typeof handlers === "function") {
  7363. isHandledElsewhere = handlers(element, renderer);
  7364. } else {
  7365. i = 0;
  7366. l = handlers.length;
  7367. while (!isHandledElsewhere && i !== l) {
  7368. isHandledElsewhere = handlers[i](element, renderer);
  7369. i++;
  7370. }
  7371. }
  7372. }
  7373. // Try class names
  7374. classNames = typeof element.className === 'string' ? element.className.split(' ') : [];
  7375. for (i = 0; i < classNames.length; i++) {
  7376. handlers = elementHandlers['.' + classNames[i]];
  7377. if (!isHandledElsewhere && handlers) {
  7378. if (typeof handlers === "function") {
  7379. isHandledElsewhere = handlers(element, renderer);
  7380. } else {
  7381. i = 0;
  7382. l = handlers.length;
  7383. while (!isHandledElsewhere && i !== l) {
  7384. isHandledElsewhere = handlers[i](element, renderer);
  7385. i++;
  7386. }
  7387. }
  7388. }
  7389. }
  7390. return isHandledElsewhere;
  7391. };
  7392. tableToJson = function tableToJson(table, renderer) {
  7393. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  7394. data = [];
  7395. headers = [];
  7396. i = 0;
  7397. l = table.rows[0].cells.length;
  7398. table_with = table.clientWidth;
  7399. while (i < l) {
  7400. cell = table.rows[0].cells[i];
  7401. headers[i] = {
  7402. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  7403. prompt: cell.textContent.replace(/\r?\n/g, ''),
  7404. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.getWidth()
  7405. };
  7406. i++;
  7407. }
  7408. i = 1;
  7409. while (i < table.rows.length) {
  7410. tableRow = table.rows[i];
  7411. rowData = {};
  7412. j = 0;
  7413. while (j < tableRow.cells.length) {
  7414. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  7415. j++;
  7416. }
  7417. data.push(rowData);
  7418. i++;
  7419. }
  7420. return table_obj = {
  7421. rows: data,
  7422. headers: headers
  7423. };
  7424. };
  7425. var SkipNode = {
  7426. SCRIPT: 1,
  7427. STYLE: 1,
  7428. NOSCRIPT: 1,
  7429. OBJECT: 1,
  7430. EMBED: 1,
  7431. SELECT: 1
  7432. };
  7433. var listCount = 1;
  7434. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  7435. var cn, cns, fragmentCSS, i, isBlock, l, table2json, cb;
  7436. cns = element.childNodes;
  7437. cn = void 0;
  7438. fragmentCSS = GetCSS(element);
  7439. isBlock = fragmentCSS.display === "block";
  7440. if (isBlock) {
  7441. renderer.setBlockBoundary();
  7442. renderer.setBlockStyle(fragmentCSS);
  7443. }
  7444. i = 0;
  7445. l = cns.length;
  7446. while (i < l) {
  7447. cn = cns[i];
  7448. if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
  7449. //execute all watcher functions to e.g. reset floating
  7450. renderer.executeWatchFunctions(cn);
  7451. /*** HEADER rendering **/
  7452. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  7453. var header = cn;
  7454. //store old top margin
  7455. var oldMarginTop = renderer.pdf.margins_doc.top;
  7456. //subscribe for new page event and render header first on every page
  7457. renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
  7458. //set current y position to old margin
  7459. renderer.y = oldMarginTop;
  7460. //render all child nodes of the header element
  7461. _DrillForContent(header, renderer, elementHandlers);
  7462. //set margin to old margin + rendered header + 10 space to prevent overlapping
  7463. //important for other plugins (e.g. table) to start rendering at correct position after header
  7464. renderer.pdf.margins_doc.top = renderer.y + 10;
  7465. renderer.y += 10;
  7466. }, false);
  7467. }
  7468. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  7469. if (~cn.textContent.indexOf("ADD_PAGE")) {
  7470. renderer.pdf.addPage();
  7471. renderer.y = renderer.pdf.margins_doc.top;
  7472. }
  7473. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  7474. /*** IMAGE RENDERING ***/
  7475. var cached_image;
  7476. if (cn.nodeName === "IMG") {
  7477. var url = cn.getAttribute("src");
  7478. cached_image = images[renderer.pdf.sHashCode(url) || url];
  7479. }
  7480. if (cached_image) {
  7481. if (renderer.pdf.internal.pageSize.getHeight() - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  7482. renderer.pdf.addPage();
  7483. renderer.y = renderer.pdf.margins_doc.top;
  7484. //check if we have to set back some values due to e.g. header rendering for new page
  7485. renderer.executeWatchFunctions(cn);
  7486. }
  7487. var imagesCSS = GetCSS(cn);
  7488. var imageX = renderer.x;
  7489. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
  7490. //define additional paddings, margins which have to be taken into account for margin calculations
  7491. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  7492. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  7493. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  7494. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
  7495. //if float is set to right, move the image to the right border
  7496. //add space if margin is set
  7497. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  7498. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  7499. } else {
  7500. imageX += additionalSpaceLeft;
  7501. }
  7502. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  7503. cached_image = undefined;
  7504. //if the float prop is specified we have to float the text around the image
  7505. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  7506. //add functiont to set back coordinates after image rendering
  7507. renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
  7508. //undo drawing box adaptions which were set by floating
  7509. if (renderer.y >= thresholdY) {
  7510. renderer.x += diffX;
  7511. renderer.settings.width += diffWidth;
  7512. return true;
  7513. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  7514. renderer.x += diffX;
  7515. renderer.y = thresholdY;
  7516. renderer.settings.width += diffWidth;
  7517. return true;
  7518. } else {
  7519. return false;
  7520. }
  7521. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
  7522. //reset floating by clear:both divs
  7523. //just set cursorY after the floating element
  7524. renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
  7525. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  7526. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  7527. renderer.y = yPositionAfterFloating;
  7528. return true;
  7529. } else {
  7530. return false;
  7531. }
  7532. } else {
  7533. return true;
  7534. }
  7535. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
  7536. //if floating is set we decrease the available width by the image width
  7537. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
  7538. //if left just add the image width to the X coordinate
  7539. if (imagesCSS['float'] === 'left') {
  7540. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  7541. }
  7542. } else {
  7543. //if no floating is set, move the rendering cursor after the image height
  7544. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  7545. }
  7546. /*** TABLE RENDERING ***/
  7547. } else if (cn.nodeName === "TABLE") {
  7548. table2json = tableToJson(cn, renderer);
  7549. renderer.y += 10;
  7550. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  7551. autoSize: false,
  7552. printHeaders: elementHandlers.printHeaders,
  7553. margins: renderer.pdf.margins_doc,
  7554. css: GetCSS(cn)
  7555. });
  7556. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  7557. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  7558. listCount = 1;
  7559. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  7560. _DrillForContent(cn, renderer, elementHandlers);
  7561. }
  7562. renderer.y += 10;
  7563. } else if (cn.nodeName === "LI") {
  7564. var temp = renderer.x;
  7565. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  7566. renderer.y += 3;
  7567. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  7568. _DrillForContent(cn, renderer, elementHandlers);
  7569. }
  7570. renderer.x = temp;
  7571. } else if (cn.nodeName === "BR") {
  7572. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  7573. renderer.addText("\u2028", clone(fragmentCSS));
  7574. } else {
  7575. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  7576. _DrillForContent(cn, renderer, elementHandlers);
  7577. }
  7578. }
  7579. } else if (cn.nodeType === 3) {
  7580. var value = cn.nodeValue;
  7581. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  7582. if (cn.parentNode.parentNode.nodeName === "OL") {
  7583. value = listCount++ + '. ' + value;
  7584. } else {
  7585. var fontSize = fragmentCSS["font-size"];
  7586. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  7587. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  7588. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  7589. cb = function cb(x, y) {
  7590. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  7591. };
  7592. }
  7593. }
  7594. // Only add the text if the text node is in the body element
  7595. // Add compatibility with IE11
  7596. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  7597. renderer.addText(value, fragmentCSS);
  7598. }
  7599. } else if (typeof cn === "string") {
  7600. renderer.addText(cn, fragmentCSS);
  7601. }
  7602. }
  7603. i++;
  7604. }
  7605. elementHandlers.outY = renderer.y;
  7606. if (isBlock) {
  7607. return renderer.setBlockBoundary(cb);
  7608. }
  7609. };
  7610. images = {};
  7611. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  7612. var imgs = element.getElementsByTagName('img'),
  7613. l = imgs.length,
  7614. found_images,
  7615. x = 0;
  7616. function done() {
  7617. renderer.pdf.internal.events.publish('imagesLoaded');
  7618. cb(found_images);
  7619. }
  7620. function loadImage(url, width, height) {
  7621. if (!url) return;
  7622. var img = new Image();
  7623. found_images = ++x;
  7624. img.crossOrigin = '';
  7625. img.onerror = img.onload = function () {
  7626. if (img.complete) {
  7627. //to support data urls in images, set width and height
  7628. //as those values are not recognized automatically
  7629. if (img.src.indexOf('data:image/') === 0) {
  7630. img.width = width || img.width || 0;
  7631. img.height = height || img.height || 0;
  7632. }
  7633. //if valid image add to known images array
  7634. if (img.width + img.height) {
  7635. var hash = renderer.pdf.sHashCode(url) || url;
  7636. images[hash] = images[hash] || img;
  7637. }
  7638. }
  7639. if (! --x) {
  7640. done();
  7641. }
  7642. };
  7643. img.src = url;
  7644. }
  7645. while (l--) {
  7646. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  7647. }return x || done();
  7648. };
  7649. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  7650. //check if we can found a <footer> element
  7651. var footer = elem.getElementsByTagName("footer");
  7652. if (footer.length > 0) {
  7653. footer = footer[0];
  7654. //bad hack to get height of footer
  7655. //creat dummy out and check new y after fake rendering
  7656. var oldOut = renderer.pdf.internal.write;
  7657. var oldY = renderer.y;
  7658. renderer.pdf.internal.write = function () {};
  7659. _DrillForContent(footer, renderer, elementHandlers);
  7660. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  7661. renderer.y = oldY;
  7662. renderer.pdf.internal.write = oldOut;
  7663. //add 20% to prevent overlapping
  7664. renderer.pdf.margins_doc.bottom += footerHeight;
  7665. //Create function render header on every page
  7666. var renderFooter = function renderFooter(pageInfo) {
  7667. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
  7668. //set current y position to old margin
  7669. var oldPosition = renderer.y;
  7670. //render all child nodes of the header element
  7671. renderer.y = renderer.pdf.internal.pageSize.getHeight() - renderer.pdf.margins_doc.bottom;
  7672. renderer.pdf.margins_doc.bottom -= footerHeight;
  7673. //check if we have to add page numbers
  7674. var spans = footer.getElementsByTagName('span');
  7675. for (var i = 0; i < spans.length; ++i) {
  7676. //if we find some span element with class pageCounter, set the page
  7677. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  7678. spans[i].innerHTML = pageNumber;
  7679. }
  7680. //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  7681. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  7682. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  7683. }
  7684. }
  7685. //render footer content
  7686. _DrillForContent(footer, renderer, elementHandlers);
  7687. //set bottom margin to previous height including the footer height
  7688. renderer.pdf.margins_doc.bottom += footerHeight;
  7689. //important for other plugins (e.g. table) to start rendering at correct position after header
  7690. renderer.y = oldPosition;
  7691. };
  7692. //check if footer contains totalPages which should be replace at the disoposal of the document
  7693. var spans = footer.getElementsByTagName('span');
  7694. for (var i = 0; i < spans.length; ++i) {
  7695. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  7696. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  7697. }
  7698. }
  7699. //register event to render footer on every new page
  7700. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
  7701. //render footer on first page
  7702. renderFooter();
  7703. //prevent footer rendering
  7704. SkipNode['FOOTER'] = 1;
  7705. }
  7706. };
  7707. process = function process(pdf, element, x, y, settings, callback) {
  7708. if (!element) return false;
  7709. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  7710. if (typeof element === "string") {
  7711. element = function (element) {
  7712. var $frame, $hiddendiv, framename, visuallyhidden;
  7713. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  7714. 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;";
  7715. $hiddendiv = document.createElement('div');
  7716. $hiddendiv.style.cssText = visuallyhidden;
  7717. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  7718. document.body.appendChild($hiddendiv);
  7719. $frame = window.frames[framename];
  7720. $frame.document.open();
  7721. $frame.document.writeln(element);
  7722. $frame.document.close();
  7723. return $frame.document.body;
  7724. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  7725. }
  7726. var r = new Renderer(pdf, x, y, settings),
  7727. out;
  7728. // 1. load images
  7729. // 2. prepare optional footer elements
  7730. // 3. render content
  7731. loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
  7732. checkForFooter(element, r, settings.elementHandlers);
  7733. _DrillForContent(element, r, settings.elementHandlers);
  7734. //send event dispose for final taks (e.g. footer totalpage replacement)
  7735. r.pdf.internal.events.publish('htmlRenderingFinished');
  7736. out = r.dispose();
  7737. if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  7738. });
  7739. return out || { x: r.x, y: r.y };
  7740. };
  7741. Renderer.prototype.init = function () {
  7742. this.paragraph = {
  7743. text: [],
  7744. style: []
  7745. };
  7746. return this.pdf.internal.write("q");
  7747. };
  7748. Renderer.prototype.dispose = function () {
  7749. this.pdf.internal.write("Q");
  7750. return {
  7751. x: this.x,
  7752. y: this.y,
  7753. ready: true
  7754. };
  7755. };
  7756. //Checks if we have to execute some watcher functions
  7757. //e.g. to end text floating around an image
  7758. Renderer.prototype.executeWatchFunctions = function (el) {
  7759. var ret = false;
  7760. var narray = [];
  7761. if (this.watchFunctions.length > 0) {
  7762. for (var i = 0; i < this.watchFunctions.length; ++i) {
  7763. if (this.watchFunctions[i](el) === true) {
  7764. ret = true;
  7765. } else {
  7766. narray.push(this.watchFunctions[i]);
  7767. }
  7768. }
  7769. this.watchFunctions = narray;
  7770. }
  7771. return ret;
  7772. };
  7773. Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
  7774. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  7775. defaultFontSize = 12;
  7776. k = this.pdf.internal.scaleFactor;
  7777. fontMetricsCache = {};
  7778. ff = void 0;
  7779. fs = void 0;
  7780. fontMetrics = void 0;
  7781. fragment = void 0;
  7782. style = void 0;
  7783. fragmentSpecificMetrics = void 0;
  7784. fragmentLength = void 0;
  7785. fragmentChopped = void 0;
  7786. line = [];
  7787. lines = [line];
  7788. currentLineLength = 0;
  7789. maxLineLength = this.settings.width;
  7790. while (fragments.length) {
  7791. fragment = fragments.shift();
  7792. style = styles.shift();
  7793. if (fragment) {
  7794. ff = style["font-family"];
  7795. fs = style["font-style"];
  7796. fontMetrics = fontMetricsCache[ff + fs];
  7797. if (!fontMetrics) {
  7798. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  7799. fontMetricsCache[ff + fs] = fontMetrics;
  7800. }
  7801. fragmentSpecificMetrics = {
  7802. widths: fontMetrics.widths,
  7803. kerning: fontMetrics.kerning,
  7804. fontSize: style["font-size"] * defaultFontSize,
  7805. textIndent: currentLineLength
  7806. };
  7807. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  7808. if (fragment == "\u2028") {
  7809. line = [];
  7810. lines.push(line);
  7811. } else if (currentLineLength + fragmentLength > maxLineLength) {
  7812. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  7813. line.push([fragmentChopped.shift(), style]);
  7814. while (fragmentChopped.length) {
  7815. line = [[fragmentChopped.shift(), style]];
  7816. lines.push(line);
  7817. }
  7818. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  7819. } else {
  7820. line.push([fragment, style]);
  7821. currentLineLength += fragmentLength;
  7822. }
  7823. }
  7824. }
  7825. //if text alignment was set, set margin/indent of each line
  7826. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  7827. for (var i = 0; i < lines.length; ++i) {
  7828. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  7829. //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  7830. if (i > 0) {
  7831. lines[i][0][1] = clone(lines[i][0][1]);
  7832. }
  7833. var space = maxLineLength - length;
  7834. if (style['text-align'] === 'right') {
  7835. lines[i][0][1]['margin-left'] = space;
  7836. //if alignment is not right, it has to be center so split the space to the left and the right
  7837. } else if (style['text-align'] === 'center') {
  7838. lines[i][0][1]['margin-left'] = space / 2;
  7839. //if justify was set, calculate the word spacing and define in by using the css property
  7840. } else if (style['text-align'] === 'justify') {
  7841. var countSpaces = lines[i][0][0].split(' ').length - 1;
  7842. lines[i][0][1]['word-spacing'] = space / countSpaces;
  7843. //ignore the last line in justify mode
  7844. if (i === lines.length - 1) {
  7845. lines[i][0][1]['word-spacing'] = 0;
  7846. }
  7847. }
  7848. }
  7849. }
  7850. return lines;
  7851. };
  7852. Renderer.prototype.RenderTextFragment = function (text, style) {
  7853. var defaultFontSize, font, maxLineHeight;
  7854. maxLineHeight = 0;
  7855. defaultFontSize = 12;
  7856. if (this.pdf.internal.pageSize.getHeight() - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  7857. this.pdf.internal.write("ET", "Q");
  7858. this.pdf.addPage();
  7859. this.y = this.pdf.margins_doc.top;
  7860. this.pdf.internal.write("q", "BT", this.getPdfColor(style.color), this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7861. //move cursor by one line on new page
  7862. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  7863. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7864. }
  7865. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  7866. // text color
  7867. var pdfTextColor = this.getPdfColor(style["color"]);
  7868. if (pdfTextColor !== this.lastTextColor) {
  7869. this.pdf.internal.write(pdfTextColor);
  7870. this.lastTextColor = pdfTextColor;
  7871. }
  7872. //set the word spacing for e.g. justify style
  7873. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  7874. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  7875. }
  7876. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  7877. //set the word spacing back to neutral => 0
  7878. if (style['word-spacing'] !== undefined) {
  7879. this.pdf.internal.write(0, "Tw");
  7880. }
  7881. };
  7882. // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  7883. Renderer.prototype.getPdfColor = function (style) {
  7884. var textColor;
  7885. var r, g, b;
  7886. var rgbColor = new RGBColor(style);
  7887. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  7888. var m = rx.exec(style);
  7889. if (m != null) {
  7890. r = parseInt(m[1]);
  7891. g = parseInt(m[2]);
  7892. b = parseInt(m[3]);
  7893. } else {
  7894. if (style.charAt(0) != '#') {
  7895. if (rgbColor.ok) {
  7896. style = rgbColor.toHex();
  7897. } else {
  7898. style = '#000000';
  7899. }
  7900. }
  7901. r = style.substring(1, 3);
  7902. r = parseInt(r, 16);
  7903. g = style.substring(3, 5);
  7904. g = parseInt(g, 16);
  7905. b = style.substring(5, 7);
  7906. b = parseInt(b, 16);
  7907. }
  7908. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  7909. var hex = parseInt(r.substr(1), 16);
  7910. r = hex >> 16 & 255;
  7911. g = hex >> 8 & 255;
  7912. b = hex & 255;
  7913. }
  7914. var f3 = this.f3;
  7915. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  7916. textColor = f3(r / 255) + ' g';
  7917. } else {
  7918. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  7919. }
  7920. return textColor;
  7921. };
  7922. Renderer.prototype.f3 = function (number) {
  7923. return number.toFixed(3); // Ie, %.3f
  7924. }, Renderer.prototype.renderParagraph = function (cb) {
  7925. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  7926. fragments = PurgeWhiteSpace(this.paragraph.text);
  7927. styles = this.paragraph.style;
  7928. blockstyle = this.paragraph.blockstyle;
  7929. priorblockstyle = this.paragraph.priorblockstyle || {};
  7930. this.paragraph = {
  7931. text: [],
  7932. style: [],
  7933. blockstyle: {},
  7934. priorblockstyle: blockstyle
  7935. };
  7936. if (!fragments.join("").trim()) {
  7937. return;
  7938. }
  7939. lines = this.splitFragmentsIntoLines(fragments, styles);
  7940. line = void 0;
  7941. maxLineHeight = void 0;
  7942. defaultFontSize = 12;
  7943. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  7944. this.priorMarginBottom = this.priorMarginBottom || 0;
  7945. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7946. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  7947. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  7948. if (blockstyle['page-break-before'] === 'always') {
  7949. this.pdf.addPage();
  7950. this.y = 0;
  7951. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  7952. }
  7953. out = this.pdf.internal.write;
  7954. i = void 0;
  7955. l = void 0;
  7956. this.y += paragraphspacing_before;
  7957. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  7958. //stores the current indent of cursor position
  7959. var currentIndent = 0;
  7960. while (lines.length) {
  7961. line = lines.shift();
  7962. maxLineHeight = 0;
  7963. i = 0;
  7964. l = line.length;
  7965. while (i !== l) {
  7966. if (line[i][0].trim()) {
  7967. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  7968. fontSize = line[i][1]["font-size"] * 7;
  7969. }
  7970. i++;
  7971. }
  7972. //if we have to move the cursor to adapt the indent
  7973. var indentMove = 0;
  7974. var wantedIndent = 0;
  7975. //if a margin was added (by e.g. a text-alignment), move the cursor
  7976. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  7977. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  7978. indentMove = wantedIndent - currentIndent;
  7979. currentIndent = wantedIndent;
  7980. }
  7981. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
  7982. //move the cursor
  7983. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  7984. i = 0;
  7985. l = line.length;
  7986. while (i !== l) {
  7987. if (line[i][0]) {
  7988. this.RenderTextFragment(line[i][0], line[i][1]);
  7989. }
  7990. i++;
  7991. }
  7992. this.y += maxLineHeight * fontToUnitRatio;
  7993. //if some watcher function was executed successful, so e.g. margin and widths were changed,
  7994. //reset line drawing and calculate position and lines again
  7995. //e.g. to stop text floating around an image
  7996. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  7997. var localFragments = [];
  7998. var localStyles = [];
  7999. //create fragment array of
  8000. lines.forEach(function (localLine) {
  8001. var i = 0;
  8002. var l = localLine.length;
  8003. while (i !== l) {
  8004. if (localLine[i][0]) {
  8005. localFragments.push(localLine[i][0] + ' ');
  8006. localStyles.push(localLine[i][1]);
  8007. }
  8008. ++i;
  8009. }
  8010. });
  8011. //split lines again due to possible coordinate changes
  8012. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
  8013. //reposition the current cursor
  8014. out("ET", "Q");
  8015. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  8016. }
  8017. }
  8018. if (cb && typeof cb === "function") {
  8019. cb.call(this, this.x - 9, this.y - fontSize / 2);
  8020. }
  8021. out("ET", "Q");
  8022. return this.y += paragraphspacing_after;
  8023. };
  8024. Renderer.prototype.setBlockBoundary = function (cb) {
  8025. return this.renderParagraph(cb);
  8026. };
  8027. Renderer.prototype.setBlockStyle = function (css) {
  8028. return this.paragraph.blockstyle = css;
  8029. };
  8030. Renderer.prototype.addText = function (text, css) {
  8031. this.paragraph.text.push(text);
  8032. return this.paragraph.style.push(css);
  8033. };
  8034. FontNameDB = {
  8035. helvetica: "helvetica",
  8036. "sans-serif": "helvetica",
  8037. "times new roman": "times",
  8038. serif: "times",
  8039. times: "times",
  8040. monospace: "courier",
  8041. courier: "courier"
  8042. };
  8043. FontWeightMap = {
  8044. 100: "normal",
  8045. 200: "normal",
  8046. 300: "normal",
  8047. 400: "normal",
  8048. 500: "bold",
  8049. 600: "bold",
  8050. 700: "bold",
  8051. 800: "bold",
  8052. 900: "bold",
  8053. normal: "normal",
  8054. bold: "bold",
  8055. bolder: "bold",
  8056. lighter: "normal"
  8057. };
  8058. FontStyleMap = {
  8059. normal: "normal",
  8060. italic: "italic",
  8061. oblique: "italic"
  8062. };
  8063. TextAlignMap = {
  8064. left: "left",
  8065. right: "right",
  8066. center: "center",
  8067. justify: "justify"
  8068. };
  8069. FloatMap = {
  8070. none: 'none',
  8071. right: 'right',
  8072. left: 'left'
  8073. };
  8074. ClearMap = {
  8075. none: 'none',
  8076. both: 'both'
  8077. };
  8078. UnitedNumberMap = {
  8079. normal: 1
  8080. };
  8081. /**
  8082. * Converts HTML-formatted text into formatted PDF text.
  8083. *
  8084. * Notes:
  8085. * 2012-07-18
  8086. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  8087. * Plugin relies on jQuery for CSS extraction.
  8088. * Targeting HTML output from Markdown templating, which is a very simple
  8089. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  8090. * Images, tables are NOT supported.
  8091. *
  8092. * @public
  8093. * @function
  8094. * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  8095. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  8096. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  8097. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  8098. * @returns {Object} jsPDF instance
  8099. */
  8100. jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
  8101. this.margins_doc = margins || {
  8102. top: 0,
  8103. bottom: 0
  8104. };
  8105. if (!settings) settings = {};
  8106. if (!settings.elementHandlers) settings.elementHandlers = {};
  8107. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  8108. };
  8109. })(jsPDF.API);
  8110. /** ====================================================================
  8111. * jsPDF JavaScript plugin
  8112. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  8113. *
  8114. *
  8115. * ====================================================================
  8116. */
  8117. /*global jsPDF */
  8118. (function (jsPDFAPI) {
  8119. var jsNamesObj, jsJsObj, text;
  8120. jsPDFAPI.addJS = function (txt) {
  8121. text = txt;
  8122. this.internal.events.subscribe('postPutResources', function (txt) {
  8123. jsNamesObj = this.internal.newObject();
  8124. this.internal.out('<<');
  8125. this.internal.out('/Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R]');
  8126. this.internal.out('>>');
  8127. this.internal.out('endobj');
  8128. jsJsObj = this.internal.newObject();
  8129. this.internal.out('<<');
  8130. this.internal.out('/S /JavaScript');
  8131. this.internal.out('/JS (' + text + ')');
  8132. this.internal.out('>>');
  8133. this.internal.out('endobj');
  8134. });
  8135. this.internal.events.subscribe('putCatalog', function () {
  8136. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  8137. this.internal.out('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  8138. }
  8139. });
  8140. return this;
  8141. };
  8142. })(jsPDF.API);
  8143. /**
  8144. * jsPDF Outline PlugIn
  8145. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  8146. *
  8147. * Licensed under the MIT License.
  8148. * http://opensource.org/licenses/mit-license
  8149. */
  8150. (function (jsPDFAPI) {
  8151. jsPDFAPI.events.push(['postPutResources', function () {
  8152. var pdf = this;
  8153. var rx = /^(\d+) 0 obj$/;
  8154. // Write action goto objects for each page
  8155. // this.outline.destsGoto = [];
  8156. // for (var i = 0; i < totalPages; i++) {
  8157. // var id = pdf.internal.newObject();
  8158. // this.outline.destsGoto.push(id);
  8159. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  8160. // null null]/S/GoTo>> endobj");
  8161. // }
  8162. //
  8163. // for (var i = 0; i < dests.length; i++) {
  8164. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  8165. // R");
  8166. // }
  8167. //
  8168. if (this.outline.root.children.length > 0) {
  8169. var lines = pdf.outline.render().split(/\r\n/);
  8170. for (var i = 0; i < lines.length; i++) {
  8171. var line = lines[i];
  8172. var m = rx.exec(line);
  8173. if (m != null) {
  8174. var oid = m[1];
  8175. pdf.internal.newObjectDeferredBegin(oid);
  8176. }
  8177. pdf.internal.write(line);
  8178. }
  8179. }
  8180. // This code will write named destination for each page reference
  8181. // (page_1, etc)
  8182. if (this.outline.createNamedDestinations) {
  8183. var totalPages = this.internal.pages.length;
  8184. // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  8185. // follow 5, 7, 9, etc
  8186. // Write destination objects for each page
  8187. var dests = [];
  8188. for (var i = 0; i < totalPages; i++) {
  8189. var id = pdf.internal.newObject();
  8190. dests.push(id);
  8191. var info = pdf.internal.getPageInfo(i + 1);
  8192. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  8193. }
  8194. // assign a name for each destination
  8195. var names2Oid = pdf.internal.newObject();
  8196. pdf.internal.write('<< /Names [ ');
  8197. for (var i = 0; i < dests.length; i++) {
  8198. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  8199. }
  8200. pdf.internal.write(' ] >>', 'endobj');
  8201. // var kids = pdf.internal.newObject();
  8202. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  8203. // pdf.internal.write(' ] >>', 'endobj');
  8204. var namesOid = pdf.internal.newObject();
  8205. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  8206. pdf.internal.write('>>', 'endobj');
  8207. }
  8208. }]);
  8209. jsPDFAPI.events.push(['putCatalog', function () {
  8210. var pdf = this;
  8211. if (pdf.outline.root.children.length > 0) {
  8212. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  8213. if (this.outline.createNamedDestinations) {
  8214. pdf.internal.write("/Names " + namesOid + " 0 R");
  8215. }
  8216. // Open with Bookmarks showing
  8217. // pdf.internal.write("/PageMode /UseOutlines");
  8218. }
  8219. }]);
  8220. jsPDFAPI.events.push(['initialized', function () {
  8221. var pdf = this;
  8222. pdf.outline = {
  8223. createNamedDestinations: false,
  8224. root: {
  8225. children: []
  8226. }
  8227. };
  8228. /**
  8229. * Options: pageNumber
  8230. */
  8231. pdf.outline.add = function (parent, title, options) {
  8232. var item = {
  8233. title: title,
  8234. options: options,
  8235. children: []
  8236. };
  8237. if (parent == null) {
  8238. parent = this.root;
  8239. }
  8240. parent.children.push(item);
  8241. return item;
  8242. };
  8243. pdf.outline.render = function () {
  8244. this.ctx = {};
  8245. this.ctx.val = '';
  8246. this.ctx.pdf = pdf;
  8247. this.genIds_r(this.root);
  8248. this.renderRoot(this.root);
  8249. this.renderItems(this.root);
  8250. return this.ctx.val;
  8251. };
  8252. pdf.outline.genIds_r = function (node) {
  8253. node.id = pdf.internal.newObjectDeferred();
  8254. for (var i = 0; i < node.children.length; i++) {
  8255. this.genIds_r(node.children[i]);
  8256. }
  8257. };
  8258. pdf.outline.renderRoot = function (node) {
  8259. this.objStart(node);
  8260. this.line('/Type /Outlines');
  8261. if (node.children.length > 0) {
  8262. this.line('/First ' + this.makeRef(node.children[0]));
  8263. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  8264. }
  8265. this.line('/Count ' + this.count_r({
  8266. count: 0
  8267. }, node));
  8268. this.objEnd();
  8269. };
  8270. pdf.outline.renderItems = function (node) {
  8271. for (var i = 0; i < node.children.length; i++) {
  8272. var item = node.children[i];
  8273. this.objStart(item);
  8274. this.line('/Title ' + this.makeString(item.title));
  8275. this.line('/Parent ' + this.makeRef(node));
  8276. if (i > 0) {
  8277. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  8278. }
  8279. if (i < node.children.length - 1) {
  8280. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  8281. }
  8282. if (item.children.length > 0) {
  8283. this.line('/First ' + this.makeRef(item.children[0]));
  8284. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  8285. }
  8286. var count = this.count = this.count_r({
  8287. count: 0
  8288. }, item);
  8289. if (count > 0) {
  8290. this.line('/Count ' + count);
  8291. }
  8292. if (item.options) {
  8293. if (item.options.pageNumber) {
  8294. // Explicit Destination
  8295. //WARNING this assumes page ids are 3,5,7, etc.
  8296. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  8297. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() * this.ctx.pdf.internal.scaleFactor + ' 0]');
  8298. // this line does not work on all clients (pageNumber instead of page ref)
  8299. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() + ' 0]');
  8300. // Named Destination
  8301. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  8302. // Action Destination
  8303. // var id = pdf.internal.newObject();
  8304. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  8305. // this.line('/A ' + id + ' 0 R' );
  8306. }
  8307. }
  8308. this.objEnd();
  8309. }
  8310. for (var i = 0; i < node.children.length; i++) {
  8311. var item = node.children[i];
  8312. this.renderItems(item);
  8313. }
  8314. };
  8315. pdf.outline.line = function (text) {
  8316. this.ctx.val += text + '\r\n';
  8317. };
  8318. pdf.outline.makeRef = function (node) {
  8319. return node.id + ' 0 R';
  8320. };
  8321. pdf.outline.makeString = function (val) {
  8322. return '(' + pdf.internal.pdfEscape(val) + ')';
  8323. };
  8324. pdf.outline.objStart = function (node) {
  8325. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  8326. };
  8327. pdf.outline.objEnd = function (node) {
  8328. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  8329. };
  8330. pdf.outline.count_r = function (ctx, node) {
  8331. for (var i = 0; i < node.children.length; i++) {
  8332. ctx.count++;
  8333. this.count_r(ctx, node.children[i]);
  8334. }
  8335. return ctx.count;
  8336. };
  8337. }]);
  8338. return this;
  8339. })(jsPDF.API);
  8340. /**@preserve
  8341. * ====================================================================
  8342. * jsPDF PNG PlugIn
  8343. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  8344. *
  8345. *
  8346. * ====================================================================
  8347. */
  8348. (function (jsPDFAPI) {
  8349. /*
  8350. * @see http://www.w3.org/TR/PNG-Chunks.html
  8351. *
  8352. Color Allowed Interpretation
  8353. Type Bit Depths
  8354. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  8355. 2 8,16 Each pixel is an R,G,B triple.
  8356. 3 1,2,4,8 Each pixel is a palette index;
  8357. a PLTE chunk must appear.
  8358. 4 8,16 Each pixel is a grayscale sample,
  8359. followed by an alpha sample.
  8360. 6 8,16 Each pixel is an R,G,B triple,
  8361. followed by an alpha sample.
  8362. */
  8363. /*
  8364. * PNG filter method types
  8365. *
  8366. * @see http://www.w3.org/TR/PNG-Filters.html
  8367. * @see http://www.libpng.org/pub/png/book/chapter09.html
  8368. *
  8369. * This is what the value 'Predictor' in decode params relates to
  8370. *
  8371. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  8372. * 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.
  8373. *
  8374. 0 None
  8375. 1 Sub
  8376. 2 Up
  8377. 3 Average
  8378. 4 Paeth
  8379. */
  8380. var doesNotHavePngJS = function doesNotHavePngJS() {
  8381. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  8382. },
  8383. canCompress = function canCompress(value) {
  8384. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  8385. },
  8386. hasCompressionJS = function hasCompressionJS() {
  8387. var inst = typeof Deflater === 'function';
  8388. if (!inst) throw new Error("requires deflate.js for compression");
  8389. return inst;
  8390. },
  8391. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  8392. var level = 5,
  8393. filter_method = filterUp;
  8394. switch (compression) {
  8395. case jsPDFAPI.image_compression.FAST:
  8396. level = 3;
  8397. filter_method = filterSub;
  8398. break;
  8399. case jsPDFAPI.image_compression.MEDIUM:
  8400. level = 6;
  8401. filter_method = filterAverage;
  8402. break;
  8403. case jsPDFAPI.image_compression.SLOW:
  8404. level = 9;
  8405. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  8406. break;
  8407. }
  8408. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  8409. var header = new Uint8Array(createZlibHeader(level));
  8410. var checksum = adler32(bytes);
  8411. var deflate = new Deflater(level);
  8412. var a = deflate.append(bytes);
  8413. var cBytes = deflate.flush();
  8414. var len = header.length + a.length + cBytes.length;
  8415. var cmpd = new Uint8Array(len + 4);
  8416. cmpd.set(header);
  8417. cmpd.set(a, header.length);
  8418. cmpd.set(cBytes, header.length + a.length);
  8419. cmpd[len++] = checksum >>> 24 & 0xff;
  8420. cmpd[len++] = checksum >>> 16 & 0xff;
  8421. cmpd[len++] = checksum >>> 8 & 0xff;
  8422. cmpd[len++] = checksum & 0xff;
  8423. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  8424. },
  8425. createZlibHeader = function createZlibHeader(bytes, level) {
  8426. /*
  8427. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  8428. */
  8429. var cm = 8;
  8430. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  8431. var cmf = cinfo << 4 | cm;
  8432. var hdr = cmf << 8;
  8433. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  8434. hdr |= flevel << 6;
  8435. hdr |= 0; //FDICT
  8436. hdr += 31 - hdr % 31;
  8437. return [cmf, hdr & 0xff & 0xff];
  8438. },
  8439. adler32 = function adler32(array, param) {
  8440. var adler = 1;
  8441. var s1 = adler & 0xffff,
  8442. s2 = adler >>> 16 & 0xffff;
  8443. var len = array.length;
  8444. var tlen;
  8445. var i = 0;
  8446. while (len > 0) {
  8447. tlen = len > param ? param : len;
  8448. len -= tlen;
  8449. do {
  8450. s1 += array[i++];
  8451. s2 += s1;
  8452. } while (--tlen);
  8453. s1 %= 65521;
  8454. s2 %= 65521;
  8455. }
  8456. return (s2 << 16 | s1) >>> 0;
  8457. },
  8458. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  8459. var lines = bytes.length / lineLength,
  8460. result = new Uint8Array(bytes.length + lines),
  8461. filter_methods = getFilterMethods(),
  8462. i = 0,
  8463. line,
  8464. prevLine,
  8465. offset;
  8466. for (; i < lines; i++) {
  8467. offset = i * lineLength;
  8468. line = bytes.subarray(offset, offset + lineLength);
  8469. if (filter_method) {
  8470. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  8471. } else {
  8472. var j = 0,
  8473. len = filter_methods.length,
  8474. results = [];
  8475. for (; j < len; j++) {
  8476. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  8477. }var ind = getIndexOfSmallestSum(results.concat());
  8478. result.set(results[ind], offset + i);
  8479. }
  8480. prevLine = line;
  8481. }
  8482. return result;
  8483. },
  8484. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  8485. /*var result = new Uint8Array(line.length + 1);
  8486. result[0] = 0;
  8487. result.set(line, 1);*/
  8488. var result = Array.apply([], line);
  8489. result.unshift(0);
  8490. return result;
  8491. },
  8492. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  8493. var result = [],
  8494. i = 0,
  8495. len = line.length,
  8496. left;
  8497. result[0] = 1;
  8498. for (; i < len; i++) {
  8499. left = line[i - colorsPerPixel] || 0;
  8500. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  8501. }
  8502. return result;
  8503. },
  8504. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  8505. var result = [],
  8506. i = 0,
  8507. len = line.length,
  8508. up;
  8509. result[0] = 2;
  8510. for (; i < len; i++) {
  8511. up = prevLine && prevLine[i] || 0;
  8512. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  8513. }
  8514. return result;
  8515. },
  8516. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  8517. var result = [],
  8518. i = 0,
  8519. len = line.length,
  8520. left,
  8521. up;
  8522. result[0] = 3;
  8523. for (; i < len; i++) {
  8524. left = line[i - colorsPerPixel] || 0;
  8525. up = prevLine && prevLine[i] || 0;
  8526. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  8527. }
  8528. return result;
  8529. },
  8530. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  8531. var result = [],
  8532. i = 0,
  8533. len = line.length,
  8534. left,
  8535. up,
  8536. upLeft,
  8537. paeth;
  8538. result[0] = 4;
  8539. for (; i < len; i++) {
  8540. left = line[i - colorsPerPixel] || 0;
  8541. up = prevLine && prevLine[i] || 0;
  8542. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  8543. paeth = paethPredictor(left, up, upLeft);
  8544. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  8545. }
  8546. return result;
  8547. },
  8548. paethPredictor = function paethPredictor(left, up, upLeft) {
  8549. var p = left + up - upLeft,
  8550. pLeft = Math.abs(p - left),
  8551. pUp = Math.abs(p - up),
  8552. pUpLeft = Math.abs(p - upLeft);
  8553. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  8554. },
  8555. getFilterMethods = function getFilterMethods() {
  8556. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  8557. },
  8558. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  8559. var i = 0,
  8560. len = arrays.length,
  8561. sum,
  8562. min,
  8563. ind;
  8564. while (i < len) {
  8565. sum = absSum(arrays[i].slice(1));
  8566. if (sum < min || !min) {
  8567. min = sum;
  8568. ind = i;
  8569. }
  8570. i++;
  8571. }
  8572. return ind;
  8573. },
  8574. absSum = function absSum(array) {
  8575. var i = 0,
  8576. len = array.length,
  8577. sum = 0;
  8578. while (i < len) {
  8579. sum += Math.abs(array[i++]);
  8580. }return sum;
  8581. },
  8582. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  8583. var predictor;
  8584. switch (compression) {
  8585. case jsPDFAPI.image_compression.FAST:
  8586. predictor = 11;
  8587. break;
  8588. case jsPDFAPI.image_compression.MEDIUM:
  8589. predictor = 13;
  8590. break;
  8591. case jsPDFAPI.image_compression.SLOW:
  8592. predictor = 14;
  8593. break;
  8594. default:
  8595. predictor = 12;
  8596. break;
  8597. }
  8598. return predictor;
  8599. };
  8600. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  8601. var colorSpace = this.color_spaces.DEVICE_RGB,
  8602. decode = this.decode.FLATE_DECODE,
  8603. bpc = 8,
  8604. img,
  8605. dp,
  8606. trns,
  8607. colors,
  8608. pal,
  8609. smask;
  8610. /* if(this.isString(imageData)) {
  8611. }*/
  8612. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  8613. if (this.isArrayBufferView(imageData)) {
  8614. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  8615. img = new PNG(imageData);
  8616. imageData = img.imgData;
  8617. bpc = img.bits;
  8618. colorSpace = img.colorSpace;
  8619. colors = img.colors;
  8620. //logImg(img);
  8621. /*
  8622. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  8623. *
  8624. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  8625. *
  8626. * Extract alpha to create two separate images, using the alpha as a sMask
  8627. */
  8628. if ([4, 6].indexOf(img.colorType) !== -1) {
  8629. /*
  8630. * processes 8 bit RGBA and grayscale + alpha images
  8631. */
  8632. if (img.bits === 8) {
  8633. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  8634. len = pixels.length,
  8635. imgData = new Uint8Array(len * img.colors),
  8636. alphaData = new Uint8Array(len),
  8637. pDiff = img.pixelBitlength - img.bits,
  8638. i = 0,
  8639. n = 0,
  8640. pixel,
  8641. pbl;
  8642. for (; i < len; i++) {
  8643. pixel = pixels[i];
  8644. pbl = 0;
  8645. while (pbl < pDiff) {
  8646. imgData[n++] = pixel >>> pbl & 0xff;
  8647. pbl = pbl + img.bits;
  8648. }
  8649. alphaData[i] = pixel >>> pbl & 0xff;
  8650. }
  8651. }
  8652. /*
  8653. * processes 16 bit RGBA and grayscale + alpha images
  8654. */
  8655. if (img.bits === 16) {
  8656. var pixels = new Uint32Array(img.decodePixels().buffer),
  8657. len = pixels.length,
  8658. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  8659. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  8660. hasColors = img.colors > 1,
  8661. i = 0,
  8662. n = 0,
  8663. a = 0,
  8664. pixel;
  8665. while (i < len) {
  8666. pixel = pixels[i++];
  8667. imgData[n++] = pixel >>> 0 & 0xFF;
  8668. if (hasColors) {
  8669. imgData[n++] = pixel >>> 16 & 0xFF;
  8670. pixel = pixels[i++];
  8671. imgData[n++] = pixel >>> 0 & 0xFF;
  8672. }
  8673. alphaData[a++] = pixel >>> 16 & 0xFF;
  8674. }
  8675. bpc = 8;
  8676. }
  8677. if (canCompress(compression)) {
  8678. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  8679. smask = compressBytes(alphaData, img.width, 1, compression);
  8680. } else {
  8681. imageData = imgData;
  8682. smask = alphaData;
  8683. decode = null;
  8684. }
  8685. }
  8686. /*
  8687. * Indexed png. Each pixel is a palette index.
  8688. */
  8689. if (img.colorType === 3) {
  8690. colorSpace = this.color_spaces.INDEXED;
  8691. pal = img.palette;
  8692. if (img.transparency.indexed) {
  8693. var trans = img.transparency.indexed;
  8694. var total = 0,
  8695. i = 0,
  8696. len = trans.length;
  8697. for (; i < len; ++i) {
  8698. total += trans[i];
  8699. }total = total / 255;
  8700. /*
  8701. * a single color is specified as 100% transparent (0),
  8702. * so we set trns to use a /Mask with that index
  8703. */
  8704. if (total === len - 1 && trans.indexOf(0) !== -1) {
  8705. trns = [trans.indexOf(0)];
  8706. /*
  8707. * there's more than one colour within the palette that specifies
  8708. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  8709. */
  8710. } else if (total !== len) {
  8711. var pixels = img.decodePixels(),
  8712. alphaData = new Uint8Array(pixels.length),
  8713. i = 0,
  8714. len = pixels.length;
  8715. for (; i < len; i++) {
  8716. alphaData[i] = trans[pixels[i]];
  8717. }smask = compressBytes(alphaData, img.width, 1);
  8718. }
  8719. }
  8720. }
  8721. var predictor = getPredictorFromCompression(compression);
  8722. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
  8723. //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  8724. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  8725. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  8726. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  8727. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  8728. }
  8729. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  8730. };
  8731. })(jsPDF.API);
  8732. /**
  8733. * jsPDF gif Support PlugIn
  8734. * Copyright (c) 2017 Aras Abbasi
  8735. *
  8736. * Licensed under the MIT License.
  8737. * http://opensource.org/licenses/mit-license
  8738. */
  8739. (function (jsPDFAPI) {
  8740. jsPDFAPI.processGIF89A = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  8741. var reader = new GifReader(imageData);
  8742. var width = reader.width,
  8743. height = reader.height;
  8744. var qu = 100;
  8745. var pixels = [];
  8746. reader.decodeAndBlitFrameRGBA(0, pixels);
  8747. var rawImageData = {
  8748. data: pixels,
  8749. width: width,
  8750. height: height
  8751. };
  8752. var encoder = new JPEGEncoder(qu);
  8753. var data = encoder.encode(rawImageData, qu);
  8754. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  8755. };
  8756. jsPDFAPI.processGIF87A = jsPDFAPI.processGIF89A;
  8757. })(jsPDF.API);
  8758. /**
  8759. * jsPDF bmp Support PlugIn
  8760. * Copyright (c) 2018 Aras Abbasi
  8761. *
  8762. * Licensed under the MIT License.
  8763. * http://opensource.org/licenses/mit-license
  8764. */
  8765. (function (jsPDFAPI) {
  8766. jsPDFAPI.processBMP = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  8767. var reader = new BmpDecoder(imageData, false);
  8768. var width = reader.width,
  8769. height = reader.height;
  8770. var qu = 100;
  8771. var pixels = reader.getData();
  8772. var rawImageData = {
  8773. data: pixels,
  8774. width: width,
  8775. height: height
  8776. };
  8777. var encoder = new JPEGEncoder(qu);
  8778. var data = encoder.encode(rawImageData, qu);
  8779. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  8780. };
  8781. })(jsPDF.API);
  8782. /**
  8783. * jsPDF setLanguage Plugin
  8784. *
  8785. * Licensed under the MIT License.
  8786. * http://opensource.org/licenses/mit-license
  8787. */
  8788. (function (jsPDFAPI) {
  8789. /**
  8790. * Add Language Tag to PDF
  8791. *
  8792. * @returns {jsPDF}
  8793. * @name setLanguage
  8794. * @example
  8795. * var doc = new jsPDF()
  8796. * doc.text(10, 10, 'This is a test')
  8797. * doc.setLanguage("en-US")
  8798. * doc.save('english.pdf')
  8799. */
  8800. jsPDFAPI.setLanguage = function (langCode) {
  8801. var langCodes = {
  8802. "af": "Afrikaans",
  8803. "sq": "Albanian",
  8804. "ar": "Arabic (Standard)",
  8805. "ar-DZ": "Arabic (Algeria)",
  8806. "ar-BH": "Arabic (Bahrain)",
  8807. "ar-EG": "Arabic (Egypt)",
  8808. "ar-IQ": "Arabic (Iraq)",
  8809. "ar-JO": "Arabic (Jordan)",
  8810. "ar-KW": "Arabic (Kuwait)",
  8811. "ar-LB": "Arabic (Lebanon)",
  8812. "ar-LY": "Arabic (Libya)",
  8813. "ar-MA": "Arabic (Morocco)",
  8814. "ar-OM": "Arabic (Oman)",
  8815. "ar-QA": "Arabic (Qatar)",
  8816. "ar-SA": "Arabic (Saudi Arabia)",
  8817. "ar-SY": "Arabic (Syria)",
  8818. "ar-TN": "Arabic (Tunisia)",
  8819. "ar-AE": "Arabic (U.A.E.)",
  8820. "ar-YE": "Arabic (Yemen)",
  8821. "an": "Aragonese",
  8822. "hy": "Armenian",
  8823. "as": "Assamese",
  8824. "ast": "Asturian",
  8825. "az": "Azerbaijani",
  8826. "eu": "Basque",
  8827. "be": "Belarusian",
  8828. "bn": "Bengali",
  8829. "bs": "Bosnian",
  8830. "br": "Breton",
  8831. "bg": "Bulgarian",
  8832. "my": "Burmese",
  8833. "ca": "Catalan",
  8834. "ch": "Chamorro",
  8835. "ce": "Chechen",
  8836. "zh": "Chinese",
  8837. "zh-HK": "Chinese (Hong Kong)",
  8838. "zh-CN": "Chinese (PRC)",
  8839. "zh-SG": "Chinese (Singapore)",
  8840. "zh-TW": "Chinese (Taiwan)",
  8841. "cv": "Chuvash",
  8842. "co": "Corsican",
  8843. "cr": "Cree",
  8844. "hr": "Croatian",
  8845. "cs": "Czech",
  8846. "da": "Danish",
  8847. "nl": "Dutch (Standard)",
  8848. "nl-BE": "Dutch (Belgian)",
  8849. "en": "English",
  8850. "en-AU": "English (Australia)",
  8851. "en-BZ": "English (Belize)",
  8852. "en-CA": "English (Canada)",
  8853. "en-IE": "English (Ireland)",
  8854. "en-JM": "English (Jamaica)",
  8855. "en-NZ": "English (New Zealand)",
  8856. "en-PH": "English (Philippines)",
  8857. "en-ZA": "English (South Africa)",
  8858. "en-TT": "English (Trinidad & Tobago)",
  8859. "en-GB": "English (United Kingdom)",
  8860. "en-US": "English (United States)",
  8861. "en-ZW": "English (Zimbabwe)",
  8862. "eo": "Esperanto",
  8863. "et": "Estonian",
  8864. "fo": "Faeroese",
  8865. "fj": "Fijian",
  8866. "fi": "Finnish",
  8867. "fr": "French (Standard)",
  8868. "fr-BE": "French (Belgium)",
  8869. "fr-CA": "French (Canada)",
  8870. "fr-FR": "French (France)",
  8871. "fr-LU": "French (Luxembourg)",
  8872. "fr-MC": "French (Monaco)",
  8873. "fr-CH": "French (Switzerland)",
  8874. "fy": "Frisian",
  8875. "fur": "Friulian",
  8876. "gd": "Gaelic (Scots)",
  8877. "gd-IE": "Gaelic (Irish)",
  8878. "gl": "Galacian",
  8879. "ka": "Georgian",
  8880. "de": "German (Standard)",
  8881. "de-AT": "German (Austria)",
  8882. "de-DE": "German (Germany)",
  8883. "de-LI": "German (Liechtenstein)",
  8884. "de-LU": "German (Luxembourg)",
  8885. "de-CH": "German (Switzerland)",
  8886. "el": "Greek",
  8887. "gu": "Gujurati",
  8888. "ht": "Haitian",
  8889. "he": "Hebrew",
  8890. "hi": "Hindi",
  8891. "hu": "Hungarian",
  8892. "is": "Icelandic",
  8893. "id": "Indonesian",
  8894. "iu": "Inuktitut",
  8895. "ga": "Irish",
  8896. "it": "Italian (Standard)",
  8897. "it-CH": "Italian (Switzerland)",
  8898. "ja": "Japanese",
  8899. "kn": "Kannada",
  8900. "ks": "Kashmiri",
  8901. "kk": "Kazakh",
  8902. "km": "Khmer",
  8903. "ky": "Kirghiz",
  8904. "tlh": "Klingon",
  8905. "ko": "Korean",
  8906. "ko-KP": "Korean (North Korea)",
  8907. "ko-KR": "Korean (South Korea)",
  8908. "la": "Latin",
  8909. "lv": "Latvian",
  8910. "lt": "Lithuanian",
  8911. "lb": "Luxembourgish",
  8912. "mk": "FYRO Macedonian",
  8913. "ms": "Malay",
  8914. "ml": "Malayalam",
  8915. "mt": "Maltese",
  8916. "mi": "Maori",
  8917. "mr": "Marathi",
  8918. "mo": "Moldavian",
  8919. "nv": "Navajo",
  8920. "ng": "Ndonga",
  8921. "ne": "Nepali",
  8922. "no": "Norwegian",
  8923. "nb": "Norwegian (Bokmal)",
  8924. "nn": "Norwegian (Nynorsk)",
  8925. "oc": "Occitan",
  8926. "or": "Oriya",
  8927. "om": "Oromo",
  8928. "fa": "Persian",
  8929. "fa-IR": "Persian/Iran",
  8930. "pl": "Polish",
  8931. "pt": "Portuguese",
  8932. "pt-BR": "Portuguese (Brazil)",
  8933. "pa": "Punjabi",
  8934. "pa-IN": "Punjabi (India)",
  8935. "pa-PK": "Punjabi (Pakistan)",
  8936. "qu": "Quechua",
  8937. "rm": "Rhaeto-Romanic",
  8938. "ro": "Romanian",
  8939. "ro-MO": "Romanian (Moldavia)",
  8940. "ru": "Russian",
  8941. "ru-MO": "Russian (Moldavia)",
  8942. "sz": "Sami (Lappish)",
  8943. "sg": "Sango",
  8944. "sa": "Sanskrit",
  8945. "sc": "Sardinian",
  8946. "sd": "Sindhi",
  8947. "si": "Singhalese",
  8948. "sr": "Serbian",
  8949. "sk": "Slovak",
  8950. "sl": "Slovenian",
  8951. "so": "Somani",
  8952. "sb": "Sorbian",
  8953. "es": "Spanish",
  8954. "es-AR": "Spanish (Argentina)",
  8955. "es-BO": "Spanish (Bolivia)",
  8956. "es-CL": "Spanish (Chile)",
  8957. "es-CO": "Spanish (Colombia)",
  8958. "es-CR": "Spanish (Costa Rica)",
  8959. "es-DO": "Spanish (Dominican Republic)",
  8960. "es-EC": "Spanish (Ecuador)",
  8961. "es-SV": "Spanish (El Salvador)",
  8962. "es-GT": "Spanish (Guatemala)",
  8963. "es-HN": "Spanish (Honduras)",
  8964. "es-MX": "Spanish (Mexico)",
  8965. "es-NI": "Spanish (Nicaragua)",
  8966. "es-PA": "Spanish (Panama)",
  8967. "es-PY": "Spanish (Paraguay)",
  8968. "es-PE": "Spanish (Peru)",
  8969. "es-PR": "Spanish (Puerto Rico)",
  8970. "es-ES": "Spanish (Spain)",
  8971. "es-UY": "Spanish (Uruguay)",
  8972. "es-VE": "Spanish (Venezuela)",
  8973. "sx": "Sutu",
  8974. "sw": "Swahili",
  8975. "sv": "Swedish",
  8976. "sv-FI": "Swedish (Finland)",
  8977. "sv-SV": "Swedish (Sweden)",
  8978. "ta": "Tamil",
  8979. "tt": "Tatar",
  8980. "te": "Teluga",
  8981. "th": "Thai",
  8982. "tig": "Tigre",
  8983. "ts": "Tsonga",
  8984. "tn": "Tswana",
  8985. "tr": "Turkish",
  8986. "tk": "Turkmen",
  8987. "uk": "Ukrainian",
  8988. "hsb": "Upper Sorbian",
  8989. "ur": "Urdu",
  8990. "ve": "Venda",
  8991. "vi": "Vietnamese",
  8992. "vo": "Volapuk",
  8993. "wa": "Walloon",
  8994. "cy": "Welsh",
  8995. "xh": "Xhosa",
  8996. "ji": "Yiddish",
  8997. "zu": "Zulu"
  8998. };
  8999. if (this.internal.languageSettings === undefined) {
  9000. this.internal.languageSettings = {};
  9001. this.internal.languageSettings.isSubscribed = false;
  9002. }
  9003. if (langCodes[langCode] !== undefined) {
  9004. this.internal.languageSettings.languageCode = langCode;
  9005. if (this.internal.languageSettings.isSubscribed === false) {
  9006. this.internal.events.subscribe("putCatalog", function () {
  9007. this.internal.write("/Lang (" + this.internal.languageSettings.languageCode + ")");
  9008. });
  9009. this.internal.languageSettings.isSubscribed = true;
  9010. }
  9011. }
  9012. return this;
  9013. };
  9014. })(jsPDF.API);
  9015. /** @preserve
  9016. * jsPDF split_text_to_size plugin - MIT license.
  9017. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  9018. * 2014 Diego Casorran, https://github.com/diegocr
  9019. */
  9020. /**
  9021. *
  9022. * ====================================================================
  9023. */
  9024. (function (API) {
  9025. /**
  9026. * Returns an array of length matching length of the 'word' string, with each
  9027. * cell occupied by the width of the char in that position.
  9028. *
  9029. * @function
  9030. * @param word {String}
  9031. * @param widths {Object}
  9032. * @param kerning {Object}
  9033. * @returns {Array}
  9034. */
  9035. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  9036. options = options || {};
  9037. var activeFont = options.font || this.internal.getFont();
  9038. var fontSize = options.fontSize || this.internal.getFontSize();
  9039. var charSpace = options.charSpace || this.internal.getCharSpace();
  9040. var widths = options.widths ? options.widths : activeFont.metadata.Unicode.widths;
  9041. var widthsFractionOf = widths.fof ? widths.fof : 1;
  9042. var kerning = options.kerning ? options.kerning : activeFont.metadata.Unicode.kerning;
  9043. var kerningFractionOf = kerning.fof ? kerning.fof : 1;
  9044. var i;
  9045. var l;
  9046. var char_code;
  9047. var prior_char_code = 0; //for kerning
  9048. var default_char_width = widths[0] || widthsFractionOf;
  9049. var output = [];
  9050. for (i = 0, l = text.length; i < l; i++) {
  9051. char_code = text.charCodeAt(i);
  9052. if (typeof activeFont.metadata.widthOfString === "function") {
  9053. output.push((activeFont.metadata.widthOfGlyph(activeFont.metadata.characterToGlyph(char_code)) + charSpace * (1000 / fontSize) || 0) / 1000);
  9054. } else {
  9055. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  9056. }
  9057. prior_char_code = char_code;
  9058. }
  9059. return output;
  9060. };
  9061. /**
  9062. * Calculate the sum of a number-array
  9063. *
  9064. * @name getArraySum
  9065. * @public
  9066. * @function
  9067. * @param {array} array of numbers
  9068. * @returns {Number}
  9069. */
  9070. var getArraySum = API.getArraySum = function (array) {
  9071. var i = array.length,
  9072. output = 0;
  9073. while (i) {
  9074. i--;
  9075. output += array[i];
  9076. }
  9077. return output;
  9078. };
  9079. /**
  9080. Returns a widths of string in a given font, if the font size is set as 1 point.
  9081. In other words, this is "proportional" value. For 1 unit of font size, the length
  9082. of the string will be that much.
  9083. Multiply by font size to get actual width in *points*
  9084. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  9085. @public
  9086. @function
  9087. @param
  9088. @returns {Type}
  9089. */
  9090. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  9091. options = options || {};
  9092. var fontSize = options.fontSize || this.internal.getFontSize();
  9093. var font = options.font || this.internal.getFont();
  9094. var charSpace = options.charSpace || this.internal.getCharSpace();
  9095. var result = 0;
  9096. if (typeof font.metadata.widthOfString === "function") {
  9097. result = font.metadata.widthOfString(text, fontSize, charSpace) / fontSize;
  9098. } else {
  9099. result = getArraySum(getCharWidthsArray.apply(this, arguments));
  9100. }
  9101. return result;
  9102. };
  9103. /**
  9104. returns array of lines
  9105. */
  9106. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  9107. var answer = [];
  9108. // 1st, chop off the piece that can fit on the hanging line.
  9109. var i = 0,
  9110. l = word.length,
  9111. workingLen = 0;
  9112. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  9113. workingLen += widths_array[i];
  9114. i++;
  9115. }
  9116. // this is first line.
  9117. answer.push(word.slice(0, i));
  9118. // 2nd. Split the rest into maxLen pieces.
  9119. var startOfLine = i;
  9120. workingLen = 0;
  9121. while (i !== l) {
  9122. if (workingLen + widths_array[i] > maxLen) {
  9123. answer.push(word.slice(startOfLine, i));
  9124. workingLen = 0;
  9125. startOfLine = i;
  9126. }
  9127. workingLen += widths_array[i];
  9128. i++;
  9129. }
  9130. if (startOfLine !== i) {
  9131. answer.push(word.slice(startOfLine, i));
  9132. }
  9133. return answer;
  9134. };
  9135. // Note, all sizing inputs for this function must be in "font measurement units"
  9136. // By default, for PDF, it's "point".
  9137. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  9138. // at this time works only on Western scripts, ones with space char
  9139. // separating the words. Feel free to expand.
  9140. if (!options) {
  9141. options = {};
  9142. }
  9143. var line = [],
  9144. lines = [line],
  9145. line_length = options.textIndent || 0,
  9146. separator_length = 0,
  9147. current_word_length = 0,
  9148. word,
  9149. widths_array,
  9150. words = text.split(' '),
  9151. spaceCharWidth = getCharWidthsArray.apply(this, [' ', options])[0],
  9152. i,
  9153. l,
  9154. tmp,
  9155. lineIndent;
  9156. if (options.lineIndent === -1) {
  9157. lineIndent = words[0].length + 2;
  9158. } else {
  9159. lineIndent = options.lineIndent || 0;
  9160. }
  9161. if (lineIndent) {
  9162. var pad = Array(lineIndent).join(" "),
  9163. wrds = [];
  9164. words.map(function (wrd) {
  9165. wrd = wrd.split(/\s*\n/);
  9166. if (wrd.length > 1) {
  9167. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  9168. return (idx && wrd.length ? "\n" : "") + wrd;
  9169. }));
  9170. } else {
  9171. wrds.push(wrd[0]);
  9172. }
  9173. });
  9174. words = wrds;
  9175. lineIndent = getStringUnitWidth.apply(this, [pad, options]);
  9176. }
  9177. for (i = 0, l = words.length; i < l; i++) {
  9178. var force = 0;
  9179. word = words[i];
  9180. if (lineIndent && word[0] == "\n") {
  9181. word = word.substr(1);
  9182. force = 1;
  9183. }
  9184. widths_array = getCharWidthsArray.apply(this, [word, options]);
  9185. current_word_length = getArraySum(widths_array);
  9186. if (line_length + separator_length + current_word_length > maxlen || force) {
  9187. if (current_word_length > maxlen) {
  9188. // this happens when you have space-less long URLs for example.
  9189. // we just chop these to size. We do NOT insert hiphens
  9190. tmp = splitLongWord.apply(this, [word, widths_array, maxlen - (line_length + separator_length), maxlen]);
  9191. // first line we add to existing line object
  9192. line.push(tmp.shift()); // it's ok to have extra space indicator there
  9193. // last line we make into new line object
  9194. line = [tmp.pop()];
  9195. // lines in the middle we apped to lines object as whole lines
  9196. while (tmp.length) {
  9197. lines.push([tmp.shift()]); // single fragment occupies whole line
  9198. }
  9199. current_word_length = getArraySum(widths_array.slice(word.length - (line[0] ? line[0].length : 0)));
  9200. } else {
  9201. // just put it on a new line
  9202. line = [word];
  9203. }
  9204. // now we attach new line to lines
  9205. lines.push(line);
  9206. line_length = current_word_length + lineIndent;
  9207. separator_length = spaceCharWidth;
  9208. } else {
  9209. line.push(word);
  9210. line_length += separator_length + current_word_length;
  9211. separator_length = spaceCharWidth;
  9212. }
  9213. }
  9214. if (lineIndent) {
  9215. var postProcess = function postProcess(ln, idx) {
  9216. return (idx ? pad : '') + ln.join(" ");
  9217. };
  9218. } else {
  9219. var postProcess = function postProcess(ln) {
  9220. return ln.join(" ");
  9221. };
  9222. }
  9223. return lines.map(postProcess);
  9224. };
  9225. /**
  9226. Splits a given string into an array of strings. Uses 'size' value
  9227. (in measurement units declared as default for the jsPDF instance)
  9228. and the font's "widths" and "Kerning" tables, where available, to
  9229. determine display length of a given string for a given font.
  9230. We use character's 100% of unit size (height) as width when Width
  9231. table or other default width is not available.
  9232. @public
  9233. @function
  9234. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  9235. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  9236. @param options {Object} Optional flags needed for chopper to do the right thing.
  9237. @returns {Array} with strings chopped to size.
  9238. */
  9239. API.splitTextToSize = function (text, maxlen, options) {
  9240. options = options || {};
  9241. var fsize = options.fontSize || this.internal.getFontSize(),
  9242. newOptions = function (options) {
  9243. var widths = {
  9244. 0: 1
  9245. },
  9246. kerning = {};
  9247. if (!options.widths || !options.kerning) {
  9248. var f = this.internal.getFont(options.fontName, options.fontStyle),
  9249. encoding = 'Unicode';
  9250. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  9251. // Actual JavaScript-native String's 16bit char codes used.
  9252. // no multi-byte logic here
  9253. if (f.metadata[encoding]) {
  9254. return {
  9255. widths: f.metadata[encoding].widths || widths,
  9256. kerning: f.metadata[encoding].kerning || kerning
  9257. };
  9258. } else {
  9259. return {
  9260. font: f.metadata,
  9261. fontSize: this.internal.getFontSize(),
  9262. charSpace: this.internal.getCharSpace()
  9263. };
  9264. }
  9265. } else {
  9266. return {
  9267. widths: options.widths,
  9268. kerning: options.kerning
  9269. };
  9270. }
  9271. // then use default values
  9272. return {
  9273. widths: widths,
  9274. kerning: kerning
  9275. };
  9276. }.call(this, options);
  9277. // first we split on end-of-line chars
  9278. var paragraphs;
  9279. if (Array.isArray(text)) {
  9280. paragraphs = text;
  9281. } else {
  9282. paragraphs = text.split(/\r?\n/);
  9283. }
  9284. // now we convert size (max length of line) into "font size units"
  9285. // at present time, the "font size unit" is always 'point'
  9286. // 'proportional' means, "in proportion to font size"
  9287. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
  9288. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  9289. // this may change in the future?
  9290. // until then, proportional_maxlen is likely to be in 'points'
  9291. // If first line is to be indented (shorter or longer) than maxLen
  9292. // we indicate that by using CSS-style "text-indent" option.
  9293. // here it's in font units too (which is likely 'points')
  9294. // it can be negative (which makes the first line longer than maxLen)
  9295. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  9296. newOptions.lineIndent = options.lineIndent;
  9297. var i,
  9298. l,
  9299. output = [];
  9300. for (i = 0, l = paragraphs.length; i < l; i++) {
  9301. output = output.concat(splitParagraphIntoLines.apply(this, [paragraphs[i], fontUnit_maxLen, newOptions]));
  9302. }
  9303. return output;
  9304. };
  9305. })(jsPDF.API);
  9306. /** @preserve
  9307. jsPDF standard_fonts_metrics plugin
  9308. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  9309. MIT license.
  9310. */
  9311. (function (API) {
  9312. /*
  9313. # reference (Python) versions of 'compress' and 'uncompress'
  9314. # only 'uncompress' function is featured lower as JavaScript
  9315. # if you want to unit test "roundtrip", just transcribe the reference
  9316. # 'compress' function from Python into JavaScript
  9317. def compress(data):
  9318. keys = '0123456789abcdef'
  9319. values = 'klmnopqrstuvwxyz'
  9320. mapping = dict(zip(keys, values))
  9321. vals = []
  9322. for key in data.keys():
  9323. value = data[key]
  9324. try:
  9325. keystring = hex(key)[2:]
  9326. keystring = keystring[:-1] + mapping[keystring[-1:]]
  9327. except:
  9328. keystring = key.join(["'","'"])
  9329. #print('Keystring is %s' % keystring)
  9330. try:
  9331. if value < 0:
  9332. valuestring = hex(value)[3:]
  9333. numberprefix = '-'
  9334. else:
  9335. valuestring = hex(value)[2:]
  9336. numberprefix = ''
  9337. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  9338. except:
  9339. if type(value) == dict:
  9340. valuestring = compress(value)
  9341. else:
  9342. raise Exception("Don't know what to do with value type %s" % type(value))
  9343. vals.append(keystring+valuestring)
  9344. return '{' + ''.join(vals) + '}'
  9345. def uncompress(data):
  9346. decoded = '0123456789abcdef'
  9347. encoded = 'klmnopqrstuvwxyz'
  9348. mapping = dict(zip(encoded, decoded))
  9349. sign = +1
  9350. stringmode = False
  9351. stringparts = []
  9352. output = {}
  9353. activeobject = output
  9354. parentchain = []
  9355. keyparts = ''
  9356. valueparts = ''
  9357. key = None
  9358. ending = set(encoded)
  9359. i = 1
  9360. l = len(data) - 1 # stripping starting, ending {}
  9361. while i != l: # stripping {}
  9362. # -, {, }, ' are special.
  9363. ch = data[i]
  9364. i += 1
  9365. if ch == "'":
  9366. if stringmode:
  9367. # end of string mode
  9368. stringmode = False
  9369. key = ''.join(stringparts)
  9370. else:
  9371. # start of string mode
  9372. stringmode = True
  9373. stringparts = []
  9374. elif stringmode == True:
  9375. #print("Adding %s to stringpart" % ch)
  9376. stringparts.append(ch)
  9377. elif ch == '{':
  9378. # start of object
  9379. parentchain.append( [activeobject, key] )
  9380. activeobject = {}
  9381. key = None
  9382. #DEBUG = True
  9383. elif ch == '}':
  9384. # end of object
  9385. parent, key = parentchain.pop()
  9386. parent[key] = activeobject
  9387. key = None
  9388. activeobject = parent
  9389. #DEBUG = False
  9390. elif ch == '-':
  9391. sign = -1
  9392. else:
  9393. # must be number
  9394. if key == None:
  9395. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  9396. if ch in ending:
  9397. #debug("End of key")
  9398. keyparts += mapping[ch]
  9399. key = int(keyparts, 16) * sign
  9400. sign = +1
  9401. keyparts = ''
  9402. else:
  9403. keyparts += ch
  9404. else:
  9405. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  9406. if ch in ending:
  9407. #debug("End of value")
  9408. valueparts += mapping[ch]
  9409. activeobject[key] = int(valueparts, 16) * sign
  9410. sign = +1
  9411. key = None
  9412. valueparts = ''
  9413. else:
  9414. valueparts += ch
  9415. #debug(activeobject)
  9416. return output
  9417. */
  9418. /**
  9419. Uncompresses data compressed into custom, base16-like format.
  9420. @public
  9421. @function
  9422. @param
  9423. @returns {Type}
  9424. */
  9425. var uncompress = function uncompress(data) {
  9426. var decoded = '0123456789abcdef',
  9427. encoded = 'klmnopqrstuvwxyz',
  9428. mapping = {};
  9429. for (var i = 0; i < encoded.length; i++) {
  9430. mapping[encoded[i]] = decoded[i];
  9431. }
  9432. var undef,
  9433. output = {},
  9434. sign = 1,
  9435. stringparts // undef. will be [] in string mode
  9436. ,
  9437. activeobject = output,
  9438. parentchain = [],
  9439. parent_key_pair,
  9440. keyparts = '',
  9441. valueparts = '',
  9442. key // undef. will be Truthy when Key is resolved.
  9443. ,
  9444. datalen = data.length - 1 // stripping ending }
  9445. ,
  9446. ch;
  9447. i = 1; // stripping starting {
  9448. while (i != datalen) {
  9449. // - { } ' are special.
  9450. ch = data[i];
  9451. i += 1;
  9452. if (ch == "'") {
  9453. if (stringparts) {
  9454. // end of string mode
  9455. key = stringparts.join('');
  9456. stringparts = undef;
  9457. } else {
  9458. // start of string mode
  9459. stringparts = [];
  9460. }
  9461. } else if (stringparts) {
  9462. stringparts.push(ch);
  9463. } else if (ch == '{') {
  9464. // start of object
  9465. parentchain.push([activeobject, key]);
  9466. activeobject = {};
  9467. key = undef;
  9468. } else if (ch == '}') {
  9469. // end of object
  9470. parent_key_pair = parentchain.pop();
  9471. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  9472. key = undef;
  9473. activeobject = parent_key_pair[0];
  9474. } else if (ch == '-') {
  9475. sign = -1;
  9476. } else {
  9477. // must be number
  9478. if (key === undef) {
  9479. if (mapping.hasOwnProperty(ch)) {
  9480. keyparts += mapping[ch];
  9481. key = parseInt(keyparts, 16) * sign;
  9482. sign = +1;
  9483. keyparts = '';
  9484. } else {
  9485. keyparts += ch;
  9486. }
  9487. } else {
  9488. if (mapping.hasOwnProperty(ch)) {
  9489. valueparts += mapping[ch];
  9490. activeobject[key] = parseInt(valueparts, 16) * sign;
  9491. sign = +1;
  9492. key = undef;
  9493. valueparts = '';
  9494. } else {
  9495. valueparts += ch;
  9496. }
  9497. }
  9498. }
  9499. } // end while
  9500. return output;
  9501. };
  9502. // encoding = 'Unicode'
  9503. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  9504. // Actual 16bit char codes used.
  9505. // no multi-byte logic here
  9506. // Unicode characters to WinAnsiEncoding:
  9507. // {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}
  9508. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  9509. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  9510. // as well as give strings with some (supported by these fonts) Unicode characters and
  9511. // these will be mapped to win cp1252
  9512. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  9513. var encodingBlock = {
  9514. 'codePages': ['WinAnsiEncoding'],
  9515. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  9516. },
  9517. encodings = { 'Unicode': {
  9518. 'Courier': encodingBlock,
  9519. 'Courier-Bold': encodingBlock,
  9520. 'Courier-BoldOblique': encodingBlock,
  9521. 'Courier-Oblique': encodingBlock,
  9522. 'Helvetica': encodingBlock,
  9523. 'Helvetica-Bold': encodingBlock,
  9524. 'Helvetica-BoldOblique': encodingBlock,
  9525. 'Helvetica-Oblique': encodingBlock,
  9526. 'Times-Roman': encodingBlock,
  9527. 'Times-Bold': encodingBlock,
  9528. 'Times-BoldItalic': encodingBlock,
  9529. 'Times-Italic': encodingBlock
  9530. // , 'Symbol'
  9531. // , 'ZapfDingbats'
  9532. }
  9533. /**
  9534. Resources:
  9535. Font metrics data is reprocessed derivative of contents of
  9536. "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
  9537. Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
  9538. This file and the 14 PostScript(R) AFM files it accompanies may be used,
  9539. copied, and distributed for any purpose and without charge, with or without
  9540. modification, provided that all copyright notices are retained; that the AFM
  9541. files are not distributed without this file; that all modifications to this
  9542. file or any of the AFM files are prominently noted in the modified file(s);
  9543. and that this paragraph is not modified. Adobe Systems has no responsibility
  9544. or obligation to support the use of the AFM files.
  9545. */
  9546. },
  9547. fontMetrics = { 'Unicode': {
  9548. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  9549. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  9550. // width is 476/1000 or 47.6% of its height (regardless of font size)
  9551. // At this time this value applies to "widths" and "kerning" numbers.
  9552. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  9553. // key 'fof' represents the "fontMetricsFractionOf" value
  9554. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  9555. '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}}}"),
  9556. '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}}}"),
  9557. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  9558. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  9559. '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}}}"),
  9560. 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"),
  9561. '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}}}"),
  9562. '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}}}"),
  9563. 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),
  9564. 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  9565. '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}}}"),
  9566. '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}}}"),
  9567. '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}}}")
  9568. } };
  9569. /*
  9570. This event handler is fired when a new jsPDF object is initialized
  9571. This event handler appends metrics data to standard fonts within
  9572. that jsPDF instance. The metrics are mapped over Unicode character
  9573. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  9574. standard PDF fonts.
  9575. Future:
  9576. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  9577. char codes to StandardEncoding character codes. The encoding table is to be used
  9578. somewhere around "pdfEscape" call.
  9579. */
  9580. API.events.push(['addFont', function (font) {
  9581. var metrics,
  9582. unicode_section,
  9583. encoding = 'Unicode',
  9584. encodingBlock;
  9585. metrics = fontMetrics[encoding][font.postScriptName];
  9586. if (metrics) {
  9587. if (font.metadata[encoding]) {
  9588. unicode_section = font.metadata[encoding];
  9589. } else {
  9590. unicode_section = font.metadata[encoding] = {};
  9591. }
  9592. unicode_section.widths = metrics.widths;
  9593. unicode_section.kerning = metrics.kerning;
  9594. }
  9595. encodingBlock = encodings[encoding][font.postScriptName];
  9596. if (encodingBlock) {
  9597. if (font.metadata[encoding]) {
  9598. unicode_section = font.metadata[encoding];
  9599. } else {
  9600. unicode_section = font.metadata[encoding] = {};
  9601. }
  9602. unicode_section.encoding = encodingBlock;
  9603. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  9604. font.encoding = encodingBlock.codePages[0];
  9605. }
  9606. }
  9607. }]); // end of adding event handler
  9608. })(jsPDF.API);
  9609. /**
  9610. *
  9611. * Licensed under the MIT License.
  9612. * http://opensource.org/licenses/mit-license
  9613. */
  9614. (function (jsPDF, global) {
  9615. jsPDF.API.events.push(['addFont', function (font) {
  9616. if (jsPDF.API.existsFileInVFS(font.postScriptName)) {
  9617. font.metadata = jsPDF.API.TTFFont.open(font.postScriptName, font.fontName, jsPDF.API.getFileFromVFS(font.postScriptName), font.encoding);
  9618. font.metadata.Unicode = font.metadata.Unicode || { encoding: {}, kerning: {}, widths: [] };
  9619. } else if (font.id.slice(1) > 14) {
  9620. console.error("Font does not exist in FileInVFS, import fonts or remove declaration doc.addFont('" + font.postScriptName + "').");
  9621. }
  9622. }]); // end of adding event handler
  9623. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  9624. /** @preserve
  9625. jsPDF SVG plugin
  9626. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  9627. */
  9628. (function (jsPDFAPI) {
  9629. /**
  9630. * Parses SVG XML and converts only some of the SVG elements into
  9631. * PDF elements.
  9632. *
  9633. * Supports:
  9634. * paths
  9635. *
  9636. * @name addSvg
  9637. * @public
  9638. * @function
  9639. * @param {String} SVG-Data as Text
  9640. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  9641. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  9642. * @param {Number} width of SVG (in units declared at inception of PDF document)
  9643. * @param {Number} height of SVG (in units declared at inception of PDF document)
  9644. * @returns {Object} jsPDF-instance
  9645. */
  9646. jsPDFAPI.addSvg = function (svgtext, x, y, w, h) {
  9647. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  9648. var undef;
  9649. if (x === undef || y === undef) {
  9650. throw new Error("addSVG needs values for 'x' and 'y'");
  9651. }
  9652. function InjectCSS(cssbody, document) {
  9653. var styletag = document.createElement('style');
  9654. styletag.type = 'text/css';
  9655. if (styletag.styleSheet) {
  9656. // ie
  9657. styletag.styleSheet.cssText = cssbody;
  9658. } else {
  9659. // others
  9660. styletag.appendChild(document.createTextNode(cssbody));
  9661. }
  9662. document.getElementsByTagName("head")[0].appendChild(styletag);
  9663. }
  9664. function createWorkerNode(document) {
  9665. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  9666. ,
  9667. frame = document.createElement('iframe');
  9668. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  9669. frame.name = frameID;
  9670. frame.setAttribute("width", 0);
  9671. frame.setAttribute("height", 0);
  9672. frame.setAttribute("frameborder", "0");
  9673. frame.setAttribute("scrolling", "no");
  9674. frame.setAttribute("seamless", "seamless");
  9675. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  9676. document.body.appendChild(frame);
  9677. return frame;
  9678. }
  9679. function attachSVGToWorkerNode(svgtext, frame) {
  9680. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  9681. framedoc.write(svgtext);
  9682. framedoc.close();
  9683. return framedoc.getElementsByTagName('svg')[0];
  9684. }
  9685. function convertPathToPDFLinesArgs(path) {
  9686. // we will use 'lines' method call. it needs:
  9687. // - starting coordinate pair
  9688. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  9689. // - scale array [horizontal, vertical] ratios
  9690. // - style (stroke, fill, both)
  9691. var x = parseFloat(path[1]),
  9692. y = parseFloat(path[2]),
  9693. vectors = [],
  9694. position = 3,
  9695. len = path.length;
  9696. while (position < len) {
  9697. if (path[position] === 'c') {
  9698. 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])]);
  9699. position += 7;
  9700. } else if (path[position] === 'l') {
  9701. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  9702. position += 3;
  9703. } else {
  9704. position += 1;
  9705. }
  9706. }
  9707. return [x, y, vectors];
  9708. }
  9709. var workernode = createWorkerNode(document),
  9710. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  9711. scale = [1, 1],
  9712. svgw = parseFloat(svgnode.getAttribute('width')),
  9713. svgh = parseFloat(svgnode.getAttribute('height'));
  9714. if (svgw && svgh) {
  9715. // setting both w and h makes image stretch to size.
  9716. // this may distort the image, but fits your demanded size
  9717. if (w && h) {
  9718. scale = [w / svgw, h / svgh];
  9719. }
  9720. // if only one is set, that value is set as max and SVG
  9721. // is scaled proportionately.
  9722. else if (w) {
  9723. scale = [w / svgw, w / svgw];
  9724. } else if (h) {
  9725. scale = [h / svgh, h / svgh];
  9726. }
  9727. }
  9728. var i,
  9729. l,
  9730. tmp,
  9731. linesargs,
  9732. items = svgnode.childNodes;
  9733. for (i = 0, l = items.length; i < l; i++) {
  9734. tmp = items[i];
  9735. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  9736. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
  9737. // path start x coordinate
  9738. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  9739. // path start y coordinate
  9740. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  9741. // the rest of lines are vectors. these will adjust with scale value auto.
  9742. this.lines.call(this, linesargs[2] // lines
  9743. , linesargs[0] // starting x
  9744. , linesargs[1] // starting y
  9745. , scale);
  9746. }
  9747. }
  9748. // clean up
  9749. // workernode.parentNode.removeChild(workernode)
  9750. return this;
  9751. };
  9752. //fallback
  9753. jsPDFAPI.addSVG = jsPDFAPI.addSvg;
  9754. /**
  9755. * Parses SVG XML and saves it as image into the PDF.
  9756. *
  9757. * Depends on canvas-element and canvg
  9758. *
  9759. * @name addSvgAsImage
  9760. * @public
  9761. * @function
  9762. * @param {String} SVG-Data as Text
  9763. * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  9764. * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  9765. * @param {Number} width of SVG-Image (in units declared at inception of PDF document)
  9766. * @param {Number} height of SVG-Image (in units declared at inception of PDF document)
  9767. * @param {String} alias of SVG-Image (if used multiple times)
  9768. * @param {String} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  9769. * @param {Number} rotation of the image in degrees (0-359)
  9770. *
  9771. * @returns jsPDF
  9772. * @methodOf jsPDF#
  9773. */
  9774. jsPDFAPI.addSvgAsImage = function (svg, x, y, w, h, alias, compression, rotation) {
  9775. if (isNaN(x) || isNaN(y)) {
  9776. console.error('jsPDF.addSvgAsImage: Invalid coordinates', arguments);
  9777. throw new Error('Invalid coordinates passed to jsPDF.addSvgAsImage');
  9778. }
  9779. if (isNaN(w) || isNaN(h)) {
  9780. console.error('jsPDF.addSvgAsImage: Invalid measurements', arguments);
  9781. throw new Error('Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage');
  9782. }
  9783. var canvas = document.createElement('canvas');
  9784. canvas.width = w;
  9785. canvas.height = h;
  9786. var ctx = canvas.getContext('2d');
  9787. ctx.fillStyle = '#fff'; /// set white fill style
  9788. ctx.fillRect(0, 0, canvas.width, canvas.height);
  9789. //load a svg snippet in the canvas with id = 'drawingArea'
  9790. canvg(canvas, svg, {
  9791. ignoreMouse: true,
  9792. ignoreAnimation: true,
  9793. ignoreDimensions: true,
  9794. ignoreClear: true
  9795. });
  9796. this.addImage(canvas.toDataURL("image/jpeg", 1.0), x, y, w, h, compression, rotation);
  9797. return this;
  9798. };
  9799. })(jsPDF.API);
  9800. /** ====================================================================
  9801. * jsPDF total_pages plugin
  9802. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  9803. *
  9804. *
  9805. * ====================================================================
  9806. */
  9807. (function (jsPDFAPI) {
  9808. jsPDFAPI.putTotalPages = function (pageExpression) {
  9809. var replaceExpression = new RegExp(pageExpression, 'g');
  9810. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  9811. for (var i = 0; i < this.internal.pages[n].length; i++) {
  9812. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
  9813. }
  9814. }
  9815. return this;
  9816. };
  9817. })(jsPDF.API);
  9818. /**
  9819. * jsPDF viewerPreferences Plugin
  9820. * @author Aras Abbasi (github.com/arasabbasi)
  9821. * Licensed under the MIT License.
  9822. * http://opensource.org/licenses/mit-license
  9823. */
  9824. /**
  9825. * Adds the ability to set ViewerPreferences and by thus
  9826. * controlling the way the document is to be presented on the
  9827. * screen or in print.
  9828. */
  9829. (function (jsPDFAPI) {
  9830. /**
  9831. * Set the ViewerPreferences of the generated PDF
  9832. *
  9833. * @param {Object} options Array with the ViewerPreferences<br />
  9834. * Example: doc.viewerPreferences({"FitWindow":true});<br />
  9835. * <br />
  9836. * You can set following preferences:<br />
  9837. * <br/>
  9838. * <b>HideToolbar</b> <i>(boolean)</i><br />
  9839. * Default value: false<br />
  9840. * <br />
  9841. * <b>HideMenubar</b> <i>(boolean)</i><br />
  9842. * Default value: false.<br />
  9843. * <br />
  9844. * <b>HideWindowUI</b> <i>(boolean)</i><br />
  9845. * Default value: false.<br />
  9846. * <br />
  9847. * <b>FitWindow</b> <i>(boolean)</i><br />
  9848. * Default value: false.<br />
  9849. * <br />
  9850. * <b>CenterWindow</b> <i>(boolean)</i><br />
  9851. * Default value: false<br />
  9852. * <br />
  9853. * <b>DisplayDocTitle</b> <i>(boolean)</i><br />
  9854. * Default value: false.<br />
  9855. * <br />
  9856. * <b>NonFullScreenPageMode</b> <i>(String)</i><br />
  9857. * Possible values: UseNone, UseOutlines, UseThumbs, UseOC<br />
  9858. * Default value: UseNone<br/>
  9859. * <br />
  9860. * <b>Direction</b> <i>(String)</i><br />
  9861. * Possible values: L2R, R2L<br />
  9862. * Default value: L2R.<br />
  9863. * <br />
  9864. * <b>ViewArea</b> <i>(String)</i><br />
  9865. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  9866. * Default value: CropBox.<br />
  9867. * <br />
  9868. * <b>ViewClip</b> <i>(String)</i><br />
  9869. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  9870. * Default value: CropBox<br />
  9871. * <br />
  9872. * <b>PrintArea</b> <i>(String)</i><br />
  9873. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  9874. * Default value: CropBox<br />
  9875. * <br />
  9876. * <b>PrintClip</b> <i>(String)</i><br />
  9877. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  9878. * Default value: CropBox.<br />
  9879. * <br />
  9880. * <b>PrintScaling</b> <i>(String)</i><br />
  9881. * Possible values: AppDefault, None<br />
  9882. * Default value: AppDefault.<br />
  9883. * <br />
  9884. * <b>Duplex</b> <i>(String)</i><br />
  9885. * Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge
  9886. * Default value: none<br />
  9887. * <br />
  9888. * <b>PickTrayByPDFSize</b> <i>(boolean)</i><br />
  9889. * Default value: false<br />
  9890. * <br />
  9891. * <b>PrintPageRange</b> <i>(Array)</i><br />
  9892. * Example: [[1,5], [7,9]]<br />
  9893. * Default value: as defined by PDF viewer application<br />
  9894. * <br />
  9895. * <b>NumCopies</b> <i>(Number)</i><br />
  9896. * Possible values: 1, 2, 3, 4, 5<br />
  9897. * Default value: 1<br />
  9898. * <br />
  9899. * For more information see the PDF Reference, sixth edition on Page 577
  9900. * @param {boolean} doReset True to reset the settings
  9901. * @function
  9902. * @returns jsPDF
  9903. * @methodOf jsPDF#
  9904. * @example
  9905. * var doc = new jsPDF()
  9906. * doc.text('This is a test', 10, 10)
  9907. * doc.viewerPreferences({'FitWindow': true}, true)
  9908. * doc.save("viewerPreferences.pdf")
  9909. *
  9910. * // Example printing 10 copies, using cropbox, and hiding UI.
  9911. * doc.viewerPreferences({
  9912. * 'HideWindowUI': true,
  9913. * 'PrintArea': 'CropBox',
  9914. * 'NumCopies': 10
  9915. * })
  9916. * @name viewerPreferences
  9917. */
  9918. jsPDFAPI.viewerPreferences = function (options, doReset) {
  9919. options = options || {};
  9920. doReset = doReset || false;
  9921. var configuration;
  9922. var configurationTemplate = {
  9923. "HideToolbar": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3 },
  9924. "HideMenubar": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3 },
  9925. "HideWindowUI": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3 },
  9926. "FitWindow": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3 },
  9927. "CenterWindow": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3 },
  9928. "DisplayDocTitle": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.4 },
  9929. "NonFullScreenPageMode": { defaultValue: "UseNone", value: "UseNone", type: "name", explicitSet: false, valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"], pdfVersion: 1.3 },
  9930. "Direction": { defaultValue: "L2R", value: "L2R", type: "name", explicitSet: false, valueSet: ["L2R", "R2L"], pdfVersion: 1.3 },
  9931. "ViewArea": { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 },
  9932. "ViewClip": { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 },
  9933. "PrintArea": { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 },
  9934. "PrintClip": { defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4 },
  9935. "PrintScaling": { defaultValue: "AppDefault", value: "AppDefault", type: "name", explicitSet: false, valueSet: ["AppDefault", "None"], pdfVersion: 1.6 },
  9936. "Duplex": { defaultValue: "", value: "none", type: "name", explicitSet: false, valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"], pdfVersion: 1.7 },
  9937. "PickTrayByPDFSize": { defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.7 },
  9938. "PrintPageRange": { defaultValue: "", value: "", type: "array", explicitSet: false, valueSet: null, pdfVersion: 1.7 },
  9939. "NumCopies": { defaultValue: 1, value: 1, type: "integer", explicitSet: false, valueSet: null, pdfVersion: 1.7 }
  9940. };
  9941. var configurationKeys = Object.keys(configurationTemplate);
  9942. var rangeArray = [];
  9943. var i = 0;
  9944. var j = 0;
  9945. var k = 0;
  9946. var isValid = true;
  9947. var method;
  9948. var value;
  9949. function arrayContainsElement(array, element) {
  9950. var iterator;
  9951. var result = false;
  9952. for (iterator = 0; iterator < array.length; iterator += 1) {
  9953. if (array[iterator] === element) {
  9954. result = true;
  9955. }
  9956. }
  9957. return result;
  9958. }
  9959. if (this.internal.viewerpreferences === undefined) {
  9960. this.internal.viewerpreferences = {};
  9961. this.internal.viewerpreferences.configuration = JSON.parse(JSON.stringify(configurationTemplate));
  9962. this.internal.viewerpreferences.isSubscribed = false;
  9963. }
  9964. configuration = this.internal.viewerpreferences.configuration;
  9965. if (options === "reset" || doReset === true) {
  9966. var len = configurationKeys.length;
  9967. for (k = 0; k < len; k += 1) {
  9968. configuration[configurationKeys[k]].value = configuration[configurationKeys[k]].defaultValue;
  9969. configuration[configurationKeys[k]].explicitSet = false;
  9970. }
  9971. }
  9972. if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") {
  9973. for (method in options) {
  9974. value = options[method];
  9975. if (arrayContainsElement(configurationKeys, method) && value !== undefined) {
  9976. if (configuration[method].type === "boolean" && typeof value === "boolean") {
  9977. configuration[method].value = value;
  9978. } else if (configuration[method].type === "name" && arrayContainsElement(configuration[method].valueSet, value)) {
  9979. configuration[method].value = value;
  9980. } else if (configuration[method].type === "integer" && Number.isInteger(value)) {
  9981. configuration[method].value = value;
  9982. } else if (configuration[method].type === "array") {
  9983. for (i = 0; i < value.length; i += 1) {
  9984. isValid = true;
  9985. if (value[i].length === 1 && typeof value[i][0] === "number") {
  9986. rangeArray.push(String(value[i]));
  9987. } else if (value[i].length > 1) {
  9988. for (j = 0; j < value[i].length; j += 1) {
  9989. if (typeof value[i][j] !== "number") {
  9990. isValid = false;
  9991. }
  9992. }
  9993. if (isValid === true) {
  9994. rangeArray.push(String(value[i].join("-")));
  9995. }
  9996. }
  9997. }
  9998. configuration[method].value = String(rangeArray);
  9999. } else {
  10000. configuration[method].value = configuration[method].defaultValue;
  10001. }
  10002. configuration[method].explicitSet = true;
  10003. }
  10004. }
  10005. }
  10006. if (this.internal.viewerpreferences.isSubscribed === false) {
  10007. this.internal.events.subscribe("putCatalog", function () {
  10008. var pdfDict = [];
  10009. var vPref;
  10010. for (vPref in configuration) {
  10011. if (configuration[vPref].explicitSet === true) {
  10012. if (configuration[vPref].type === "name") {
  10013. pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
  10014. } else {
  10015. pdfDict.push("/" + vPref + " " + configuration[vPref].value);
  10016. }
  10017. }
  10018. }
  10019. if (pdfDict.length !== 0) {
  10020. this.internal.write("/ViewerPreferences\n<<\n" + pdfDict.join("\n") + "\n>>");
  10021. }
  10022. });
  10023. this.internal.viewerpreferences.isSubscribed = true;
  10024. }
  10025. this.internal.viewerpreferences.configuration = configuration;
  10026. return this;
  10027. };
  10028. })(jsPDF.API);
  10029. /** ====================================================================
  10030. * jsPDF XMP metadata plugin
  10031. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  10032. *
  10033. *
  10034. * ====================================================================
  10035. */
  10036. /*global jsPDF */
  10037. /**
  10038. * Adds XMP formatted metadata to PDF
  10039. *
  10040. * @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.
  10041. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  10042. * @function
  10043. * @returns {jsPDF}
  10044. * @methodOf jsPDF#
  10045. * @name addMetadata
  10046. */
  10047. (function (jsPDFAPI) {
  10048. var xmpmetadata = "";
  10049. var xmpnamespaceuri = "";
  10050. var metadata_object_number = "";
  10051. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  10052. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  10053. xmpmetadata = metadata;
  10054. this.internal.events.subscribe('postPutResources', function () {
  10055. if (!xmpmetadata) {
  10056. metadata_object_number = "";
  10057. } else {
  10058. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  10059. 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>';
  10060. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  10061. var xmpmeta_ending = '</x:xmpmeta>';
  10062. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  10063. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  10064. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  10065. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  10066. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  10067. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  10068. metadata_object_number = this.internal.newObject();
  10069. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  10070. this.internal.write('stream');
  10071. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  10072. this.internal.write('endstream');
  10073. this.internal.write('endobj');
  10074. }
  10075. });
  10076. this.internal.events.subscribe('putCatalog', function () {
  10077. if (metadata_object_number) {
  10078. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  10079. }
  10080. });
  10081. return this;
  10082. };
  10083. })(jsPDF.API);
  10084. (function (jsPDF, global) {
  10085. var jsPDFAPI = jsPDF.API;
  10086. var glyID = [0];
  10087. /**************************************************/
  10088. /* function : toHex */
  10089. /* comment : Replace str with a hex string. */
  10090. /**************************************************/
  10091. function toHex(str) {
  10092. var hex = '';
  10093. for (var i = 0; i < str.length; i++) {
  10094. hex += '' + str.charCodeAt(i).toString(16);
  10095. }
  10096. return hex;
  10097. }
  10098. /***************************************************************************************************/
  10099. /* function : pdfEscape16 */
  10100. /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
  10101. /* the corresponding glyph id and width, and then adding padding to the string. */
  10102. /***************************************************************************************************/
  10103. var pdfEscape16 = function pdfEscape16(text, font) {
  10104. var widths = font.metadata.Unicode.widths; var padz = ["", "0", "00", "000", "0000"];
  10105. var ar = [""];
  10106. for (var i = 0, l = text.length, t; i < l; ++i) {
  10107. t = font.metadata.characterToGlyph(text.charCodeAt(i));
  10108. glyID.push(t);
  10109. if (widths.indexOf(t) == -1) {
  10110. widths.push(t);
  10111. widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
  10112. }
  10113. if (t == '0') {
  10114. //Spaces are not allowed in cmap.
  10115. return ar.join("");
  10116. } else {
  10117. t = t.toString(16);
  10118. ar.push(padz[4 - t.length], t);
  10119. }
  10120. }
  10121. return ar.join("");
  10122. };
  10123. var identityHFunction = function identityHFunction(font, out, newObject) {
  10124. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'Identity-H') {
  10125. //Tag with Identity-H
  10126. var widths = font.metadata.Unicode.widths;
  10127. var data = font.metadata.subset.encode(glyID);
  10128. var pdfOutput = data;
  10129. var pdfOutput2 = "";
  10130. for (var i = 0; i < pdfOutput.length; i++) {
  10131. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  10132. }
  10133. var fontTable = newObject();
  10134. out('<<');
  10135. out('/Length ' + pdfOutput2.length);
  10136. out('/Length1 ' + pdfOutput2.length);
  10137. out('>>');
  10138. out('stream');
  10139. out(pdfOutput2);
  10140. out('endstream');
  10141. out('endobj');
  10142. var fontDescriptor = newObject();
  10143. out('<<');
  10144. out('/Type /FontDescriptor');
  10145. out('/FontName /' + font.fontName);
  10146. out('/FontFile2 ' + fontTable + ' 0 R');
  10147. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  10148. out('/Flags ' + font.metadata.flags);
  10149. out('/StemV ' + font.metadata.stemV);
  10150. out('/ItalicAngle ' + font.metadata.italicAngle);
  10151. out('/Ascent ' + font.metadata.ascender);
  10152. out('/Descent ' + font.metadata.decender);
  10153. out('/CapHeight ' + font.metadata.capHeight);
  10154. out('>>');
  10155. out('endobj');
  10156. var DescendantFont = newObject();
  10157. out('<<');
  10158. out('/Type /Font');
  10159. out('/BaseFont /' + font.fontName);
  10160. out('/FontDescriptor ' + fontDescriptor + ' 0 R');
  10161. out('/W ' + jsPDF.API.PDFObject.convert(widths));
  10162. out('/CIDToGIDMap /Identity');
  10163. out('/DW 1000');
  10164. out('/Subtype /CIDFontType2');
  10165. out('/CIDSystemInfo');
  10166. out('<<');
  10167. out('/Supplement 0');
  10168. out('/Registry (Adobe)');
  10169. out('/Ordering (' + font.encoding + ')');
  10170. out('>>');
  10171. out('>>');
  10172. out('endobj');
  10173. font.objectNumber = newObject();
  10174. out('<<');
  10175. out('/Type /Font');
  10176. out('/Subtype /Type0');
  10177. out('/BaseFont /' + font.fontName);
  10178. out('/Encoding /' + font.encoding);
  10179. out('/DescendantFonts [' + DescendantFont + ' 0 R]');
  10180. out('>>');
  10181. out('endobj');
  10182. font.isAlreadyPutted = true;
  10183. }
  10184. };
  10185. jsPDFAPI.events.push(['putFont', function (args) {
  10186. identityHFunction(args.font, args.out, args.newObject);
  10187. }]);
  10188. var winAnsiEncodingFunction = function winAnsiEncodingFunction(font, out, newObject) {
  10189. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'WinAnsiEncoding') {
  10190. //Tag with WinAnsi encoding
  10191. var widths = font.metadata.Unicode.widths;
  10192. var data = font.metadata.rawData;
  10193. var pdfOutput = data;
  10194. var pdfOutput2 = "";
  10195. for (var i = 0; i < pdfOutput.length; i++) {
  10196. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  10197. }
  10198. var fontTable = newObject();
  10199. out('<<');
  10200. out('/Length ' + pdfOutput2.length);
  10201. out('/Length1 ' + pdfOutput2.length);
  10202. out('>>');
  10203. out('stream');
  10204. out(pdfOutput2);
  10205. out('endstream');
  10206. out('endobj');
  10207. var fontDescriptor = newObject();
  10208. out('<<');
  10209. out('/Descent ' + font.metadata.decender);
  10210. out('/CapHeight ' + font.metadata.capHeight);
  10211. out('/StemV ' + font.metadata.stemV);
  10212. out('/Type /FontDescriptor');
  10213. out('/FontFile2 ' + fontTable + ' 0 R');
  10214. out('/Flags 96');
  10215. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  10216. out('/FontName /' + font.fontName);
  10217. out('/ItalicAngle ' + font.metadata.italicAngle);
  10218. out('/Ascent ' + font.metadata.ascender);
  10219. out('>>');
  10220. out('endobj');
  10221. font.objectNumber = newObject();
  10222. for (var i = 0; i < font.metadata.hmtx.widths.length; i++) {
  10223. font.metadata.hmtx.widths[i] = parseInt(font.metadata.hmtx.widths[i] * (1000 / font.metadata.head.unitsPerEm)); //Change the width of Em units to Point units.
  10224. }
  10225. out('<</Subtype/TrueType/Type/Font/BaseFont/' + font.fontName + '/FontDescriptor ' + fontDescriptor + ' 0 R' + '/Encoding/' + font.encoding + ' /FirstChar 29 /LastChar 255 /Widths ' + jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) + '>>');
  10226. out('endobj');
  10227. font.isAlreadyPutted = true;
  10228. }
  10229. };
  10230. jsPDFAPI.events.push(['putFont', function (args) {
  10231. winAnsiEncodingFunction(args.font, args.out, args.newObject);
  10232. }]);
  10233. var utf8TextFunction = function utf8TextFunction(args) {
  10234. var text = args.text || '';
  10235. var x = args.x;
  10236. var y = args.y;
  10237. var options = args.options || {};
  10238. var mutex = args.mutex || {};
  10239. var pdfEscape = mutex.pdfEscape;
  10240. var activeFontKey = mutex.activeFontKey;
  10241. var fonts = mutex.fonts;
  10242. var key,
  10243. fontSize = mutex.activeFontSize;
  10244. var str = '',
  10245. s = 0,
  10246. cmapConfirm;
  10247. var strText = '';
  10248. var key = activeFontKey;
  10249. var encoding = fonts[key].encoding;
  10250. if (fonts[key].encoding !== 'Identity-H') {
  10251. return {
  10252. text: text,
  10253. x: x,
  10254. y: y,
  10255. options: options,
  10256. mutex: mutex
  10257. };
  10258. }
  10259. strText = text;
  10260. key = activeFontKey;
  10261. if (Object.prototype.toString.call(text) === '[object Array]') {
  10262. strText = text[0];
  10263. }
  10264. for (s = 0; s < strText.length; s += 1) {
  10265. if (fonts[key].metadata.hasOwnProperty('cmap')) {
  10266. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
  10267. /*
  10268. if (Object.prototype.toString.call(text) === '[object Array]') {
  10269. var i = 0;
  10270. // for (i = 0; i < text.length; i += 1) {
  10271. if (Object.prototype.toString.call(text[s]) === '[object Array]') {
  10272. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  10273. } else {
  10274. }
  10275. //}
  10276. } else {
  10277. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  10278. }*/
  10279. }
  10280. if (!cmapConfirm) {
  10281. if (strText[s].charCodeAt(0) < 256 && fonts[key].metadata.hasOwnProperty('Unicode')) {
  10282. str += strText[s];
  10283. } else {
  10284. str += '';
  10285. }
  10286. } else {
  10287. str += strText[s];
  10288. }
  10289. }
  10290. var result = '';
  10291. if (parseInt(key.slice(1)) < 14 || encoding === 'WinAnsiEncoding') {
  10292. //For the default 13 font
  10293. result = toHex(pdfEscape(str, key));
  10294. } else if (encoding === 'Identity-H') {
  10295. result = pdfEscape16(str, fonts[key]);
  10296. }
  10297. mutex.isHex = true;
  10298. return {
  10299. text: result,
  10300. x: x,
  10301. y: y,
  10302. options: options,
  10303. mutex: mutex
  10304. };
  10305. };
  10306. var utf8EscapeFunction = function utf8EscapeFunction(parms) {
  10307. var text = parms.text || '',
  10308. x = parms.x,
  10309. y = parms.y,
  10310. options = parms.options,
  10311. mutex = parms.mutex;
  10312. var lang = options.lang;
  10313. var tmpText = [];
  10314. var args = {
  10315. text: text,
  10316. x: x,
  10317. y: y,
  10318. options: options,
  10319. mutex: mutex
  10320. };
  10321. if (Object.prototype.toString.call(text) === '[object Array]') {
  10322. var i = 0;
  10323. for (i = 0; i < text.length; i += 1) {
  10324. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  10325. if (text[i].length === 3) {
  10326. tmpText.push([utf8TextFunction(Object.assign({}, args, { text: text[i][0] })).text, text[i][1], text[i][2]]);
  10327. } else {
  10328. tmpText.push(utf8TextFunction(Object.assign({}, args, { text: text[i] })).text);
  10329. }
  10330. } else {
  10331. tmpText.push(utf8TextFunction(Object.assign({}, args, { text: text[i] })).text);
  10332. }
  10333. }
  10334. parms.text = tmpText;
  10335. } else {
  10336. parms.text = utf8TextFunction(Object.assign({}, args, { text: text })).text;
  10337. }
  10338. };
  10339. jsPDFAPI.events.push(['postProcessText', utf8EscapeFunction]);
  10340. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  10341. /**
  10342. * jsPDF virtual FileSystem functionality
  10343. *
  10344. * Licensed under the MIT License.
  10345. * http://opensource.org/licenses/mit-license
  10346. */
  10347. /**
  10348. * Use the vFS to handle files
  10349. */
  10350. (function (jsPDFAPI) {
  10351. var vFS = {};
  10352. /* Check if the file exists in the vFS
  10353. * @returns {boolean}
  10354. * @name existsFileInVFS
  10355. * @example
  10356. * doc.existsFileInVFS("someFile.txt");
  10357. */
  10358. jsPDFAPI.existsFileInVFS = function (filename) {
  10359. return vFS.hasOwnProperty(filename);
  10360. };
  10361. /* Add a file to the vFS
  10362. * @returns {jsPDF}
  10363. * @name addFileToVFS
  10364. * @example
  10365. * doc.addFileToVFS("someFile.txt", "BADFACE1");
  10366. */
  10367. jsPDFAPI.addFileToVFS = function (filename, filecontent) {
  10368. vFS[filename] = filecontent;
  10369. return this;
  10370. };
  10371. /* Get the file from the vFS
  10372. * @returns {string}
  10373. * @name addFileToVFS
  10374. * @example
  10375. * doc.getFileFromVFS("someFile.txt");
  10376. */
  10377. jsPDFAPI.getFileFromVFS = function (filename) {
  10378. if (vFS.hasOwnProperty(filename)) {
  10379. return vFS[filename];
  10380. }
  10381. return null;
  10382. };
  10383. })(jsPDF.API);
  10384. /* Blob.js
  10385. * A Blob implementation.
  10386. * 2014-07-24
  10387. *
  10388. * By Eli Grey, http://eligrey.com
  10389. * By Devin Samarin, https://github.com/dsamarin
  10390. * License: X11/MIT
  10391. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  10392. */
  10393. /*global self, unescape */
  10394. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  10395. plusplus: true */
  10396. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  10397. (function (view) {
  10398. view.URL = view.URL || view.webkitURL;
  10399. if (view.Blob && view.URL) {
  10400. try {
  10401. new Blob;
  10402. return;
  10403. } catch (e) {}
  10404. }
  10405. // Internally we use a BlobBuilder implementation to base Blob off of
  10406. // in order to support older browsers that only have BlobBuilder
  10407. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
  10408. var
  10409. get_class = function(object) {
  10410. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  10411. }
  10412. , FakeBlobBuilder = function BlobBuilder() {
  10413. this.data = [];
  10414. }
  10415. , FakeBlob = function Blob(data, type, encoding) {
  10416. this.data = data;
  10417. this.size = data.length;
  10418. this.type = type;
  10419. this.encoding = encoding;
  10420. }
  10421. , FBB_proto = FakeBlobBuilder.prototype
  10422. , FB_proto = FakeBlob.prototype
  10423. , FileReaderSync = view.FileReaderSync
  10424. , FileException = function(type) {
  10425. this.code = this[this.name = type];
  10426. }
  10427. , file_ex_codes = (
  10428. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
  10429. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  10430. ).split(" ")
  10431. , file_ex_code = file_ex_codes.length
  10432. , real_URL = view.URL || view.webkitURL || view
  10433. , real_create_object_URL = real_URL.createObjectURL
  10434. , real_revoke_object_URL = real_URL.revokeObjectURL
  10435. , URL = real_URL
  10436. , btoa = view.btoa
  10437. , atob = view.atob
  10438. , ArrayBuffer = view.ArrayBuffer
  10439. , Uint8Array = view.Uint8Array
  10440. , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/
  10441. ;
  10442. FakeBlob.fake = FB_proto.fake = true;
  10443. while (file_ex_code--) {
  10444. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  10445. }
  10446. // Polyfill URL
  10447. if (!real_URL.createObjectURL) {
  10448. URL = view.URL = function(uri) {
  10449. var
  10450. uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
  10451. , uri_origin
  10452. ;
  10453. uri_info.href = uri;
  10454. if (!("origin" in uri_info)) {
  10455. if (uri_info.protocol.toLowerCase() === "data:") {
  10456. uri_info.origin = null;
  10457. } else {
  10458. uri_origin = uri.match(origin);
  10459. uri_info.origin = uri_origin && uri_origin[1];
  10460. }
  10461. }
  10462. return uri_info;
  10463. };
  10464. }
  10465. URL.createObjectURL = function(blob) {
  10466. var
  10467. type = blob.type
  10468. , data_URI_header
  10469. ;
  10470. if (type === null) {
  10471. type = "application/octet-stream";
  10472. }
  10473. if (blob instanceof FakeBlob) {
  10474. data_URI_header = "data:" + type;
  10475. if (blob.encoding === "base64") {
  10476. return data_URI_header + ";base64," + blob.data;
  10477. } else if (blob.encoding === "URI") {
  10478. return data_URI_header + "," + decodeURIComponent(blob.data);
  10479. } if (btoa) {
  10480. return data_URI_header + ";base64," + btoa(blob.data);
  10481. } else {
  10482. return data_URI_header + "," + encodeURIComponent(blob.data);
  10483. }
  10484. } else if (real_create_object_URL) {
  10485. return real_create_object_URL.call(real_URL, blob);
  10486. }
  10487. };
  10488. URL.revokeObjectURL = function(object_URL) {
  10489. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  10490. real_revoke_object_URL.call(real_URL, object_URL);
  10491. }
  10492. };
  10493. FBB_proto.append = function(data/*, endings*/) {
  10494. var bb = this.data;
  10495. // decode data to a binary string
  10496. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
  10497. var
  10498. str = ""
  10499. , buf = new Uint8Array(data)
  10500. , i = 0
  10501. , buf_len = buf.length
  10502. ;
  10503. for (; i < buf_len; i++) {
  10504. str += String.fromCharCode(buf[i]);
  10505. }
  10506. bb.push(str);
  10507. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  10508. if (FileReaderSync) {
  10509. var fr = new FileReaderSync;
  10510. bb.push(fr.readAsBinaryString(data));
  10511. } else {
  10512. // async FileReader won't work as BlobBuilder is sync
  10513. throw new FileException("NOT_READABLE_ERR");
  10514. }
  10515. } else if (data instanceof FakeBlob) {
  10516. if (data.encoding === "base64" && atob) {
  10517. bb.push(atob(data.data));
  10518. } else if (data.encoding === "URI") {
  10519. bb.push(decodeURIComponent(data.data));
  10520. } else if (data.encoding === "raw") {
  10521. bb.push(data.data);
  10522. }
  10523. } else {
  10524. if (typeof data !== "string") {
  10525. data += ""; // convert unsupported types to strings
  10526. }
  10527. // decode UTF-16 to binary string
  10528. bb.push(unescape(encodeURIComponent(data)));
  10529. }
  10530. };
  10531. FBB_proto.getBlob = function(type) {
  10532. if (!arguments.length) {
  10533. type = null;
  10534. }
  10535. return new FakeBlob(this.data.join(""), type, "raw");
  10536. };
  10537. FBB_proto.toString = function() {
  10538. return "[object BlobBuilder]";
  10539. };
  10540. FB_proto.slice = function(start, end, type) {
  10541. var args = arguments.length;
  10542. if (args < 3) {
  10543. type = null;
  10544. }
  10545. return new FakeBlob(
  10546. this.data.slice(start, args > 1 ? end : this.data.length)
  10547. , type
  10548. , this.encoding
  10549. );
  10550. };
  10551. FB_proto.toString = function() {
  10552. return "[object Blob]";
  10553. };
  10554. FB_proto.close = function() {
  10555. this.size = 0;
  10556. delete this.data;
  10557. };
  10558. return FakeBlobBuilder;
  10559. }(view));
  10560. view.Blob = function(blobParts, options) {
  10561. var type = options ? (options.type || "") : "";
  10562. var builder = new BlobBuilder();
  10563. if (blobParts) {
  10564. for (var i = 0, len = blobParts.length; i < len; i++) {
  10565. if (Uint8Array && blobParts[i] instanceof Uint8Array) {
  10566. builder.append(blobParts[i].buffer);
  10567. }
  10568. else {
  10569. builder.append(blobParts[i]);
  10570. }
  10571. }
  10572. }
  10573. var blob = builder.getBlob(type);
  10574. if (!blob.slice && blob.webkitSlice) {
  10575. blob.slice = blob.webkitSlice;
  10576. }
  10577. return blob;
  10578. };
  10579. var getPrototypeOf = Object.getPrototypeOf || function(object) {
  10580. return object.__proto__;
  10581. };
  10582. view.Blob.prototype = getPrototypeOf(new view.Blob());
  10583. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || window.content || window));
  10584. /* FileSaver.js
  10585. * A saveAs() FileSaver implementation.
  10586. * 1.3.2
  10587. * 2016-06-16 18:25:19
  10588. *
  10589. * By Eli Grey, http://eligrey.com
  10590. * License: MIT
  10591. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  10592. */
  10593. /*global self */
  10594. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  10595. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  10596. var saveAs = saveAs || (function(view) {
  10597. // IE <10 is explicitly unsupported
  10598. if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  10599. return;
  10600. }
  10601. var
  10602. doc = view.document
  10603. // only get URL when necessary in case Blob.js hasn't overridden it yet
  10604. , get_URL = function() {
  10605. return view.URL || view.webkitURL || view;
  10606. }
  10607. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  10608. , can_use_save_link = "download" in save_link
  10609. , click = function(node) {
  10610. var event = new MouseEvent("click");
  10611. node.dispatchEvent(event);
  10612. }
  10613. , is_safari = /constructor/i.test(view.HTMLElement) || view.safari
  10614. , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
  10615. , throw_outside = function(ex) {
  10616. (view.setImmediate || view.setTimeout)(function() {
  10617. throw ex;
  10618. }, 0);
  10619. }
  10620. , force_saveable_type = "application/octet-stream"
  10621. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  10622. , arbitrary_revoke_timeout = 1000 * 40 // in ms
  10623. , revoke = function(file) {
  10624. var revoker = function() {
  10625. if (typeof file === "string") { // file is an object URL
  10626. get_URL().revokeObjectURL(file);
  10627. } else { // file is a File
  10628. file.remove();
  10629. }
  10630. };
  10631. setTimeout(revoker, arbitrary_revoke_timeout);
  10632. }
  10633. , dispatch = function(filesaver, event_types, event) {
  10634. event_types = [].concat(event_types);
  10635. var i = event_types.length;
  10636. while (i--) {
  10637. var listener = filesaver["on" + event_types[i]];
  10638. if (typeof listener === "function") {
  10639. try {
  10640. listener.call(filesaver, event || filesaver);
  10641. } catch (ex) {
  10642. throw_outside(ex);
  10643. }
  10644. }
  10645. }
  10646. }
  10647. , auto_bom = function(blob) {
  10648. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  10649. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  10650. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  10651. return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
  10652. }
  10653. return blob;
  10654. }
  10655. , FileSaver = function(blob, name, no_auto_bom) {
  10656. if (!no_auto_bom) {
  10657. blob = auto_bom(blob);
  10658. }
  10659. // First try a.download, then web filesystem, then object URLs
  10660. var
  10661. filesaver = this
  10662. , type = blob.type
  10663. , force = type === force_saveable_type
  10664. , object_url
  10665. , dispatch_all = function() {
  10666. dispatch(filesaver, "writestart progress write writeend".split(" "));
  10667. }
  10668. // on any filesys errors revert to saving with object URLs
  10669. , fs_error = function() {
  10670. if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
  10671. // Safari doesn't allow downloading of blob urls
  10672. var reader = new FileReader();
  10673. reader.onloadend = function() {
  10674. var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
  10675. var popup = view.open(url, '_blank');
  10676. if(!popup) view.location.href = url;
  10677. url=undefined; // release reference before dispatching
  10678. filesaver.readyState = filesaver.DONE;
  10679. dispatch_all();
  10680. };
  10681. reader.readAsDataURL(blob);
  10682. filesaver.readyState = filesaver.INIT;
  10683. return;
  10684. }
  10685. // don't create more object URLs than needed
  10686. if (!object_url) {
  10687. object_url = get_URL().createObjectURL(blob);
  10688. }
  10689. if (force) {
  10690. view.location.href = object_url;
  10691. } else {
  10692. var opened = view.open(object_url, "_blank");
  10693. if (!opened) {
  10694. // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
  10695. view.location.href = object_url;
  10696. }
  10697. }
  10698. filesaver.readyState = filesaver.DONE;
  10699. dispatch_all();
  10700. revoke(object_url);
  10701. }
  10702. ;
  10703. filesaver.readyState = filesaver.INIT;
  10704. if (can_use_save_link) {
  10705. object_url = get_URL().createObjectURL(blob);
  10706. setTimeout(function() {
  10707. save_link.href = object_url;
  10708. save_link.download = name;
  10709. click(save_link);
  10710. dispatch_all();
  10711. revoke(object_url);
  10712. filesaver.readyState = filesaver.DONE;
  10713. });
  10714. return;
  10715. }
  10716. fs_error();
  10717. }
  10718. , FS_proto = FileSaver.prototype
  10719. , saveAs = function(blob, name, no_auto_bom) {
  10720. return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
  10721. }
  10722. ;
  10723. // IE 10+ (native saveAs)
  10724. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  10725. return function(blob, name, no_auto_bom) {
  10726. name = name || blob.name || "download";
  10727. if (!no_auto_bom) {
  10728. blob = auto_bom(blob);
  10729. }
  10730. return navigator.msSaveOrOpenBlob(blob, name);
  10731. };
  10732. }
  10733. FS_proto.abort = function(){};
  10734. FS_proto.readyState = FS_proto.INIT = 0;
  10735. FS_proto.WRITING = 1;
  10736. FS_proto.DONE = 2;
  10737. FS_proto.error =
  10738. FS_proto.onwritestart =
  10739. FS_proto.onprogress =
  10740. FS_proto.onwrite =
  10741. FS_proto.onabort =
  10742. FS_proto.onerror =
  10743. FS_proto.onwriteend =
  10744. null;
  10745. return saveAs;
  10746. }(
  10747. typeof self !== "undefined" && self
  10748. || typeof window !== "undefined" && window
  10749. || window.content
  10750. ));
  10751. // `self` is undefined in Firefox for Android content script context
  10752. // while `this` is nsIContentFrameMessageManager
  10753. // with an attribute `content` that corresponds to the window
  10754. if (typeof module !== "undefined" && module.exports) {
  10755. module.exports.saveAs = saveAs;
  10756. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  10757. define("FileSaver.js", function() {
  10758. return saveAs;
  10759. });
  10760. }
  10761. /*
  10762. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  10763. *
  10764. * Licensed under the MIT License.
  10765. * http://opensource.org/licenses/mit-license
  10766. */
  10767. (function(jsPDF, callback) {
  10768. jsPDF.API.adler32cs = callback();
  10769. })(jsPDF, function() {
  10770. var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
  10771. typeof Uint8Array === 'function';
  10772. var _Buffer = null, _isBuffer = (function() {
  10773. if (!_hasArrayBuffer)
  10774. return function _isBuffer() { return false };
  10775. return function _isBuffer(value) {
  10776. return value instanceof ArrayBuffer ||
  10777. _Buffer !== null && value instanceof _Buffer;
  10778. };
  10779. }());
  10780. var _utf8ToBinary = (function() {
  10781. if (_Buffer !== null) {
  10782. return function _utf8ToBinary(utf8String) {
  10783. return new _Buffer(utf8String, 'utf8').toString('binary');
  10784. };
  10785. } else {
  10786. return function _utf8ToBinary(utf8String) {
  10787. return unescape(encodeURIComponent(utf8String));
  10788. };
  10789. }
  10790. }());
  10791. var MOD = 65521;
  10792. var _update = function _update(checksum, binaryString) {
  10793. var a = checksum & 0xFFFF, b = checksum >>> 16;
  10794. for (var i = 0, length = binaryString.length; i < length; i++) {
  10795. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  10796. b = (b + a) % MOD;
  10797. }
  10798. return (b << 16 | a) >>> 0;
  10799. };
  10800. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  10801. var a = checksum & 0xFFFF, b = checksum >>> 16;
  10802. for (var i = 0, length = uint8Array.length; i < length; i++) {
  10803. a = (a + uint8Array[i]) % MOD;
  10804. b = (b + a) % MOD;
  10805. }
  10806. return (b << 16 | a) >>> 0
  10807. };
  10808. var exports = {};
  10809. var Adler32 = exports.Adler32 = (function() {
  10810. var ctor = function Adler32(checksum) {
  10811. if (!(this instanceof ctor)) {
  10812. throw new TypeError(
  10813. 'Constructor cannot called be as a function.');
  10814. }
  10815. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  10816. throw new Error(
  10817. 'First arguments needs to be a finite number.');
  10818. }
  10819. this.checksum = checksum >>> 0;
  10820. };
  10821. var proto = ctor.prototype = {};
  10822. proto.constructor = ctor;
  10823. ctor.from = function(from) {
  10824. from.prototype = proto;
  10825. return from;
  10826. }(function from(binaryString) {
  10827. if (!(this instanceof ctor)) {
  10828. throw new TypeError(
  10829. 'Constructor cannot called be as a function.');
  10830. }
  10831. if (binaryString == null)
  10832. throw new Error('First argument needs to be a string.');
  10833. this.checksum = _update(1, binaryString.toString());
  10834. });
  10835. ctor.fromUtf8 = function(fromUtf8) {
  10836. fromUtf8.prototype = proto;
  10837. return fromUtf8;
  10838. }(function fromUtf8(utf8String) {
  10839. if (!(this instanceof ctor)) {
  10840. throw new TypeError(
  10841. 'Constructor cannot called be as a function.');
  10842. }
  10843. if (utf8String == null)
  10844. throw new Error('First argument needs to be a string.');
  10845. var binaryString = _utf8ToBinary(utf8String.toString());
  10846. this.checksum = _update(1, binaryString);
  10847. });
  10848. if (_hasArrayBuffer) {
  10849. ctor.fromBuffer = function(fromBuffer) {
  10850. fromBuffer.prototype = proto;
  10851. return fromBuffer;
  10852. }(function fromBuffer(buffer) {
  10853. if (!(this instanceof ctor)) {
  10854. throw new TypeError(
  10855. 'Constructor cannot called be as a function.');
  10856. }
  10857. if (!_isBuffer(buffer))
  10858. throw new Error('First argument needs to be ArrayBuffer.');
  10859. var array = new Uint8Array(buffer);
  10860. return this.checksum = _updateUint8Array(1, array);
  10861. });
  10862. }
  10863. proto.update = function update(binaryString) {
  10864. if (binaryString == null)
  10865. throw new Error('First argument needs to be a string.');
  10866. binaryString = binaryString.toString();
  10867. return this.checksum = _update(this.checksum, binaryString);
  10868. };
  10869. proto.updateUtf8 = function updateUtf8(utf8String) {
  10870. if (utf8String == null)
  10871. throw new Error('First argument needs to be a string.');
  10872. var binaryString = _utf8ToBinary(utf8String.toString());
  10873. return this.checksum = _update(this.checksum, binaryString);
  10874. };
  10875. if (_hasArrayBuffer) {
  10876. proto.updateBuffer = function updateBuffer(buffer) {
  10877. if (!_isBuffer(buffer))
  10878. throw new Error('First argument needs to be ArrayBuffer.');
  10879. var array = new Uint8Array(buffer);
  10880. return this.checksum = _updateUint8Array(this.checksum, array);
  10881. };
  10882. }
  10883. proto.clone = function clone() {
  10884. return new Adler32(this.checksum);
  10885. };
  10886. return ctor;
  10887. }());
  10888. exports.from = function from(binaryString) {
  10889. if (binaryString == null)
  10890. throw new Error('First argument needs to be a string.');
  10891. return _update(1, binaryString.toString());
  10892. };
  10893. exports.fromUtf8 = function fromUtf8(utf8String) {
  10894. if (utf8String == null)
  10895. throw new Error('First argument needs to be a string.');
  10896. var binaryString = _utf8ToBinary(utf8String.toString());
  10897. return _update(1, binaryString);
  10898. };
  10899. if (_hasArrayBuffer) {
  10900. exports.fromBuffer = function fromBuffer(buffer) {
  10901. if (!_isBuffer(buffer))
  10902. throw new Error('First argument need to be ArrayBuffer.');
  10903. var array = new Uint8Array(buffer);
  10904. return _updateUint8Array(1, array);
  10905. };
  10906. }
  10907. return exports;
  10908. });
  10909. // (c) Dean McNamee <dean@gmail.com>, 2013.
  10910. //
  10911. // https://github.com/deanm/omggif
  10912. //
  10913. //
  10914. //
  10915. // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
  10916. // including animation and compression. It does not rely on any specific
  10917. // underlying system, so should run in the browser, Node, or Plask.
  10918. function GifWriter(buf, width, height, gopts) {
  10919. var p = 0;
  10920. var gopts = gopts === undefined ? { } : gopts;
  10921. var loop_count = gopts.loop === undefined ? null : gopts.loop;
  10922. var global_palette = gopts.palette === undefined ? null : gopts.palette;
  10923. if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
  10924. throw "Width/Height invalid."
  10925. function check_palette_and_num_colors(palette) {
  10926. var num_colors = palette.length;
  10927. if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1))
  10928. throw "Invalid code/color length, must be power of 2 and 2 .. 256.";
  10929. return num_colors;
  10930. }
  10931. // - Header.
  10932. buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF
  10933. buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a
  10934. // Handling of Global Color Table (palette) and background index.
  10935. var gp_num_colors_pow2 = 0;
  10936. var background = 0;
  10937. if (global_palette !== null) {
  10938. var gp_num_colors = check_palette_and_num_colors(global_palette);
  10939. while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
  10940. gp_num_colors = 1 << gp_num_colors_pow2;
  10941. --gp_num_colors_pow2;
  10942. if (gopts.background !== undefined) {
  10943. background = gopts.background;
  10944. if (background >= gp_num_colors) throw "Background index out of range.";
  10945. // The GIF spec states that a background index of 0 should be ignored, so
  10946. // this is probably a mistake and you really want to set it to another
  10947. // slot in the palette. But actually in the end most browsers, etc end
  10948. // up ignoring this almost completely (including for dispose background).
  10949. if (background === 0)
  10950. throw "Background index explicitly passed as 0.";
  10951. }
  10952. }
  10953. // - Logical Screen Descriptor.
  10954. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
  10955. buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;
  10956. buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;
  10957. // NOTE: Indicates 0-bpp original color resolution (unused?).
  10958. buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
  10959. gp_num_colors_pow2; // NOTE: No sort flag (unused?).
  10960. buf[p++] = background; // Background Color Index.
  10961. buf[p++] = 0; // Pixel aspect ratio (unused?).
  10962. // - Global Color Table
  10963. if (global_palette !== null) {
  10964. for (var i = 0, il = global_palette.length; i < il; ++i) {
  10965. var rgb = global_palette[i];
  10966. buf[p++] = rgb >> 16 & 0xff;
  10967. buf[p++] = rgb >> 8 & 0xff;
  10968. buf[p++] = rgb & 0xff;
  10969. }
  10970. }
  10971. if (loop_count !== null) { // Netscape block for looping.
  10972. if (loop_count < 0 || loop_count > 65535)
  10973. throw "Loop count invalid."
  10974. // Extension code, label, and length.
  10975. buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;
  10976. // NETSCAPE2.0
  10977. buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;
  10978. buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;
  10979. buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;
  10980. // Sub-block
  10981. buf[p++] = 0x03; buf[p++] = 0x01;
  10982. buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;
  10983. buf[p++] = 0x00; // Terminator.
  10984. }
  10985. var ended = false;
  10986. this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
  10987. if (ended === true) { --p; ended = false; } // Un-end.
  10988. opts = opts === undefined ? { } : opts;
  10989. // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
  10990. // canvas width/height, I imagine?
  10991. if (x < 0 || y < 0 || x > 65535 || y > 65535)
  10992. throw "x/y invalid."
  10993. if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
  10994. throw "Width/Height invalid."
  10995. if (indexed_pixels.length < w * h)
  10996. throw "Not enough pixels for the frame size.";
  10997. var using_local_palette = true;
  10998. var palette = opts.palette;
  10999. if (palette === undefined || palette === null) {
  11000. using_local_palette = false;
  11001. palette = global_palette;
  11002. }
  11003. if (palette === undefined || palette === null)
  11004. throw "Must supply either a local or global palette.";
  11005. var num_colors = check_palette_and_num_colors(palette);
  11006. // Compute the min_code_size (power of 2), destroying num_colors.
  11007. var min_code_size = 0;
  11008. while (num_colors >>= 1) ++min_code_size;
  11009. num_colors = 1 << min_code_size; // Now we can easily get it back.
  11010. var delay = opts.delay === undefined ? 0 : opts.delay;
  11011. // From the spec:
  11012. // 0 - No disposal specified. The decoder is
  11013. // not required to take any action.
  11014. // 1 - Do not dispose. The graphic is to be left
  11015. // in place.
  11016. // 2 - Restore to background color. The area used by the
  11017. // graphic must be restored to the background color.
  11018. // 3 - Restore to previous. The decoder is required to
  11019. // restore the area overwritten by the graphic with
  11020. // what was there prior to rendering the graphic.
  11021. // 4-7 - To be defined.
  11022. // NOTE(deanm): Dispose background doesn't really work, apparently most
  11023. // browsers ignore the background palette index and clear to transparency.
  11024. var disposal = opts.disposal === undefined ? 0 : opts.disposal;
  11025. if (disposal < 0 || disposal > 3) // 4-7 is reserved.
  11026. throw "Disposal out of range.";
  11027. var use_transparency = false;
  11028. var transparent_index = 0;
  11029. if (opts.transparent !== undefined && opts.transparent !== null) {
  11030. use_transparency = true;
  11031. transparent_index = opts.transparent;
  11032. if (transparent_index < 0 || transparent_index >= num_colors)
  11033. throw "Transparent color index.";
  11034. }
  11035. if (disposal !== 0 || use_transparency || delay !== 0) {
  11036. // - Graphics Control Extension
  11037. buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.
  11038. buf[p++] = 4; // Byte size.
  11039. buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
  11040. buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;
  11041. buf[p++] = transparent_index; // Transparent color index.
  11042. buf[p++] = 0; // Block Terminator.
  11043. }
  11044. // - Image Descriptor
  11045. buf[p++] = 0x2c; // Image Seperator.
  11046. buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.
  11047. buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.
  11048. buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;
  11049. buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;
  11050. // NOTE: No sort flag (unused?).
  11051. // TODO(deanm): Support interlace.
  11052. buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;
  11053. // - Local Color Table
  11054. if (using_local_palette === true) {
  11055. for (var i = 0, il = palette.length; i < il; ++i) {
  11056. var rgb = palette[i];
  11057. buf[p++] = rgb >> 16 & 0xff;
  11058. buf[p++] = rgb >> 8 & 0xff;
  11059. buf[p++] = rgb & 0xff;
  11060. }
  11061. }
  11062. p = GifWriterOutputLZWCodeStream(
  11063. buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
  11064. };
  11065. this.end = function() {
  11066. if (ended === false) {
  11067. buf[p++] = 0x3b; // Trailer.
  11068. ended = true;
  11069. }
  11070. return p;
  11071. };
  11072. }
  11073. // Main compression routine, palette indexes -> LZW code stream.
  11074. // |index_stream| must have at least one entry.
  11075. function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
  11076. buf[p++] = min_code_size;
  11077. var cur_subblock = p++; // Pointing at the length field.
  11078. var clear_code = 1 << min_code_size;
  11079. var code_mask = clear_code - 1;
  11080. var eoi_code = clear_code + 1;
  11081. var next_code = eoi_code + 1;
  11082. var cur_code_size = min_code_size + 1; // Number of bits per code.
  11083. var cur_shift = 0;
  11084. // We have at most 12-bit codes, so we should have to hold a max of 19
  11085. // bits here (and then we would write out).
  11086. var cur = 0;
  11087. function emit_bytes_to_buffer(bit_block_size) {
  11088. while (cur_shift >= bit_block_size) {
  11089. buf[p++] = cur & 0xff;
  11090. cur >>= 8; cur_shift -= 8;
  11091. if (p === cur_subblock + 256) { // Finished a subblock.
  11092. buf[cur_subblock] = 255;
  11093. cur_subblock = p++;
  11094. }
  11095. }
  11096. }
  11097. function emit_code(c) {
  11098. cur |= c << cur_shift;
  11099. cur_shift += cur_code_size;
  11100. emit_bytes_to_buffer(8);
  11101. }
  11102. // I am not an expert on the topic, and I don't want to write a thesis.
  11103. // However, it is good to outline here the basic algorithm and the few data
  11104. // structures and optimizations here that make this implementation fast.
  11105. // The basic idea behind LZW is to build a table of previously seen runs
  11106. // addressed by a short id (herein called output code). All data is
  11107. // referenced by a code, which represents one or more values from the
  11108. // original input stream. All input bytes can be referenced as the same
  11109. // value as an output code. So if you didn't want any compression, you
  11110. // could more or less just output the original bytes as codes (there are
  11111. // some details to this, but it is the idea). In order to achieve
  11112. // compression, values greater then the input range (codes can be up to
  11113. // 12-bit while input only 8-bit) represent a sequence of previously seen
  11114. // inputs. The decompressor is able to build the same mapping while
  11115. // decoding, so there is always a shared common knowledge between the
  11116. // encoding and decoder, which is also important for "timing" aspects like
  11117. // how to handle variable bit width code encoding.
  11118. //
  11119. // One obvious but very important consequence of the table system is there
  11120. // is always a unique id (at most 12-bits) to map the runs. 'A' might be
  11121. // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
  11122. // can be used for an effecient lookup strategy for the code mapping. We
  11123. // need to know if a run has been seen before, and be able to map that run
  11124. // to the output code. Since we start with known unique ids (input bytes),
  11125. // and then from those build more unique ids (table entries), we can
  11126. // continue this chain (almost like a linked list) to always have small
  11127. // integer values that represent the current byte chains in the encoder.
  11128. // This means instead of tracking the input bytes (AAAABCD) to know our
  11129. // current state, we can track the table entry for AAAABC (it is guaranteed
  11130. // to exist by the nature of the algorithm) and the next character D.
  11131. // Therefor the tuple of (table_entry, byte) is guaranteed to also be
  11132. // unique. This allows us to create a simple lookup key for mapping input
  11133. // sequences to codes (table indices) without having to store or search
  11134. // any of the code sequences. So if 'AAAA' has a table entry of 12, the
  11135. // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
  11136. // key. This leads to a integer value at most 20-bits, which can always
  11137. // fit in an SMI value and be used as a fast sparse array / object key.
  11138. // Output code for the current contents of the index buffer.
  11139. var ib_code = index_stream[0] & code_mask; // Load first input index.
  11140. var code_table = { }; // Key'd on our 20-bit "tuple".
  11141. emit_code(clear_code); // Spec says first code should be a clear code.
  11142. // First index already loaded, process the rest of the stream.
  11143. for (var i = 1, il = index_stream.length; i < il; ++i) {
  11144. var k = index_stream[i] & code_mask;
  11145. var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.
  11146. var cur_code = code_table[cur_key]; // buffer + k.
  11147. // Check if we have to create a new code table entry.
  11148. if (cur_code === undefined) { // We don't have buffer + k.
  11149. // Emit index buffer (without k).
  11150. // This is an inline version of emit_code, because this is the core
  11151. // writing routine of the compressor (and V8 cannot inline emit_code
  11152. // because it is a closure here in a different context). Additionally
  11153. // we can call emit_byte_to_buffer less often, because we can have
  11154. // 30-bits (from our 31-bit signed SMI), and we know our codes will only
  11155. // be 12-bits, so can safely have 18-bits there without overflow.
  11156. // emit_code(ib_code);
  11157. cur |= ib_code << cur_shift;
  11158. cur_shift += cur_code_size;
  11159. while (cur_shift >= 8) {
  11160. buf[p++] = cur & 0xff;
  11161. cur >>= 8; cur_shift -= 8;
  11162. if (p === cur_subblock + 256) { // Finished a subblock.
  11163. buf[cur_subblock] = 255;
  11164. cur_subblock = p++;
  11165. }
  11166. }
  11167. if (next_code === 4096) { // Table full, need a clear.
  11168. emit_code(clear_code);
  11169. next_code = eoi_code + 1;
  11170. cur_code_size = min_code_size + 1;
  11171. code_table = { };
  11172. } else { // Table not full, insert a new entry.
  11173. // Increase our variable bit code sizes if necessary. This is a bit
  11174. // tricky as it is based on "timing" between the encoding and
  11175. // decoder. From the encoders perspective this should happen after
  11176. // we've already emitted the index buffer and are about to create the
  11177. // first table entry that would overflow our current code bit size.
  11178. if (next_code >= (1 << cur_code_size)) ++cur_code_size;
  11179. code_table[cur_key] = next_code++; // Insert into code table.
  11180. }
  11181. ib_code = k; // Index buffer to single input k.
  11182. } else {
  11183. ib_code = cur_code; // Index buffer to sequence in code table.
  11184. }
  11185. }
  11186. emit_code(ib_code); // There will still be something in the index buffer.
  11187. emit_code(eoi_code); // End Of Information.
  11188. // Flush / finalize the sub-blocks stream to the buffer.
  11189. emit_bytes_to_buffer(1);
  11190. // Finish the sub-blocks, writing out any unfinished lengths and
  11191. // terminating with a sub-block of length 0. If we have already started
  11192. // but not yet used a sub-block it can just become the terminator.
  11193. if (cur_subblock + 1 === p) { // Started but unused.
  11194. buf[cur_subblock] = 0;
  11195. } else { // Started and used, write length and additional terminator block.
  11196. buf[cur_subblock] = p - cur_subblock - 1;
  11197. buf[p++] = 0;
  11198. }
  11199. return p;
  11200. }
  11201. function GifReader(buf) {
  11202. var p = 0;
  11203. // - Header (GIF87a or GIF89a).
  11204. if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||
  11205. buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {
  11206. throw "Invalid GIF 87a/89a header.";
  11207. }
  11208. // - Logical Screen Descriptor.
  11209. var width = buf[p++] | buf[p++] << 8;
  11210. var height = buf[p++] | buf[p++] << 8;
  11211. var pf0 = buf[p++]; // <Packed Fields>.
  11212. var global_palette_flag = pf0 >> 7;
  11213. var num_global_colors_pow2 = pf0 & 0x7;
  11214. var num_global_colors = 1 << (num_global_colors_pow2 + 1);
  11215. var background = buf[p++];
  11216. buf[p++]; // Pixel aspect ratio (unused?).
  11217. var global_palette_offset = null;
  11218. if (global_palette_flag) {
  11219. global_palette_offset = p;
  11220. p += num_global_colors * 3; // Seek past palette.
  11221. }
  11222. var no_eof = true;
  11223. var frames = [ ];
  11224. var delay = 0;
  11225. var transparent_index = null;
  11226. var disposal = 0; // 0 - No disposal specified.
  11227. var loop_count = null;
  11228. this.width = width;
  11229. this.height = height;
  11230. while (no_eof && p < buf.length) {
  11231. switch (buf[p++]) {
  11232. case 0x21: // Graphics Control Extension Block
  11233. switch (buf[p++]) {
  11234. case 0xff: // Application specific block
  11235. // Try if it's a Netscape block (with animation loop counter).
  11236. if (buf[p ] !== 0x0b || // 21 FF already read, check block size.
  11237. // NETSCAPE2.0
  11238. buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&
  11239. buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&
  11240. buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&
  11241. buf[p+10] == 0x2e && buf[p+11] == 0x30 &&
  11242. // Sub-block
  11243. buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {
  11244. p += 14;
  11245. loop_count = buf[p++] | buf[p++] << 8;
  11246. p++; // Skip terminator.
  11247. } else { // We don't know what it is, just try to get past it.
  11248. p += 12;
  11249. while (true) { // Seek through subblocks.
  11250. var block_size = buf[p++];
  11251. if (block_size === 0) break;
  11252. p += block_size;
  11253. }
  11254. }
  11255. break;
  11256. case 0xf9: // Graphics Control Extension
  11257. if (buf[p++] !== 0x4 || buf[p+4] !== 0)
  11258. throw "Invalid graphics extension block.";
  11259. var pf1 = buf[p++];
  11260. delay = buf[p++] | buf[p++] << 8;
  11261. transparent_index = buf[p++];
  11262. if ((pf1 & 1) === 0) transparent_index = null;
  11263. disposal = pf1 >> 2 & 0x7;
  11264. p++; // Skip terminator.
  11265. break;
  11266. case 0xfe: // Comment Extension.
  11267. while (true) { // Seek through subblocks.
  11268. var block_size = buf[p++];
  11269. if (block_size === 0) break;
  11270. // console.log(buf.slice(p, p+block_size).toString('ascii'));
  11271. p += block_size;
  11272. }
  11273. break;
  11274. default:
  11275. throw "Unknown graphic control label: 0x" + buf[p-1].toString(16);
  11276. }
  11277. break;
  11278. case 0x2c: // Image Descriptor.
  11279. var x = buf[p++] | buf[p++] << 8;
  11280. var y = buf[p++] | buf[p++] << 8;
  11281. var w = buf[p++] | buf[p++] << 8;
  11282. var h = buf[p++] | buf[p++] << 8;
  11283. var pf2 = buf[p++];
  11284. var local_palette_flag = pf2 >> 7;
  11285. var interlace_flag = pf2 >> 6 & 1;
  11286. var num_local_colors_pow2 = pf2 & 0x7;
  11287. var num_local_colors = 1 << (num_local_colors_pow2 + 1);
  11288. var palette_offset = global_palette_offset;
  11289. var has_local_palette = false;
  11290. if (local_palette_flag) {
  11291. var has_local_palette = true;
  11292. palette_offset = p; // Override with local palette.
  11293. p += num_local_colors * 3; // Seek past palette.
  11294. }
  11295. var data_offset = p;
  11296. p++; // codesize
  11297. while (true) {
  11298. var block_size = buf[p++];
  11299. if (block_size === 0) break;
  11300. p += block_size;
  11301. }
  11302. frames.push({x: x, y: y, width: w, height: h,
  11303. has_local_palette: has_local_palette,
  11304. palette_offset: palette_offset,
  11305. data_offset: data_offset,
  11306. data_length: p - data_offset,
  11307. transparent_index: transparent_index,
  11308. interlaced: !!interlace_flag,
  11309. delay: delay,
  11310. disposal: disposal});
  11311. break;
  11312. case 0x3b: // Trailer Marker (end of file).
  11313. no_eof = false;
  11314. break;
  11315. default:
  11316. throw "Unknown gif block: 0x" + buf[p-1].toString(16);
  11317. break;
  11318. }
  11319. }
  11320. this.numFrames = function() {
  11321. return frames.length;
  11322. };
  11323. this.loopCount = function() {
  11324. return loop_count;
  11325. };
  11326. this.frameInfo = function(frame_num) {
  11327. if (frame_num < 0 || frame_num >= frames.length)
  11328. throw "Frame index out of range.";
  11329. return frames[frame_num];
  11330. };
  11331. this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
  11332. var frame = this.frameInfo(frame_num);
  11333. var num_pixels = frame.width * frame.height;
  11334. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  11335. GifReaderLZWOutputIndexStream(
  11336. buf, frame.data_offset, index_stream, num_pixels);
  11337. var palette_offset = frame.palette_offset;
  11338. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  11339. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  11340. // the profile, not sure if it's related to using a Uint8Array.
  11341. var trans = frame.transparent_index;
  11342. if (trans === null) trans = 256;
  11343. // We are possibly just blitting to a portion of the entire frame.
  11344. // That is a subrect within the framerect, so the additional pixels
  11345. // must be skipped over after we finished a scanline.
  11346. var framewidth = frame.width;
  11347. var framestride = width - framewidth;
  11348. var xleft = framewidth; // Number of subrect pixels left in scanline.
  11349. // Output indicies of the top left and bottom right corners of the subrect.
  11350. var opbeg = ((frame.y * width) + frame.x) * 4;
  11351. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  11352. var op = opbeg;
  11353. var scanstride = framestride * 4;
  11354. // Use scanstride to skip past the rows when interlacing. This is skipping
  11355. // 7 rows for the first two passes, then 3 then 1.
  11356. if (frame.interlaced === true) {
  11357. scanstride += (framewidth + framestride) * 4 * 7; // Pass 1.
  11358. }
  11359. var interlaceskip = 8; // Tracking the row interval in the current pass.
  11360. for (var i = 0, il = index_stream.length; i < il; ++i) {
  11361. var index = index_stream[i];
  11362. if (xleft === 0) { // Beginning of new scan line
  11363. op += scanstride;
  11364. xleft = framewidth;
  11365. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  11366. scanstride =
  11367. framestride + (framewidth + framestride) * 4 * (interlaceskip-1);
  11368. // interlaceskip / 2 * 4 is interlaceskip << 1.
  11369. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  11370. interlaceskip >>= 1;
  11371. }
  11372. }
  11373. if (index === trans) {
  11374. op += 4;
  11375. } else {
  11376. var r = buf[palette_offset + index * 3];
  11377. var g = buf[palette_offset + index * 3 + 1];
  11378. var b = buf[palette_offset + index * 3 + 2];
  11379. pixels[op++] = b;
  11380. pixels[op++] = g;
  11381. pixels[op++] = r;
  11382. pixels[op++] = 255;
  11383. }
  11384. --xleft;
  11385. }
  11386. };
  11387. // I will go to copy and paste hell one day...
  11388. this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
  11389. var frame = this.frameInfo(frame_num);
  11390. var num_pixels = frame.width * frame.height;
  11391. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  11392. GifReaderLZWOutputIndexStream(
  11393. buf, frame.data_offset, index_stream, num_pixels);
  11394. var palette_offset = frame.palette_offset;
  11395. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  11396. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  11397. // the profile, not sure if it's related to using a Uint8Array.
  11398. var trans = frame.transparent_index;
  11399. if (trans === null) trans = 256;
  11400. // We are possibly just blitting to a portion of the entire frame.
  11401. // That is a subrect within the framerect, so the additional pixels
  11402. // must be skipped over after we finished a scanline.
  11403. var framewidth = frame.width;
  11404. var framestride = width - framewidth;
  11405. var xleft = framewidth; // Number of subrect pixels left in scanline.
  11406. // Output indicies of the top left and bottom right corners of the subrect.
  11407. var opbeg = ((frame.y * width) + frame.x) * 4;
  11408. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  11409. var op = opbeg;
  11410. var scanstride = framestride * 4;
  11411. // Use scanstride to skip past the rows when interlacing. This is skipping
  11412. // 7 rows for the first two passes, then 3 then 1.
  11413. if (frame.interlaced === true) {
  11414. scanstride += (framewidth + framestride) * 4 * 7; // Pass 1.
  11415. }
  11416. var interlaceskip = 8; // Tracking the row interval in the current pass.
  11417. for (var i = 0, il = index_stream.length; i < il; ++i) {
  11418. var index = index_stream[i];
  11419. if (xleft === 0) { // Beginning of new scan line
  11420. op += scanstride;
  11421. xleft = framewidth;
  11422. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  11423. scanstride =
  11424. framestride + (framewidth + framestride) * 4 * (interlaceskip-1);
  11425. // interlaceskip / 2 * 4 is interlaceskip << 1.
  11426. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  11427. interlaceskip >>= 1;
  11428. }
  11429. }
  11430. if (index === trans) {
  11431. op += 4;
  11432. } else {
  11433. var r = buf[palette_offset + index * 3];
  11434. var g = buf[palette_offset + index * 3 + 1];
  11435. var b = buf[palette_offset + index * 3 + 2];
  11436. pixels[op++] = r;
  11437. pixels[op++] = g;
  11438. pixels[op++] = b;
  11439. pixels[op++] = 255;
  11440. }
  11441. --xleft;
  11442. }
  11443. };
  11444. }
  11445. function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
  11446. var min_code_size = code_stream[p++];
  11447. var clear_code = 1 << min_code_size;
  11448. var eoi_code = clear_code + 1;
  11449. var next_code = eoi_code + 1;
  11450. var cur_code_size = min_code_size + 1; // Number of bits per code.
  11451. // NOTE: This shares the same name as the encoder, but has a different
  11452. // meaning here. Here this masks each code coming from the code stream.
  11453. var code_mask = (1 << cur_code_size) - 1;
  11454. var cur_shift = 0;
  11455. var cur = 0;
  11456. var op = 0; // Output pointer.
  11457. var subblock_size = code_stream[p++];
  11458. // TODO(deanm): Would using a TypedArray be any faster? At least it would
  11459. // solve the fast mode / backing store uncertainty.
  11460. // var code_table = Array(4096);
  11461. var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
  11462. var prev_code = null; // Track code-1.
  11463. while (true) {
  11464. // Read up to two bytes, making sure we always 12-bits for max sized code.
  11465. while (cur_shift < 16) {
  11466. if (subblock_size === 0) break; // No more data to be read.
  11467. cur |= code_stream[p++] << cur_shift;
  11468. cur_shift += 8;
  11469. if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
  11470. subblock_size = code_stream[p++]; // Next subblock.
  11471. } else {
  11472. --subblock_size;
  11473. }
  11474. }
  11475. // TODO(deanm): We should never really get here, we should have received
  11476. // and EOI.
  11477. if (cur_shift < cur_code_size)
  11478. break;
  11479. var code = cur & code_mask;
  11480. cur >>= cur_code_size;
  11481. cur_shift -= cur_code_size;
  11482. // TODO(deanm): Maybe should check that the first code was a clear code,
  11483. // at least this is what you're supposed to do. But actually our encoder
  11484. // now doesn't emit a clear code first anyway.
  11485. if (code === clear_code) {
  11486. // We don't actually have to clear the table. This could be a good idea
  11487. // for greater error checking, but we don't really do any anyway. We
  11488. // will just track it with next_code and overwrite old entries.
  11489. next_code = eoi_code + 1;
  11490. cur_code_size = min_code_size + 1;
  11491. code_mask = (1 << cur_code_size) - 1;
  11492. // Don't update prev_code ?
  11493. prev_code = null;
  11494. continue;
  11495. } else if (code === eoi_code) {
  11496. break;
  11497. }
  11498. // We have a similar situation as the decoder, where we want to store
  11499. // variable length entries (code table entries), but we want to do in a
  11500. // faster manner than an array of arrays. The code below stores sort of a
  11501. // linked list within the code table, and then "chases" through it to
  11502. // construct the dictionary entries. When a new entry is created, just the
  11503. // last byte is stored, and the rest (prefix) of the entry is only
  11504. // referenced by its table entry. Then the code chases through the
  11505. // prefixes until it reaches a single byte code. We have to chase twice,
  11506. // first to compute the length, and then to actually copy the data to the
  11507. // output (backwards, since we know the length). The alternative would be
  11508. // storing something in an intermediate stack, but that doesn't make any
  11509. // more sense. I implemented an approach where it also stored the length
  11510. // in the code table, although it's a bit tricky because you run out of
  11511. // bits (12 + 12 + 8), but I didn't measure much improvements (the table
  11512. // entries are generally not the long). Even when I created benchmarks for
  11513. // very long table entries the complexity did not seem worth it.
  11514. // The code table stores the prefix entry in 12 bits and then the suffix
  11515. // byte in 8 bits, so each entry is 20 bits.
  11516. var chase_code = code < next_code ? code : prev_code;
  11517. // Chase what we will output, either {CODE} or {CODE-1}.
  11518. var chase_length = 0;
  11519. var chase = chase_code;
  11520. while (chase > clear_code) {
  11521. chase = code_table[chase] >> 8;
  11522. ++chase_length;
  11523. }
  11524. var k = chase;
  11525. var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
  11526. if (op_end > output_length) {
  11527. console.log("Warning, gif stream longer than expected.");
  11528. return;
  11529. }
  11530. // Already have the first byte from the chase, might as well write it fast.
  11531. output[op++] = k;
  11532. op += chase_length;
  11533. var b = op; // Track pointer, writing backwards.
  11534. if (chase_code !== code) // The case of emitting {CODE-1} + k.
  11535. output[op++] = k;
  11536. chase = chase_code;
  11537. while (chase_length--) {
  11538. chase = code_table[chase];
  11539. output[--b] = chase & 0xff; // Write backwards.
  11540. chase >>= 8; // Pull down to the prefix code.
  11541. }
  11542. if (prev_code !== null && next_code < 4096) {
  11543. code_table[next_code++] = prev_code << 8 | k;
  11544. // TODO(deanm): Figure out this clearing vs code growth logic better. I
  11545. // have an feeling that it should just happen somewhere else, for now it
  11546. // is awkward between when we grow past the max and then hit a clear code.
  11547. // For now just check if we hit the max 12-bits (then a clear code should
  11548. // follow, also of course encoded in 12-bits).
  11549. if (next_code >= code_mask+1 && cur_code_size < 12) {
  11550. ++cur_code_size;
  11551. code_mask = code_mask << 1 | 1;
  11552. }
  11553. }
  11554. prev_code = code;
  11555. }
  11556. if (op !== output_length) {
  11557. console.log("Warning, gif stream shorter than expected.");
  11558. }
  11559. return output;
  11560. }
  11561. try { exports.GifWriter = GifWriter; exports.GifReader = GifReader; } catch(e) { } // CommonJS.
  11562. /*
  11563. Copyright (c) 2008, Adobe Systems Incorporated
  11564. All rights reserved.
  11565. Redistribution and use in source and binary forms, with or without
  11566. modification, are permitted provided that the following conditions are
  11567. met:
  11568. * Redistributions of source code must retain the above copyright notice,
  11569. this list of conditions and the following disclaimer.
  11570. * Redistributions in binary form must reproduce the above copyright
  11571. notice, this list of conditions and the following disclaimer in the
  11572. documentation and/or other materials provided with the distribution.
  11573. * Neither the name of Adobe Systems Incorporated nor the names of its
  11574. contributors may be used to endorse or promote products derived from
  11575. this software without specific prior written permission.
  11576. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  11577. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  11578. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  11579. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  11580. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  11581. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  11582. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11583. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  11584. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  11585. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  11586. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11587. */
  11588. /*
  11589. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  11590. Basic GUI blocking jpeg encoder
  11591. */
  11592. function JPEGEncoder(quality) {
  11593. var ffloor = Math.floor;
  11594. var YTable = new Array(64);
  11595. var UVTable = new Array(64);
  11596. var fdtbl_Y = new Array(64);
  11597. var fdtbl_UV = new Array(64);
  11598. var YDC_HT;
  11599. var UVDC_HT;
  11600. var YAC_HT;
  11601. var UVAC_HT;
  11602. var bitcode = new Array(65535);
  11603. var category = new Array(65535);
  11604. var outputfDCTQuant = new Array(64);
  11605. var DU = new Array(64);
  11606. var byteout = [];
  11607. var bytenew = 0;
  11608. var bytepos = 7;
  11609. var YDU = new Array(64);
  11610. var UDU = new Array(64);
  11611. var VDU = new Array(64);
  11612. var clt = new Array(256);
  11613. var RGB_YUV_TABLE = new Array(2048);
  11614. var currentQuality;
  11615. var ZigZag = [
  11616. 0, 1, 5, 6,14,15,27,28,
  11617. 2, 4, 7,13,16,26,29,42,
  11618. 3, 8,12,17,25,30,41,43,
  11619. 9,11,18,24,31,40,44,53,
  11620. 10,19,23,32,39,45,52,54,
  11621. 20,22,33,38,46,51,55,60,
  11622. 21,34,37,47,50,56,59,61,
  11623. 35,36,48,49,57,58,62,63
  11624. ];
  11625. var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
  11626. var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  11627. var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
  11628. var std_ac_luminance_values = [
  11629. 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
  11630. 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
  11631. 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
  11632. 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
  11633. 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
  11634. 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
  11635. 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
  11636. 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
  11637. 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
  11638. 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
  11639. 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
  11640. 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
  11641. 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
  11642. 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
  11643. 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
  11644. 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
  11645. 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
  11646. 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
  11647. 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
  11648. 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  11649. 0xf9,0xfa
  11650. ];
  11651. var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
  11652. var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  11653. var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
  11654. var std_ac_chrominance_values = [
  11655. 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
  11656. 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
  11657. 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
  11658. 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
  11659. 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
  11660. 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
  11661. 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
  11662. 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
  11663. 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
  11664. 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
  11665. 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
  11666. 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
  11667. 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
  11668. 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
  11669. 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
  11670. 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
  11671. 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
  11672. 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
  11673. 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
  11674. 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  11675. 0xf9,0xfa
  11676. ];
  11677. function initQuantTables(sf){
  11678. var YQT = [
  11679. 16, 11, 10, 16, 24, 40, 51, 61,
  11680. 12, 12, 14, 19, 26, 58, 60, 55,
  11681. 14, 13, 16, 24, 40, 57, 69, 56,
  11682. 14, 17, 22, 29, 51, 87, 80, 62,
  11683. 18, 22, 37, 56, 68,109,103, 77,
  11684. 24, 35, 55, 64, 81,104,113, 92,
  11685. 49, 64, 78, 87,103,121,120,101,
  11686. 72, 92, 95, 98,112,100,103, 99
  11687. ];
  11688. for (var i = 0; i < 64; i++) {
  11689. var t = ffloor((YQT[i]*sf+50)/100);
  11690. if (t < 1) {
  11691. t = 1;
  11692. } else if (t > 255) {
  11693. t = 255;
  11694. }
  11695. YTable[ZigZag[i]] = t;
  11696. }
  11697. var UVQT = [
  11698. 17, 18, 24, 47, 99, 99, 99, 99,
  11699. 18, 21, 26, 66, 99, 99, 99, 99,
  11700. 24, 26, 56, 99, 99, 99, 99, 99,
  11701. 47, 66, 99, 99, 99, 99, 99, 99,
  11702. 99, 99, 99, 99, 99, 99, 99, 99,
  11703. 99, 99, 99, 99, 99, 99, 99, 99,
  11704. 99, 99, 99, 99, 99, 99, 99, 99,
  11705. 99, 99, 99, 99, 99, 99, 99, 99
  11706. ];
  11707. for (var j = 0; j < 64; j++) {
  11708. var u = ffloor((UVQT[j]*sf+50)/100);
  11709. if (u < 1) {
  11710. u = 1;
  11711. } else if (u > 255) {
  11712. u = 255;
  11713. }
  11714. UVTable[ZigZag[j]] = u;
  11715. }
  11716. var aasf = [
  11717. 1.0, 1.387039845, 1.306562965, 1.175875602,
  11718. 1.0, 0.785694958, 0.541196100, 0.275899379
  11719. ];
  11720. var k = 0;
  11721. for (var row = 0; row < 8; row++)
  11722. {
  11723. for (var col = 0; col < 8; col++)
  11724. {
  11725. fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  11726. fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  11727. k++;
  11728. }
  11729. }
  11730. }
  11731. function computeHuffmanTbl(nrcodes, std_table){
  11732. var codevalue = 0;
  11733. var pos_in_table = 0;
  11734. var HT = new Array();
  11735. for (var k = 1; k <= 16; k++) {
  11736. for (var j = 1; j <= nrcodes[k]; j++) {
  11737. HT[std_table[pos_in_table]] = [];
  11738. HT[std_table[pos_in_table]][0] = codevalue;
  11739. HT[std_table[pos_in_table]][1] = k;
  11740. pos_in_table++;
  11741. codevalue++;
  11742. }
  11743. codevalue*=2;
  11744. }
  11745. return HT;
  11746. }
  11747. function initHuffmanTbl()
  11748. {
  11749. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
  11750. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
  11751. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
  11752. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
  11753. }
  11754. function initCategoryNumber()
  11755. {
  11756. var nrlower = 1;
  11757. var nrupper = 2;
  11758. for (var cat = 1; cat <= 15; cat++) {
  11759. //Positive numbers
  11760. for (var nr = nrlower; nr<nrupper; nr++) {
  11761. category[32767+nr] = cat;
  11762. bitcode[32767+nr] = [];
  11763. bitcode[32767+nr][1] = cat;
  11764. bitcode[32767+nr][0] = nr;
  11765. }
  11766. //Negative numbers
  11767. for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
  11768. category[32767+nrneg] = cat;
  11769. bitcode[32767+nrneg] = [];
  11770. bitcode[32767+nrneg][1] = cat;
  11771. bitcode[32767+nrneg][0] = nrupper-1+nrneg;
  11772. }
  11773. nrlower <<= 1;
  11774. nrupper <<= 1;
  11775. }
  11776. }
  11777. function initRGBYUVTable() {
  11778. for(var i = 0; i < 256;i++) {
  11779. RGB_YUV_TABLE[i] = 19595 * i;
  11780. RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
  11781. RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
  11782. RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
  11783. RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
  11784. RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
  11785. RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
  11786. RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
  11787. }
  11788. }
  11789. // IO functions
  11790. function writeBits(bs)
  11791. {
  11792. var value = bs[0];
  11793. var posval = bs[1]-1;
  11794. while ( posval >= 0 ) {
  11795. if (value & (1 << posval) ) {
  11796. bytenew |= (1 << bytepos);
  11797. }
  11798. posval--;
  11799. bytepos--;
  11800. if (bytepos < 0) {
  11801. if (bytenew == 0xFF) {
  11802. writeByte(0xFF);
  11803. writeByte(0);
  11804. }
  11805. else {
  11806. writeByte(bytenew);
  11807. }
  11808. bytepos=7;
  11809. bytenew=0;
  11810. }
  11811. }
  11812. }
  11813. function writeByte(value)
  11814. {
  11815. //byteout.push(clt[value]); // write char directly instead of converting later
  11816. byteout.push(value);
  11817. }
  11818. function writeWord(value)
  11819. {
  11820. writeByte((value>>8)&0xFF);
  11821. writeByte((value )&0xFF);
  11822. }
  11823. // DCT & quantization core
  11824. function fDCTQuant(data, fdtbl)
  11825. {
  11826. var d0, d1, d2, d3, d4, d5, d6, d7;
  11827. /* Pass 1: process rows. */
  11828. var dataOff=0;
  11829. var i;
  11830. var I8 = 8;
  11831. var I64 = 64;
  11832. for (i=0; i<I8; ++i)
  11833. {
  11834. d0 = data[dataOff];
  11835. d1 = data[dataOff+1];
  11836. d2 = data[dataOff+2];
  11837. d3 = data[dataOff+3];
  11838. d4 = data[dataOff+4];
  11839. d5 = data[dataOff+5];
  11840. d6 = data[dataOff+6];
  11841. d7 = data[dataOff+7];
  11842. var tmp0 = d0 + d7;
  11843. var tmp7 = d0 - d7;
  11844. var tmp1 = d1 + d6;
  11845. var tmp6 = d1 - d6;
  11846. var tmp2 = d2 + d5;
  11847. var tmp5 = d2 - d5;
  11848. var tmp3 = d3 + d4;
  11849. var tmp4 = d3 - d4;
  11850. /* Even part */
  11851. var tmp10 = tmp0 + tmp3; /* phase 2 */
  11852. var tmp13 = tmp0 - tmp3;
  11853. var tmp11 = tmp1 + tmp2;
  11854. var tmp12 = tmp1 - tmp2;
  11855. data[dataOff] = tmp10 + tmp11; /* phase 3 */
  11856. data[dataOff+4] = tmp10 - tmp11;
  11857. var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
  11858. data[dataOff+2] = tmp13 + z1; /* phase 5 */
  11859. data[dataOff+6] = tmp13 - z1;
  11860. /* Odd part */
  11861. tmp10 = tmp4 + tmp5; /* phase 2 */
  11862. tmp11 = tmp5 + tmp6;
  11863. tmp12 = tmp6 + tmp7;
  11864. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  11865. var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
  11866. var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
  11867. var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
  11868. var z3 = tmp11 * 0.707106781; /* c4 */
  11869. var z11 = tmp7 + z3; /* phase 5 */
  11870. var z13 = tmp7 - z3;
  11871. data[dataOff+5] = z13 + z2; /* phase 6 */
  11872. data[dataOff+3] = z13 - z2;
  11873. data[dataOff+1] = z11 + z4;
  11874. data[dataOff+7] = z11 - z4;
  11875. dataOff += 8; /* advance pointer to next row */
  11876. }
  11877. /* Pass 2: process columns. */
  11878. dataOff = 0;
  11879. for (i=0; i<I8; ++i)
  11880. {
  11881. d0 = data[dataOff];
  11882. d1 = data[dataOff + 8];
  11883. d2 = data[dataOff + 16];
  11884. d3 = data[dataOff + 24];
  11885. d4 = data[dataOff + 32];
  11886. d5 = data[dataOff + 40];
  11887. d6 = data[dataOff + 48];
  11888. d7 = data[dataOff + 56];
  11889. var tmp0p2 = d0 + d7;
  11890. var tmp7p2 = d0 - d7;
  11891. var tmp1p2 = d1 + d6;
  11892. var tmp6p2 = d1 - d6;
  11893. var tmp2p2 = d2 + d5;
  11894. var tmp5p2 = d2 - d5;
  11895. var tmp3p2 = d3 + d4;
  11896. var tmp4p2 = d3 - d4;
  11897. /* Even part */
  11898. var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
  11899. var tmp13p2 = tmp0p2 - tmp3p2;
  11900. var tmp11p2 = tmp1p2 + tmp2p2;
  11901. var tmp12p2 = tmp1p2 - tmp2p2;
  11902. data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
  11903. data[dataOff+32] = tmp10p2 - tmp11p2;
  11904. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
  11905. data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
  11906. data[dataOff+48] = tmp13p2 - z1p2;
  11907. /* Odd part */
  11908. tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
  11909. tmp11p2 = tmp5p2 + tmp6p2;
  11910. tmp12p2 = tmp6p2 + tmp7p2;
  11911. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  11912. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
  11913. var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
  11914. var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
  11915. var z3p2 = tmp11p2 * 0.707106781; /* c4 */
  11916. var z11p2 = tmp7p2 + z3p2; /* phase 5 */
  11917. var z13p2 = tmp7p2 - z3p2;
  11918. data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
  11919. data[dataOff+24] = z13p2 - z2p2;
  11920. data[dataOff+ 8] = z11p2 + z4p2;
  11921. data[dataOff+56] = z11p2 - z4p2;
  11922. dataOff++; /* advance pointer to next column */
  11923. }
  11924. // Quantize/descale the coefficients
  11925. var fDCTQuant;
  11926. for (i=0; i<I64; ++i)
  11927. {
  11928. // Apply the quantization and scaling factor & Round to nearest integer
  11929. fDCTQuant = data[i]*fdtbl[i];
  11930. outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
  11931. //outputfDCTQuant[i] = fround(fDCTQuant);
  11932. }
  11933. return outputfDCTQuant;
  11934. }
  11935. function writeAPP0()
  11936. {
  11937. writeWord(0xFFE0); // marker
  11938. writeWord(16); // length
  11939. writeByte(0x4A); // J
  11940. writeByte(0x46); // F
  11941. writeByte(0x49); // I
  11942. writeByte(0x46); // F
  11943. writeByte(0); // = "JFIF",'\0'
  11944. writeByte(1); // versionhi
  11945. writeByte(1); // versionlo
  11946. writeByte(0); // xyunits
  11947. writeWord(1); // xdensity
  11948. writeWord(1); // ydensity
  11949. writeByte(0); // thumbnwidth
  11950. writeByte(0); // thumbnheight
  11951. }
  11952. function writeSOF0(width, height)
  11953. {
  11954. writeWord(0xFFC0); // marker
  11955. writeWord(17); // length, truecolor YUV JPG
  11956. writeByte(8); // precision
  11957. writeWord(height);
  11958. writeWord(width);
  11959. writeByte(3); // nrofcomponents
  11960. writeByte(1); // IdY
  11961. writeByte(0x11); // HVY
  11962. writeByte(0); // QTY
  11963. writeByte(2); // IdU
  11964. writeByte(0x11); // HVU
  11965. writeByte(1); // QTU
  11966. writeByte(3); // IdV
  11967. writeByte(0x11); // HVV
  11968. writeByte(1); // QTV
  11969. }
  11970. function writeDQT()
  11971. {
  11972. writeWord(0xFFDB); // marker
  11973. writeWord(132); // length
  11974. writeByte(0);
  11975. for (var i=0; i<64; i++) {
  11976. writeByte(YTable[i]);
  11977. }
  11978. writeByte(1);
  11979. for (var j=0; j<64; j++) {
  11980. writeByte(UVTable[j]);
  11981. }
  11982. }
  11983. function writeDHT()
  11984. {
  11985. writeWord(0xFFC4); // marker
  11986. writeWord(0x01A2); // length
  11987. writeByte(0); // HTYDCinfo
  11988. for (var i=0; i<16; i++) {
  11989. writeByte(std_dc_luminance_nrcodes[i+1]);
  11990. }
  11991. for (var j=0; j<=11; j++) {
  11992. writeByte(std_dc_luminance_values[j]);
  11993. }
  11994. writeByte(0x10); // HTYACinfo
  11995. for (var k=0; k<16; k++) {
  11996. writeByte(std_ac_luminance_nrcodes[k+1]);
  11997. }
  11998. for (var l=0; l<=161; l++) {
  11999. writeByte(std_ac_luminance_values[l]);
  12000. }
  12001. writeByte(1); // HTUDCinfo
  12002. for (var m=0; m<16; m++) {
  12003. writeByte(std_dc_chrominance_nrcodes[m+1]);
  12004. }
  12005. for (var n=0; n<=11; n++) {
  12006. writeByte(std_dc_chrominance_values[n]);
  12007. }
  12008. writeByte(0x11); // HTUACinfo
  12009. for (var o=0; o<16; o++) {
  12010. writeByte(std_ac_chrominance_nrcodes[o+1]);
  12011. }
  12012. for (var p=0; p<=161; p++) {
  12013. writeByte(std_ac_chrominance_values[p]);
  12014. }
  12015. }
  12016. function writeSOS()
  12017. {
  12018. writeWord(0xFFDA); // marker
  12019. writeWord(12); // length
  12020. writeByte(3); // nrofcomponents
  12021. writeByte(1); // IdY
  12022. writeByte(0); // HTY
  12023. writeByte(2); // IdU
  12024. writeByte(0x11); // HTU
  12025. writeByte(3); // IdV
  12026. writeByte(0x11); // HTV
  12027. writeByte(0); // Ss
  12028. writeByte(0x3f); // Se
  12029. writeByte(0); // Bf
  12030. }
  12031. function processDU(CDU, fdtbl, DC, HTDC, HTAC){
  12032. var EOB = HTAC[0x00];
  12033. var M16zeroes = HTAC[0xF0];
  12034. var pos;
  12035. var I16 = 16;
  12036. var I63 = 63;
  12037. var I64 = 64;
  12038. var DU_DCT = fDCTQuant(CDU, fdtbl);
  12039. //ZigZag reorder
  12040. for (var j=0;j<I64;++j) {
  12041. DU[ZigZag[j]]=DU_DCT[j];
  12042. }
  12043. var Diff = DU[0] - DC; DC = DU[0];
  12044. //Encode DC
  12045. if (Diff==0) {
  12046. writeBits(HTDC[0]); // Diff might be 0
  12047. } else {
  12048. pos = 32767+Diff;
  12049. writeBits(HTDC[category[pos]]);
  12050. writeBits(bitcode[pos]);
  12051. }
  12052. //Encode ACs
  12053. var end0pos = 63; // was const... which is crazy
  12054. for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {} //end0pos = first element in reverse order !=0
  12055. if ( end0pos == 0) {
  12056. writeBits(EOB);
  12057. return DC;
  12058. }
  12059. var i = 1;
  12060. var lng;
  12061. while ( i <= end0pos ) {
  12062. var startpos = i;
  12063. for (; (DU[i]==0) && (i<=end0pos); ++i) {}
  12064. var nrzeroes = i-startpos;
  12065. if ( nrzeroes >= I16 ) {
  12066. lng = nrzeroes>>4;
  12067. for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
  12068. writeBits(M16zeroes);
  12069. nrzeroes = nrzeroes&0xF;
  12070. }
  12071. pos = 32767+DU[i];
  12072. writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
  12073. writeBits(bitcode[pos]);
  12074. i++;
  12075. }
  12076. if ( end0pos != I63 ) {
  12077. writeBits(EOB);
  12078. }
  12079. return DC;
  12080. }
  12081. function initCharLookupTable(){
  12082. var sfcc = String.fromCharCode;
  12083. for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
  12084. clt[i] = sfcc(i);
  12085. }
  12086. }
  12087. this.encode = function(image,quality) // image data object
  12088. {
  12089. var time_start = new Date().getTime();
  12090. if(quality) setQuality(quality);
  12091. // Initialize bit writer
  12092. byteout = new Array();
  12093. bytenew=0;
  12094. bytepos=7;
  12095. // Add JPEG headers
  12096. writeWord(0xFFD8); // SOI
  12097. writeAPP0();
  12098. writeDQT();
  12099. writeSOF0(image.width,image.height);
  12100. writeDHT();
  12101. writeSOS();
  12102. // Encode 8x8 macroblocks
  12103. var DCY=0;
  12104. var DCU=0;
  12105. var DCV=0;
  12106. bytenew=0;
  12107. bytepos=7;
  12108. this.encode.displayName = "_encode_";
  12109. var imageData = image.data;
  12110. var width = image.width;
  12111. var height = image.height;
  12112. var quadWidth = width*4;
  12113. var x, y = 0;
  12114. var r, g, b;
  12115. var start,p, col,row,pos;
  12116. while(y < height){
  12117. x = 0;
  12118. while(x < quadWidth){
  12119. start = quadWidth * y + x;
  12120. p = start;
  12121. col = -1;
  12122. row = 0;
  12123. for(pos=0; pos < 64; pos++){
  12124. row = pos >> 3;// /8
  12125. col = ( pos & 7 ) * 4; // %8
  12126. p = start + ( row * quadWidth ) + col;
  12127. if(y+row >= height){ // padding bottom
  12128. p-= (quadWidth*(y+1+row-height));
  12129. }
  12130. if(x+col >= quadWidth){ // padding right
  12131. p-= ((x+col) - quadWidth +4);
  12132. }
  12133. r = imageData[ p++ ];
  12134. g = imageData[ p++ ];
  12135. b = imageData[ p++ ];
  12136. /* // calculate YUV values dynamically
  12137. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  12138. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  12139. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  12140. */
  12141. // use lookup table (slightly faster)
  12142. YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
  12143. UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
  12144. VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
  12145. }
  12146. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  12147. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  12148. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  12149. x+=32;
  12150. }
  12151. y+=8;
  12152. }
  12153. ////////////////////////////////////////////////////////////////
  12154. // Do the bit alignment of the EOI marker
  12155. if ( bytepos >= 0 ) {
  12156. var fillbits = [];
  12157. fillbits[1] = bytepos+1;
  12158. fillbits[0] = (1<<(bytepos+1))-1;
  12159. writeBits(fillbits);
  12160. }
  12161. writeWord(0xFFD9); //EOI
  12162. return new Uint8Array(byteout);
  12163. //return new Buffer(byteout);
  12164. var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
  12165. byteout = [];
  12166. // benchmarking
  12167. var duration = new Date().getTime() - time_start;
  12168. //console.log('Encoding time: '+ duration + 'ms');
  12169. //
  12170. return jpegDataUri
  12171. };
  12172. function setQuality(quality){
  12173. if (quality <= 0) {
  12174. quality = 1;
  12175. }
  12176. if (quality > 100) {
  12177. quality = 100;
  12178. }
  12179. if(currentQuality == quality) return // don't recalc if unchanged
  12180. var sf = 0;
  12181. if (quality < 50) {
  12182. sf = Math.floor(5000 / quality);
  12183. } else {
  12184. sf = Math.floor(200 - quality*2);
  12185. }
  12186. initQuantTables(sf);
  12187. currentQuality = quality;
  12188. //console.log('Quality set to: '+quality +'%');
  12189. }
  12190. function init(){
  12191. var time_start = new Date().getTime();
  12192. if(!quality) quality = 50;
  12193. // Create tables
  12194. initCharLookupTable();
  12195. initHuffmanTbl();
  12196. initCategoryNumber();
  12197. initRGBYUVTable();
  12198. setQuality(quality);
  12199. var duration = new Date().getTime() - time_start;
  12200. //console.log('Initialization '+ duration + 'ms');
  12201. }
  12202. init();
  12203. }
  12204. try { module.exports = JPEGEncoder; } catch(e) { } // CommonJS.
  12205. /**
  12206. * @author shaozilee
  12207. *
  12208. * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
  12209. *
  12210. */
  12211. function BmpDecoder(buffer,is_with_alpha) {
  12212. this.pos = 0;
  12213. this.buffer = buffer;
  12214. this.datav = new DataView(buffer.buffer);
  12215. this.is_with_alpha = !!is_with_alpha;
  12216. this.bottom_up = true;
  12217. this.flag = String.fromCharCode(this.buffer[0]) + String.fromCharCode(this.buffer[1]);
  12218. this.pos += 2;
  12219. if (["BM","BA", "CI", "CP", "IC", "PT"].indexOf(this.flag) === -1) throw new Error("Invalid BMP File");
  12220. this.parseHeader();
  12221. this.parseBGR();
  12222. }
  12223. BmpDecoder.prototype.parseHeader = function() {
  12224. this.fileSize = this.datav.getUint32(this.pos, true);
  12225. this.pos += 4;
  12226. this.reserved = this.datav.getUint32(this.pos, true);
  12227. this.pos += 4;
  12228. this.offset = this.datav.getUint32(this.pos, true);
  12229. this.pos += 4;
  12230. this.headerSize = this.datav.getUint32(this.pos, true);
  12231. this.pos += 4;
  12232. this.width = this.datav.getUint32(this.pos, true);
  12233. this.pos += 4;
  12234. this.height = this.datav.getInt32(this.pos, true); this.pos += 4;
  12235. this.planes = this.datav.getUint16(this.pos, true);
  12236. this.pos += 2;
  12237. this.bitPP = this.datav.getUint16(this.pos, true);
  12238. this.pos += 2;
  12239. this.compress = this.datav.getUint32(this.pos, true);
  12240. this.pos += 4;
  12241. this.rawSize = this.datav.getUint32(this.pos, true);
  12242. this.pos += 4;
  12243. this.hr = this.datav.getUint32(this.pos, true);
  12244. this.pos += 4;
  12245. this.vr = this.datav.getUint32(this.pos, true);
  12246. this.pos += 4;
  12247. this.colors = this.datav.getUint32(this.pos, true);
  12248. this.pos += 4;
  12249. this.importantColors = this.datav.getUint32(this.pos, true);
  12250. this.pos += 4;
  12251. if(this.bitPP === 16 && this.is_with_alpha){
  12252. this.bitPP = 15;
  12253. }
  12254. if (this.bitPP < 15) {
  12255. var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
  12256. this.palette = new Array(len);
  12257. for (var i = 0; i < len; i++) {
  12258. var blue = this.datav.getUint8(this.pos++, true); var green = this.datav.getUint8(this.pos++, true); var red = this.datav.getUint8(this.pos++, true); var quad = this.datav.getUint8(this.pos++, true); this.palette[i] = {
  12259. red: red,
  12260. green: green,
  12261. blue: blue,
  12262. quad: quad
  12263. };
  12264. }
  12265. }
  12266. if(this.height < 0) {
  12267. this.height *= -1;
  12268. this.bottom_up = false;
  12269. }
  12270. };
  12271. BmpDecoder.prototype.parseBGR = function() {
  12272. this.pos = this.offset;
  12273. try {
  12274. var bitn = "bit" + this.bitPP;
  12275. var len = this.width * this.height * 4;
  12276. this.data = new Uint8Array(len);
  12277. this[bitn]();
  12278. } catch (e) {
  12279. console.log("bit decode error:" + e);
  12280. }
  12281. };
  12282. BmpDecoder.prototype.bit1 = function() {
  12283. var xlen = Math.ceil(this.width / 8);
  12284. var mode = xlen%4;
  12285. var y = this.height >= 0 ? this.height - 1 : -this.height;
  12286. for (var y = this.height - 1; y >= 0; y--) {
  12287. var line = this.bottom_up ? y : this.height - 1 - y;
  12288. for (var x = 0; x < xlen; x++) {
  12289. var b = this.datav.getUint8(this.pos++, true); var location = line * this.width * 4 + x*8*4;
  12290. for (var i = 0; i < 8; i++) {
  12291. if(x*8+i<this.width){
  12292. var rgb = this.palette[((b>>(7-i))&0x1)];
  12293. this.data[location+i*4] = rgb.blue;
  12294. this.data[location+i*4 + 1] = rgb.green;
  12295. this.data[location+i*4 + 2] = rgb.red;
  12296. this.data[location+i*4 + 3] = 0xFF;
  12297. }else{
  12298. break;
  12299. }
  12300. }
  12301. }
  12302. if (mode != 0){
  12303. this.pos+=(4 - mode);
  12304. }
  12305. }
  12306. };
  12307. BmpDecoder.prototype.bit4 = function() {
  12308. var xlen = Math.ceil(this.width/2);
  12309. var mode = xlen%4;
  12310. for (var y = this.height - 1; y >= 0; y--) {
  12311. var line = this.bottom_up ? y : this.height - 1 - y;
  12312. for (var x = 0; x < xlen; x++) {
  12313. var b = this.datav.getUint8(this.pos++, true); var location = line * this.width * 4 + x*2*4;
  12314. var before = b>>4;
  12315. var after = b&0x0F;
  12316. var rgb = this.palette[before];
  12317. this.data[location] = rgb.blue;
  12318. this.data[location + 1] = rgb.green;
  12319. this.data[location + 2] = rgb.red;
  12320. this.data[location + 3] = 0xFF;
  12321. if(x*2+1>=this.width)break;
  12322. rgb = this.palette[after];
  12323. this.data[location+4] = rgb.blue;
  12324. this.data[location+4 + 1] = rgb.green;
  12325. this.data[location+4 + 2] = rgb.red;
  12326. this.data[location+4 + 3] = 0xFF;
  12327. }
  12328. if (mode != 0){
  12329. this.pos+=(4 - mode);
  12330. }
  12331. }
  12332. };
  12333. BmpDecoder.prototype.bit8 = function() {
  12334. var mode = this.width%4;
  12335. for (var y = this.height - 1; y >= 0; y--) {
  12336. var line = this.bottom_up ? y : this.height - 1 - y;
  12337. for (var x = 0; x < this.width; x++) {
  12338. var b = this.datav.getUint8(this.pos++, true); var location = line * this.width * 4 + x*4;
  12339. if(b < this.palette.length) {
  12340. var rgb = this.palette[b];
  12341. this.data[location] = rgb.red;
  12342. this.data[location + 1] = rgb.green;
  12343. this.data[location + 2] = rgb.blue;
  12344. this.data[location + 3] = 0xFF;
  12345. } else {
  12346. this.data[location] = 0xFF;
  12347. this.data[location + 1] = 0xFF;
  12348. this.data[location + 2] = 0xFF;
  12349. this.data[location + 3] = 0xFF;
  12350. }
  12351. }
  12352. if (mode != 0){
  12353. this.pos+=(4 - mode);
  12354. }
  12355. }
  12356. };
  12357. BmpDecoder.prototype.bit15 = function() {
  12358. var dif_w =this.width % 3;
  12359. var _11111 = parseInt("11111", 2),_1_5 = _11111;
  12360. for (var y = this.height - 1; y >= 0; y--) {
  12361. var line = this.bottom_up ? y : this.height - 1 - y;
  12362. for (var x = 0; x < this.width; x++) {
  12363. var B = this.datav.getUint16(this.pos, true);
  12364. this.pos+=2;
  12365. var blue = (B & _1_5) / _1_5 * 255 | 0;
  12366. var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0;
  12367. var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
  12368. var alpha = (B>>15)?0xFF:0x00;
  12369. var location = line * this.width * 4 + x * 4;
  12370. this.data[location] = red;
  12371. this.data[location + 1] = green;
  12372. this.data[location + 2] = blue;
  12373. this.data[location + 3] = alpha;
  12374. }
  12375. //skip extra bytes
  12376. this.pos += dif_w;
  12377. }
  12378. };
  12379. BmpDecoder.prototype.bit16 = function() {
  12380. var dif_w =this.width % 3;
  12381. var _11111 = parseInt("11111", 2),_1_5 = _11111;
  12382. var _111111 = parseInt("111111", 2),_1_6 = _111111;
  12383. for (var y = this.height - 1; y >= 0; y--) {
  12384. var line = this.bottom_up ? y : this.height - 1 - y;
  12385. for (var x = 0; x < this.width; x++) {
  12386. var B = this.datav.getUint16(this.pos, true);
  12387. this.pos+=2;
  12388. var alpha = 0xFF;
  12389. var blue = (B & _1_5) / _1_5 * 255 | 0;
  12390. var green = (B >> 5 & _1_6 ) / _1_6 * 255 | 0;
  12391. var red = (B >> 11) / _1_5 * 255 | 0;
  12392. var location = line * this.width * 4 + x * 4;
  12393. this.data[location] = red;
  12394. this.data[location + 1] = green;
  12395. this.data[location + 2] = blue;
  12396. this.data[location + 3] = alpha;
  12397. }
  12398. //skip extra bytes
  12399. this.pos += dif_w;
  12400. }
  12401. };
  12402. BmpDecoder.prototype.bit24 = function() {
  12403. //when height > 0
  12404. for (var y = this.height - 1; y >= 0; y--) {
  12405. var line = this.bottom_up ? y : this.height - 1 - y;
  12406. for (var x = 0; x < this.width; x++) {
  12407. var blue = this.datav.getUint8(this.pos++, true); var green = this.datav.getUint8(this.pos++, true); var red = this.datav.getUint8(this.pos++, true); var location = line * this.width * 4 + x * 4;
  12408. this.data[location] = red;
  12409. this.data[location + 1] = green;
  12410. this.data[location + 2] = blue;
  12411. this.data[location + 3] = 0xFF;
  12412. }
  12413. //skip extra bytes
  12414. this.pos += (this.width % 4);
  12415. }
  12416. };
  12417. /**
  12418. * add 32bit decode func
  12419. * @author soubok
  12420. */
  12421. BmpDecoder.prototype.bit32 = function() {
  12422. //when height > 0
  12423. for (var y = this.height - 1; y >= 0; y--) {
  12424. var line = this.bottom_up ? y : this.height - 1 - y;
  12425. for (var x = 0; x < this.width; x++) {
  12426. var blue = this.datav.getUint8(this.pos++, true); var green = this.datav.getUint8(this.pos++, true); var red = this.datav.getUint8(this.pos++, true); var alpha = this.datav.getUint8(this.pos++, true); var location = line * this.width * 4 + x * 4;
  12427. this.data[location] = red;
  12428. this.data[location + 1] = green;
  12429. this.data[location + 2] = blue;
  12430. this.data[location + 3] = alpha;
  12431. }
  12432. //skip extra bytes
  12433. //this.pos += (this.width % 4);
  12434. }
  12435. };
  12436. BmpDecoder.prototype.getData = function() {
  12437. return this.data;
  12438. };
  12439. try {
  12440. module.exports = function(bmpData) {
  12441. var decoder = new BmpDecoder(bmpData);
  12442. return {
  12443. data: decoder.getData(),
  12444. width: decoder.width,
  12445. height: decoder.height
  12446. };
  12447. };
  12448. } catch(e) { } // CommonJS.
  12449. /*
  12450. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  12451. Redistribution and use in source and binary forms, with or without
  12452. modification, are permitted provided that the following conditions are met:
  12453. 1. Redistributions of source code must retain the above copyright notice,
  12454. this list of conditions and the following disclaimer.
  12455. 2. Redistributions in binary form must reproduce the above copyright
  12456. notice, this list of conditions and the following disclaimer in
  12457. the documentation and/or other materials provided with the distribution.
  12458. 3. The names of the authors may not be used to endorse or promote products
  12459. derived from this software without specific prior written permission.
  12460. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  12461. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12462. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  12463. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  12464. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  12465. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  12466. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  12467. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  12468. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  12469. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  12470. */
  12471. /*
  12472. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  12473. * JZlib is based on zlib-1.1.3, so all credit should go authors
  12474. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  12475. * and contributors of zlib.
  12476. */
  12477. (function(global) {
  12478. // Global
  12479. var MAX_BITS = 15;
  12480. var D_CODES = 30;
  12481. var BL_CODES = 19;
  12482. var LENGTH_CODES = 29;
  12483. var LITERALS = 256;
  12484. var L_CODES = (LITERALS + 1 + LENGTH_CODES);
  12485. var HEAP_SIZE = (2 * L_CODES + 1);
  12486. var END_BLOCK = 256;
  12487. // Bit length codes must not exceed MAX_BL_BITS bits
  12488. var MAX_BL_BITS = 7;
  12489. // repeat previous bit length 3-6 times (2 bits of repeat count)
  12490. var REP_3_6 = 16;
  12491. // repeat a zero length 3-10 times (3 bits of repeat count)
  12492. var REPZ_3_10 = 17;
  12493. // repeat a zero length 11-138 times (7 bits of repeat count)
  12494. var REPZ_11_138 = 18;
  12495. // The lengths of the bit length codes are sent in order of decreasing
  12496. // probability, to avoid transmitting the lengths for unused bit
  12497. // length codes.
  12498. var Buf_size = 8 * 2;
  12499. // JZlib version : "1.0.2"
  12500. var Z_DEFAULT_COMPRESSION = -1;
  12501. // compression strategy
  12502. var Z_FILTERED = 1;
  12503. var Z_HUFFMAN_ONLY = 2;
  12504. var Z_DEFAULT_STRATEGY = 0;
  12505. var Z_NO_FLUSH = 0;
  12506. var Z_PARTIAL_FLUSH = 1;
  12507. var Z_FULL_FLUSH = 3;
  12508. var Z_FINISH = 4;
  12509. var Z_OK = 0;
  12510. var Z_STREAM_END = 1;
  12511. var Z_NEED_DICT = 2;
  12512. var Z_STREAM_ERROR = -2;
  12513. var Z_DATA_ERROR = -3;
  12514. var Z_BUF_ERROR = -5;
  12515. // Tree
  12516. // see definition of array dist_code below
  12517. 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,
  12518. 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,
  12519. 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,
  12520. 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,
  12521. 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,
  12522. 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,
  12523. 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,
  12524. 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,
  12525. 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,
  12526. 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,
  12527. 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,
  12528. 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,
  12529. 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,
  12530. 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 ];
  12531. function Tree() {
  12532. var that = this;
  12533. // dyn_tree; // the dynamic tree
  12534. // max_code; // largest code with non zero frequency
  12535. // stat_desc; // the corresponding static tree
  12536. // Compute the optimal bit lengths for a tree and update the total bit
  12537. // length
  12538. // for the current block.
  12539. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  12540. // above are the tree nodes sorted by increasing frequency.
  12541. // OUT assertions: the field len is set to the optimal bit length, the
  12542. // array bl_count contains the frequencies for each bit length.
  12543. // The length opt_len is updated; static_len is also updated if stree is
  12544. // not null.
  12545. function gen_bitlen(s) {
  12546. var tree = that.dyn_tree;
  12547. var stree = that.stat_desc.static_tree;
  12548. var extra = that.stat_desc.extra_bits;
  12549. var base = that.stat_desc.extra_base;
  12550. var max_length = that.stat_desc.max_length;
  12551. var h; // heap index
  12552. var n, m; // iterate over the tree elements
  12553. var bits; // bit length
  12554. var xbits; // extra bits
  12555. var f; // frequency
  12556. var overflow = 0; // number of elements with bit length too large
  12557. for (bits = 0; bits <= MAX_BITS; bits++)
  12558. s.bl_count[bits] = 0;
  12559. // In a first pass, compute the optimal bit lengths (which may
  12560. // overflow in the case of the bit length tree).
  12561. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  12562. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  12563. n = s.heap[h];
  12564. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  12565. if (bits > max_length) {
  12566. bits = max_length;
  12567. overflow++;
  12568. }
  12569. tree[n * 2 + 1] = bits;
  12570. // We overwrite tree[n*2+1] which is no longer needed
  12571. if (n > that.max_code)
  12572. continue; // not a leaf node
  12573. s.bl_count[bits]++;
  12574. xbits = 0;
  12575. if (n >= base)
  12576. xbits = extra[n - base];
  12577. f = tree[n * 2];
  12578. s.opt_len += f * (bits + xbits);
  12579. if (stree)
  12580. s.static_len += f * (stree[n * 2 + 1] + xbits);
  12581. }
  12582. if (overflow === 0)
  12583. return;
  12584. // This happens for example on obj2 and pic of the Calgary corpus
  12585. // Find the first bit length which could increase:
  12586. do {
  12587. bits = max_length - 1;
  12588. while (s.bl_count[bits] === 0)
  12589. bits--;
  12590. s.bl_count[bits]--; // move one leaf down the tree
  12591. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  12592. s.bl_count[max_length]--;
  12593. // The brother of the overflow item also moves one step up,
  12594. // but this does not affect bl_count[max_length]
  12595. overflow -= 2;
  12596. } while (overflow > 0);
  12597. for (bits = max_length; bits !== 0; bits--) {
  12598. n = s.bl_count[bits];
  12599. while (n !== 0) {
  12600. m = s.heap[--h];
  12601. if (m > that.max_code)
  12602. continue;
  12603. if (tree[m * 2 + 1] != bits) {
  12604. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  12605. tree[m * 2 + 1] = bits;
  12606. }
  12607. n--;
  12608. }
  12609. }
  12610. }
  12611. // Reverse the first len bits of a code, using straightforward code (a
  12612. // faster
  12613. // method would use a table)
  12614. // IN assertion: 1 <= len <= 15
  12615. function bi_reverse(code, // the value to invert
  12616. len // its bit length
  12617. ) {
  12618. var res = 0;
  12619. do {
  12620. res |= code & 1;
  12621. code >>>= 1;
  12622. res <<= 1;
  12623. } while (--len > 0);
  12624. return res >>> 1;
  12625. }
  12626. // Generate the codes for a given tree and bit counts (which need not be
  12627. // optimal).
  12628. // IN assertion: the array bl_count contains the bit length statistics for
  12629. // the given tree and the field len is set for all tree elements.
  12630. // OUT assertion: the field code is set for all tree elements of non
  12631. // zero code length.
  12632. function gen_codes(tree, // the tree to decorate
  12633. max_code, // largest code with non zero frequency
  12634. bl_count // number of codes at each bit length
  12635. ) {
  12636. var next_code = []; // next code value for each
  12637. // bit length
  12638. var code = 0; // running code value
  12639. var bits; // bit index
  12640. var n; // code index
  12641. var len;
  12642. // The distribution counts are first used to generate the code values
  12643. // without bit reversal.
  12644. for (bits = 1; bits <= MAX_BITS; bits++) {
  12645. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  12646. }
  12647. // Check that the bit counts in bl_count are consistent. The last code
  12648. // must be all ones.
  12649. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  12650. // "inconsistent bit counts");
  12651. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  12652. for (n = 0; n <= max_code; n++) {
  12653. len = tree[n * 2 + 1];
  12654. if (len === 0)
  12655. continue;
  12656. // Now reverse the bits
  12657. tree[n * 2] = bi_reverse(next_code[len]++, len);
  12658. }
  12659. }
  12660. // Construct one Huffman tree and assigns the code bit strings and lengths.
  12661. // Update the total bit length for the current block.
  12662. // IN assertion: the field freq is set for all tree elements.
  12663. // OUT assertions: the fields len and code are set to the optimal bit length
  12664. // and corresponding code. The length opt_len is updated; static_len is
  12665. // also updated if stree is not null. The field max_code is set.
  12666. that.build_tree = function(s) {
  12667. var tree = that.dyn_tree;
  12668. var stree = that.stat_desc.static_tree;
  12669. var elems = that.stat_desc.elems;
  12670. var n, m; // iterate over heap elements
  12671. var max_code = -1; // largest code with non zero frequency
  12672. var node; // new node being created
  12673. // Construct the initial heap, with least frequent element in
  12674. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  12675. // heap[0] is not used.
  12676. s.heap_len = 0;
  12677. s.heap_max = HEAP_SIZE;
  12678. for (n = 0; n < elems; n++) {
  12679. if (tree[n * 2] !== 0) {
  12680. s.heap[++s.heap_len] = max_code = n;
  12681. s.depth[n] = 0;
  12682. } else {
  12683. tree[n * 2 + 1] = 0;
  12684. }
  12685. }
  12686. // The pkzip format requires that at least one distance code exists,
  12687. // and that at least one bit should be sent even if there is only one
  12688. // possible code. So to avoid special checks later on we force at least
  12689. // two codes of non zero frequency.
  12690. while (s.heap_len < 2) {
  12691. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  12692. tree[node * 2] = 1;
  12693. s.depth[node] = 0;
  12694. s.opt_len--;
  12695. if (stree)
  12696. s.static_len -= stree[node * 2 + 1];
  12697. // node is 0 or 1 so it does not have extra bits
  12698. }
  12699. that.max_code = max_code;
  12700. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  12701. // establish sub-heaps of increasing lengths:
  12702. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  12703. s.pqdownheap(tree, n);
  12704. // Construct the Huffman tree by repeatedly combining the least two
  12705. // frequent nodes.
  12706. node = elems; // next internal node of the tree
  12707. do {
  12708. // n = node of least frequency
  12709. n = s.heap[1];
  12710. s.heap[1] = s.heap[s.heap_len--];
  12711. s.pqdownheap(tree, 1);
  12712. m = s.heap[1]; // m = node of next least frequency
  12713. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  12714. s.heap[--s.heap_max] = m;
  12715. // Create a new node father of n and m
  12716. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  12717. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  12718. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  12719. // and insert the new node in the heap
  12720. s.heap[1] = node++;
  12721. s.pqdownheap(tree, 1);
  12722. } while (s.heap_len >= 2);
  12723. s.heap[--s.heap_max] = s.heap[1];
  12724. // At this point, the fields freq and dad are set. We can now
  12725. // generate the bit lengths.
  12726. gen_bitlen(s);
  12727. // The field len is now set, we can generate the bit codes
  12728. gen_codes(tree, that.max_code, s.bl_count);
  12729. };
  12730. }
  12731. 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,
  12732. 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,
  12733. 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,
  12734. 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,
  12735. 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,
  12736. 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,
  12737. 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 ];
  12738. 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 ];
  12739. 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,
  12740. 24576 ];
  12741. // Mapping from a distance to a distance code. dist is the distance - 1 and
  12742. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  12743. // used.
  12744. Tree.d_code = function(dist) {
  12745. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  12746. };
  12747. // extra bits for each length code
  12748. 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 ];
  12749. // extra bits for each distance code
  12750. 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 ];
  12751. // extra bits for each bit length code
  12752. Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
  12753. Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  12754. // StaticTree
  12755. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  12756. var that = this;
  12757. that.static_tree = static_tree;
  12758. that.extra_bits = extra_bits;
  12759. that.extra_base = extra_base;
  12760. that.elems = elems;
  12761. that.max_length = max_length;
  12762. }
  12763. 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,
  12764. 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,
  12765. 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,
  12766. 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,
  12767. 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,
  12768. 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,
  12769. 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,
  12770. 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,
  12771. 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,
  12772. 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,
  12773. 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,
  12774. 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,
  12775. 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,
  12776. 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,
  12777. 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,
  12778. 99, 8, 227, 8 ];
  12779. 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,
  12780. 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
  12781. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  12782. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  12783. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  12784. // Deflate
  12785. var MAX_MEM_LEVEL = 9;
  12786. var DEF_MEM_LEVEL = 8;
  12787. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  12788. var that = this;
  12789. that.good_length = good_length;
  12790. that.max_lazy = max_lazy;
  12791. that.nice_length = nice_length;
  12792. that.max_chain = max_chain;
  12793. that.func = func;
  12794. }
  12795. var STORED = 0;
  12796. var FAST = 1;
  12797. var SLOW = 2;
  12798. 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),
  12799. 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),
  12800. new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
  12801. var z_errmsg = [ "need dictionary", // Z_NEED_DICT
  12802. // 2
  12803. "stream end", // Z_STREAM_END 1
  12804. "", // Z_OK 0
  12805. "", // Z_ERRNO (-1)
  12806. "stream error", // Z_STREAM_ERROR (-2)
  12807. "data error", // Z_DATA_ERROR (-3)
  12808. "", // Z_MEM_ERROR (-4)
  12809. "buffer error", // Z_BUF_ERROR (-5)
  12810. "",// Z_VERSION_ERROR (-6)
  12811. "" ];
  12812. // block not completed, need more input or more output
  12813. var NeedMore = 0;
  12814. // block flush performed
  12815. var BlockDone = 1;
  12816. // finish started, need only more output at next deflate
  12817. var FinishStarted = 2;
  12818. // finish done, accept no more input or output
  12819. var FinishDone = 3;
  12820. // preset dictionary flag in zlib header
  12821. var PRESET_DICT = 0x20;
  12822. var INIT_STATE = 42;
  12823. var BUSY_STATE = 113;
  12824. var FINISH_STATE = 666;
  12825. // The deflate compression method
  12826. var Z_DEFLATED = 8;
  12827. var STORED_BLOCK = 0;
  12828. var STATIC_TREES = 1;
  12829. var DYN_TREES = 2;
  12830. var MIN_MATCH = 3;
  12831. var MAX_MATCH = 258;
  12832. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  12833. function smaller(tree, n, m, depth) {
  12834. var tn2 = tree[n * 2];
  12835. var tm2 = tree[m * 2];
  12836. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  12837. }
  12838. function Deflate() {
  12839. var that = this;
  12840. var strm; // pointer back to this zlib stream
  12841. var status; // as the name implies
  12842. // pending_buf; // output still pending
  12843. var pending_buf_size; // size of pending_buf
  12844. var last_flush; // value of flush param for previous deflate call
  12845. var w_size; // LZ77 window size (32K by default)
  12846. var w_bits; // log2(w_size) (8..16)
  12847. var w_mask; // w_size - 1
  12848. var window;
  12849. // Sliding window. Input bytes are read into the second half of the window,
  12850. // and move to the first half later to keep a dictionary of at least wSize
  12851. // bytes. With this organization, matches are limited to a distance of
  12852. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  12853. // performed with a length multiple of the block size. Also, it limits
  12854. // the window size to 64K, which is quite useful on MSDOS.
  12855. // To do: use the user input buffer as sliding window.
  12856. var window_size;
  12857. // Actual size of window: 2*wSize, except when the user input buffer
  12858. // is directly used as sliding window.
  12859. var prev;
  12860. // Link to older string with same hash index. To limit the size of this
  12861. // array to 64K, this link is maintained only for the last 32K strings.
  12862. // An index in this array is thus a window index modulo 32K.
  12863. var head; // Heads of the hash chains or NIL.
  12864. var ins_h; // hash index of string to be inserted
  12865. var hash_size; // number of elements in hash table
  12866. var hash_bits; // log2(hash_size)
  12867. var hash_mask; // hash_size-1
  12868. // Number of bits by which ins_h must be shifted at each input
  12869. // step. It must be such that after MIN_MATCH steps, the oldest
  12870. // byte no longer takes part in the hash key, that is:
  12871. // hash_shift * MIN_MATCH >= hash_bits
  12872. var hash_shift;
  12873. // Window position at the beginning of the current output block. Gets
  12874. // negative when the window is moved backwards.
  12875. var block_start;
  12876. var match_length; // length of best match
  12877. var prev_match; // previous match
  12878. var match_available; // set if previous match exists
  12879. var strstart; // start of string to insert
  12880. var match_start; // start of matching string
  12881. var lookahead; // number of valid bytes ahead in window
  12882. // Length of the best match at previous step. Matches not greater than this
  12883. // are discarded. This is used in the lazy match evaluation.
  12884. var prev_length;
  12885. // To speed up deflation, hash chains are never searched beyond this
  12886. // length. A higher limit improves compression ratio but degrades the speed.
  12887. var max_chain_length;
  12888. // Attempt to find a better match only when the current match is strictly
  12889. // smaller than this value. This mechanism is used only for compression
  12890. // levels >= 4.
  12891. var max_lazy_match;
  12892. // Insert new strings in the hash table only if the match length is not
  12893. // greater than this length. This saves time but degrades compression.
  12894. // max_insert_length is used only for compression levels <= 3.
  12895. var level; // compression level (1..9)
  12896. var strategy; // favor or force Huffman coding
  12897. // Use a faster search when the previous match is longer than this
  12898. var good_match;
  12899. // Stop searching when current match exceeds this
  12900. var nice_match;
  12901. var dyn_ltree; // literal and length tree
  12902. var dyn_dtree; // distance tree
  12903. var bl_tree; // Huffman tree for bit lengths
  12904. var l_desc = new Tree(); // desc for literal tree
  12905. var d_desc = new Tree(); // desc for distance tree
  12906. var bl_desc = new Tree(); // desc for bit length tree
  12907. // that.heap_len; // number of elements in the heap
  12908. // that.heap_max; // element of largest frequency
  12909. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  12910. // The same heap array is used to build all trees.
  12911. // Depth of each subtree used as tie breaker for trees of equal frequency
  12912. that.depth = [];
  12913. var l_buf; // index for literals or lengths */
  12914. // Size of match buffer for literals/lengths. There are 4 reasons for
  12915. // limiting lit_bufsize to 64K:
  12916. // - frequencies can be kept in 16 bit counters
  12917. // - if compression is not successful for the first block, all input
  12918. // data is still in the window so we can still emit a stored block even
  12919. // when input comes from standard input. (This can also be done for
  12920. // all blocks if lit_bufsize is not greater than 32K.)
  12921. // - if compression is not successful for a file smaller than 64K, we can
  12922. // even emit a stored file instead of a stored block (saving 5 bytes).
  12923. // This is applicable only for zip (not gzip or zlib).
  12924. // - creating new Huffman trees less frequently may not provide fast
  12925. // adaptation to changes in the input data statistics. (Take for
  12926. // example a binary file with poorly compressible code followed by
  12927. // a highly compressible string table.) Smaller buffer sizes give
  12928. // fast adaptation but have of course the overhead of transmitting
  12929. // trees more frequently.
  12930. // - I can't count above 4
  12931. var lit_bufsize;
  12932. var last_lit; // running index in l_buf
  12933. // Buffer for distances. To simplify the code, d_buf and l_buf have
  12934. // the same number of elements. To use different lengths, an extra flag
  12935. // array would be necessary.
  12936. var d_buf; // index of pendig_buf
  12937. // that.opt_len; // bit length of current block with optimal trees
  12938. // that.static_len; // bit length of current block with static trees
  12939. var matches; // number of string matches in current block
  12940. var last_eob_len; // bit length of EOB code for last block
  12941. // Output buffer. bits are inserted starting at the bottom (least
  12942. // significant bits).
  12943. var bi_buf;
  12944. // Number of valid bits in bi_buf. All bits above the last valid bit
  12945. // are always zero.
  12946. var bi_valid;
  12947. // number of codes at each bit length for an optimal tree
  12948. that.bl_count = [];
  12949. // heap used to build the Huffman trees
  12950. that.heap = [];
  12951. dyn_ltree = [];
  12952. dyn_dtree = [];
  12953. bl_tree = [];
  12954. function lm_init() {
  12955. var i;
  12956. window_size = 2 * w_size;
  12957. head[hash_size - 1] = 0;
  12958. for (i = 0; i < hash_size - 1; i++) {
  12959. head[i] = 0;
  12960. }
  12961. // Set the default configuration parameters:
  12962. max_lazy_match = config_table[level].max_lazy;
  12963. good_match = config_table[level].good_length;
  12964. nice_match = config_table[level].nice_length;
  12965. max_chain_length = config_table[level].max_chain;
  12966. strstart = 0;
  12967. block_start = 0;
  12968. lookahead = 0;
  12969. match_length = prev_length = MIN_MATCH - 1;
  12970. match_available = 0;
  12971. ins_h = 0;
  12972. }
  12973. function init_block() {
  12974. var i;
  12975. // Initialize the trees.
  12976. for (i = 0; i < L_CODES; i++)
  12977. dyn_ltree[i * 2] = 0;
  12978. for (i = 0; i < D_CODES; i++)
  12979. dyn_dtree[i * 2] = 0;
  12980. for (i = 0; i < BL_CODES; i++)
  12981. bl_tree[i * 2] = 0;
  12982. dyn_ltree[END_BLOCK * 2] = 1;
  12983. that.opt_len = that.static_len = 0;
  12984. last_lit = matches = 0;
  12985. }
  12986. // Initialize the tree data structures for a new zlib stream.
  12987. function tr_init() {
  12988. l_desc.dyn_tree = dyn_ltree;
  12989. l_desc.stat_desc = StaticTree.static_l_desc;
  12990. d_desc.dyn_tree = dyn_dtree;
  12991. d_desc.stat_desc = StaticTree.static_d_desc;
  12992. bl_desc.dyn_tree = bl_tree;
  12993. bl_desc.stat_desc = StaticTree.static_bl_desc;
  12994. bi_buf = 0;
  12995. bi_valid = 0;
  12996. last_eob_len = 8; // enough lookahead for inflate
  12997. // Initialize the first block of the first file:
  12998. init_block();
  12999. }
  13000. // Restore the heap property by moving down the tree starting at node k,
  13001. // exchanging a node with the smallest of its two sons if necessary,
  13002. // stopping
  13003. // when the heap property is re-established (each father smaller than its
  13004. // two sons).
  13005. that.pqdownheap = function(tree, // the tree to restore
  13006. k // node to move down
  13007. ) {
  13008. var heap = that.heap;
  13009. var v = heap[k];
  13010. var j = k << 1; // left son of k
  13011. while (j <= that.heap_len) {
  13012. // Set j to the smallest of the two sons:
  13013. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  13014. j++;
  13015. }
  13016. // Exit if v is smaller than both sons
  13017. if (smaller(tree, v, heap[j], that.depth))
  13018. break;
  13019. // Exchange v with the smallest son
  13020. heap[k] = heap[j];
  13021. k = j;
  13022. // And continue down the tree, setting j to the left son of k
  13023. j <<= 1;
  13024. }
  13025. heap[k] = v;
  13026. };
  13027. // Scan a literal or distance tree to determine the frequencies of the codes
  13028. // in the bit length tree.
  13029. function scan_tree(tree,// the tree to be scanned
  13030. max_code // and its largest code of non zero frequency
  13031. ) {
  13032. var n; // iterates over all tree elements
  13033. var prevlen = -1; // last emitted length
  13034. var curlen; // length of current code
  13035. var nextlen = tree[0 * 2 + 1]; // length of next code
  13036. var count = 0; // repeat count of the current code
  13037. var max_count = 7; // max repeat count
  13038. var min_count = 4; // min repeat count
  13039. if (nextlen === 0) {
  13040. max_count = 138;
  13041. min_count = 3;
  13042. }
  13043. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  13044. for (n = 0; n <= max_code; n++) {
  13045. curlen = nextlen;
  13046. nextlen = tree[(n + 1) * 2 + 1];
  13047. if (++count < max_count && curlen == nextlen) {
  13048. continue;
  13049. } else if (count < min_count) {
  13050. bl_tree[curlen * 2] += count;
  13051. } else if (curlen !== 0) {
  13052. if (curlen != prevlen)
  13053. bl_tree[curlen * 2]++;
  13054. bl_tree[REP_3_6 * 2]++;
  13055. } else if (count <= 10) {
  13056. bl_tree[REPZ_3_10 * 2]++;
  13057. } else {
  13058. bl_tree[REPZ_11_138 * 2]++;
  13059. }
  13060. count = 0;
  13061. prevlen = curlen;
  13062. if (nextlen === 0) {
  13063. max_count = 138;
  13064. min_count = 3;
  13065. } else if (curlen == nextlen) {
  13066. max_count = 6;
  13067. min_count = 3;
  13068. } else {
  13069. max_count = 7;
  13070. min_count = 4;
  13071. }
  13072. }
  13073. }
  13074. // Construct the Huffman tree for the bit lengths and return the index in
  13075. // bl_order of the last bit length code to send.
  13076. function build_bl_tree() {
  13077. var max_blindex; // index of last bit length code of non zero freq
  13078. // Determine the bit length frequencies for literal and distance trees
  13079. scan_tree(dyn_ltree, l_desc.max_code);
  13080. scan_tree(dyn_dtree, d_desc.max_code);
  13081. // Build the bit length tree:
  13082. bl_desc.build_tree(that);
  13083. // opt_len now includes the length of the tree representations, except
  13084. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  13085. // counts.
  13086. // Determine the number of bit length codes to send. The pkzip format
  13087. // requires that at least 4 bit length codes be sent. (appnote.txt says
  13088. // 3 but the actual value used is 4.)
  13089. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  13090. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  13091. break;
  13092. }
  13093. // Update opt_len to include the bit length tree and counts
  13094. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  13095. return max_blindex;
  13096. }
  13097. // Output a byte on the stream.
  13098. // IN assertion: there is enough room in pending_buf.
  13099. function put_byte(p) {
  13100. that.pending_buf[that.pending++] = p;
  13101. }
  13102. function put_short(w) {
  13103. put_byte(w & 0xff);
  13104. put_byte((w >>> 8) & 0xff);
  13105. }
  13106. function putShortMSB(b) {
  13107. put_byte((b >> 8) & 0xff);
  13108. put_byte((b & 0xff) & 0xff);
  13109. }
  13110. function send_bits(value, length) {
  13111. var val, len = length;
  13112. if (bi_valid > Buf_size - len) {
  13113. val = value;
  13114. // bi_buf |= (val << bi_valid);
  13115. bi_buf |= ((val << bi_valid) & 0xffff);
  13116. put_short(bi_buf);
  13117. bi_buf = val >>> (Buf_size - bi_valid);
  13118. bi_valid += len - Buf_size;
  13119. } else {
  13120. // bi_buf |= (value) << bi_valid;
  13121. bi_buf |= (((value) << bi_valid) & 0xffff);
  13122. bi_valid += len;
  13123. }
  13124. }
  13125. function send_code(c, tree) {
  13126. var c2 = c * 2;
  13127. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  13128. }
  13129. // Send a literal or distance tree in compressed form, using the codes in
  13130. // bl_tree.
  13131. function send_tree(tree,// the tree to be sent
  13132. max_code // and its largest code of non zero frequency
  13133. ) {
  13134. var n; // iterates over all tree elements
  13135. var prevlen = -1; // last emitted length
  13136. var curlen; // length of current code
  13137. var nextlen = tree[0 * 2 + 1]; // length of next code
  13138. var count = 0; // repeat count of the current code
  13139. var max_count = 7; // max repeat count
  13140. var min_count = 4; // min repeat count
  13141. if (nextlen === 0) {
  13142. max_count = 138;
  13143. min_count = 3;
  13144. }
  13145. for (n = 0; n <= max_code; n++) {
  13146. curlen = nextlen;
  13147. nextlen = tree[(n + 1) * 2 + 1];
  13148. if (++count < max_count && curlen == nextlen) {
  13149. continue;
  13150. } else if (count < min_count) {
  13151. do {
  13152. send_code(curlen, bl_tree);
  13153. } while (--count !== 0);
  13154. } else if (curlen !== 0) {
  13155. if (curlen != prevlen) {
  13156. send_code(curlen, bl_tree);
  13157. count--;
  13158. }
  13159. send_code(REP_3_6, bl_tree);
  13160. send_bits(count - 3, 2);
  13161. } else if (count <= 10) {
  13162. send_code(REPZ_3_10, bl_tree);
  13163. send_bits(count - 3, 3);
  13164. } else {
  13165. send_code(REPZ_11_138, bl_tree);
  13166. send_bits(count - 11, 7);
  13167. }
  13168. count = 0;
  13169. prevlen = curlen;
  13170. if (nextlen === 0) {
  13171. max_count = 138;
  13172. min_count = 3;
  13173. } else if (curlen == nextlen) {
  13174. max_count = 6;
  13175. min_count = 3;
  13176. } else {
  13177. max_count = 7;
  13178. min_count = 4;
  13179. }
  13180. }
  13181. }
  13182. // Send the header for a block using dynamic Huffman trees: the counts, the
  13183. // lengths of the bit length codes, the literal tree and the distance tree.
  13184. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  13185. function send_all_trees(lcodes, dcodes, blcodes) {
  13186. var rank; // index in bl_order
  13187. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  13188. send_bits(dcodes - 1, 5);
  13189. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  13190. for (rank = 0; rank < blcodes; rank++) {
  13191. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  13192. }
  13193. send_tree(dyn_ltree, lcodes - 1); // literal tree
  13194. send_tree(dyn_dtree, dcodes - 1); // distance tree
  13195. }
  13196. // Flush the bit buffer, keeping at most 7 bits in it.
  13197. function bi_flush() {
  13198. if (bi_valid == 16) {
  13199. put_short(bi_buf);
  13200. bi_buf = 0;
  13201. bi_valid = 0;
  13202. } else if (bi_valid >= 8) {
  13203. put_byte(bi_buf & 0xff);
  13204. bi_buf >>>= 8;
  13205. bi_valid -= 8;
  13206. }
  13207. }
  13208. // Send one empty static block to give enough lookahead for inflate.
  13209. // This takes 10 bits, of which 7 may remain in the bit buffer.
  13210. // The current inflate code requires 9 bits of lookahead. If the
  13211. // last two codes for the previous block (real code plus EOB) were coded
  13212. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  13213. // the last real code. In this case we send two empty static blocks instead
  13214. // of one. (There are no problems if the previous block is stored or fixed.)
  13215. // To simplify the code, we assume the worst case of last real code encoded
  13216. // on one bit only.
  13217. function _tr_align() {
  13218. send_bits(STATIC_TREES << 1, 3);
  13219. send_code(END_BLOCK, StaticTree.static_ltree);
  13220. bi_flush();
  13221. // Of the 10 bits for the empty block, we have already sent
  13222. // (10 - bi_valid) bits. The lookahead for the last real code (before
  13223. // the EOB of the previous block) was thus at least one plus the length
  13224. // of the EOB plus what we have just sent of the empty static block.
  13225. if (1 + last_eob_len + 10 - bi_valid < 9) {
  13226. send_bits(STATIC_TREES << 1, 3);
  13227. send_code(END_BLOCK, StaticTree.static_ltree);
  13228. bi_flush();
  13229. }
  13230. last_eob_len = 7;
  13231. }
  13232. // Save the match info and tally the frequency counts. Return true if
  13233. // the current block must be flushed.
  13234. function _tr_tally(dist, // distance of matched string
  13235. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  13236. ) {
  13237. var out_length, in_length, dcode;
  13238. that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
  13239. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  13240. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  13241. last_lit++;
  13242. if (dist === 0) {
  13243. // lc is the unmatched char
  13244. dyn_ltree[lc * 2]++;
  13245. } else {
  13246. matches++;
  13247. // Here, lc is the match length - MIN_MATCH
  13248. dist--; // dist = match distance - 1
  13249. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  13250. dyn_dtree[Tree.d_code(dist) * 2]++;
  13251. }
  13252. if ((last_lit & 0x1fff) === 0 && level > 2) {
  13253. // Compute an upper bound for the compressed length
  13254. out_length = last_lit * 8;
  13255. in_length = strstart - block_start;
  13256. for (dcode = 0; dcode < D_CODES; dcode++) {
  13257. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  13258. }
  13259. out_length >>>= 3;
  13260. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  13261. return true;
  13262. }
  13263. return (last_lit == lit_bufsize - 1);
  13264. // We avoid equality with lit_bufsize because of wraparound at 64K
  13265. // on 16 bit machines and because stored blocks are restricted to
  13266. // 64K-1 bytes.
  13267. }
  13268. // Send the block data compressed using the given Huffman trees
  13269. function compress_block(ltree, dtree) {
  13270. var dist; // distance of matched string
  13271. var lc; // match length or unmatched char (if dist === 0)
  13272. var lx = 0; // running index in l_buf
  13273. var code; // the code to send
  13274. var extra; // number of extra bits to send
  13275. if (last_lit !== 0) {
  13276. do {
  13277. dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
  13278. lc = (that.pending_buf[l_buf + lx]) & 0xff;
  13279. lx++;
  13280. if (dist === 0) {
  13281. send_code(lc, ltree); // send a literal byte
  13282. } else {
  13283. // Here, lc is the match length - MIN_MATCH
  13284. code = Tree._length_code[lc];
  13285. send_code(code + LITERALS + 1, ltree); // send the length
  13286. // code
  13287. extra = Tree.extra_lbits[code];
  13288. if (extra !== 0) {
  13289. lc -= Tree.base_length[code];
  13290. send_bits(lc, extra); // send the extra length bits
  13291. }
  13292. dist--; // dist is now the match distance - 1
  13293. code = Tree.d_code(dist);
  13294. send_code(code, dtree); // send the distance code
  13295. extra = Tree.extra_dbits[code];
  13296. if (extra !== 0) {
  13297. dist -= Tree.base_dist[code];
  13298. send_bits(dist, extra); // send the extra distance bits
  13299. }
  13300. } // literal or match pair ?
  13301. // Check that the overlay between pending_buf and d_buf+l_buf is
  13302. // ok:
  13303. } while (lx < last_lit);
  13304. }
  13305. send_code(END_BLOCK, ltree);
  13306. last_eob_len = ltree[END_BLOCK * 2 + 1];
  13307. }
  13308. // Flush the bit buffer and align the output on a byte boundary
  13309. function bi_windup() {
  13310. if (bi_valid > 8) {
  13311. put_short(bi_buf);
  13312. } else if (bi_valid > 0) {
  13313. put_byte(bi_buf & 0xff);
  13314. }
  13315. bi_buf = 0;
  13316. bi_valid = 0;
  13317. }
  13318. // Copy a stored block, storing first the length and its
  13319. // one's complement if requested.
  13320. function copy_block(buf, // the input data
  13321. len, // its length
  13322. header // true if block header must be written
  13323. ) {
  13324. bi_windup(); // align on byte boundary
  13325. last_eob_len = 8; // enough lookahead for inflate
  13326. if (header) {
  13327. put_short(len);
  13328. put_short(~len);
  13329. }
  13330. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  13331. that.pending += len;
  13332. }
  13333. // Send a stored block
  13334. function _tr_stored_block(buf, // input block
  13335. stored_len, // length of input block
  13336. eof // true if this is the last block for a file
  13337. ) {
  13338. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  13339. copy_block(buf, stored_len, true); // with header
  13340. }
  13341. // Determine the best encoding for the current block: dynamic trees, static
  13342. // trees or store, and output the encoded block to the zip file.
  13343. function _tr_flush_block(buf, // input block, or NULL if too old
  13344. stored_len, // length of input block
  13345. eof // true if this is the last block for a file
  13346. ) {
  13347. var opt_lenb, static_lenb;// opt_len and static_len in bytes
  13348. var max_blindex = 0; // index of last bit length code of non zero freq
  13349. // Build the Huffman trees unless a stored block is forced
  13350. if (level > 0) {
  13351. // Construct the literal and distance trees
  13352. l_desc.build_tree(that);
  13353. d_desc.build_tree(that);
  13354. // At this point, opt_len and static_len are the total bit lengths
  13355. // of
  13356. // the compressed block data, excluding the tree representations.
  13357. // Build the bit length tree for the above two trees, and get the
  13358. // index
  13359. // in bl_order of the last bit length code to send.
  13360. max_blindex = build_bl_tree();
  13361. // Determine the best encoding. Compute first the block length in
  13362. // bytes
  13363. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  13364. static_lenb = (that.static_len + 3 + 7) >>> 3;
  13365. if (static_lenb <= opt_lenb)
  13366. opt_lenb = static_lenb;
  13367. } else {
  13368. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  13369. }
  13370. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  13371. // 4: two words for the lengths
  13372. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  13373. // Otherwise we can't have processed more than WSIZE input bytes
  13374. // since
  13375. // the last block flush, because compression would have been
  13376. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  13377. // transform a block into a stored block.
  13378. _tr_stored_block(buf, stored_len, eof);
  13379. } else if (static_lenb == opt_lenb) {
  13380. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  13381. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  13382. } else {
  13383. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  13384. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  13385. compress_block(dyn_ltree, dyn_dtree);
  13386. }
  13387. // The above check is made mod 2^32, for files larger than 512 MB
  13388. // and uLong implemented on 32 bits.
  13389. init_block();
  13390. if (eof) {
  13391. bi_windup();
  13392. }
  13393. }
  13394. function flush_block_only(eof) {
  13395. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  13396. block_start = strstart;
  13397. strm.flush_pending();
  13398. }
  13399. // Fill the window when the lookahead becomes insufficient.
  13400. // Updates strstart and lookahead.
  13401. //
  13402. // IN assertion: lookahead < MIN_LOOKAHEAD
  13403. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13404. // At least one byte has been read, or avail_in === 0; reads are
  13405. // performed for at least two bytes (required for the zip translate_eol
  13406. // option -- not supported here).
  13407. function fill_window() {
  13408. var n, m;
  13409. var p;
  13410. var more; // Amount of free space at the end of the window.
  13411. do {
  13412. more = (window_size - lookahead - strstart);
  13413. // Deal with !@#$% 64K limit:
  13414. if (more === 0 && strstart === 0 && lookahead === 0) {
  13415. more = w_size;
  13416. } else if (more == -1) {
  13417. // Very unlikely, but possible on 16 bit machine if strstart ==
  13418. // 0
  13419. // and lookahead == 1 (input done one byte at time)
  13420. more--;
  13421. // If the window is almost full and there is insufficient
  13422. // lookahead,
  13423. // move the upper half to the lower one to make room in the
  13424. // upper half.
  13425. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  13426. window.set(window.subarray(w_size, w_size + w_size), 0);
  13427. match_start -= w_size;
  13428. strstart -= w_size; // we now have strstart >= MAX_DIST
  13429. block_start -= w_size;
  13430. // Slide the hash table (could be avoided with 32 bit values
  13431. // at the expense of memory usage). We slide even when level ==
  13432. // 0
  13433. // to keep the hash table consistent if we switch back to level
  13434. // > 0
  13435. // later. (Using level 0 permanently is not an optimal usage of
  13436. // zlib, so we don't care about this pathological case.)
  13437. n = hash_size;
  13438. p = n;
  13439. do {
  13440. m = (head[--p] & 0xffff);
  13441. head[p] = (m >= w_size ? m - w_size : 0);
  13442. } while (--n !== 0);
  13443. n = w_size;
  13444. p = n;
  13445. do {
  13446. m = (prev[--p] & 0xffff);
  13447. prev[p] = (m >= w_size ? m - w_size : 0);
  13448. // If n is not on any hash chain, prev[n] is garbage but
  13449. // its value will never be used.
  13450. } while (--n !== 0);
  13451. more += w_size;
  13452. }
  13453. if (strm.avail_in === 0)
  13454. return;
  13455. // If there was no sliding:
  13456. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13457. // more == window_size - lookahead - strstart
  13458. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13459. // => more >= window_size - 2*WSIZE + 2
  13460. // In the BIG_MEM or MMAP case (not yet supported),
  13461. // window_size == input_size + MIN_LOOKAHEAD &&
  13462. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13463. // Otherwise, window_size == 2*WSIZE so more >= 2.
  13464. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13465. n = strm.read_buf(window, strstart + lookahead, more);
  13466. lookahead += n;
  13467. // Initialize the hash value now that we have some input:
  13468. if (lookahead >= MIN_MATCH) {
  13469. ins_h = window[strstart] & 0xff;
  13470. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  13471. }
  13472. // If the whole input has less than MIN_MATCH bytes, ins_h is
  13473. // garbage,
  13474. // but this is not important since only literal bytes will be
  13475. // emitted.
  13476. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  13477. }
  13478. // Copy without compression as much as possible from the input stream,
  13479. // return
  13480. // the current block state.
  13481. // This function does not insert new strings in the dictionary since
  13482. // uncompressible data is probably not useful. This function is used
  13483. // only for the level=0 compression option.
  13484. // NOTE: this function should be optimized to avoid extra copying from
  13485. // window to pending_buf.
  13486. function deflate_stored(flush) {
  13487. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13488. // to pending_buf_size, and each stored block has a 5 byte header:
  13489. var max_block_size = 0xffff;
  13490. var max_start;
  13491. if (max_block_size > pending_buf_size - 5) {
  13492. max_block_size = pending_buf_size - 5;
  13493. }
  13494. // Copy as much as possible from input to output:
  13495. while (true) {
  13496. // Fill the window as much as possible:
  13497. if (lookahead <= 1) {
  13498. fill_window();
  13499. if (lookahead === 0 && flush == Z_NO_FLUSH)
  13500. return NeedMore;
  13501. if (lookahead === 0)
  13502. break; // flush the current block
  13503. }
  13504. strstart += lookahead;
  13505. lookahead = 0;
  13506. // Emit a stored block if pending_buf will be full:
  13507. max_start = block_start + max_block_size;
  13508. if (strstart === 0 || strstart >= max_start) {
  13509. // strstart === 0 is possible when wraparound on 16-bit machine
  13510. lookahead = (strstart - max_start);
  13511. strstart = max_start;
  13512. flush_block_only(false);
  13513. if (strm.avail_out === 0)
  13514. return NeedMore;
  13515. }
  13516. // Flush if we may have to slide, otherwise block_start may become
  13517. // negative and the data will be gone:
  13518. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  13519. flush_block_only(false);
  13520. if (strm.avail_out === 0)
  13521. return NeedMore;
  13522. }
  13523. }
  13524. flush_block_only(flush == Z_FINISH);
  13525. if (strm.avail_out === 0)
  13526. return (flush == Z_FINISH) ? FinishStarted : NeedMore;
  13527. return flush == Z_FINISH ? FinishDone : BlockDone;
  13528. }
  13529. function longest_match(cur_match) {
  13530. var chain_length = max_chain_length; // max hash chain length
  13531. var scan = strstart; // current string
  13532. var match; // matched string
  13533. var len; // length of current match
  13534. var best_len = prev_length; // best match length so far
  13535. var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  13536. var _nice_match = nice_match;
  13537. // Stop when cur_match becomes <= limit. To simplify the code,
  13538. // we prevent matches with the string of window index 0.
  13539. var wmask = w_mask;
  13540. var strend = strstart + MAX_MATCH;
  13541. var scan_end1 = window[scan + best_len - 1];
  13542. var scan_end = window[scan + best_len];
  13543. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  13544. // 16.
  13545. // It is easy to get rid of this optimization if necessary.
  13546. // Do not waste too much time if we already have a good match:
  13547. if (prev_length >= good_match) {
  13548. chain_length >>= 2;
  13549. }
  13550. // Do not look for matches beyond the end of the input. This is
  13551. // necessary
  13552. // to make deflate deterministic.
  13553. if (_nice_match > lookahead)
  13554. _nice_match = lookahead;
  13555. do {
  13556. match = cur_match;
  13557. // Skip to next match if the match length cannot increase
  13558. // or if the match length is less than 2:
  13559. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
  13560. || window[++match] != window[scan + 1])
  13561. continue;
  13562. // The check at best_len-1 can be removed because it will be made
  13563. // again later. (This heuristic is not always a win.)
  13564. // It is not necessary to compare scan[2] and match[2] since they
  13565. // are always equal when the other bytes match, given that
  13566. // the hash keys are equal and that HASH_BITS >= 8.
  13567. scan += 2;
  13568. match++;
  13569. // We check for insufficient lookahead only every 8th comparison;
  13570. // the 256th check will be made at strstart+258.
  13571. do {
  13572. } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  13573. && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
  13574. && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  13575. len = MAX_MATCH - (strend - scan);
  13576. scan = strend - MAX_MATCH;
  13577. if (len > best_len) {
  13578. match_start = cur_match;
  13579. best_len = len;
  13580. if (len >= _nice_match)
  13581. break;
  13582. scan_end1 = window[scan + best_len - 1];
  13583. scan_end = window[scan + best_len];
  13584. }
  13585. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  13586. if (best_len <= lookahead)
  13587. return best_len;
  13588. return lookahead;
  13589. }
  13590. // Compress as much as possible from the input stream, return the current
  13591. // block state.
  13592. // This function does not perform lazy evaluation of matches and inserts
  13593. // new strings in the dictionary only for unmatched strings or for short
  13594. // matches. It is used only for the fast compression options.
  13595. function deflate_fast(flush) {
  13596. // short hash_head = 0; // head of the hash chain
  13597. var hash_head = 0; // head of the hash chain
  13598. var bflush; // set if current block must be flushed
  13599. while (true) {
  13600. // Make sure that we always have enough lookahead, except
  13601. // at the end of the input file. We need MAX_MATCH bytes
  13602. // for the next match, plus MIN_MATCH bytes to insert the
  13603. // string following the next match.
  13604. if (lookahead < MIN_LOOKAHEAD) {
  13605. fill_window();
  13606. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  13607. return NeedMore;
  13608. }
  13609. if (lookahead === 0)
  13610. break; // flush the current block
  13611. }
  13612. // Insert the string window[strstart .. strstart+2] in the
  13613. // dictionary, and set hash_head to the head of the hash chain:
  13614. if (lookahead >= MIN_MATCH) {
  13615. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  13616. // prev[strstart&w_mask]=hash_head=head[ins_h];
  13617. hash_head = (head[ins_h] & 0xffff);
  13618. prev[strstart & w_mask] = head[ins_h];
  13619. head[ins_h] = strstart;
  13620. }
  13621. // Find the longest match, discarding those <= prev_length.
  13622. // At this point we have always match_length < MIN_MATCH
  13623. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  13624. // To simplify the code, we prevent matches with the string
  13625. // of window index 0 (in particular we have to avoid a match
  13626. // of the string with itself at the start of the input file).
  13627. if (strategy != Z_HUFFMAN_ONLY) {
  13628. match_length = longest_match(hash_head);
  13629. }
  13630. // longest_match() sets match_start
  13631. }
  13632. if (match_length >= MIN_MATCH) {
  13633. // check_match(strstart, match_start, match_length);
  13634. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  13635. lookahead -= match_length;
  13636. // Insert new strings in the hash table only if the match length
  13637. // is not too large. This saves time but degrades compression.
  13638. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  13639. match_length--; // string at strstart already in hash table
  13640. do {
  13641. strstart++;
  13642. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  13643. // prev[strstart&w_mask]=hash_head=head[ins_h];
  13644. hash_head = (head[ins_h] & 0xffff);
  13645. prev[strstart & w_mask] = head[ins_h];
  13646. head[ins_h] = strstart;
  13647. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  13648. // always MIN_MATCH bytes ahead.
  13649. } while (--match_length !== 0);
  13650. strstart++;
  13651. } else {
  13652. strstart += match_length;
  13653. match_length = 0;
  13654. ins_h = window[strstart] & 0xff;
  13655. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  13656. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  13657. // not
  13658. // matter since it will be recomputed at next deflate call.
  13659. }
  13660. } else {
  13661. // No match, output a literal byte
  13662. bflush = _tr_tally(0, window[strstart] & 0xff);
  13663. lookahead--;
  13664. strstart++;
  13665. }
  13666. if (bflush) {
  13667. flush_block_only(false);
  13668. if (strm.avail_out === 0)
  13669. return NeedMore;
  13670. }
  13671. }
  13672. flush_block_only(flush == Z_FINISH);
  13673. if (strm.avail_out === 0) {
  13674. if (flush == Z_FINISH)
  13675. return FinishStarted;
  13676. else
  13677. return NeedMore;
  13678. }
  13679. return flush == Z_FINISH ? FinishDone : BlockDone;
  13680. }
  13681. // Same as above, but achieves better compression. We use a lazy
  13682. // evaluation for matches: a match is finally adopted only if there is
  13683. // no better match at the next window position.
  13684. function deflate_slow(flush) {
  13685. // short hash_head = 0; // head of hash chain
  13686. var hash_head = 0; // head of hash chain
  13687. var bflush; // set if current block must be flushed
  13688. var max_insert;
  13689. // Process the input block.
  13690. while (true) {
  13691. // Make sure that we always have enough lookahead, except
  13692. // at the end of the input file. We need MAX_MATCH bytes
  13693. // for the next match, plus MIN_MATCH bytes to insert the
  13694. // string following the next match.
  13695. if (lookahead < MIN_LOOKAHEAD) {
  13696. fill_window();
  13697. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  13698. return NeedMore;
  13699. }
  13700. if (lookahead === 0)
  13701. break; // flush the current block
  13702. }
  13703. // Insert the string window[strstart .. strstart+2] in the
  13704. // dictionary, and set hash_head to the head of the hash chain:
  13705. if (lookahead >= MIN_MATCH) {
  13706. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  13707. // prev[strstart&w_mask]=hash_head=head[ins_h];
  13708. hash_head = (head[ins_h] & 0xffff);
  13709. prev[strstart & w_mask] = head[ins_h];
  13710. head[ins_h] = strstart;
  13711. }
  13712. // Find the longest match, discarding those <= prev_length.
  13713. prev_length = match_length;
  13714. prev_match = match_start;
  13715. match_length = MIN_MATCH - 1;
  13716. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  13717. // To simplify the code, we prevent matches with the string
  13718. // of window index 0 (in particular we have to avoid a match
  13719. // of the string with itself at the start of the input file).
  13720. if (strategy != Z_HUFFMAN_ONLY) {
  13721. match_length = longest_match(hash_head);
  13722. }
  13723. // longest_match() sets match_start
  13724. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  13725. // If prev_match is also MIN_MATCH, match_start is garbage
  13726. // but we will ignore the current match anyway.
  13727. match_length = MIN_MATCH - 1;
  13728. }
  13729. }
  13730. // If there was a match at the previous step and the current
  13731. // match is not better, output the previous match:
  13732. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  13733. max_insert = strstart + lookahead - MIN_MATCH;
  13734. // Do not insert strings in hash table beyond this.
  13735. // check_match(strstart-1, prev_match, prev_length);
  13736. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  13737. // Insert in hash table all strings up to the end of the match.
  13738. // strstart-1 and strstart are already inserted. If there is not
  13739. // enough lookahead, the last two strings are not inserted in
  13740. // the hash table.
  13741. lookahead -= prev_length - 1;
  13742. prev_length -= 2;
  13743. do {
  13744. if (++strstart <= max_insert) {
  13745. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  13746. // prev[strstart&w_mask]=hash_head=head[ins_h];
  13747. hash_head = (head[ins_h] & 0xffff);
  13748. prev[strstart & w_mask] = head[ins_h];
  13749. head[ins_h] = strstart;
  13750. }
  13751. } while (--prev_length !== 0);
  13752. match_available = 0;
  13753. match_length = MIN_MATCH - 1;
  13754. strstart++;
  13755. if (bflush) {
  13756. flush_block_only(false);
  13757. if (strm.avail_out === 0)
  13758. return NeedMore;
  13759. }
  13760. } else if (match_available !== 0) {
  13761. // If there was no match at the previous position, output a
  13762. // single literal. If there was a match but the current match
  13763. // is longer, truncate the previous match to a single literal.
  13764. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  13765. if (bflush) {
  13766. flush_block_only(false);
  13767. }
  13768. strstart++;
  13769. lookahead--;
  13770. if (strm.avail_out === 0)
  13771. return NeedMore;
  13772. } else {
  13773. // There is no previous match to compare with, wait for
  13774. // the next step to decide.
  13775. match_available = 1;
  13776. strstart++;
  13777. lookahead--;
  13778. }
  13779. }
  13780. if (match_available !== 0) {
  13781. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  13782. match_available = 0;
  13783. }
  13784. flush_block_only(flush == Z_FINISH);
  13785. if (strm.avail_out === 0) {
  13786. if (flush == Z_FINISH)
  13787. return FinishStarted;
  13788. else
  13789. return NeedMore;
  13790. }
  13791. return flush == Z_FINISH ? FinishDone : BlockDone;
  13792. }
  13793. function deflateReset(strm) {
  13794. strm.total_in = strm.total_out = 0;
  13795. strm.msg = null; //
  13796. that.pending = 0;
  13797. that.pending_out = 0;
  13798. status = BUSY_STATE;
  13799. last_flush = Z_NO_FLUSH;
  13800. tr_init();
  13801. lm_init();
  13802. return Z_OK;
  13803. }
  13804. that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
  13805. if (!_method)
  13806. _method = Z_DEFLATED;
  13807. if (!memLevel)
  13808. memLevel = DEF_MEM_LEVEL;
  13809. if (!_strategy)
  13810. _strategy = Z_DEFAULT_STRATEGY;
  13811. // byte[] my_version=ZLIB_VERSION;
  13812. //
  13813. // if (!version || version[0] != my_version[0]
  13814. // || stream_size != sizeof(z_stream)) {
  13815. // return Z_VERSION_ERROR;
  13816. // }
  13817. strm.msg = null;
  13818. if (_level == Z_DEFAULT_COMPRESSION)
  13819. _level = 6;
  13820. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  13821. || _strategy > Z_HUFFMAN_ONLY) {
  13822. return Z_STREAM_ERROR;
  13823. }
  13824. strm.dstate = that;
  13825. w_bits = bits;
  13826. w_size = 1 << w_bits;
  13827. w_mask = w_size - 1;
  13828. hash_bits = memLevel + 7;
  13829. hash_size = 1 << hash_bits;
  13830. hash_mask = hash_size - 1;
  13831. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  13832. window = new Uint8Array(w_size * 2);
  13833. prev = [];
  13834. head = [];
  13835. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  13836. // We overlay pending_buf and d_buf+l_buf. This works since the average
  13837. // output size for (length,distance) codes is <= 24 bits.
  13838. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  13839. pending_buf_size = lit_bufsize * 4;
  13840. d_buf = Math.floor(lit_bufsize / 2);
  13841. l_buf = (1 + 2) * lit_bufsize;
  13842. level = _level;
  13843. strategy = _strategy;
  13844. return deflateReset(strm);
  13845. };
  13846. that.deflateEnd = function() {
  13847. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  13848. return Z_STREAM_ERROR;
  13849. }
  13850. // Deallocate in reverse order of allocations:
  13851. that.pending_buf = null;
  13852. head = null;
  13853. prev = null;
  13854. window = null;
  13855. // free
  13856. that.dstate = null;
  13857. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  13858. };
  13859. that.deflateParams = function(strm, _level, _strategy) {
  13860. var err = Z_OK;
  13861. if (_level == Z_DEFAULT_COMPRESSION) {
  13862. _level = 6;
  13863. }
  13864. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  13865. return Z_STREAM_ERROR;
  13866. }
  13867. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  13868. // Flush the last buffer:
  13869. err = strm.deflate(Z_PARTIAL_FLUSH);
  13870. }
  13871. if (level != _level) {
  13872. level = _level;
  13873. max_lazy_match = config_table[level].max_lazy;
  13874. good_match = config_table[level].good_length;
  13875. nice_match = config_table[level].nice_length;
  13876. max_chain_length = config_table[level].max_chain;
  13877. }
  13878. strategy = _strategy;
  13879. return err;
  13880. };
  13881. that.deflateSetDictionary = function(strm, dictionary, dictLength) {
  13882. var length = dictLength;
  13883. var n, index = 0;
  13884. if (!dictionary || status != INIT_STATE)
  13885. return Z_STREAM_ERROR;
  13886. if (length < MIN_MATCH)
  13887. return Z_OK;
  13888. if (length > w_size - MIN_LOOKAHEAD) {
  13889. length = w_size - MIN_LOOKAHEAD;
  13890. index = dictLength - length; // use the tail of the dictionary
  13891. }
  13892. window.set(dictionary.subarray(index, index + length), 0);
  13893. strstart = length;
  13894. block_start = length;
  13895. // Insert all strings in the hash table (except for the last two bytes).
  13896. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  13897. // call of fill_window.
  13898. ins_h = window[0] & 0xff;
  13899. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  13900. for (n = 0; n <= length - MIN_MATCH; n++) {
  13901. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  13902. prev[n & w_mask] = head[ins_h];
  13903. head[ins_h] = n;
  13904. }
  13905. return Z_OK;
  13906. };
  13907. that.deflate = function(_strm, flush) {
  13908. var i, header, level_flags, old_flush, bstate;
  13909. if (flush > Z_FINISH || flush < 0) {
  13910. return Z_STREAM_ERROR;
  13911. }
  13912. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
  13913. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  13914. return Z_STREAM_ERROR;
  13915. }
  13916. if (_strm.avail_out === 0) {
  13917. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  13918. return Z_BUF_ERROR;
  13919. }
  13920. strm = _strm; // just in case
  13921. old_flush = last_flush;
  13922. last_flush = flush;
  13923. // Write the zlib header
  13924. if (status == INIT_STATE) {
  13925. header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  13926. level_flags = ((level - 1) & 0xff) >> 1;
  13927. if (level_flags > 3)
  13928. level_flags = 3;
  13929. header |= (level_flags << 6);
  13930. if (strstart !== 0)
  13931. header |= PRESET_DICT;
  13932. header += 31 - (header % 31);
  13933. status = BUSY_STATE;
  13934. putShortMSB(header);
  13935. }
  13936. // Flush as much pending output as possible
  13937. if (that.pending !== 0) {
  13938. strm.flush_pending();
  13939. if (strm.avail_out === 0) {
  13940. // console.log(" avail_out==0");
  13941. // Since avail_out is 0, deflate will be called again with
  13942. // more output space, but possibly with both pending and
  13943. // avail_in equal to zero. There won't be anything to do,
  13944. // but this is not an error situation so make sure we
  13945. // return OK instead of BUF_ERROR at next call of deflate:
  13946. last_flush = -1;
  13947. return Z_OK;
  13948. }
  13949. // Make sure there is something to do and avoid duplicate
  13950. // consecutive
  13951. // flushes. For repeated and useless calls with Z_FINISH, we keep
  13952. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  13953. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  13954. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  13955. return Z_BUF_ERROR;
  13956. }
  13957. // User must not provide more input after the first FINISH:
  13958. if (status == FINISH_STATE && strm.avail_in !== 0) {
  13959. _strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  13960. return Z_BUF_ERROR;
  13961. }
  13962. // Start a new block or continue the current one.
  13963. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
  13964. bstate = -1;
  13965. switch (config_table[level].func) {
  13966. case STORED:
  13967. bstate = deflate_stored(flush);
  13968. break;
  13969. case FAST:
  13970. bstate = deflate_fast(flush);
  13971. break;
  13972. case SLOW:
  13973. bstate = deflate_slow(flush);
  13974. break;
  13975. default:
  13976. }
  13977. if (bstate == FinishStarted || bstate == FinishDone) {
  13978. status = FINISH_STATE;
  13979. }
  13980. if (bstate == NeedMore || bstate == FinishStarted) {
  13981. if (strm.avail_out === 0) {
  13982. last_flush = -1; // avoid BUF_ERROR next call, see above
  13983. }
  13984. return Z_OK;
  13985. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  13986. // of deflate should use the same flush parameter to make sure
  13987. // that the flush is complete. So we don't have to output an
  13988. // empty block here, this will be done at next call. This also
  13989. // ensures that for a very small output buffer, we emit at most
  13990. // one empty block.
  13991. }
  13992. if (bstate == BlockDone) {
  13993. if (flush == Z_PARTIAL_FLUSH) {
  13994. _tr_align();
  13995. } else { // FULL_FLUSH or SYNC_FLUSH
  13996. _tr_stored_block(0, 0, false);
  13997. // For a full flush, this empty block will be recognized
  13998. // as a special marker by inflate_sync().
  13999. if (flush == Z_FULL_FLUSH) {
  14000. // state.head[s.hash_size-1]=0;
  14001. for (i = 0; i < hash_size/*-1*/; i++)
  14002. // forget history
  14003. head[i] = 0;
  14004. }
  14005. }
  14006. strm.flush_pending();
  14007. if (strm.avail_out === 0) {
  14008. last_flush = -1; // avoid BUF_ERROR at next call, see above
  14009. return Z_OK;
  14010. }
  14011. }
  14012. }
  14013. if (flush != Z_FINISH)
  14014. return Z_OK;
  14015. return Z_STREAM_END;
  14016. };
  14017. }
  14018. // ZStream
  14019. function ZStream() {
  14020. var that = this;
  14021. that.next_in_index = 0;
  14022. that.next_out_index = 0;
  14023. // that.next_in; // next input byte
  14024. that.avail_in = 0; // number of bytes available at next_in
  14025. that.total_in = 0; // total nb of input bytes read so far
  14026. // that.next_out; // next output byte should be put there
  14027. that.avail_out = 0; // remaining free space at next_out
  14028. that.total_out = 0; // total nb of bytes output so far
  14029. // that.msg;
  14030. // that.dstate;
  14031. }
  14032. ZStream.prototype = {
  14033. deflateInit : function(level, bits) {
  14034. var that = this;
  14035. that.dstate = new Deflate();
  14036. if (!bits)
  14037. bits = MAX_BITS;
  14038. return that.dstate.deflateInit(that, level, bits);
  14039. },
  14040. deflate : function(flush) {
  14041. var that = this;
  14042. if (!that.dstate) {
  14043. return Z_STREAM_ERROR;
  14044. }
  14045. return that.dstate.deflate(that, flush);
  14046. },
  14047. deflateEnd : function() {
  14048. var that = this;
  14049. if (!that.dstate)
  14050. return Z_STREAM_ERROR;
  14051. var ret = that.dstate.deflateEnd();
  14052. that.dstate = null;
  14053. return ret;
  14054. },
  14055. deflateParams : function(level, strategy) {
  14056. var that = this;
  14057. if (!that.dstate)
  14058. return Z_STREAM_ERROR;
  14059. return that.dstate.deflateParams(that, level, strategy);
  14060. },
  14061. deflateSetDictionary : function(dictionary, dictLength) {
  14062. var that = this;
  14063. if (!that.dstate)
  14064. return Z_STREAM_ERROR;
  14065. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  14066. },
  14067. // Read a new buffer from the current input stream, update the
  14068. // total number of bytes read. All deflate() input goes through
  14069. // this function so some applications may wish to modify it to avoid
  14070. // allocating a large strm->next_in buffer and copying from it.
  14071. // (See also flush_pending()).
  14072. read_buf : function(buf, start, size) {
  14073. var that = this;
  14074. var len = that.avail_in;
  14075. if (len > size)
  14076. len = size;
  14077. if (len === 0)
  14078. return 0;
  14079. that.avail_in -= len;
  14080. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  14081. that.next_in_index += len;
  14082. that.total_in += len;
  14083. return len;
  14084. },
  14085. // Flush as much pending output as possible. All deflate() output goes
  14086. // through this function so some applications may wish to modify it
  14087. // to avoid allocating a large strm->next_out buffer and copying into it.
  14088. // (See also read_buf()).
  14089. flush_pending : function() {
  14090. var that = this;
  14091. var len = that.dstate.pending;
  14092. if (len > that.avail_out)
  14093. len = that.avail_out;
  14094. if (len === 0)
  14095. return;
  14096. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  14097. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  14098. // len)) {
  14099. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  14100. // that.next_out_index + ", " + len);
  14101. // console.log("avail_out=" + that.avail_out);
  14102. // }
  14103. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  14104. that.next_out_index += len;
  14105. that.dstate.pending_out += len;
  14106. that.total_out += len;
  14107. that.avail_out -= len;
  14108. that.dstate.pending -= len;
  14109. if (that.dstate.pending === 0) {
  14110. that.dstate.pending_out = 0;
  14111. }
  14112. }
  14113. };
  14114. // Deflater
  14115. function Deflater(options) {
  14116. var that = this;
  14117. var z = new ZStream();
  14118. var bufsize = 512;
  14119. var flush = Z_NO_FLUSH;
  14120. var buf = new Uint8Array(bufsize);
  14121. var level = options ? options.level : Z_DEFAULT_COMPRESSION;
  14122. if (typeof level == "undefined")
  14123. level = Z_DEFAULT_COMPRESSION;
  14124. z.deflateInit(level);
  14125. z.next_out = buf;
  14126. that.append = function(data, onprogress) {
  14127. var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
  14128. if (!data.length)
  14129. return;
  14130. z.next_in_index = 0;
  14131. z.next_in = data;
  14132. z.avail_in = data.length;
  14133. do {
  14134. z.next_out_index = 0;
  14135. z.avail_out = bufsize;
  14136. err = z.deflate(flush);
  14137. if (err != Z_OK)
  14138. throw new Error("deflating: " + z.msg);
  14139. if (z.next_out_index)
  14140. if (z.next_out_index == bufsize)
  14141. buffers.push(new Uint8Array(buf));
  14142. else
  14143. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  14144. bufferSize += z.next_out_index;
  14145. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  14146. onprogress(z.next_in_index);
  14147. lastIndex = z.next_in_index;
  14148. }
  14149. } while (z.avail_in > 0 || z.avail_out === 0);
  14150. array = new Uint8Array(bufferSize);
  14151. buffers.forEach(function(chunk) {
  14152. array.set(chunk, bufferIndex);
  14153. bufferIndex += chunk.length;
  14154. });
  14155. return array;
  14156. };
  14157. that.flush = function() {
  14158. var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
  14159. do {
  14160. z.next_out_index = 0;
  14161. z.avail_out = bufsize;
  14162. err = z.deflate(Z_FINISH);
  14163. if (err != Z_STREAM_END && err != Z_OK)
  14164. throw new Error("deflating: " + z.msg);
  14165. if (bufsize - z.avail_out > 0)
  14166. buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  14167. bufferSize += z.next_out_index;
  14168. } while (z.avail_in > 0 || z.avail_out === 0);
  14169. z.deflateEnd();
  14170. array = new Uint8Array(bufferSize);
  14171. buffers.forEach(function(chunk) {
  14172. array.set(chunk, bufferIndex);
  14173. bufferIndex += chunk.length;
  14174. });
  14175. return array;
  14176. };
  14177. }
  14178. // 'zip' may not be defined in z-worker and some tests
  14179. var env = global.zip || global;
  14180. env.Deflater = env._jzlib_Deflater = Deflater;
  14181. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()));
  14182. // `self` is undefined in Firefox for Android content script context
  14183. // while `this` is nsIContentFrameMessageManager
  14184. // with an attribute `content` that corresponds to the window
  14185. /**
  14186. * A class to parse color values
  14187. * @author Stoyan Stefanov <sstoo@gmail.com>
  14188. * @link http://www.phpied.com/rgb-color-parser-in-javascript/
  14189. * @license Use it if you like it
  14190. */
  14191. (function ( global ) {
  14192. function RGBColor(color_string)
  14193. {
  14194. this.ok = false;
  14195. // strip any leading #
  14196. if (color_string.charAt(0) == '#') { // remove # if any
  14197. color_string = color_string.substr(1,6);
  14198. }
  14199. color_string = color_string.replace(/ /g,'');
  14200. color_string = color_string.toLowerCase();
  14201. var channels;
  14202. // before getting into regexps, try simple matches
  14203. // and overwrite the input
  14204. var simple_colors = {
  14205. aliceblue: 'f0f8ff',
  14206. antiquewhite: 'faebd7',
  14207. aqua: '00ffff',
  14208. aquamarine: '7fffd4',
  14209. azure: 'f0ffff',
  14210. beige: 'f5f5dc',
  14211. bisque: 'ffe4c4',
  14212. black: '000000',
  14213. blanchedalmond: 'ffebcd',
  14214. blue: '0000ff',
  14215. blueviolet: '8a2be2',
  14216. brown: 'a52a2a',
  14217. burlywood: 'deb887',
  14218. cadetblue: '5f9ea0',
  14219. chartreuse: '7fff00',
  14220. chocolate: 'd2691e',
  14221. coral: 'ff7f50',
  14222. cornflowerblue: '6495ed',
  14223. cornsilk: 'fff8dc',
  14224. crimson: 'dc143c',
  14225. cyan: '00ffff',
  14226. darkblue: '00008b',
  14227. darkcyan: '008b8b',
  14228. darkgoldenrod: 'b8860b',
  14229. darkgray: 'a9a9a9',
  14230. darkgreen: '006400',
  14231. darkkhaki: 'bdb76b',
  14232. darkmagenta: '8b008b',
  14233. darkolivegreen: '556b2f',
  14234. darkorange: 'ff8c00',
  14235. darkorchid: '9932cc',
  14236. darkred: '8b0000',
  14237. darksalmon: 'e9967a',
  14238. darkseagreen: '8fbc8f',
  14239. darkslateblue: '483d8b',
  14240. darkslategray: '2f4f4f',
  14241. darkturquoise: '00ced1',
  14242. darkviolet: '9400d3',
  14243. deeppink: 'ff1493',
  14244. deepskyblue: '00bfff',
  14245. dimgray: '696969',
  14246. dodgerblue: '1e90ff',
  14247. feldspar: 'd19275',
  14248. firebrick: 'b22222',
  14249. floralwhite: 'fffaf0',
  14250. forestgreen: '228b22',
  14251. fuchsia: 'ff00ff',
  14252. gainsboro: 'dcdcdc',
  14253. ghostwhite: 'f8f8ff',
  14254. gold: 'ffd700',
  14255. goldenrod: 'daa520',
  14256. gray: '808080',
  14257. green: '008000',
  14258. greenyellow: 'adff2f',
  14259. honeydew: 'f0fff0',
  14260. hotpink: 'ff69b4',
  14261. indianred : 'cd5c5c',
  14262. indigo : '4b0082',
  14263. ivory: 'fffff0',
  14264. khaki: 'f0e68c',
  14265. lavender: 'e6e6fa',
  14266. lavenderblush: 'fff0f5',
  14267. lawngreen: '7cfc00',
  14268. lemonchiffon: 'fffacd',
  14269. lightblue: 'add8e6',
  14270. lightcoral: 'f08080',
  14271. lightcyan: 'e0ffff',
  14272. lightgoldenrodyellow: 'fafad2',
  14273. lightgrey: 'd3d3d3',
  14274. lightgreen: '90ee90',
  14275. lightpink: 'ffb6c1',
  14276. lightsalmon: 'ffa07a',
  14277. lightseagreen: '20b2aa',
  14278. lightskyblue: '87cefa',
  14279. lightslateblue: '8470ff',
  14280. lightslategray: '778899',
  14281. lightsteelblue: 'b0c4de',
  14282. lightyellow: 'ffffe0',
  14283. lime: '00ff00',
  14284. limegreen: '32cd32',
  14285. linen: 'faf0e6',
  14286. magenta: 'ff00ff',
  14287. maroon: '800000',
  14288. mediumaquamarine: '66cdaa',
  14289. mediumblue: '0000cd',
  14290. mediumorchid: 'ba55d3',
  14291. mediumpurple: '9370d8',
  14292. mediumseagreen: '3cb371',
  14293. mediumslateblue: '7b68ee',
  14294. mediumspringgreen: '00fa9a',
  14295. mediumturquoise: '48d1cc',
  14296. mediumvioletred: 'c71585',
  14297. midnightblue: '191970',
  14298. mintcream: 'f5fffa',
  14299. mistyrose: 'ffe4e1',
  14300. moccasin: 'ffe4b5',
  14301. navajowhite: 'ffdead',
  14302. navy: '000080',
  14303. oldlace: 'fdf5e6',
  14304. olive: '808000',
  14305. olivedrab: '6b8e23',
  14306. orange: 'ffa500',
  14307. orangered: 'ff4500',
  14308. orchid: 'da70d6',
  14309. palegoldenrod: 'eee8aa',
  14310. palegreen: '98fb98',
  14311. paleturquoise: 'afeeee',
  14312. palevioletred: 'd87093',
  14313. papayawhip: 'ffefd5',
  14314. peachpuff: 'ffdab9',
  14315. peru: 'cd853f',
  14316. pink: 'ffc0cb',
  14317. plum: 'dda0dd',
  14318. powderblue: 'b0e0e6',
  14319. purple: '800080',
  14320. red: 'ff0000',
  14321. rosybrown: 'bc8f8f',
  14322. royalblue: '4169e1',
  14323. saddlebrown: '8b4513',
  14324. salmon: 'fa8072',
  14325. sandybrown: 'f4a460',
  14326. seagreen: '2e8b57',
  14327. seashell: 'fff5ee',
  14328. sienna: 'a0522d',
  14329. silver: 'c0c0c0',
  14330. skyblue: '87ceeb',
  14331. slateblue: '6a5acd',
  14332. slategray: '708090',
  14333. snow: 'fffafa',
  14334. springgreen: '00ff7f',
  14335. steelblue: '4682b4',
  14336. tan: 'd2b48c',
  14337. teal: '008080',
  14338. thistle: 'd8bfd8',
  14339. tomato: 'ff6347',
  14340. turquoise: '40e0d0',
  14341. violet: 'ee82ee',
  14342. violetred: 'd02090',
  14343. wheat: 'f5deb3',
  14344. white: 'ffffff',
  14345. whitesmoke: 'f5f5f5',
  14346. yellow: 'ffff00',
  14347. yellowgreen: '9acd32'
  14348. };
  14349. for (var key in simple_colors) {
  14350. if (color_string == key) {
  14351. color_string = simple_colors[key];
  14352. }
  14353. }
  14354. // emd of simple type-in colors
  14355. // array of color definition objects
  14356. var color_defs = [
  14357. {
  14358. re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
  14359. example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
  14360. process: function (bits){
  14361. return [
  14362. parseInt(bits[1]),
  14363. parseInt(bits[2]),
  14364. parseInt(bits[3])
  14365. ];
  14366. }
  14367. },
  14368. {
  14369. re: /^(\w{2})(\w{2})(\w{2})$/,
  14370. example: ['#00ff00', '336699'],
  14371. process: function (bits){
  14372. return [
  14373. parseInt(bits[1], 16),
  14374. parseInt(bits[2], 16),
  14375. parseInt(bits[3], 16)
  14376. ];
  14377. }
  14378. },
  14379. {
  14380. re: /^(\w{1})(\w{1})(\w{1})$/,
  14381. example: ['#fb0', 'f0f'],
  14382. process: function (bits){
  14383. return [
  14384. parseInt(bits[1] + bits[1], 16),
  14385. parseInt(bits[2] + bits[2], 16),
  14386. parseInt(bits[3] + bits[3], 16)
  14387. ];
  14388. }
  14389. }
  14390. ];
  14391. // search through the definitions to find a match
  14392. for (var i = 0; i < color_defs.length; i++) {
  14393. var re = color_defs[i].re;
  14394. var processor = color_defs[i].process;
  14395. var bits = re.exec(color_string);
  14396. if (bits) {
  14397. channels = processor(bits);
  14398. this.r = channels[0];
  14399. this.g = channels[1];
  14400. this.b = channels[2];
  14401. this.ok = true;
  14402. }
  14403. }
  14404. // validate/cleanup values
  14405. this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
  14406. this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
  14407. this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
  14408. // some getters
  14409. this.toRGB = function () {
  14410. return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
  14411. };
  14412. this.toHex = function () {
  14413. var r = this.r.toString(16);
  14414. var g = this.g.toString(16);
  14415. var b = this.b.toString(16);
  14416. if (r.length == 1) r = '0' + r;
  14417. if (g.length == 1) g = '0' + g;
  14418. if (b.length == 1) b = '0' + b;
  14419. return '#' + r + g + b;
  14420. };
  14421. // help
  14422. this.getHelpXML = function () {
  14423. var examples = new Array();
  14424. // add regexps
  14425. for (var i = 0; i < color_defs.length; i++) {
  14426. var example = color_defs[i].example;
  14427. for (var j = 0; j < example.length; j++) {
  14428. examples[examples.length] = example[j];
  14429. }
  14430. }
  14431. // add type-in colors
  14432. for (var sc in simple_colors) {
  14433. examples[examples.length] = sc;
  14434. }
  14435. var xml = document.createElement('ul');
  14436. xml.setAttribute('id', 'rgbcolor-examples');
  14437. for (var i = 0; i < examples.length; i++) {
  14438. try {
  14439. var list_item = document.createElement('li');
  14440. var list_color = new RGBColor(examples[i]);
  14441. var example_div = document.createElement('div');
  14442. example_div.style.cssText =
  14443. 'margin: 3px; '
  14444. + 'border: 1px solid black; '
  14445. + 'background:' + list_color.toHex() + '; '
  14446. + 'color:' + list_color.toHex()
  14447. ;
  14448. example_div.appendChild(document.createTextNode('test'));
  14449. var list_item_value = document.createTextNode(
  14450. ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
  14451. );
  14452. list_item.appendChild(example_div);
  14453. list_item.appendChild(list_item_value);
  14454. xml.appendChild(list_item);
  14455. } catch(e){}
  14456. }
  14457. return xml;
  14458. };
  14459. }
  14460. // export as AMD...
  14461. if ( typeof define !== 'undefined' && define.amd ) {
  14462. define('RGBColor', function () { return RGBColor; });
  14463. }
  14464. // ...or as browserify
  14465. else if (typeof module !== 'undefined' && module.exports ) {
  14466. module.exports = RGBColor;
  14467. }
  14468. global.RGBColor = RGBColor;
  14469. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()));
  14470. // `self` is undefined in Firefox for Android content script context
  14471. // while `this` is nsIContentFrameMessageManager
  14472. // with an attribute `content` that corresponds to the window
  14473. /*
  14474. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  14475. Copyright (c) 2016 Niklas von Hertzen
  14476. Released under License
  14477. */
  14478. !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(){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){
  14479. (function (global){
  14480. (function(root) {
  14481. /** Detect free variables */
  14482. var freeExports = typeof exports == 'object' && exports;
  14483. var freeModule = typeof module == 'object' && module &&
  14484. module.exports == freeExports && module;
  14485. var freeGlobal = typeof global == 'object' && global;
  14486. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  14487. root = freeGlobal;
  14488. }
  14489. /**
  14490. * The `punycode` object.
  14491. * @name punycode
  14492. * @type Object
  14493. */
  14494. var punycode,
  14495. /** Highest positive signed 32-bit float value */
  14496. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  14497. /** Bootstring parameters */
  14498. base = 36,
  14499. tMin = 1,
  14500. tMax = 26,
  14501. skew = 38,
  14502. damp = 700,
  14503. initialBias = 72,
  14504. initialN = 128, // 0x80
  14505. delimiter = '-', // '\x2D'
  14506. /** Regular expressions */
  14507. regexPunycode = /^xn--/,
  14508. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  14509. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  14510. /** Error messages */
  14511. errors = {
  14512. 'overflow': 'Overflow: input needs wider integers to process',
  14513. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  14514. 'invalid-input': 'Invalid input'
  14515. },
  14516. /** Convenience shortcuts */
  14517. baseMinusTMin = base - tMin,
  14518. floor = Math.floor,
  14519. stringFromCharCode = String.fromCharCode,
  14520. /** Temporary variable */
  14521. key;
  14522. /*--------------------------------------------------------------------------*/
  14523. /**
  14524. * A generic error utility function.
  14525. * @private
  14526. * @param {String} type The error type.
  14527. * @returns {Error} Throws a `RangeError` with the applicable error message.
  14528. */
  14529. function error(type) {
  14530. throw RangeError(errors[type]);
  14531. }
  14532. /**
  14533. * A generic `Array#map` utility function.
  14534. * @private
  14535. * @param {Array} array The array to iterate over.
  14536. * @param {Function} callback The function that gets called for every array
  14537. * item.
  14538. * @returns {Array} A new array of values returned by the callback function.
  14539. */
  14540. function map(array, fn) {
  14541. var length = array.length;
  14542. while (length--) {
  14543. array[length] = fn(array[length]);
  14544. }
  14545. return array;
  14546. }
  14547. /**
  14548. * A simple `Array#map`-like wrapper to work with domain name strings.
  14549. * @private
  14550. * @param {String} domain The domain name.
  14551. * @param {Function} callback The function that gets called for every
  14552. * character.
  14553. * @returns {Array} A new string of characters returned by the callback
  14554. * function.
  14555. */
  14556. function mapDomain(string, fn) {
  14557. return map(string.split(regexSeparators), fn).join('.');
  14558. }
  14559. /**
  14560. * Creates an array containing the numeric code points of each Unicode
  14561. * character in the string. While JavaScript uses UCS-2 internally,
  14562. * this function will convert a pair of surrogate halves (each of which
  14563. * UCS-2 exposes as separate characters) into a single code point,
  14564. * matching UTF-16.
  14565. * @see `punycode.ucs2.encode`
  14566. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  14567. * @memberOf punycode.ucs2
  14568. * @name decode
  14569. * @param {String} string The Unicode input string (UCS-2).
  14570. * @returns {Array} The new array of code points.
  14571. */
  14572. function ucs2decode(string) {
  14573. var output = [],
  14574. counter = 0,
  14575. length = string.length,
  14576. value,
  14577. extra;
  14578. while (counter < length) {
  14579. value = string.charCodeAt(counter++);
  14580. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  14581. // high surrogate, and there is a next character
  14582. extra = string.charCodeAt(counter++);
  14583. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  14584. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  14585. } else {
  14586. // unmatched surrogate; only append this code unit, in case the next
  14587. // code unit is the high surrogate of a surrogate pair
  14588. output.push(value);
  14589. counter--;
  14590. }
  14591. } else {
  14592. output.push(value);
  14593. }
  14594. }
  14595. return output;
  14596. }
  14597. /**
  14598. * Creates a string based on an array of numeric code points.
  14599. * @see `punycode.ucs2.decode`
  14600. * @memberOf punycode.ucs2
  14601. * @name encode
  14602. * @param {Array} codePoints The array of numeric code points.
  14603. * @returns {String} The new Unicode string (UCS-2).
  14604. */
  14605. function ucs2encode(array) {
  14606. return map(array, function(value) {
  14607. var output = '';
  14608. if (value > 0xFFFF) {
  14609. value -= 0x10000;
  14610. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  14611. value = 0xDC00 | value & 0x3FF;
  14612. }
  14613. output += stringFromCharCode(value);
  14614. return output;
  14615. }).join('');
  14616. }
  14617. /**
  14618. * Converts a basic code point into a digit/integer.
  14619. * @see `digitToBasic()`
  14620. * @private
  14621. * @param {Number} codePoint The basic numeric code point value.
  14622. * @returns {Number} The numeric value of a basic code point (for use in
  14623. * representing integers) in the range `0` to `base - 1`, or `base` if
  14624. * the code point does not represent a value.
  14625. */
  14626. function basicToDigit(codePoint) {
  14627. if (codePoint - 48 < 10) {
  14628. return codePoint - 22;
  14629. }
  14630. if (codePoint - 65 < 26) {
  14631. return codePoint - 65;
  14632. }
  14633. if (codePoint - 97 < 26) {
  14634. return codePoint - 97;
  14635. }
  14636. return base;
  14637. }
  14638. /**
  14639. * Converts a digit/integer into a basic code point.
  14640. * @see `basicToDigit()`
  14641. * @private
  14642. * @param {Number} digit The numeric value of a basic code point.
  14643. * @returns {Number} The basic code point whose value (when used for
  14644. * representing integers) is `digit`, which needs to be in the range
  14645. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  14646. * used; else, the lowercase form is used. The behavior is undefined
  14647. * if `flag` is non-zero and `digit` has no uppercase form.
  14648. */
  14649. function digitToBasic(digit, flag) {
  14650. // 0..25 map to ASCII a..z or A..Z
  14651. // 26..35 map to ASCII 0..9
  14652. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  14653. }
  14654. /**
  14655. * Bias adaptation function as per section 3.4 of RFC 3492.
  14656. * http://tools.ietf.org/html/rfc3492#section-3.4
  14657. * @private
  14658. */
  14659. function adapt(delta, numPoints, firstTime) {
  14660. var k = 0;
  14661. delta = firstTime ? floor(delta / damp) : delta >> 1;
  14662. delta += floor(delta / numPoints);
  14663. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  14664. delta = floor(delta / baseMinusTMin);
  14665. }
  14666. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  14667. }
  14668. /**
  14669. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  14670. * symbols.
  14671. * @memberOf punycode
  14672. * @param {String} input The Punycode string of ASCII-only symbols.
  14673. * @returns {String} The resulting string of Unicode symbols.
  14674. */
  14675. function decode(input) {
  14676. // Don't use UCS-2
  14677. var output = [],
  14678. inputLength = input.length,
  14679. out,
  14680. i = 0,
  14681. n = initialN,
  14682. bias = initialBias,
  14683. basic,
  14684. j,
  14685. index,
  14686. oldi,
  14687. w,
  14688. k,
  14689. digit,
  14690. t,
  14691. /** Cached calculation results */
  14692. baseMinusT;
  14693. // Handle the basic code points: let `basic` be the number of input code
  14694. // points before the last delimiter, or `0` if there is none, then copy
  14695. // the first basic code points to the output.
  14696. basic = input.lastIndexOf(delimiter);
  14697. if (basic < 0) {
  14698. basic = 0;
  14699. }
  14700. for (j = 0; j < basic; ++j) {
  14701. // if it's not a basic code point
  14702. if (input.charCodeAt(j) >= 0x80) {
  14703. error('not-basic');
  14704. }
  14705. output.push(input.charCodeAt(j));
  14706. }
  14707. // Main decoding loop: start just after the last delimiter if any basic code
  14708. // points were copied; start at the beginning otherwise.
  14709. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  14710. // `index` is the index of the next character to be consumed.
  14711. // Decode a generalized variable-length integer into `delta`,
  14712. // which gets added to `i`. The overflow checking is easier
  14713. // if we increase `i` as we go, then subtract off its starting
  14714. // value at the end to obtain `delta`.
  14715. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  14716. if (index >= inputLength) {
  14717. error('invalid-input');
  14718. }
  14719. digit = basicToDigit(input.charCodeAt(index++));
  14720. if (digit >= base || digit > floor((maxInt - i) / w)) {
  14721. error('overflow');
  14722. }
  14723. i += digit * w;
  14724. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  14725. if (digit < t) {
  14726. break;
  14727. }
  14728. baseMinusT = base - t;
  14729. if (w > floor(maxInt / baseMinusT)) {
  14730. error('overflow');
  14731. }
  14732. w *= baseMinusT;
  14733. }
  14734. out = output.length + 1;
  14735. bias = adapt(i - oldi, out, oldi == 0);
  14736. // `i` was supposed to wrap around from `out` to `0`,
  14737. // incrementing `n` each time, so we'll fix that now:
  14738. if (floor(i / out) > maxInt - n) {
  14739. error('overflow');
  14740. }
  14741. n += floor(i / out);
  14742. i %= out;
  14743. // Insert `n` at position `i` of the output
  14744. output.splice(i++, 0, n);
  14745. }
  14746. return ucs2encode(output);
  14747. }
  14748. /**
  14749. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  14750. * symbols.
  14751. * @memberOf punycode
  14752. * @param {String} input The string of Unicode symbols.
  14753. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  14754. */
  14755. function encode(input) {
  14756. var n,
  14757. delta,
  14758. handledCPCount,
  14759. basicLength,
  14760. bias,
  14761. j,
  14762. m,
  14763. q,
  14764. k,
  14765. t,
  14766. currentValue,
  14767. output = [],
  14768. /** `inputLength` will hold the number of code points in `input`. */
  14769. inputLength,
  14770. /** Cached calculation results */
  14771. handledCPCountPlusOne,
  14772. baseMinusT,
  14773. qMinusT;
  14774. // Convert the input in UCS-2 to Unicode
  14775. input = ucs2decode(input);
  14776. // Cache the length
  14777. inputLength = input.length;
  14778. // Initialize the state
  14779. n = initialN;
  14780. delta = 0;
  14781. bias = initialBias;
  14782. // Handle the basic code points
  14783. for (j = 0; j < inputLength; ++j) {
  14784. currentValue = input[j];
  14785. if (currentValue < 0x80) {
  14786. output.push(stringFromCharCode(currentValue));
  14787. }
  14788. }
  14789. handledCPCount = basicLength = output.length;
  14790. // `handledCPCount` is the number of code points that have been handled;
  14791. // `basicLength` is the number of basic code points.
  14792. // Finish the basic string - if it is not empty - with a delimiter
  14793. if (basicLength) {
  14794. output.push(delimiter);
  14795. }
  14796. // Main encoding loop:
  14797. while (handledCPCount < inputLength) {
  14798. // All non-basic code points < n have been handled already. Find the next
  14799. // larger one:
  14800. for (m = maxInt, j = 0; j < inputLength; ++j) {
  14801. currentValue = input[j];
  14802. if (currentValue >= n && currentValue < m) {
  14803. m = currentValue;
  14804. }
  14805. }
  14806. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  14807. // but guard against overflow
  14808. handledCPCountPlusOne = handledCPCount + 1;
  14809. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  14810. error('overflow');
  14811. }
  14812. delta += (m - n) * handledCPCountPlusOne;
  14813. n = m;
  14814. for (j = 0; j < inputLength; ++j) {
  14815. currentValue = input[j];
  14816. if (currentValue < n && ++delta > maxInt) {
  14817. error('overflow');
  14818. }
  14819. if (currentValue == n) {
  14820. // Represent delta as a generalized variable-length integer
  14821. for (q = delta, k = base; /* no condition */; k += base) {
  14822. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  14823. if (q < t) {
  14824. break;
  14825. }
  14826. qMinusT = q - t;
  14827. baseMinusT = base - t;
  14828. output.push(
  14829. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  14830. );
  14831. q = floor(qMinusT / baseMinusT);
  14832. }
  14833. output.push(stringFromCharCode(digitToBasic(q, 0)));
  14834. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  14835. delta = 0;
  14836. ++handledCPCount;
  14837. }
  14838. }
  14839. ++delta;
  14840. ++n;
  14841. }
  14842. return output.join('');
  14843. }
  14844. /**
  14845. * Converts a Punycode string representing a domain name to Unicode. Only the
  14846. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  14847. * matter if you call it on a string that has already been converted to
  14848. * Unicode.
  14849. * @memberOf punycode
  14850. * @param {String} domain The Punycode domain name to convert to Unicode.
  14851. * @returns {String} The Unicode representation of the given Punycode
  14852. * string.
  14853. */
  14854. function toUnicode(domain) {
  14855. return mapDomain(domain, function(string) {
  14856. return regexPunycode.test(string)
  14857. ? decode(string.slice(4).toLowerCase())
  14858. : string;
  14859. });
  14860. }
  14861. /**
  14862. * Converts a Unicode string representing a domain name to Punycode. Only the
  14863. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  14864. * matter if you call it with a domain that's already in ASCII.
  14865. * @memberOf punycode
  14866. * @param {String} domain The domain name to convert, as a Unicode string.
  14867. * @returns {String} The Punycode representation of the given domain name.
  14868. */
  14869. function toASCII(domain) {
  14870. return mapDomain(domain, function(string) {
  14871. return regexNonASCII.test(string)
  14872. ? 'xn--' + encode(string)
  14873. : string;
  14874. });
  14875. }
  14876. /*--------------------------------------------------------------------------*/
  14877. /** Define the public API */
  14878. punycode = {
  14879. /**
  14880. * A string representing the current Punycode.js version number.
  14881. * @memberOf punycode
  14882. * @type String
  14883. */
  14884. 'version': '1.2.4',
  14885. /**
  14886. * An object of methods to convert from JavaScript's internal character
  14887. * representation (UCS-2) to Unicode code points, and back.
  14888. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  14889. * @memberOf punycode
  14890. * @type Object
  14891. */
  14892. 'ucs2': {
  14893. 'decode': ucs2decode,
  14894. 'encode': ucs2encode
  14895. },
  14896. 'decode': decode,
  14897. 'encode': encode,
  14898. 'toASCII': toASCII,
  14899. 'toUnicode': toUnicode
  14900. };
  14901. /** Expose `punycode` */
  14902. // Some AMD build optimizers, like r.js, check for specific condition patterns
  14903. // like the following:
  14904. if (freeExports && !freeExports.nodeType) {
  14905. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  14906. freeModule.exports = punycode;
  14907. } else { // in Narwhal or RingoJS v0.7.0-
  14908. for (key in punycode) {
  14909. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  14910. }
  14911. }
  14912. } else { // in Rhino or a web browser
  14913. root.punycode = punycode;
  14914. }
  14915. }(this));
  14916. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
  14917. },{}],2:[function(_dereq_,module,exports){
  14918. var log = _dereq_('./log');
  14919. function restoreOwnerScroll(ownerDocument, x, y) {
  14920. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  14921. ownerDocument.defaultView.scrollTo(x, y);
  14922. }
  14923. }
  14924. function cloneCanvasContents(canvas, clonedCanvas) {
  14925. try {
  14926. if (clonedCanvas) {
  14927. clonedCanvas.width = canvas.width;
  14928. clonedCanvas.height = canvas.height;
  14929. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  14930. }
  14931. } catch(e) {
  14932. log("Unable to copy canvas content from", canvas, e);
  14933. }
  14934. }
  14935. function cloneNode(node, javascriptEnabled) {
  14936. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  14937. var child = node.firstChild;
  14938. while(child) {
  14939. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  14940. clone.appendChild(cloneNode(child, javascriptEnabled));
  14941. }
  14942. child = child.nextSibling;
  14943. }
  14944. if (node.nodeType === 1) {
  14945. clone._scrollTop = node.scrollTop;
  14946. clone._scrollLeft = node.scrollLeft;
  14947. if (node.nodeName === "CANVAS") {
  14948. cloneCanvasContents(node, clone);
  14949. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  14950. clone.value = node.value;
  14951. }
  14952. }
  14953. return clone;
  14954. }
  14955. function initNode(node) {
  14956. if (node.nodeType === 1) {
  14957. node.scrollTop = node._scrollTop;
  14958. node.scrollLeft = node._scrollLeft;
  14959. var child = node.firstChild;
  14960. while(child) {
  14961. initNode(child);
  14962. child = child.nextSibling;
  14963. }
  14964. }
  14965. }
  14966. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  14967. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  14968. var container = containerDocument.createElement("iframe");
  14969. container.className = "html2canvas-container";
  14970. container.style.visibility = "hidden";
  14971. container.style.position = "fixed";
  14972. container.style.left = "-10000px";
  14973. container.style.top = "0px";
  14974. container.style.border = "0";
  14975. container.width = width;
  14976. container.height = height;
  14977. container.scrolling = "no"; // ios won't scroll without it
  14978. containerDocument.body.appendChild(container);
  14979. return new Promise(function(resolve) {
  14980. var documentClone = container.contentWindow.document;
  14981. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  14982. if window url is about:blank, we can assign the url to current by writing onto the document
  14983. */
  14984. container.contentWindow.onload = container.onload = function() {
  14985. var interval = setInterval(function() {
  14986. if (documentClone.body.childNodes.length > 0) {
  14987. initNode(documentClone.documentElement);
  14988. clearInterval(interval);
  14989. if (options.type === "view") {
  14990. container.contentWindow.scrollTo(x, y);
  14991. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  14992. documentClone.documentElement.style.top = (-y) + "px";
  14993. documentClone.documentElement.style.left = (-x) + "px";
  14994. documentClone.documentElement.style.position = 'absolute';
  14995. }
  14996. }
  14997. resolve(container);
  14998. }
  14999. }, 50);
  15000. };
  15001. documentClone.open();
  15002. documentClone.write("<!DOCTYPE html><html></html>");
  15003. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  15004. restoreOwnerScroll(ownerDocument, x, y);
  15005. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  15006. documentClone.close();
  15007. });
  15008. };
  15009. },{"./log":13}],3:[function(_dereq_,module,exports){
  15010. // http://dev.w3.org/csswg/css-color/
  15011. function Color(value) {
  15012. this.r = 0;
  15013. this.g = 0;
  15014. this.b = 0;
  15015. this.a = null;
  15016. var result = this.fromArray(value) ||
  15017. this.namedColor(value) ||
  15018. this.rgb(value) ||
  15019. this.rgba(value) ||
  15020. this.hex6(value) ||
  15021. this.hex3(value);
  15022. }
  15023. Color.prototype.darken = function(amount) {
  15024. var a = 1 - amount;
  15025. return new Color([
  15026. Math.round(this.r * a),
  15027. Math.round(this.g * a),
  15028. Math.round(this.b * a),
  15029. this.a
  15030. ]);
  15031. };
  15032. Color.prototype.isTransparent = function() {
  15033. return this.a === 0;
  15034. };
  15035. Color.prototype.isBlack = function() {
  15036. return this.r === 0 && this.g === 0 && this.b === 0;
  15037. };
  15038. Color.prototype.fromArray = function(array) {
  15039. if (Array.isArray(array)) {
  15040. this.r = Math.min(array[0], 255);
  15041. this.g = Math.min(array[1], 255);
  15042. this.b = Math.min(array[2], 255);
  15043. if (array.length > 3) {
  15044. this.a = array[3];
  15045. }
  15046. }
  15047. return (Array.isArray(array));
  15048. };
  15049. var _hex3 = /^#([a-f0-9]{3})$/i;
  15050. Color.prototype.hex3 = function(value) {
  15051. var match = null;
  15052. if ((match = value.match(_hex3)) !== null) {
  15053. this.r = parseInt(match[1][0] + match[1][0], 16);
  15054. this.g = parseInt(match[1][1] + match[1][1], 16);
  15055. this.b = parseInt(match[1][2] + match[1][2], 16);
  15056. }
  15057. return match !== null;
  15058. };
  15059. var _hex6 = /^#([a-f0-9]{6})$/i;
  15060. Color.prototype.hex6 = function(value) {
  15061. var match = null;
  15062. if ((match = value.match(_hex6)) !== null) {
  15063. this.r = parseInt(match[1].substring(0, 2), 16);
  15064. this.g = parseInt(match[1].substring(2, 4), 16);
  15065. this.b = parseInt(match[1].substring(4, 6), 16);
  15066. }
  15067. return match !== null;
  15068. };
  15069. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  15070. Color.prototype.rgb = function(value) {
  15071. var match = null;
  15072. if ((match = value.match(_rgb)) !== null) {
  15073. this.r = Number(match[1]);
  15074. this.g = Number(match[2]);
  15075. this.b = Number(match[3]);
  15076. }
  15077. return match !== null;
  15078. };
  15079. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  15080. Color.prototype.rgba = function(value) {
  15081. var match = null;
  15082. if ((match = value.match(_rgba)) !== null) {
  15083. this.r = Number(match[1]);
  15084. this.g = Number(match[2]);
  15085. this.b = Number(match[3]);
  15086. this.a = Number(match[4]);
  15087. }
  15088. return match !== null;
  15089. };
  15090. Color.prototype.toString = function() {
  15091. return this.a !== null && this.a !== 1 ?
  15092. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  15093. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  15094. };
  15095. Color.prototype.namedColor = function(value) {
  15096. value = value.toLowerCase();
  15097. var color = colors[value];
  15098. if (color) {
  15099. this.r = color[0];
  15100. this.g = color[1];
  15101. this.b = color[2];
  15102. } else if (value === "transparent") {
  15103. this.r = this.g = this.b = this.a = 0;
  15104. return true;
  15105. }
  15106. return !!color;
  15107. };
  15108. Color.prototype.isColor = true;
  15109. // 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}, {}))
  15110. var colors = {
  15111. "aliceblue": [240, 248, 255],
  15112. "antiquewhite": [250, 235, 215],
  15113. "aqua": [0, 255, 255],
  15114. "aquamarine": [127, 255, 212],
  15115. "azure": [240, 255, 255],
  15116. "beige": [245, 245, 220],
  15117. "bisque": [255, 228, 196],
  15118. "black": [0, 0, 0],
  15119. "blanchedalmond": [255, 235, 205],
  15120. "blue": [0, 0, 255],
  15121. "blueviolet": [138, 43, 226],
  15122. "brown": [165, 42, 42],
  15123. "burlywood": [222, 184, 135],
  15124. "cadetblue": [95, 158, 160],
  15125. "chartreuse": [127, 255, 0],
  15126. "chocolate": [210, 105, 30],
  15127. "coral": [255, 127, 80],
  15128. "cornflowerblue": [100, 149, 237],
  15129. "cornsilk": [255, 248, 220],
  15130. "crimson": [220, 20, 60],
  15131. "cyan": [0, 255, 255],
  15132. "darkblue": [0, 0, 139],
  15133. "darkcyan": [0, 139, 139],
  15134. "darkgoldenrod": [184, 134, 11],
  15135. "darkgray": [169, 169, 169],
  15136. "darkgreen": [0, 100, 0],
  15137. "darkgrey": [169, 169, 169],
  15138. "darkkhaki": [189, 183, 107],
  15139. "darkmagenta": [139, 0, 139],
  15140. "darkolivegreen": [85, 107, 47],
  15141. "darkorange": [255, 140, 0],
  15142. "darkorchid": [153, 50, 204],
  15143. "darkred": [139, 0, 0],
  15144. "darksalmon": [233, 150, 122],
  15145. "darkseagreen": [143, 188, 143],
  15146. "darkslateblue": [72, 61, 139],
  15147. "darkslategray": [47, 79, 79],
  15148. "darkslategrey": [47, 79, 79],
  15149. "darkturquoise": [0, 206, 209],
  15150. "darkviolet": [148, 0, 211],
  15151. "deeppink": [255, 20, 147],
  15152. "deepskyblue": [0, 191, 255],
  15153. "dimgray": [105, 105, 105],
  15154. "dimgrey": [105, 105, 105],
  15155. "dodgerblue": [30, 144, 255],
  15156. "firebrick": [178, 34, 34],
  15157. "floralwhite": [255, 250, 240],
  15158. "forestgreen": [34, 139, 34],
  15159. "fuchsia": [255, 0, 255],
  15160. "gainsboro": [220, 220, 220],
  15161. "ghostwhite": [248, 248, 255],
  15162. "gold": [255, 215, 0],
  15163. "goldenrod": [218, 165, 32],
  15164. "gray": [128, 128, 128],
  15165. "green": [0, 128, 0],
  15166. "greenyellow": [173, 255, 47],
  15167. "grey": [128, 128, 128],
  15168. "honeydew": [240, 255, 240],
  15169. "hotpink": [255, 105, 180],
  15170. "indianred": [205, 92, 92],
  15171. "indigo": [75, 0, 130],
  15172. "ivory": [255, 255, 240],
  15173. "khaki": [240, 230, 140],
  15174. "lavender": [230, 230, 250],
  15175. "lavenderblush": [255, 240, 245],
  15176. "lawngreen": [124, 252, 0],
  15177. "lemonchiffon": [255, 250, 205],
  15178. "lightblue": [173, 216, 230],
  15179. "lightcoral": [240, 128, 128],
  15180. "lightcyan": [224, 255, 255],
  15181. "lightgoldenrodyellow": [250, 250, 210],
  15182. "lightgray": [211, 211, 211],
  15183. "lightgreen": [144, 238, 144],
  15184. "lightgrey": [211, 211, 211],
  15185. "lightpink": [255, 182, 193],
  15186. "lightsalmon": [255, 160, 122],
  15187. "lightseagreen": [32, 178, 170],
  15188. "lightskyblue": [135, 206, 250],
  15189. "lightslategray": [119, 136, 153],
  15190. "lightslategrey": [119, 136, 153],
  15191. "lightsteelblue": [176, 196, 222],
  15192. "lightyellow": [255, 255, 224],
  15193. "lime": [0, 255, 0],
  15194. "limegreen": [50, 205, 50],
  15195. "linen": [250, 240, 230],
  15196. "magenta": [255, 0, 255],
  15197. "maroon": [128, 0, 0],
  15198. "mediumaquamarine": [102, 205, 170],
  15199. "mediumblue": [0, 0, 205],
  15200. "mediumorchid": [186, 85, 211],
  15201. "mediumpurple": [147, 112, 219],
  15202. "mediumseagreen": [60, 179, 113],
  15203. "mediumslateblue": [123, 104, 238],
  15204. "mediumspringgreen": [0, 250, 154],
  15205. "mediumturquoise": [72, 209, 204],
  15206. "mediumvioletred": [199, 21, 133],
  15207. "midnightblue": [25, 25, 112],
  15208. "mintcream": [245, 255, 250],
  15209. "mistyrose": [255, 228, 225],
  15210. "moccasin": [255, 228, 181],
  15211. "navajowhite": [255, 222, 173],
  15212. "navy": [0, 0, 128],
  15213. "oldlace": [253, 245, 230],
  15214. "olive": [128, 128, 0],
  15215. "olivedrab": [107, 142, 35],
  15216. "orange": [255, 165, 0],
  15217. "orangered": [255, 69, 0],
  15218. "orchid": [218, 112, 214],
  15219. "palegoldenrod": [238, 232, 170],
  15220. "palegreen": [152, 251, 152],
  15221. "paleturquoise": [175, 238, 238],
  15222. "palevioletred": [219, 112, 147],
  15223. "papayawhip": [255, 239, 213],
  15224. "peachpuff": [255, 218, 185],
  15225. "peru": [205, 133, 63],
  15226. "pink": [255, 192, 203],
  15227. "plum": [221, 160, 221],
  15228. "powderblue": [176, 224, 230],
  15229. "purple": [128, 0, 128],
  15230. "rebeccapurple": [102, 51, 153],
  15231. "red": [255, 0, 0],
  15232. "rosybrown": [188, 143, 143],
  15233. "royalblue": [65, 105, 225],
  15234. "saddlebrown": [139, 69, 19],
  15235. "salmon": [250, 128, 114],
  15236. "sandybrown": [244, 164, 96],
  15237. "seagreen": [46, 139, 87],
  15238. "seashell": [255, 245, 238],
  15239. "sienna": [160, 82, 45],
  15240. "silver": [192, 192, 192],
  15241. "skyblue": [135, 206, 235],
  15242. "slateblue": [106, 90, 205],
  15243. "slategray": [112, 128, 144],
  15244. "slategrey": [112, 128, 144],
  15245. "snow": [255, 250, 250],
  15246. "springgreen": [0, 255, 127],
  15247. "steelblue": [70, 130, 180],
  15248. "tan": [210, 180, 140],
  15249. "teal": [0, 128, 128],
  15250. "thistle": [216, 191, 216],
  15251. "tomato": [255, 99, 71],
  15252. "turquoise": [64, 224, 208],
  15253. "violet": [238, 130, 238],
  15254. "wheat": [245, 222, 179],
  15255. "white": [255, 255, 255],
  15256. "whitesmoke": [245, 245, 245],
  15257. "yellow": [255, 255, 0],
  15258. "yellowgreen": [154, 205, 50]
  15259. };
  15260. module.exports = Color;
  15261. },{}],4:[function(_dereq_,module,exports){
  15262. var Support = _dereq_('./support');
  15263. var CanvasRenderer = _dereq_('./renderers/canvas');
  15264. var ImageLoader = _dereq_('./imageloader');
  15265. var NodeParser = _dereq_('./nodeparser');
  15266. var NodeContainer = _dereq_('./nodecontainer');
  15267. var log = _dereq_('./log');
  15268. var utils = _dereq_('./utils');
  15269. var createWindowClone = _dereq_('./clone');
  15270. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  15271. var getBounds = utils.getBounds;
  15272. var html2canvasNodeAttribute = "data-html2canvas-node";
  15273. var html2canvasCloneIndex = 0;
  15274. function html2canvas(nodeList, options) {
  15275. var index = html2canvasCloneIndex++;
  15276. options = options || {};
  15277. if (options.logging) {
  15278. log.options.logging = true;
  15279. log.options.start = Date.now();
  15280. }
  15281. options.async = typeof(options.async) === "undefined" ? true : options.async;
  15282. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  15283. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  15284. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  15285. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  15286. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  15287. options.strict = !!options.strict;
  15288. if (typeof(nodeList) === "string") {
  15289. if (typeof(options.proxy) !== "string") {
  15290. return Promise.reject("Proxy must be used when rendering url");
  15291. }
  15292. var width = options.width != null ? options.width : window.innerWidth;
  15293. var height = options.height != null ? options.height : window.innerHeight;
  15294. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  15295. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  15296. });
  15297. }
  15298. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  15299. node.setAttribute(html2canvasNodeAttribute + index, index);
  15300. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  15301. if (typeof(options.onrendered) === "function") {
  15302. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  15303. options.onrendered(canvas);
  15304. }
  15305. return canvas;
  15306. });
  15307. }
  15308. html2canvas.CanvasRenderer = CanvasRenderer;
  15309. html2canvas.NodeContainer = NodeContainer;
  15310. html2canvas.log = log;
  15311. html2canvas.utils = utils;
  15312. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  15313. return Promise.reject("No canvas support");
  15314. } : html2canvas;
  15315. module.exports = html2canvasExport;
  15316. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  15317. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  15318. log("Document cloned");
  15319. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  15320. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  15321. document.querySelector(selector).removeAttribute(attributeName);
  15322. var clonedWindow = container.contentWindow;
  15323. var node = clonedWindow.document.querySelector(selector);
  15324. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  15325. return oncloneHandler.then(function() {
  15326. return renderWindow(node, container, options, windowWidth, windowHeight);
  15327. });
  15328. });
  15329. }
  15330. function renderWindow(node, container, options, windowWidth, windowHeight) {
  15331. var clonedWindow = container.contentWindow;
  15332. var support = new Support(clonedWindow.document);
  15333. var imageLoader = new ImageLoader(options, support);
  15334. var bounds = getBounds(node);
  15335. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  15336. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  15337. var renderer = new options.renderer(width, height, imageLoader, options, document);
  15338. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  15339. return parser.ready.then(function() {
  15340. log("Finished rendering");
  15341. var canvas;
  15342. if (options.type === "view") {
  15343. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  15344. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  15345. canvas = renderer.canvas;
  15346. } else {
  15347. 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});
  15348. }
  15349. cleanupContainer(container, options);
  15350. return canvas;
  15351. });
  15352. }
  15353. function cleanupContainer(container, options) {
  15354. if (options.removeContainer) {
  15355. container.parentNode.removeChild(container);
  15356. log("Cleaned up container");
  15357. }
  15358. }
  15359. function crop(canvas, bounds) {
  15360. var croppedCanvas = document.createElement("canvas");
  15361. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  15362. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  15363. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  15364. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  15365. croppedCanvas.width = bounds.width;
  15366. croppedCanvas.height = bounds.height;
  15367. var width = x2-x1;
  15368. var height = y2-y1;
  15369. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  15370. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  15371. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  15372. return croppedCanvas;
  15373. }
  15374. function documentWidth (doc) {
  15375. return Math.max(
  15376. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  15377. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  15378. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  15379. );
  15380. }
  15381. function documentHeight (doc) {
  15382. return Math.max(
  15383. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  15384. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  15385. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  15386. );
  15387. }
  15388. function absoluteUrl(url) {
  15389. var link = document.createElement("a");
  15390. link.href = url;
  15391. link.href = link.href;
  15392. return link;
  15393. }
  15394. },{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
  15395. var log = _dereq_('./log');
  15396. var smallImage = _dereq_('./utils').smallImage;
  15397. function DummyImageContainer(src) {
  15398. this.src = src;
  15399. log("DummyImageContainer for", src);
  15400. if (!this.promise || !this.image) {
  15401. log("Initiating DummyImageContainer");
  15402. DummyImageContainer.prototype.image = new Image();
  15403. var image = this.image;
  15404. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  15405. image.onload = resolve;
  15406. image.onerror = reject;
  15407. image.src = smallImage();
  15408. if (image.complete === true) {
  15409. resolve(image);
  15410. }
  15411. });
  15412. }
  15413. }
  15414. module.exports = DummyImageContainer;
  15415. },{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
  15416. var smallImage = _dereq_('./utils').smallImage;
  15417. function Font(family, size) {
  15418. var container = document.createElement('div'),
  15419. img = document.createElement('img'),
  15420. span = document.createElement('span'),
  15421. sampleText = 'Hidden Text',
  15422. baseline,
  15423. middle;
  15424. container.style.visibility = "hidden";
  15425. container.style.fontFamily = family;
  15426. container.style.fontSize = size;
  15427. container.style.margin = 0;
  15428. container.style.padding = 0;
  15429. document.body.appendChild(container);
  15430. img.src = smallImage();
  15431. img.width = 1;
  15432. img.height = 1;
  15433. img.style.margin = 0;
  15434. img.style.padding = 0;
  15435. img.style.verticalAlign = "baseline";
  15436. span.style.fontFamily = family;
  15437. span.style.fontSize = size;
  15438. span.style.margin = 0;
  15439. span.style.padding = 0;
  15440. span.appendChild(document.createTextNode(sampleText));
  15441. container.appendChild(span);
  15442. container.appendChild(img);
  15443. baseline = (img.offsetTop - span.offsetTop) + 1;
  15444. container.removeChild(span);
  15445. container.appendChild(document.createTextNode(sampleText));
  15446. container.style.lineHeight = "normal";
  15447. img.style.verticalAlign = "super";
  15448. middle = (img.offsetTop-container.offsetTop) + 1;
  15449. document.body.removeChild(container);
  15450. this.baseline = baseline;
  15451. this.lineWidth = 1;
  15452. this.middle = middle;
  15453. }
  15454. module.exports = Font;
  15455. },{"./utils":26}],7:[function(_dereq_,module,exports){
  15456. var Font = _dereq_('./font');
  15457. function FontMetrics() {
  15458. this.data = {};
  15459. }
  15460. FontMetrics.prototype.getMetrics = function(family, size) {
  15461. if (this.data[family + "-" + size] === undefined) {
  15462. this.data[family + "-" + size] = new Font(family, size);
  15463. }
  15464. return this.data[family + "-" + size];
  15465. };
  15466. module.exports = FontMetrics;
  15467. },{"./font":6}],8:[function(_dereq_,module,exports){
  15468. var utils = _dereq_('./utils');
  15469. var getBounds = utils.getBounds;
  15470. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  15471. function FrameContainer(container, sameOrigin, options) {
  15472. this.image = null;
  15473. this.src = container;
  15474. var self = this;
  15475. var bounds = getBounds(container);
  15476. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  15477. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  15478. container.contentWindow.onload = container.onload = function() {
  15479. resolve(container);
  15480. };
  15481. } else {
  15482. resolve(container);
  15483. }
  15484. })).then(function(container) {
  15485. var html2canvas = _dereq_('./core');
  15486. 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});
  15487. }).then(function(canvas) {
  15488. return self.image = canvas;
  15489. });
  15490. }
  15491. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  15492. var container = this.src;
  15493. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  15494. };
  15495. module.exports = FrameContainer;
  15496. },{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
  15497. function GradientContainer(imageData) {
  15498. this.src = imageData.value;
  15499. this.colorStops = [];
  15500. this.type = null;
  15501. this.x0 = 0.5;
  15502. this.y0 = 0.5;
  15503. this.x1 = 0.5;
  15504. this.y1 = 0.5;
  15505. this.promise = Promise.resolve(true);
  15506. }
  15507. GradientContainer.TYPES = {
  15508. LINEAR: 1,
  15509. RADIAL: 2
  15510. };
  15511. // TODO: support hsl[a], negative %/length values
  15512. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  15513. 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;
  15514. module.exports = GradientContainer;
  15515. },{}],10:[function(_dereq_,module,exports){
  15516. function ImageContainer(src, cors) {
  15517. this.src = src;
  15518. this.image = new Image();
  15519. var self = this;
  15520. this.tainted = null;
  15521. this.promise = new Promise(function(resolve, reject) {
  15522. self.image.onload = resolve;
  15523. self.image.onerror = reject;
  15524. if (cors) {
  15525. self.image.crossOrigin = "anonymous";
  15526. }
  15527. self.image.src = src;
  15528. if (self.image.complete === true) {
  15529. resolve(self.image);
  15530. }
  15531. });
  15532. }
  15533. module.exports = ImageContainer;
  15534. },{}],11:[function(_dereq_,module,exports){
  15535. var log = _dereq_('./log');
  15536. var ImageContainer = _dereq_('./imagecontainer');
  15537. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  15538. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  15539. var FrameContainer = _dereq_('./framecontainer');
  15540. var SVGContainer = _dereq_('./svgcontainer');
  15541. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  15542. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  15543. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  15544. var bind = _dereq_('./utils').bind;
  15545. function ImageLoader(options, support) {
  15546. this.link = null;
  15547. this.options = options;
  15548. this.support = support;
  15549. this.origin = this.getOrigin(window.location.href);
  15550. }
  15551. ImageLoader.prototype.findImages = function(nodes) {
  15552. var images = [];
  15553. nodes.reduce(function(imageNodes, container) {
  15554. switch(container.node.nodeName) {
  15555. case "IMG":
  15556. return imageNodes.concat([{
  15557. args: [container.node.src],
  15558. method: "url"
  15559. }]);
  15560. case "svg":
  15561. case "IFRAME":
  15562. return imageNodes.concat([{
  15563. args: [container.node],
  15564. method: container.node.nodeName
  15565. }]);
  15566. }
  15567. return imageNodes;
  15568. }, []).forEach(this.addImage(images, this.loadImage), this);
  15569. return images;
  15570. };
  15571. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  15572. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  15573. return images;
  15574. };
  15575. ImageLoader.prototype.addImage = function(images, callback) {
  15576. return function(newImage) {
  15577. newImage.args.forEach(function(image) {
  15578. if (!this.imageExists(images, image)) {
  15579. images.splice(0, 0, callback.call(this, newImage));
  15580. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  15581. }
  15582. }, this);
  15583. };
  15584. };
  15585. ImageLoader.prototype.hasImageBackground = function(imageData) {
  15586. return imageData.method !== "none";
  15587. };
  15588. ImageLoader.prototype.loadImage = function(imageData) {
  15589. if (imageData.method === "url") {
  15590. var src = imageData.args[0];
  15591. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  15592. return new SVGContainer(src);
  15593. } else if (src.match(/data:image\/.*;base64,/i)) {
  15594. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  15595. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  15596. return new ImageContainer(src, false);
  15597. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  15598. return new ImageContainer(src, true);
  15599. } else if (this.options.proxy) {
  15600. return new ProxyImageContainer(src, this.options.proxy);
  15601. } else {
  15602. return new DummyImageContainer(src);
  15603. }
  15604. } else if (imageData.method === "linear-gradient") {
  15605. return new LinearGradientContainer(imageData);
  15606. } else if (imageData.method === "gradient") {
  15607. return new WebkitGradientContainer(imageData);
  15608. } else if (imageData.method === "svg") {
  15609. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  15610. } else if (imageData.method === "IFRAME") {
  15611. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  15612. } else {
  15613. return new DummyImageContainer(imageData);
  15614. }
  15615. };
  15616. ImageLoader.prototype.isSVG = function(src) {
  15617. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  15618. };
  15619. ImageLoader.prototype.imageExists = function(images, src) {
  15620. return images.some(function(image) {
  15621. return image.src === src;
  15622. });
  15623. };
  15624. ImageLoader.prototype.isSameOrigin = function(url) {
  15625. return (this.getOrigin(url) === this.origin);
  15626. };
  15627. ImageLoader.prototype.getOrigin = function(url) {
  15628. var link = this.link || (this.link = document.createElement("a"));
  15629. link.href = url;
  15630. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  15631. return link.protocol + link.hostname + link.port;
  15632. };
  15633. ImageLoader.prototype.getPromise = function(container) {
  15634. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  15635. var dummy = new DummyImageContainer(container.src);
  15636. return dummy.promise.then(function(image) {
  15637. container.image = image;
  15638. });
  15639. });
  15640. };
  15641. ImageLoader.prototype.get = function(src) {
  15642. var found = null;
  15643. return this.images.some(function(img) {
  15644. return (found = img).src === src;
  15645. }) ? found : null;
  15646. };
  15647. ImageLoader.prototype.fetch = function(nodes) {
  15648. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  15649. this.images.forEach(function(image, index) {
  15650. image.promise.then(function() {
  15651. log("Succesfully loaded image #"+ (index+1), image);
  15652. }, function(e) {
  15653. log("Failed loading image #"+ (index+1), image, e);
  15654. });
  15655. });
  15656. this.ready = Promise.all(this.images.map(this.getPromise, this));
  15657. log("Finished searching images");
  15658. return this;
  15659. };
  15660. ImageLoader.prototype.timeout = function(container, timeout) {
  15661. var timer;
  15662. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  15663. timer = setTimeout(function() {
  15664. log("Timed out loading image", container);
  15665. reject(container);
  15666. }, timeout);
  15667. })]).then(function(container) {
  15668. clearTimeout(timer);
  15669. return container;
  15670. });
  15671. promise['catch'](function() {
  15672. clearTimeout(timer);
  15673. });
  15674. return promise;
  15675. };
  15676. module.exports = ImageLoader;
  15677. },{"./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){
  15678. var GradientContainer = _dereq_('./gradientcontainer');
  15679. var Color = _dereq_('./color');
  15680. function LinearGradientContainer(imageData) {
  15681. GradientContainer.apply(this, arguments);
  15682. this.type = GradientContainer.TYPES.LINEAR;
  15683. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
  15684. !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
  15685. if (hasDirection) {
  15686. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  15687. switch(position) {
  15688. case "left":
  15689. this.x0 = 0;
  15690. this.x1 = 1;
  15691. break;
  15692. case "top":
  15693. this.y0 = 0;
  15694. this.y1 = 1;
  15695. break;
  15696. case "right":
  15697. this.x0 = 1;
  15698. this.x1 = 0;
  15699. break;
  15700. case "bottom":
  15701. this.y0 = 1;
  15702. this.y1 = 0;
  15703. break;
  15704. case "to":
  15705. var y0 = this.y0;
  15706. var x0 = this.x0;
  15707. this.y0 = this.y1;
  15708. this.x0 = this.x1;
  15709. this.x1 = x0;
  15710. this.y1 = y0;
  15711. break;
  15712. case "center":
  15713. break; // centered by default
  15714. // Firefox internally converts position keywords to percentages:
  15715. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  15716. default: // percentage or absolute length
  15717. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  15718. var ratio = parseFloat(position, 10) * 1e-2;
  15719. if (isNaN(ratio)) { // invalid or unhandled value
  15720. break;
  15721. }
  15722. if (index === 0) {
  15723. this.y0 = ratio;
  15724. this.y1 = 1 - this.y0;
  15725. } else {
  15726. this.x0 = ratio;
  15727. this.x1 = 1 - this.x0;
  15728. }
  15729. break;
  15730. }
  15731. }, this);
  15732. } else {
  15733. this.y0 = 0;
  15734. this.y1 = 1;
  15735. }
  15736. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  15737. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  15738. var value = +colorStopMatch[2];
  15739. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  15740. return {
  15741. color: new Color(colorStopMatch[1]),
  15742. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  15743. stop: unit === "%" ? value / 100 : null
  15744. };
  15745. });
  15746. if (this.colorStops[0].stop === null) {
  15747. this.colorStops[0].stop = 0;
  15748. }
  15749. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  15750. this.colorStops[this.colorStops.length - 1].stop = 1;
  15751. }
  15752. // calculates and fills-in explicit stop positions when omitted from rule
  15753. this.colorStops.forEach(function(colorStop, index) {
  15754. if (colorStop.stop === null) {
  15755. this.colorStops.slice(index).some(function(find, count) {
  15756. if (find.stop !== null) {
  15757. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  15758. return true;
  15759. } else {
  15760. return false;
  15761. }
  15762. }, this);
  15763. }
  15764. }, this);
  15765. }
  15766. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  15767. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  15768. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  15769. module.exports = LinearGradientContainer;
  15770. },{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
  15771. var logger = function() {
  15772. if (logger.options.logging && window.console && window.console.log) {
  15773. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  15774. }
  15775. };
  15776. logger.options = {logging: false};
  15777. module.exports = logger;
  15778. },{}],14:[function(_dereq_,module,exports){
  15779. var Color = _dereq_('./color');
  15780. var utils = _dereq_('./utils');
  15781. var getBounds = utils.getBounds;
  15782. var parseBackgrounds = utils.parseBackgrounds;
  15783. var offsetBounds = utils.offsetBounds;
  15784. function NodeContainer(node, parent) {
  15785. this.node = node;
  15786. this.parent = parent;
  15787. this.stack = null;
  15788. this.bounds = null;
  15789. this.borders = null;
  15790. this.clip = [];
  15791. this.backgroundClip = [];
  15792. this.offsetBounds = null;
  15793. this.visible = null;
  15794. this.computedStyles = null;
  15795. this.colors = {};
  15796. this.styles = {};
  15797. this.backgroundImages = null;
  15798. this.transformData = null;
  15799. this.transformMatrix = null;
  15800. this.isPseudoElement = false;
  15801. this.opacity = null;
  15802. }
  15803. NodeContainer.prototype.cloneTo = function(stack) {
  15804. stack.visible = this.visible;
  15805. stack.borders = this.borders;
  15806. stack.bounds = this.bounds;
  15807. stack.clip = this.clip;
  15808. stack.backgroundClip = this.backgroundClip;
  15809. stack.computedStyles = this.computedStyles;
  15810. stack.styles = this.styles;
  15811. stack.backgroundImages = this.backgroundImages;
  15812. stack.opacity = this.opacity;
  15813. };
  15814. NodeContainer.prototype.getOpacity = function() {
  15815. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  15816. };
  15817. NodeContainer.prototype.assignStack = function(stack) {
  15818. this.stack = stack;
  15819. stack.children.push(this);
  15820. };
  15821. NodeContainer.prototype.isElementVisible = function() {
  15822. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  15823. this.css('display') !== "none" &&
  15824. this.css('visibility') !== "hidden" &&
  15825. !this.node.hasAttribute("data-html2canvas-ignore") &&
  15826. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  15827. );
  15828. };
  15829. NodeContainer.prototype.css = function(attribute) {
  15830. if (!this.computedStyles) {
  15831. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  15832. }
  15833. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  15834. };
  15835. NodeContainer.prototype.prefixedCss = function(attribute) {
  15836. var prefixes = ["webkit", "moz", "ms", "o"];
  15837. var value = this.css(attribute);
  15838. if (value === undefined) {
  15839. prefixes.some(function(prefix) {
  15840. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  15841. return value !== undefined;
  15842. }, this);
  15843. }
  15844. return value === undefined ? null : value;
  15845. };
  15846. NodeContainer.prototype.computedStyle = function(type) {
  15847. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  15848. };
  15849. NodeContainer.prototype.cssInt = function(attribute) {
  15850. var value = parseInt(this.css(attribute), 10);
  15851. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  15852. };
  15853. NodeContainer.prototype.color = function(attribute) {
  15854. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  15855. };
  15856. NodeContainer.prototype.cssFloat = function(attribute) {
  15857. var value = parseFloat(this.css(attribute));
  15858. return (isNaN(value)) ? 0 : value;
  15859. };
  15860. NodeContainer.prototype.fontWeight = function() {
  15861. var weight = this.css("fontWeight");
  15862. switch(parseInt(weight, 10)){
  15863. case 401:
  15864. weight = "bold";
  15865. break;
  15866. case 400:
  15867. weight = "normal";
  15868. break;
  15869. }
  15870. return weight;
  15871. };
  15872. NodeContainer.prototype.parseClip = function() {
  15873. var matches = this.css('clip').match(this.CLIP);
  15874. if (matches) {
  15875. return {
  15876. top: parseInt(matches[1], 10),
  15877. right: parseInt(matches[2], 10),
  15878. bottom: parseInt(matches[3], 10),
  15879. left: parseInt(matches[4], 10)
  15880. };
  15881. }
  15882. return null;
  15883. };
  15884. NodeContainer.prototype.parseBackgroundImages = function() {
  15885. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  15886. };
  15887. NodeContainer.prototype.cssList = function(property, index) {
  15888. var value = (this.css(property) || '').split(',');
  15889. value = value[index || 0] || value[0] || 'auto';
  15890. value = value.trim().split(' ');
  15891. if (value.length === 1) {
  15892. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  15893. }
  15894. return value;
  15895. };
  15896. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  15897. var size = this.cssList("backgroundSize", index);
  15898. var width, height;
  15899. if (isPercentage(size[0])) {
  15900. width = bounds.width * parseFloat(size[0]) / 100;
  15901. } else if (/contain|cover/.test(size[0])) {
  15902. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  15903. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  15904. } else {
  15905. width = parseInt(size[0], 10);
  15906. }
  15907. if (size[0] === 'auto' && size[1] === 'auto') {
  15908. height = image.height;
  15909. } else if (size[1] === 'auto') {
  15910. height = width / image.width * image.height;
  15911. } else if (isPercentage(size[1])) {
  15912. height = bounds.height * parseFloat(size[1]) / 100;
  15913. } else {
  15914. height = parseInt(size[1], 10);
  15915. }
  15916. if (size[0] === 'auto') {
  15917. width = height / image.height * image.width;
  15918. }
  15919. return {width: width, height: height};
  15920. };
  15921. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  15922. var position = this.cssList('backgroundPosition', index);
  15923. var left, top;
  15924. if (isPercentage(position[0])){
  15925. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  15926. } else {
  15927. left = parseInt(position[0], 10);
  15928. }
  15929. if (position[1] === 'auto') {
  15930. top = left / image.width * image.height;
  15931. } else if (isPercentage(position[1])){
  15932. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  15933. } else {
  15934. top = parseInt(position[1], 10);
  15935. }
  15936. if (position[0] === 'auto') {
  15937. left = top / image.height * image.width;
  15938. }
  15939. return {left: left, top: top};
  15940. };
  15941. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  15942. return this.cssList("backgroundRepeat", index)[0];
  15943. };
  15944. NodeContainer.prototype.parseTextShadows = function() {
  15945. var textShadow = this.css("textShadow");
  15946. var results = [];
  15947. if (textShadow && textShadow !== 'none') {
  15948. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  15949. for (var i = 0; shadows && (i < shadows.length); i++) {
  15950. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  15951. results.push({
  15952. color: new Color(s[0]),
  15953. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  15954. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  15955. blur: s[3] ? s[3].replace('px', '') : 0
  15956. });
  15957. }
  15958. }
  15959. return results;
  15960. };
  15961. NodeContainer.prototype.parseTransform = function() {
  15962. if (!this.transformData) {
  15963. if (this.hasTransform()) {
  15964. var offset = this.parseBounds();
  15965. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  15966. origin[0] += offset.left;
  15967. origin[1] += offset.top;
  15968. this.transformData = {
  15969. origin: origin,
  15970. matrix: this.parseTransformMatrix()
  15971. };
  15972. } else {
  15973. this.transformData = {
  15974. origin: [0, 0],
  15975. matrix: [1, 0, 0, 1, 0, 0]
  15976. };
  15977. }
  15978. }
  15979. return this.transformData;
  15980. };
  15981. NodeContainer.prototype.parseTransformMatrix = function() {
  15982. if (!this.transformMatrix) {
  15983. var transform = this.prefixedCss("transform");
  15984. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  15985. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  15986. }
  15987. return this.transformMatrix;
  15988. };
  15989. NodeContainer.prototype.parseBounds = function() {
  15990. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  15991. };
  15992. NodeContainer.prototype.hasTransform = function() {
  15993. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  15994. };
  15995. NodeContainer.prototype.getValue = function() {
  15996. var value = this.node.value || "";
  15997. if (this.node.tagName === "SELECT") {
  15998. value = selectionValue(this.node);
  15999. } else if (this.node.type === "password") {
  16000. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  16001. }
  16002. return value.length === 0 ? (this.node.placeholder || "") : value;
  16003. };
  16004. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  16005. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  16006. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  16007. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  16008. function selectionValue(node) {
  16009. var option = node.options[node.selectedIndex || 0];
  16010. return option ? (option.text || "") : "";
  16011. }
  16012. function parseMatrix(match) {
  16013. if (match && match[1] === "matrix") {
  16014. return match[2].split(",").map(function(s) {
  16015. return parseFloat(s.trim());
  16016. });
  16017. } else if (match && match[1] === "matrix3d") {
  16018. var matrix3d = match[2].split(",").map(function(s) {
  16019. return parseFloat(s.trim());
  16020. });
  16021. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  16022. }
  16023. }
  16024. function isPercentage(value) {
  16025. return value.toString().indexOf("%") !== -1;
  16026. }
  16027. function removePx(str) {
  16028. return str.replace("px", "");
  16029. }
  16030. function asFloat(str) {
  16031. return parseFloat(str);
  16032. }
  16033. module.exports = NodeContainer;
  16034. },{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
  16035. var log = _dereq_('./log');
  16036. var punycode = _dereq_('punycode');
  16037. var NodeContainer = _dereq_('./nodecontainer');
  16038. var TextContainer = _dereq_('./textcontainer');
  16039. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  16040. var FontMetrics = _dereq_('./fontmetrics');
  16041. var Color = _dereq_('./color');
  16042. var StackingContext = _dereq_('./stackingcontext');
  16043. var utils = _dereq_('./utils');
  16044. var bind = utils.bind;
  16045. var getBounds = utils.getBounds;
  16046. var parseBackgrounds = utils.parseBackgrounds;
  16047. var offsetBounds = utils.offsetBounds;
  16048. function NodeParser(element, renderer, support, imageLoader, options) {
  16049. log("Starting NodeParser");
  16050. this.renderer = renderer;
  16051. this.options = options;
  16052. this.range = null;
  16053. this.support = support;
  16054. this.renderQueue = [];
  16055. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  16056. var parent = new NodeContainer(element, null);
  16057. if (options.background) {
  16058. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  16059. }
  16060. if (element === element.ownerDocument.documentElement) {
  16061. // http://www.w3.org/TR/css3-background/#special-backgrounds
  16062. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  16063. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  16064. }
  16065. parent.visibile = parent.isElementVisible();
  16066. this.createPseudoHideStyles(element.ownerDocument);
  16067. this.disableAnimations(element.ownerDocument);
  16068. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  16069. return container.visible = container.isElementVisible();
  16070. }).map(this.getPseudoElements, this));
  16071. this.fontMetrics = new FontMetrics();
  16072. log("Fetched nodes, total:", this.nodes.length);
  16073. log("Calculate overflow clips");
  16074. this.calculateOverflowClips();
  16075. log("Start fetching images");
  16076. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  16077. this.ready = this.images.ready.then(bind(function() {
  16078. log("Images loaded, starting parsing");
  16079. log("Creating stacking contexts");
  16080. this.createStackingContexts();
  16081. log("Sorting stacking contexts");
  16082. this.sortStackingContexts(this.stack);
  16083. this.parse(this.stack);
  16084. log("Render queue created with " + this.renderQueue.length + " items");
  16085. return new Promise(bind(function(resolve) {
  16086. if (!options.async) {
  16087. this.renderQueue.forEach(this.paint, this);
  16088. resolve();
  16089. } else if (typeof(options.async) === "function") {
  16090. options.async.call(this, this.renderQueue, resolve);
  16091. } else if (this.renderQueue.length > 0){
  16092. this.renderIndex = 0;
  16093. this.asyncRenderer(this.renderQueue, resolve);
  16094. } else {
  16095. resolve();
  16096. }
  16097. }, this));
  16098. }, this));
  16099. }
  16100. NodeParser.prototype.calculateOverflowClips = function() {
  16101. this.nodes.forEach(function(container) {
  16102. if (isElement(container)) {
  16103. if (isPseudoElement(container)) {
  16104. container.appendToDOM();
  16105. }
  16106. container.borders = this.parseBorders(container);
  16107. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  16108. var cssClip = container.parseClip();
  16109. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  16110. clip.push([["rect",
  16111. container.bounds.left + cssClip.left,
  16112. container.bounds.top + cssClip.top,
  16113. cssClip.right - cssClip.left,
  16114. cssClip.bottom - cssClip.top
  16115. ]]);
  16116. }
  16117. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  16118. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  16119. if (isPseudoElement(container)) {
  16120. container.cleanDOM();
  16121. }
  16122. } else if (isTextNode(container)) {
  16123. container.clip = hasParentClip(container) ? container.parent.clip : [];
  16124. }
  16125. if (!isPseudoElement(container)) {
  16126. container.bounds = null;
  16127. }
  16128. }, this);
  16129. };
  16130. function hasParentClip(container) {
  16131. return container.parent && container.parent.clip.length;
  16132. }
  16133. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  16134. asyncTimer = asyncTimer || Date.now();
  16135. this.paint(queue[this.renderIndex++]);
  16136. if (queue.length === this.renderIndex) {
  16137. resolve();
  16138. } else if (asyncTimer + 20 > Date.now()) {
  16139. this.asyncRenderer(queue, resolve, asyncTimer);
  16140. } else {
  16141. setTimeout(bind(function() {
  16142. this.asyncRenderer(queue, resolve);
  16143. }, this), 0);
  16144. }
  16145. };
  16146. NodeParser.prototype.createPseudoHideStyles = function(document) {
  16147. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  16148. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  16149. };
  16150. NodeParser.prototype.disableAnimations = function(document) {
  16151. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  16152. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  16153. };
  16154. NodeParser.prototype.createStyles = function(document, styles) {
  16155. var hidePseudoElements = document.createElement('style');
  16156. hidePseudoElements.innerHTML = styles;
  16157. document.body.appendChild(hidePseudoElements);
  16158. };
  16159. NodeParser.prototype.getPseudoElements = function(container) {
  16160. var nodes = [[container]];
  16161. if (container.node.nodeType === Node.ELEMENT_NODE) {
  16162. var before = this.getPseudoElement(container, ":before");
  16163. var after = this.getPseudoElement(container, ":after");
  16164. if (before) {
  16165. nodes.push(before);
  16166. }
  16167. if (after) {
  16168. nodes.push(after);
  16169. }
  16170. }
  16171. return flatten(nodes);
  16172. };
  16173. function toCamelCase(str) {
  16174. return str.replace(/(\-[a-z])/g, function(match){
  16175. return match.toUpperCase().replace('-','');
  16176. });
  16177. }
  16178. NodeParser.prototype.getPseudoElement = function(container, type) {
  16179. var style = container.computedStyle(type);
  16180. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  16181. return null;
  16182. }
  16183. var content = stripQuotes(style.content);
  16184. var isImage = content.substr(0, 3) === 'url';
  16185. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  16186. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  16187. for (var i = style.length-1; i >= 0; i--) {
  16188. var property = toCamelCase(style.item(i));
  16189. pseudoNode.style[property] = style[property];
  16190. }
  16191. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  16192. if (isImage) {
  16193. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  16194. return [pseudoContainer];
  16195. } else {
  16196. var text = document.createTextNode(content);
  16197. pseudoNode.appendChild(text);
  16198. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  16199. }
  16200. };
  16201. NodeParser.prototype.getChildren = function(parentContainer) {
  16202. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  16203. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  16204. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  16205. }, this));
  16206. };
  16207. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  16208. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  16209. container.cloneTo(stack);
  16210. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  16211. parentStack.contexts.push(stack);
  16212. container.stack = stack;
  16213. };
  16214. NodeParser.prototype.createStackingContexts = function() {
  16215. this.nodes.forEach(function(container) {
  16216. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  16217. this.newStackingContext(container, true);
  16218. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  16219. this.newStackingContext(container, false);
  16220. } else {
  16221. container.assignStack(container.parent.stack);
  16222. }
  16223. }, this);
  16224. };
  16225. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  16226. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  16227. };
  16228. NodeParser.prototype.isRootElement = function(container) {
  16229. return container.parent === null;
  16230. };
  16231. NodeParser.prototype.sortStackingContexts = function(stack) {
  16232. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  16233. stack.contexts.forEach(this.sortStackingContexts, this);
  16234. };
  16235. NodeParser.prototype.parseTextBounds = function(container) {
  16236. return function(text, index, textList) {
  16237. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  16238. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  16239. var offset = textList.slice(0, index).join("").length;
  16240. return this.getRangeBounds(container.node, offset, text.length);
  16241. } else if (container.node && typeof(container.node.data) === "string") {
  16242. var replacementNode = container.node.splitText(text.length);
  16243. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  16244. container.node = replacementNode;
  16245. return bounds;
  16246. }
  16247. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  16248. container.node = container.node.splitText(text.length);
  16249. }
  16250. return {};
  16251. };
  16252. };
  16253. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  16254. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  16255. var parent = node.parentNode,
  16256. backupText = node.cloneNode(true);
  16257. wrapper.appendChild(node.cloneNode(true));
  16258. parent.replaceChild(wrapper, node);
  16259. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  16260. parent.replaceChild(backupText, wrapper);
  16261. return bounds;
  16262. };
  16263. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  16264. var range = this.range || (this.range = node.ownerDocument.createRange());
  16265. range.setStart(node, offset);
  16266. range.setEnd(node, offset + length);
  16267. return range.getBoundingClientRect();
  16268. };
  16269. function ClearTransform() {}
  16270. NodeParser.prototype.parse = function(stack) {
  16271. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  16272. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  16273. var descendantElements = stack.children.filter(isElement);
  16274. var descendantNonFloats = descendantElements.filter(not(isFloating));
  16275. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  16276. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  16277. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  16278. 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.
  16279. var text = stack.children.filter(isTextNode).filter(hasText);
  16280. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  16281. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  16282. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  16283. this.renderQueue.push(container);
  16284. if (isStackingContext(container)) {
  16285. this.parse(container);
  16286. this.renderQueue.push(new ClearTransform());
  16287. }
  16288. }, this);
  16289. };
  16290. NodeParser.prototype.paint = function(container) {
  16291. try {
  16292. if (container instanceof ClearTransform) {
  16293. this.renderer.ctx.restore();
  16294. } else if (isTextNode(container)) {
  16295. if (isPseudoElement(container.parent)) {
  16296. container.parent.appendToDOM();
  16297. }
  16298. this.paintText(container);
  16299. if (isPseudoElement(container.parent)) {
  16300. container.parent.cleanDOM();
  16301. }
  16302. } else {
  16303. this.paintNode(container);
  16304. }
  16305. } catch(e) {
  16306. log(e);
  16307. if (this.options.strict) {
  16308. throw e;
  16309. }
  16310. }
  16311. };
  16312. NodeParser.prototype.paintNode = function(container) {
  16313. if (isStackingContext(container)) {
  16314. this.renderer.setOpacity(container.opacity);
  16315. this.renderer.ctx.save();
  16316. if (container.hasTransform()) {
  16317. this.renderer.setTransform(container.parseTransform());
  16318. }
  16319. }
  16320. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  16321. this.paintCheckbox(container);
  16322. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  16323. this.paintRadio(container);
  16324. } else {
  16325. this.paintElement(container);
  16326. }
  16327. };
  16328. NodeParser.prototype.paintElement = function(container) {
  16329. var bounds = container.parseBounds();
  16330. this.renderer.clip(container.backgroundClip, function() {
  16331. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  16332. }, this);
  16333. this.renderer.clip(container.clip, function() {
  16334. this.renderer.renderBorders(container.borders.borders);
  16335. }, this);
  16336. this.renderer.clip(container.backgroundClip, function() {
  16337. switch (container.node.nodeName) {
  16338. case "svg":
  16339. case "IFRAME":
  16340. var imgContainer = this.images.get(container.node);
  16341. if (imgContainer) {
  16342. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  16343. } else {
  16344. log("Error loading <" + container.node.nodeName + ">", container.node);
  16345. }
  16346. break;
  16347. case "IMG":
  16348. var imageContainer = this.images.get(container.node.src);
  16349. if (imageContainer) {
  16350. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  16351. } else {
  16352. log("Error loading <img>", container.node.src);
  16353. }
  16354. break;
  16355. case "CANVAS":
  16356. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  16357. break;
  16358. case "SELECT":
  16359. case "INPUT":
  16360. case "TEXTAREA":
  16361. this.paintFormValue(container);
  16362. break;
  16363. }
  16364. }, this);
  16365. };
  16366. NodeParser.prototype.paintCheckbox = function(container) {
  16367. var b = container.parseBounds();
  16368. var size = Math.min(b.width, b.height);
  16369. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  16370. var r = [3, 3];
  16371. var radius = [r, r, r, r];
  16372. var borders = [1,1,1,1].map(function(w) {
  16373. return {color: new Color('#A5A5A5'), width: w};
  16374. });
  16375. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  16376. this.renderer.clip(container.backgroundClip, function() {
  16377. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  16378. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  16379. if (container.node.checked) {
  16380. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  16381. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  16382. }
  16383. }, this);
  16384. };
  16385. NodeParser.prototype.paintRadio = function(container) {
  16386. var bounds = container.parseBounds();
  16387. var size = Math.min(bounds.width, bounds.height) - 2;
  16388. this.renderer.clip(container.backgroundClip, function() {
  16389. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  16390. if (container.node.checked) {
  16391. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  16392. }
  16393. }, this);
  16394. };
  16395. NodeParser.prototype.paintFormValue = function(container) {
  16396. var value = container.getValue();
  16397. if (value.length > 0) {
  16398. var document = container.node.ownerDocument;
  16399. var wrapper = document.createElement('html2canvaswrapper');
  16400. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  16401. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  16402. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  16403. 'boxSizing', 'whiteSpace', 'wordWrap'];
  16404. properties.forEach(function(property) {
  16405. try {
  16406. wrapper.style[property] = container.css(property);
  16407. } catch(e) {
  16408. // Older IE has issues with "border"
  16409. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  16410. }
  16411. });
  16412. var bounds = container.parseBounds();
  16413. wrapper.style.position = "fixed";
  16414. wrapper.style.left = bounds.left + "px";
  16415. wrapper.style.top = bounds.top + "px";
  16416. wrapper.textContent = value;
  16417. document.body.appendChild(wrapper);
  16418. this.paintText(new TextContainer(wrapper.firstChild, container));
  16419. document.body.removeChild(wrapper);
  16420. }
  16421. };
  16422. NodeParser.prototype.paintText = function(container) {
  16423. container.applyTextTransform();
  16424. var characters = punycode.ucs2.decode(container.node.data);
  16425. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  16426. return punycode.ucs2.encode([character]);
  16427. });
  16428. var weight = container.parent.fontWeight();
  16429. var size = container.parent.css('fontSize');
  16430. var family = container.parent.css('fontFamily');
  16431. var shadows = container.parent.parseTextShadows();
  16432. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  16433. if (shadows.length) {
  16434. // TODO: support multiple text shadows
  16435. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  16436. } else {
  16437. this.renderer.clearShadow();
  16438. }
  16439. this.renderer.clip(container.parent.clip, function() {
  16440. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  16441. if (bounds && /^\s*$/.test(textList[index]) === false) {
  16442. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  16443. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  16444. }
  16445. }, this);
  16446. }, this);
  16447. };
  16448. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  16449. switch(container.css("textDecoration").split(" ")[0]) {
  16450. case "underline":
  16451. // Draws a line at the baseline of the font
  16452. // 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
  16453. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  16454. break;
  16455. case "overline":
  16456. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  16457. break;
  16458. case "line-through":
  16459. // TODO try and find exact position for line-through
  16460. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  16461. break;
  16462. }
  16463. };
  16464. var borderColorTransforms = {
  16465. inset: [
  16466. ["darken", 0.60],
  16467. ["darken", 0.10],
  16468. ["darken", 0.10],
  16469. ["darken", 0.60]
  16470. ]
  16471. };
  16472. NodeParser.prototype.parseBorders = function(container) {
  16473. var nodeBounds = container.parseBounds();
  16474. var radius = getBorderRadiusData(container);
  16475. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  16476. var style = container.css('border' + side + 'Style');
  16477. var color = container.color('border' + side + 'Color');
  16478. if (style === "inset" && color.isBlack()) {
  16479. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  16480. }
  16481. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  16482. return {
  16483. width: container.cssInt('border' + side + 'Width'),
  16484. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  16485. args: null
  16486. };
  16487. });
  16488. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  16489. return {
  16490. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  16491. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  16492. };
  16493. };
  16494. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  16495. return borders.map(function(border, borderSide) {
  16496. if (border.width > 0) {
  16497. var bx = nodeBounds.left;
  16498. var by = nodeBounds.top;
  16499. var bw = nodeBounds.width;
  16500. var bh = nodeBounds.height - (borders[2].width);
  16501. switch(borderSide) {
  16502. case 0:
  16503. // top border
  16504. bh = borders[0].width;
  16505. border.args = drawSide({
  16506. c1: [bx, by],
  16507. c2: [bx + bw, by],
  16508. c3: [bx + bw - borders[1].width, by + bh],
  16509. c4: [bx + borders[3].width, by + bh]
  16510. }, radius[0], radius[1],
  16511. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  16512. break;
  16513. case 1:
  16514. // right border
  16515. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  16516. bw = borders[1].width;
  16517. border.args = drawSide({
  16518. c1: [bx + bw, by],
  16519. c2: [bx + bw, by + bh + borders[2].width],
  16520. c3: [bx, by + bh],
  16521. c4: [bx, by + borders[0].width]
  16522. }, radius[1], radius[2],
  16523. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  16524. break;
  16525. case 2:
  16526. // bottom border
  16527. by = (by + nodeBounds.height) - (borders[2].width);
  16528. bh = borders[2].width;
  16529. border.args = drawSide({
  16530. c1: [bx + bw, by + bh],
  16531. c2: [bx, by + bh],
  16532. c3: [bx + borders[3].width, by],
  16533. c4: [bx + bw - borders[3].width, by]
  16534. }, radius[2], radius[3],
  16535. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  16536. break;
  16537. case 3:
  16538. // left border
  16539. bw = borders[3].width;
  16540. border.args = drawSide({
  16541. c1: [bx, by + bh + borders[2].width],
  16542. c2: [bx, by],
  16543. c3: [bx + bw, by + borders[0].width],
  16544. c4: [bx + bw, by + bh]
  16545. }, radius[3], radius[0],
  16546. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  16547. break;
  16548. }
  16549. }
  16550. return border;
  16551. });
  16552. }
  16553. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  16554. var backgroundClip = container.css('backgroundClip'),
  16555. borderArgs = [];
  16556. switch(backgroundClip) {
  16557. case "content-box":
  16558. case "padding-box":
  16559. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  16560. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  16561. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  16562. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  16563. break;
  16564. default:
  16565. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  16566. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  16567. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  16568. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  16569. break;
  16570. }
  16571. return borderArgs;
  16572. };
  16573. function getCurvePoints(x, y, r1, r2) {
  16574. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  16575. var ox = (r1) * kappa, // control point offset horizontal
  16576. oy = (r2) * kappa, // control point offset vertical
  16577. xm = x + r1, // x-middle
  16578. ym = y + r2; // y-middle
  16579. return {
  16580. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  16581. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  16582. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  16583. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  16584. };
  16585. }
  16586. function calculateCurvePoints(bounds, borderRadius, borders) {
  16587. var x = bounds.left,
  16588. y = bounds.top,
  16589. width = bounds.width,
  16590. height = bounds.height,
  16591. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  16592. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  16593. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  16594. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  16595. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  16596. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  16597. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  16598. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  16599. var topWidth = width - trh,
  16600. rightHeight = height - brv,
  16601. bottomWidth = width - brh,
  16602. leftHeight = height - blv;
  16603. return {
  16604. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  16605. 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),
  16606. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  16607. 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),
  16608. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  16609. 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),
  16610. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  16611. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  16612. };
  16613. }
  16614. function bezierCurve(start, startControl, endControl, end) {
  16615. var lerp = function (a, b, t) {
  16616. return {
  16617. x: a.x + (b.x - a.x) * t,
  16618. y: a.y + (b.y - a.y) * t
  16619. };
  16620. };
  16621. return {
  16622. start: start,
  16623. startControl: startControl,
  16624. endControl: endControl,
  16625. end: end,
  16626. subdivide: function(t) {
  16627. var ab = lerp(start, startControl, t),
  16628. bc = lerp(startControl, endControl, t),
  16629. cd = lerp(endControl, end, t),
  16630. abbc = lerp(ab, bc, t),
  16631. bccd = lerp(bc, cd, t),
  16632. dest = lerp(abbc, bccd, t);
  16633. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  16634. },
  16635. curveTo: function(borderArgs) {
  16636. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  16637. },
  16638. curveToReversed: function(borderArgs) {
  16639. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  16640. }
  16641. };
  16642. }
  16643. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  16644. var borderArgs = [];
  16645. if (radius1[0] > 0 || radius1[1] > 0) {
  16646. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  16647. outer1[1].curveTo(borderArgs);
  16648. } else {
  16649. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  16650. }
  16651. if (radius2[0] > 0 || radius2[1] > 0) {
  16652. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  16653. outer2[0].curveTo(borderArgs);
  16654. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  16655. inner2[0].curveToReversed(borderArgs);
  16656. } else {
  16657. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  16658. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  16659. }
  16660. if (radius1[0] > 0 || radius1[1] > 0) {
  16661. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  16662. inner1[1].curveToReversed(borderArgs);
  16663. } else {
  16664. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  16665. }
  16666. return borderArgs;
  16667. }
  16668. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  16669. if (radius1[0] > 0 || radius1[1] > 0) {
  16670. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  16671. corner1[0].curveTo(borderArgs);
  16672. corner1[1].curveTo(borderArgs);
  16673. } else {
  16674. borderArgs.push(["line", x, y]);
  16675. }
  16676. if (radius2[0] > 0 || radius2[1] > 0) {
  16677. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  16678. }
  16679. }
  16680. function negativeZIndex(container) {
  16681. return container.cssInt("zIndex") < 0;
  16682. }
  16683. function positiveZIndex(container) {
  16684. return container.cssInt("zIndex") > 0;
  16685. }
  16686. function zIndex0(container) {
  16687. return container.cssInt("zIndex") === 0;
  16688. }
  16689. function inlineLevel(container) {
  16690. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  16691. }
  16692. function isStackingContext(container) {
  16693. return (container instanceof StackingContext);
  16694. }
  16695. function hasText(container) {
  16696. return container.node.data.trim().length > 0;
  16697. }
  16698. function noLetterSpacing(container) {
  16699. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  16700. }
  16701. function getBorderRadiusData(container) {
  16702. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  16703. var value = container.css('border' + side + 'Radius');
  16704. var arr = value.split(" ");
  16705. if (arr.length <= 1) {
  16706. arr[1] = arr[0];
  16707. }
  16708. return arr.map(asInt);
  16709. });
  16710. }
  16711. function renderableNode(node) {
  16712. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  16713. }
  16714. function isPositionedForStacking(container) {
  16715. var position = container.css("position");
  16716. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  16717. return zIndex !== "auto";
  16718. }
  16719. function isPositioned(container) {
  16720. return container.css("position") !== "static";
  16721. }
  16722. function isFloating(container) {
  16723. return container.css("float") !== "none";
  16724. }
  16725. function isInlineBlock(container) {
  16726. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  16727. }
  16728. function not(callback) {
  16729. var context = this;
  16730. return function() {
  16731. return !callback.apply(context, arguments);
  16732. };
  16733. }
  16734. function isElement(container) {
  16735. return container.node.nodeType === Node.ELEMENT_NODE;
  16736. }
  16737. function isPseudoElement(container) {
  16738. return container.isPseudoElement === true;
  16739. }
  16740. function isTextNode(container) {
  16741. return container.node.nodeType === Node.TEXT_NODE;
  16742. }
  16743. function zIndexSort(contexts) {
  16744. return function(a, b) {
  16745. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  16746. };
  16747. }
  16748. function hasOpacity(container) {
  16749. return container.getOpacity() < 1;
  16750. }
  16751. function asInt(value) {
  16752. return parseInt(value, 10);
  16753. }
  16754. function getWidth(border) {
  16755. return border.width;
  16756. }
  16757. function nonIgnoredElement(nodeContainer) {
  16758. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  16759. }
  16760. function flatten(arrays) {
  16761. return [].concat.apply([], arrays);
  16762. }
  16763. function stripQuotes(content) {
  16764. var first = content.substr(0, 1);
  16765. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  16766. }
  16767. function getWords(characters) {
  16768. var words = [], i = 0, onWordBoundary = false, word;
  16769. while(characters.length) {
  16770. if (isWordBoundary(characters[i]) === onWordBoundary) {
  16771. word = characters.splice(0, i);
  16772. if (word.length) {
  16773. words.push(punycode.ucs2.encode(word));
  16774. }
  16775. onWordBoundary =! onWordBoundary;
  16776. i = 0;
  16777. } else {
  16778. i++;
  16779. }
  16780. if (i >= characters.length) {
  16781. word = characters.splice(0, i);
  16782. if (word.length) {
  16783. words.push(punycode.ucs2.encode(word));
  16784. }
  16785. }
  16786. }
  16787. return words;
  16788. }
  16789. function isWordBoundary(characterCode) {
  16790. return [
  16791. 32, // <space>
  16792. 13, // \r
  16793. 10, // \n
  16794. 9, // \t
  16795. 45 // -
  16796. ].indexOf(characterCode) !== -1;
  16797. }
  16798. function hasUnicode(string) {
  16799. return (/[^\u0000-\u00ff]/).test(string);
  16800. }
  16801. module.exports = NodeParser;
  16802. },{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
  16803. var XHR = _dereq_('./xhr');
  16804. var utils = _dereq_('./utils');
  16805. var log = _dereq_('./log');
  16806. var createWindowClone = _dereq_('./clone');
  16807. var decode64 = utils.decode64;
  16808. function Proxy(src, proxyUrl, document) {
  16809. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  16810. if (!proxyUrl) {
  16811. return Promise.reject("No proxy configured");
  16812. }
  16813. var callback = createCallback(supportsCORS);
  16814. var url = createProxyUrl(proxyUrl, src, callback);
  16815. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  16816. return decode64(response.content);
  16817. }));
  16818. }
  16819. var proxyCount = 0;
  16820. function ProxyURL(src, proxyUrl, document) {
  16821. var supportsCORSImage = ('crossOrigin' in new Image());
  16822. var callback = createCallback(supportsCORSImage);
  16823. var url = createProxyUrl(proxyUrl, src, callback);
  16824. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  16825. return "data:" + response.type + ";base64," + response.content;
  16826. }));
  16827. }
  16828. function jsonp(document, url, callback) {
  16829. return new Promise(function(resolve, reject) {
  16830. var s = document.createElement("script");
  16831. var cleanup = function() {
  16832. delete window.html2canvas.proxy[callback];
  16833. document.body.removeChild(s);
  16834. };
  16835. window.html2canvas.proxy[callback] = function(response) {
  16836. cleanup();
  16837. resolve(response);
  16838. };
  16839. s.src = url;
  16840. s.onerror = function(e) {
  16841. cleanup();
  16842. reject(e);
  16843. };
  16844. document.body.appendChild(s);
  16845. });
  16846. }
  16847. function createCallback(useCORS) {
  16848. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  16849. }
  16850. function createProxyUrl(proxyUrl, src, callback) {
  16851. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  16852. }
  16853. function documentFromHTML(src) {
  16854. return function(html) {
  16855. var parser = new DOMParser(), doc;
  16856. try {
  16857. doc = parser.parseFromString(html, "text/html");
  16858. } catch(e) {
  16859. log("DOMParser not supported, falling back to createHTMLDocument");
  16860. doc = document.implementation.createHTMLDocument("");
  16861. try {
  16862. doc.open();
  16863. doc.write(html);
  16864. doc.close();
  16865. } catch(ee) {
  16866. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  16867. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  16868. }
  16869. }
  16870. var b = doc.querySelector("base");
  16871. if (!b || !b.href.host) {
  16872. var base = doc.createElement("base");
  16873. base.href = src;
  16874. doc.head.insertBefore(base, doc.head.firstChild);
  16875. }
  16876. return doc;
  16877. };
  16878. }
  16879. function loadUrlDocument(src, proxy, document, width, height, options) {
  16880. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  16881. return createWindowClone(doc, document, width, height, options, 0, 0);
  16882. });
  16883. }
  16884. exports.Proxy = Proxy;
  16885. exports.ProxyURL = ProxyURL;
  16886. exports.loadUrlDocument = loadUrlDocument;
  16887. },{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
  16888. var ProxyURL = _dereq_('./proxy').ProxyURL;
  16889. function ProxyImageContainer(src, proxy) {
  16890. var link = document.createElement("a");
  16891. link.href = src;
  16892. src = link.href;
  16893. this.src = src;
  16894. this.image = new Image();
  16895. var self = this;
  16896. this.promise = new Promise(function(resolve, reject) {
  16897. self.image.crossOrigin = "Anonymous";
  16898. self.image.onload = resolve;
  16899. self.image.onerror = reject;
  16900. new ProxyURL(src, proxy, document).then(function(url) {
  16901. self.image.src = url;
  16902. })['catch'](reject);
  16903. });
  16904. }
  16905. module.exports = ProxyImageContainer;
  16906. },{"./proxy":16}],18:[function(_dereq_,module,exports){
  16907. var NodeContainer = _dereq_('./nodecontainer');
  16908. function PseudoElementContainer(node, parent, type) {
  16909. NodeContainer.call(this, node, parent);
  16910. this.isPseudoElement = true;
  16911. this.before = type === ":before";
  16912. }
  16913. PseudoElementContainer.prototype.cloneTo = function(stack) {
  16914. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  16915. stack.isPseudoElement = true;
  16916. stack.before = this.before;
  16917. };
  16918. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  16919. PseudoElementContainer.prototype.appendToDOM = function() {
  16920. if (this.before) {
  16921. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  16922. } else {
  16923. this.parent.node.appendChild(this.node);
  16924. }
  16925. this.parent.node.className += " " + this.getHideClass();
  16926. };
  16927. PseudoElementContainer.prototype.cleanDOM = function() {
  16928. this.node.parentNode.removeChild(this.node);
  16929. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  16930. };
  16931. PseudoElementContainer.prototype.getHideClass = function() {
  16932. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  16933. };
  16934. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  16935. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  16936. module.exports = PseudoElementContainer;
  16937. },{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
  16938. var log = _dereq_('./log');
  16939. function Renderer(width, height, images, options, document) {
  16940. this.width = width;
  16941. this.height = height;
  16942. this.images = images;
  16943. this.options = options;
  16944. this.document = document;
  16945. }
  16946. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  16947. var paddingLeft = container.cssInt('paddingLeft'),
  16948. paddingTop = container.cssInt('paddingTop'),
  16949. paddingRight = container.cssInt('paddingRight'),
  16950. paddingBottom = container.cssInt('paddingBottom'),
  16951. borders = borderData.borders;
  16952. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  16953. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  16954. this.drawImage(
  16955. imageContainer,
  16956. 0,
  16957. 0,
  16958. imageContainer.image.width || width,
  16959. imageContainer.image.height || height,
  16960. bounds.left + paddingLeft + borders[3].width,
  16961. bounds.top + paddingTop + borders[0].width,
  16962. width,
  16963. height
  16964. );
  16965. };
  16966. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  16967. if (bounds.height > 0 && bounds.width > 0) {
  16968. this.renderBackgroundColor(container, bounds);
  16969. this.renderBackgroundImage(container, bounds, borderData);
  16970. }
  16971. };
  16972. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  16973. var color = container.color("backgroundColor");
  16974. if (!color.isTransparent()) {
  16975. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  16976. }
  16977. };
  16978. Renderer.prototype.renderBorders = function(borders) {
  16979. borders.forEach(this.renderBorder, this);
  16980. };
  16981. Renderer.prototype.renderBorder = function(data) {
  16982. if (!data.color.isTransparent() && data.args !== null) {
  16983. this.drawShape(data.args, data.color);
  16984. }
  16985. };
  16986. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  16987. var backgroundImages = container.parseBackgroundImages();
  16988. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  16989. switch(backgroundImage.method) {
  16990. case "url":
  16991. var image = this.images.get(backgroundImage.args[0]);
  16992. if (image) {
  16993. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  16994. } else {
  16995. log("Error loading background-image", backgroundImage.args[0]);
  16996. }
  16997. break;
  16998. case "linear-gradient":
  16999. case "gradient":
  17000. var gradientImage = this.images.get(backgroundImage.value);
  17001. if (gradientImage) {
  17002. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  17003. } else {
  17004. log("Error loading background-image", backgroundImage.args[0]);
  17005. }
  17006. break;
  17007. case "none":
  17008. break;
  17009. default:
  17010. log("Unknown background-image type", backgroundImage.args[0]);
  17011. }
  17012. }, this);
  17013. };
  17014. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  17015. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  17016. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  17017. var repeat = container.parseBackgroundRepeat(index);
  17018. switch (repeat) {
  17019. case "repeat-x":
  17020. case "repeat no-repeat":
  17021. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  17022. break;
  17023. case "repeat-y":
  17024. case "no-repeat repeat":
  17025. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  17026. break;
  17027. case "no-repeat":
  17028. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  17029. break;
  17030. default:
  17031. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  17032. break;
  17033. }
  17034. };
  17035. module.exports = Renderer;
  17036. },{"./log":13}],20:[function(_dereq_,module,exports){
  17037. var Renderer = _dereq_('../renderer');
  17038. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  17039. var log = _dereq_('../log');
  17040. function CanvasRenderer(width, height) {
  17041. Renderer.apply(this, arguments);
  17042. this.canvas = this.options.canvas || this.document.createElement("canvas");
  17043. if (!this.options.canvas) {
  17044. this.canvas.width = width;
  17045. this.canvas.height = height;
  17046. }
  17047. this.ctx = this.canvas.getContext("2d");
  17048. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  17049. this.ctx.textBaseline = "bottom";
  17050. this.variables = {};
  17051. log("Initialized CanvasRenderer with size", width, "x", height);
  17052. }
  17053. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  17054. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  17055. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  17056. return this.ctx;
  17057. };
  17058. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  17059. this.setFillStyle(color).fillRect(left, top, width, height);
  17060. };
  17061. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  17062. this.setFillStyle(color);
  17063. this.ctx.beginPath();
  17064. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  17065. this.ctx.closePath();
  17066. this.ctx.fill();
  17067. };
  17068. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  17069. this.circle(left, top, size, color);
  17070. this.ctx.strokeStyle = strokeColor.toString();
  17071. this.ctx.stroke();
  17072. };
  17073. CanvasRenderer.prototype.drawShape = function(shape, color) {
  17074. this.shape(shape);
  17075. this.setFillStyle(color).fill();
  17076. };
  17077. CanvasRenderer.prototype.taints = function(imageContainer) {
  17078. if (imageContainer.tainted === null) {
  17079. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  17080. try {
  17081. this.taintCtx.getImageData(0, 0, 1, 1);
  17082. imageContainer.tainted = false;
  17083. } catch(e) {
  17084. this.taintCtx = document.createElement("canvas").getContext("2d");
  17085. imageContainer.tainted = true;
  17086. }
  17087. }
  17088. return imageContainer.tainted;
  17089. };
  17090. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  17091. if (!this.taints(imageContainer) || this.options.allowTaint) {
  17092. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  17093. }
  17094. };
  17095. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  17096. this.ctx.save();
  17097. shapes.filter(hasEntries).forEach(function(shape) {
  17098. this.shape(shape).clip();
  17099. }, this);
  17100. callback.call(context);
  17101. this.ctx.restore();
  17102. };
  17103. CanvasRenderer.prototype.shape = function(shape) {
  17104. this.ctx.beginPath();
  17105. shape.forEach(function(point, index) {
  17106. if (point[0] === "rect") {
  17107. this.ctx.rect.apply(this.ctx, point.slice(1));
  17108. } else {
  17109. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  17110. }
  17111. }, this);
  17112. this.ctx.closePath();
  17113. return this.ctx;
  17114. };
  17115. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  17116. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  17117. };
  17118. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  17119. this.setVariable("shadowColor", color.toString())
  17120. .setVariable("shadowOffsetY", offsetX)
  17121. .setVariable("shadowOffsetX", offsetY)
  17122. .setVariable("shadowBlur", blur);
  17123. };
  17124. CanvasRenderer.prototype.clearShadow = function() {
  17125. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  17126. };
  17127. CanvasRenderer.prototype.setOpacity = function(opacity) {
  17128. this.ctx.globalAlpha = opacity;
  17129. };
  17130. CanvasRenderer.prototype.setTransform = function(transform) {
  17131. this.ctx.translate(transform.origin[0], transform.origin[1]);
  17132. this.ctx.transform.apply(this.ctx, transform.matrix);
  17133. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  17134. };
  17135. CanvasRenderer.prototype.setVariable = function(property, value) {
  17136. if (this.variables[property] !== value) {
  17137. this.variables[property] = this.ctx[property] = value;
  17138. }
  17139. return this;
  17140. };
  17141. CanvasRenderer.prototype.text = function(text, left, bottom) {
  17142. this.ctx.fillText(text, left, bottom);
  17143. };
  17144. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  17145. var shape = [
  17146. ["line", Math.round(left), Math.round(top)],
  17147. ["line", Math.round(left + width), Math.round(top)],
  17148. ["line", Math.round(left + width), Math.round(height + top)],
  17149. ["line", Math.round(left), Math.round(height + top)]
  17150. ];
  17151. this.clip([shape], function() {
  17152. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  17153. }, this);
  17154. };
  17155. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  17156. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  17157. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  17158. this.ctx.translate(offsetX, offsetY);
  17159. this.ctx.fill();
  17160. this.ctx.translate(-offsetX, -offsetY);
  17161. };
  17162. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  17163. if (gradientImage instanceof LinearGradientContainer) {
  17164. var gradient = this.ctx.createLinearGradient(
  17165. bounds.left + bounds.width * gradientImage.x0,
  17166. bounds.top + bounds.height * gradientImage.y0,
  17167. bounds.left + bounds.width * gradientImage.x1,
  17168. bounds.top + bounds.height * gradientImage.y1);
  17169. gradientImage.colorStops.forEach(function(colorStop) {
  17170. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  17171. });
  17172. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  17173. }
  17174. };
  17175. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  17176. var image = imageContainer.image;
  17177. if(image.width === size.width && image.height === size.height) {
  17178. return image;
  17179. }
  17180. var ctx, canvas = document.createElement('canvas');
  17181. canvas.width = size.width;
  17182. canvas.height = size.height;
  17183. ctx = canvas.getContext("2d");
  17184. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  17185. return canvas;
  17186. };
  17187. function hasEntries(array) {
  17188. return array.length > 0;
  17189. }
  17190. module.exports = CanvasRenderer;
  17191. },{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
  17192. var NodeContainer = _dereq_('./nodecontainer');
  17193. function StackingContext(hasOwnStacking, opacity, element, parent) {
  17194. NodeContainer.call(this, element, parent);
  17195. this.ownStacking = hasOwnStacking;
  17196. this.contexts = [];
  17197. this.children = [];
  17198. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  17199. }
  17200. StackingContext.prototype = Object.create(NodeContainer.prototype);
  17201. StackingContext.prototype.getParentStack = function(context) {
  17202. var parentStack = (this.parent) ? this.parent.stack : null;
  17203. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  17204. };
  17205. module.exports = StackingContext;
  17206. },{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
  17207. function Support(document) {
  17208. this.rangeBounds = this.testRangeBounds(document);
  17209. this.cors = this.testCORS();
  17210. this.svg = this.testSVG();
  17211. }
  17212. Support.prototype.testRangeBounds = function(document) {
  17213. var range, testElement, rangeBounds, rangeHeight, support = false;
  17214. if (document.createRange) {
  17215. range = document.createRange();
  17216. if (range.getBoundingClientRect) {
  17217. testElement = document.createElement('boundtest');
  17218. testElement.style.height = "123px";
  17219. testElement.style.display = "block";
  17220. document.body.appendChild(testElement);
  17221. range.selectNode(testElement);
  17222. rangeBounds = range.getBoundingClientRect();
  17223. rangeHeight = rangeBounds.height;
  17224. if (rangeHeight === 123) {
  17225. support = true;
  17226. }
  17227. document.body.removeChild(testElement);
  17228. }
  17229. }
  17230. return support;
  17231. };
  17232. Support.prototype.testCORS = function() {
  17233. return typeof((new Image()).crossOrigin) !== "undefined";
  17234. };
  17235. Support.prototype.testSVG = function() {
  17236. var img = new Image();
  17237. var canvas = document.createElement("canvas");
  17238. var ctx = canvas.getContext("2d");
  17239. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  17240. try {
  17241. ctx.drawImage(img, 0, 0);
  17242. canvas.toDataURL();
  17243. } catch(e) {
  17244. return false;
  17245. }
  17246. return true;
  17247. };
  17248. module.exports = Support;
  17249. },{}],23:[function(_dereq_,module,exports){
  17250. var XHR = _dereq_('./xhr');
  17251. var decode64 = _dereq_('./utils').decode64;
  17252. function SVGContainer(src) {
  17253. this.src = src;
  17254. this.image = null;
  17255. var self = this;
  17256. this.promise = this.hasFabric().then(function() {
  17257. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  17258. }).then(function(svg) {
  17259. return new Promise(function(resolve) {
  17260. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  17261. });
  17262. });
  17263. }
  17264. SVGContainer.prototype.hasFabric = function() {
  17265. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  17266. };
  17267. SVGContainer.prototype.inlineFormatting = function(src) {
  17268. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  17269. };
  17270. SVGContainer.prototype.removeContentType = function(src) {
  17271. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  17272. };
  17273. SVGContainer.prototype.isInline = function(src) {
  17274. return (/^data:image\/svg\+xml/i.test(src));
  17275. };
  17276. SVGContainer.prototype.createCanvas = function(resolve) {
  17277. var self = this;
  17278. return function (objects, options) {
  17279. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  17280. self.image = canvas.lowerCanvasEl;
  17281. canvas
  17282. .setWidth(options.width)
  17283. .setHeight(options.height)
  17284. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  17285. .renderAll();
  17286. resolve(canvas.lowerCanvasEl);
  17287. };
  17288. };
  17289. SVGContainer.prototype.decode64 = function(str) {
  17290. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  17291. };
  17292. module.exports = SVGContainer;
  17293. },{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
  17294. var SVGContainer = _dereq_('./svgcontainer');
  17295. function SVGNodeContainer(node, _native) {
  17296. this.src = node;
  17297. this.image = null;
  17298. var self = this;
  17299. this.promise = _native ? new Promise(function(resolve, reject) {
  17300. self.image = new Image();
  17301. self.image.onload = resolve;
  17302. self.image.onerror = reject;
  17303. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  17304. if (self.image.complete === true) {
  17305. resolve(self.image);
  17306. }
  17307. }) : this.hasFabric().then(function() {
  17308. return new Promise(function(resolve) {
  17309. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  17310. });
  17311. });
  17312. }
  17313. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  17314. module.exports = SVGNodeContainer;
  17315. },{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
  17316. var NodeContainer = _dereq_('./nodecontainer');
  17317. function TextContainer(node, parent) {
  17318. NodeContainer.call(this, node, parent);
  17319. }
  17320. TextContainer.prototype = Object.create(NodeContainer.prototype);
  17321. TextContainer.prototype.applyTextTransform = function() {
  17322. this.node.data = this.transform(this.parent.css("textTransform"));
  17323. };
  17324. TextContainer.prototype.transform = function(transform) {
  17325. var text = this.node.data;
  17326. switch(transform){
  17327. case "lowercase":
  17328. return text.toLowerCase();
  17329. case "capitalize":
  17330. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  17331. case "uppercase":
  17332. return text.toUpperCase();
  17333. default:
  17334. return text;
  17335. }
  17336. };
  17337. function capitalize(m, p1, p2) {
  17338. if (m.length > 0) {
  17339. return p1 + p2.toUpperCase();
  17340. }
  17341. }
  17342. module.exports = TextContainer;
  17343. },{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
  17344. exports.smallImage = function smallImage() {
  17345. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  17346. };
  17347. exports.bind = function(callback, context) {
  17348. return function() {
  17349. return callback.apply(context, arguments);
  17350. };
  17351. };
  17352. /*
  17353. * base64-arraybuffer
  17354. * https://github.com/niklasvh/base64-arraybuffer
  17355. *
  17356. * Copyright (c) 2012 Niklas von Hertzen
  17357. * Licensed under the MIT license.
  17358. */
  17359. exports.decode64 = function(base64) {
  17360. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  17361. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  17362. var output = "";
  17363. for (i = 0; i < len; i+=4) {
  17364. encoded1 = chars.indexOf(base64[i]);
  17365. encoded2 = chars.indexOf(base64[i+1]);
  17366. encoded3 = chars.indexOf(base64[i+2]);
  17367. encoded4 = chars.indexOf(base64[i+3]);
  17368. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  17369. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  17370. byte3 = ((encoded3 & 3) << 6) | encoded4;
  17371. if (encoded3 === 64) {
  17372. output += String.fromCharCode(byte1);
  17373. } else if (encoded4 === 64 || encoded4 === -1) {
  17374. output += String.fromCharCode(byte1, byte2);
  17375. } else{
  17376. output += String.fromCharCode(byte1, byte2, byte3);
  17377. }
  17378. }
  17379. return output;
  17380. };
  17381. exports.getBounds = function(node) {
  17382. if (node.getBoundingClientRect) {
  17383. var clientRect = node.getBoundingClientRect();
  17384. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  17385. return {
  17386. top: clientRect.top,
  17387. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  17388. right: clientRect.left + width,
  17389. left: clientRect.left,
  17390. width: width,
  17391. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  17392. };
  17393. }
  17394. return {};
  17395. };
  17396. exports.offsetBounds = function(node) {
  17397. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  17398. return {
  17399. top: node.offsetTop + parent.top,
  17400. bottom: node.offsetTop + node.offsetHeight + parent.top,
  17401. right: node.offsetLeft + parent.left + node.offsetWidth,
  17402. left: node.offsetLeft + parent.left,
  17403. width: node.offsetWidth,
  17404. height: node.offsetHeight
  17405. };
  17406. };
  17407. exports.parseBackgrounds = function(backgroundImage) {
  17408. var whitespace = ' \r\n\t',
  17409. method, definition, prefix, prefix_i, block, results = [],
  17410. mode = 0, numParen = 0, quote, args;
  17411. var appendResult = function() {
  17412. if(method) {
  17413. if (definition.substr(0, 1) === '"') {
  17414. definition = definition.substr(1, definition.length - 2);
  17415. }
  17416. if (definition) {
  17417. args.push(definition);
  17418. }
  17419. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  17420. prefix = method.substr(0, prefix_i);
  17421. method = method.substr(prefix_i);
  17422. }
  17423. results.push({
  17424. prefix: prefix,
  17425. method: method.toLowerCase(),
  17426. value: block,
  17427. args: args,
  17428. image: null
  17429. });
  17430. }
  17431. args = [];
  17432. method = prefix = definition = block = '';
  17433. };
  17434. args = [];
  17435. method = prefix = definition = block = '';
  17436. backgroundImage.split("").forEach(function(c) {
  17437. if (mode === 0 && whitespace.indexOf(c) > -1) {
  17438. return;
  17439. }
  17440. switch(c) {
  17441. case '"':
  17442. if(!quote) {
  17443. quote = c;
  17444. } else if(quote === c) {
  17445. quote = null;
  17446. }
  17447. break;
  17448. case '(':
  17449. if(quote) {
  17450. break;
  17451. } else if(mode === 0) {
  17452. mode = 1;
  17453. block += c;
  17454. return;
  17455. } else {
  17456. numParen++;
  17457. }
  17458. break;
  17459. case ')':
  17460. if (quote) {
  17461. break;
  17462. } else if(mode === 1) {
  17463. if(numParen === 0) {
  17464. mode = 0;
  17465. block += c;
  17466. appendResult();
  17467. return;
  17468. } else {
  17469. numParen--;
  17470. }
  17471. }
  17472. break;
  17473. case ',':
  17474. if (quote) {
  17475. break;
  17476. } else if(mode === 0) {
  17477. appendResult();
  17478. return;
  17479. } else if (mode === 1) {
  17480. if (numParen === 0 && !method.match(/^url$/i)) {
  17481. args.push(definition);
  17482. definition = '';
  17483. block += c;
  17484. return;
  17485. }
  17486. }
  17487. break;
  17488. }
  17489. block += c;
  17490. if (mode === 0) {
  17491. method += c;
  17492. } else {
  17493. definition += c;
  17494. }
  17495. });
  17496. appendResult();
  17497. return results;
  17498. };
  17499. },{}],27:[function(_dereq_,module,exports){
  17500. var GradientContainer = _dereq_('./gradientcontainer');
  17501. function WebkitGradientContainer(imageData) {
  17502. GradientContainer.apply(this, arguments);
  17503. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  17504. }
  17505. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  17506. module.exports = WebkitGradientContainer;
  17507. },{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
  17508. function XHR(url) {
  17509. return new Promise(function(resolve, reject) {
  17510. var xhr = new XMLHttpRequest();
  17511. xhr.open('GET', url);
  17512. xhr.onload = function() {
  17513. if (xhr.status === 200) {
  17514. resolve(xhr.responseText);
  17515. } else {
  17516. reject(new Error(xhr.statusText));
  17517. }
  17518. };
  17519. xhr.onerror = function() {
  17520. reject(new Error("Network Error"));
  17521. };
  17522. xhr.send();
  17523. });
  17524. }
  17525. module.exports = XHR;
  17526. },{}]},{},[4])(4)
  17527. });
  17528. /************************************************
  17529. * Title : custom font *
  17530. * Start Data : 2017. 01. 22. *
  17531. * Comment : TEXT API *
  17532. ************************************************/
  17533. /******************************
  17534. * jsPDF extension API Design *
  17535. * ****************************/
  17536. (function(jsPDF){
  17537. var PLUS = '+'.charCodeAt(0);
  17538. var SLASH = '/'.charCodeAt(0);
  17539. var NUMBER = '0'.charCodeAt(0);
  17540. var LOWER = 'a'.charCodeAt(0);
  17541. var UPPER = 'A'.charCodeAt(0);
  17542. var PLUS_URL_SAFE = '-'.charCodeAt(0);
  17543. var SLASH_URL_SAFE = '_'.charCodeAt(0);
  17544. /*****************************************************************/
  17545. /* function : b64ToByteArray */
  17546. /* comment : Base64 encoded TTF file contents (b64) are decoded */
  17547. /* by Byte array and stored. */
  17548. /*****************************************************************/
  17549. var b64ToByteArray = function(b64) {
  17550. var i, j, l, tmp, placeHolders, arr;
  17551. if (b64.length % 4 > 0) {
  17552. throw new Error('Invalid string. Length must be a multiple of 4')
  17553. }
  17554. // the number of equal signs (place holders)
  17555. // if there are two placeholders, than the two characters before it
  17556. // represent one byte
  17557. // if there is only one, then the three characters before it represent 2 bytes
  17558. // this is just a cheap hack to not do indexOf twice
  17559. var len = b64.length;
  17560. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0;
  17561. // base64 is 4/3 + up to two characters of the original data
  17562. arr = new Uint8Array(b64.length * 3 / 4 - placeHolders);
  17563. // if there are placeholders, only get up to the last complete 4 chars
  17564. l = placeHolders > 0 ? b64.length - 4 : b64.length;
  17565. var L = 0;
  17566. function push(v) {
  17567. arr[L++] = v;
  17568. }
  17569. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  17570. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3));
  17571. push((tmp & 0xFF0000) >> 16);
  17572. push((tmp & 0xFF00) >> 8);
  17573. push(tmp & 0xFF);
  17574. }
  17575. if (placeHolders === 2) {
  17576. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4);
  17577. push(tmp & 0xFF);
  17578. }
  17579. else if (placeHolders === 1) {
  17580. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2);
  17581. push((tmp >> 8) & 0xFF);
  17582. push(tmp & 0xFF);
  17583. }
  17584. return arr
  17585. };
  17586. /***************************************************************/
  17587. /* function : decode */
  17588. /* comment : Change the base64 encoded font's content to match */
  17589. /* the base64 index value. */
  17590. /***************************************************************/
  17591. var decode = function(elt) {
  17592. var code = elt.charCodeAt(0);
  17593. if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+'
  17594. if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/'
  17595. if (code < NUMBER) return -1 //no match
  17596. if (code < NUMBER + 10) return code - NUMBER + 26 + 26
  17597. if (code < UPPER + 26) return code - UPPER
  17598. if (code < LOWER + 26) return code - LOWER + 26
  17599. };
  17600. jsPDF.API.TTFFont = (function () {
  17601. /************************************************************************/
  17602. /* function : open */
  17603. /* comment : Decode the encoded ttf content and create a TTFFont object. */
  17604. /************************************************************************/
  17605. TTFFont.open = function (filename, name, vfs, encoding) {
  17606. var contents;
  17607. contents = b64ToByteArray(vfs);
  17608. return new TTFFont(contents, name, encoding);
  17609. };
  17610. /***************************************************************/
  17611. /* function : TTFFont gernerator */
  17612. /* comment : Decode TTF contents are parsed, Data, */
  17613. /* Subset object is created, and registerTTF function is called.*/
  17614. /***************************************************************/
  17615. function TTFFont(rawData, name, encoding) {
  17616. var data;
  17617. this.rawData = rawData;
  17618. data = this.contents = new Data(rawData);
  17619. this.contents.pos = 4;
  17620. if (data.readString(4) === 'ttcf') {
  17621. if (!name) {
  17622. throw new Error("Must specify a font name for TTC files.");
  17623. }
  17624. throw new Error("Font " + name + " not found in TTC file.");
  17625. }
  17626. else {
  17627. data.pos = 0;
  17628. this.parse();
  17629. this.subset = new Subset(this);
  17630. this.registerTTF();
  17631. }
  17632. }
  17633. /********************************************************/
  17634. /* function : parse */
  17635. /* comment : TTF Parses the file contents by each table.*/
  17636. /********************************************************/
  17637. TTFFont.prototype.parse = function () {
  17638. this.directory = new Directory(this.contents);
  17639. this.head = new HeadTable(this);
  17640. this.name = new NameTable(this);
  17641. this.cmap = new CmapTable(this);
  17642. this.hhea = new HheaTable(this);
  17643. this.maxp = new MaxpTable(this);
  17644. this.hmtx = new HmtxTable(this);
  17645. this.post = new PostTable(this);
  17646. this.os2 = new OS2Table(this);
  17647. this.loca = new LocaTable(this);
  17648. this.glyf = new GlyfTable(this);
  17649. this.ascender = (this.os2.exists && this.os2.ascender) || this.hhea.ascender;
  17650. this.decender = (this.os2.exists && this.os2.decender) || this.hhea.decender;
  17651. this.lineGap = (this.os2.exists && this.os2.lineGap) || this.hhea.lineGap;
  17652. return this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax];
  17653. };
  17654. /***************************************************************/
  17655. /* function : registerTTF */
  17656. /* comment : Get the value to assign pdf font descriptors. */
  17657. /***************************************************************/
  17658. TTFFont.prototype.registerTTF = function () {
  17659. var e, hi, low, raw, _ref;
  17660. this.scaleFactor = 1000.0 / this.head.unitsPerEm;
  17661. this.bbox = (function () {
  17662. var _i, _len, _ref, _results;
  17663. _ref = this.bbox;
  17664. _results = [];
  17665. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  17666. e = _ref[_i];
  17667. _results.push(Math.round(e * this.scaleFactor));
  17668. }
  17669. return _results;
  17670. }).call(this);
  17671. this.stemV = 0;
  17672. if (this.post.exists) {
  17673. raw = this.post.italic_angle;
  17674. hi = raw >> 16;
  17675. low = raw & 0xFF;
  17676. if (hi & 0x8000 !== 0) {
  17677. hi = -((hi ^ 0xFFFF) + 1);
  17678. }
  17679. this.italicAngle = +("" + hi + "." + low);
  17680. }
  17681. else {
  17682. this.italicAngle = 0;
  17683. }
  17684. this.ascender = Math.round(this.ascender * this.scaleFactor);
  17685. this.decender = Math.round(this.decender * this.scaleFactor);
  17686. this.lineGap = Math.round(this.lineGap * this.scaleFactor);
  17687. this.capHeight = (this.os2.exists && this.os2.capHeight) || this.ascender;
  17688. this.xHeight = (this.os2.exists && this.os2.xHeight) || 0;
  17689. this.familyClass = (this.os2.exists && this.os2.familyClass || 0) >> 8;
  17690. this.isSerif = (_ref = this.familyClass) === 1 || _ref === 2 || _ref === 3 || _ref === 4 || _ref === 5 || _ref === 7;
  17691. this.isScript = this.familyClass === 10;
  17692. this.flags = 0;
  17693. if (this.post.isFixedPitch) {
  17694. this.flags |= 1 << 0;
  17695. }
  17696. if (this.isSerif) {
  17697. this.flags |= 1 << 1;
  17698. }
  17699. if (this.isScript) {
  17700. this.flags |= 1 << 3;
  17701. }
  17702. if (this.italicAngle !== 0) {
  17703. this.flags |= 1 << 6;
  17704. }
  17705. this.flags |= 1 << 5;
  17706. if (!this.cmap.unicode) {
  17707. throw new Error('No unicode cmap for font');
  17708. }
  17709. };
  17710. TTFFont.prototype.characterToGlyph = function (character) {
  17711. var _ref;
  17712. return ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) || 0;
  17713. };
  17714. TTFFont.prototype.widthOfGlyph = function (glyph) {
  17715. var scale;
  17716. scale = 1000.0 / this.head.unitsPerEm;
  17717. return this.hmtx.forGlyph(glyph).advance * scale;
  17718. };
  17719. TTFFont.prototype.widthOfString = function (string, size, charSpace) {
  17720. var charCode, i, scale, width, _i, _ref, charSpace;
  17721. string = '' + string;
  17722. width = 0;
  17723. for (i = _i = 0, _ref = string.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17724. charCode = string.charCodeAt(i);
  17725. width += (this.widthOfGlyph(this.characterToGlyph(charCode)) + charSpace * (1000/ size)) || 0;
  17726. }
  17727. scale = size / 1000;
  17728. return width * scale;
  17729. };
  17730. TTFFont.prototype.lineHeight = function (size, includeGap) {
  17731. var gap;
  17732. if (includeGap == null) {
  17733. includeGap = false;
  17734. }
  17735. gap = includeGap ? this.lineGap : 0;
  17736. return (this.ascender + gap - this.decender) / 1000 * size;
  17737. };
  17738. return TTFFont;
  17739. })();
  17740. /************************************************************************************************/
  17741. /* function : Data */
  17742. /* comment : The ttf data decoded and stored in an array is read and written to the Data object.*/
  17743. /************************************************************************************************/
  17744. var Data = (function () {
  17745. function Data(data) {
  17746. this.data = data != null ? data : [];
  17747. this.pos = 0;
  17748. this.length = this.data.length;
  17749. }
  17750. Data.prototype.readByte = function () {
  17751. return this.data[this.pos++];
  17752. };
  17753. Data.prototype.writeByte = function (byte) {
  17754. return this.data[this.pos++] = byte;
  17755. };
  17756. Data.prototype.readUInt32 = function () {
  17757. var b1, b2, b3, b4;
  17758. b1 = this.readByte() * 0x1000000;
  17759. b2 = this.readByte() << 16;
  17760. b3 = this.readByte() << 8;
  17761. b4 = this.readByte();
  17762. return b1 + b2 + b3 + b4;
  17763. };
  17764. Data.prototype.writeUInt32 = function (val) {
  17765. this.writeByte((val >>> 24) & 0xff);
  17766. this.writeByte((val >> 16) & 0xff);
  17767. this.writeByte((val >> 8) & 0xff);
  17768. return this.writeByte(val & 0xff);
  17769. };
  17770. Data.prototype.readInt32 = function () {
  17771. var int;
  17772. int = this.readUInt32();
  17773. if (int >= 0x80000000) {
  17774. return int - 0x100000000;
  17775. }
  17776. else {
  17777. return int;
  17778. }
  17779. };
  17780. Data.prototype.writeInt32 = function (val) {
  17781. if (val < 0) {
  17782. val += 0x100000000;
  17783. }
  17784. return this.writeUInt32(val);
  17785. };
  17786. Data.prototype.readUInt16 = function () {
  17787. var b1, b2;
  17788. b1 = this.readByte() << 8;
  17789. b2 = this.readByte();
  17790. return b1 | b2;
  17791. };
  17792. Data.prototype.writeUInt16 = function (val) {
  17793. this.writeByte((val >> 8) & 0xff);
  17794. return this.writeByte(val & 0xff);
  17795. };
  17796. Data.prototype.readInt16 = function () {
  17797. var int;
  17798. int = this.readUInt16();
  17799. if (int >= 0x8000) {
  17800. return int - 0x10000;
  17801. }
  17802. else {
  17803. return int;
  17804. }
  17805. };
  17806. Data.prototype.writeInt16 = function (val) {
  17807. if (val < 0) {
  17808. val += 0x10000;
  17809. }
  17810. return this.writeUInt16(val);
  17811. };
  17812. Data.prototype.readString = function (length) {
  17813. var i, ret, _i;
  17814. ret = [];
  17815. for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
  17816. ret[i] = String.fromCharCode(this.readByte());
  17817. }
  17818. return ret.join('');
  17819. };
  17820. Data.prototype.writeString = function (val) {
  17821. var i, _i, _ref, _results;
  17822. _results = [];
  17823. for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17824. _results.push(this.writeByte(val.charCodeAt(i)));
  17825. }
  17826. return _results;
  17827. };
  17828. /*Data.prototype.stringAt = function (pos, length) {
  17829. this.pos = pos;
  17830. return this.readString(length);
  17831. };*/
  17832. Data.prototype.readShort = function () {
  17833. return this.readInt16();
  17834. };
  17835. Data.prototype.writeShort = function (val) {
  17836. return this.writeInt16(val);
  17837. };
  17838. Data.prototype.readLongLong = function () {
  17839. var b1, b2, b3, b4, b5, b6, b7, b8;
  17840. b1 = this.readByte();
  17841. b2 = this.readByte();
  17842. b3 = this.readByte();
  17843. b4 = this.readByte();
  17844. b5 = this.readByte();
  17845. b6 = this.readByte();
  17846. b7 = this.readByte();
  17847. b8 = this.readByte();
  17848. if (b1 & 0x80) {
  17849. return ((b1 ^ 0xff) * 0x100000000000000 + (b2 ^ 0xff) * 0x1000000000000 + (b3 ^ 0xff) * 0x10000000000 + (b4 ^ 0xff) * 0x100000000 + (b5 ^ 0xff) * 0x1000000 + (b6 ^ 0xff) * 0x10000 + (b7 ^ 0xff) * 0x100 + (b8 ^ 0xff) + 1) * -1;
  17850. }
  17851. return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8;
  17852. };
  17853. /*Data.prototype.writeLongLong = function (val) {
  17854. var high, low;
  17855. high = Math.floor(val / 0x100000000);
  17856. low = val & 0xffffffff;
  17857. this.writeByte((high >> 24) & 0xff);
  17858. this.writeByte((high >> 16) & 0xff);
  17859. this.writeByte((high >> 8) & 0xff);
  17860. this.writeByte(high & 0xff);
  17861. this.writeByte((low >> 24) & 0xff);
  17862. this.writeByte((low >> 16) & 0xff);
  17863. this.writeByte((low >> 8) & 0xff);
  17864. return this.writeByte(low & 0xff);
  17865. };*/
  17866. Data.prototype.readInt = function () {
  17867. return this.readInt32();
  17868. };
  17869. Data.prototype.writeInt = function (val) {
  17870. return this.writeInt32(val);
  17871. };
  17872. /*Data.prototype.slice = function (start, end) {
  17873. return this.data.slice(start, end);
  17874. };*/
  17875. Data.prototype.read = function (bytes) {
  17876. var buf, i, _i;
  17877. buf = [];
  17878. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  17879. buf.push(this.readByte());
  17880. }
  17881. return buf;
  17882. };
  17883. Data.prototype.write = function (bytes) {
  17884. var byte, _i, _len, _results;
  17885. _results = [];
  17886. for (_i = 0, _len = bytes.length; _i < _len; _i++) {
  17887. byte = bytes[_i];
  17888. _results.push(this.writeByte(byte));
  17889. }
  17890. return _results;
  17891. };
  17892. return Data;
  17893. })();
  17894. var Directory = (function () {
  17895. var checksum;
  17896. /*****************************************************************************************************/
  17897. /* function : Directory generator */
  17898. /* comment : Initialize the offset, tag, length, and checksum for each table for the font to be used.*/
  17899. /*****************************************************************************************************/
  17900. function Directory(data) {
  17901. var entry, i, _i, _ref;
  17902. this.scalarType = data.readInt();
  17903. this.tableCount = data.readShort();
  17904. this.searchRange = data.readShort();
  17905. this.entrySelector = data.readShort();
  17906. this.rangeShift = data.readShort();
  17907. this.tables = {};
  17908. for (i = _i = 0, _ref = this.tableCount; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17909. entry = {
  17910. tag: data.readString(4)
  17911. , checksum: data.readInt()
  17912. , offset: data.readInt()
  17913. , length: data.readInt()
  17914. };
  17915. this.tables[entry.tag] = entry;
  17916. }
  17917. }
  17918. /********************************************************************************************************/
  17919. /* function : encode */
  17920. /* comment : It encodes and stores the font table object and information used for the directory object. */
  17921. /********************************************************************************************************/
  17922. Directory.prototype.encode = function (tables) {
  17923. var adjustment, directory, directoryLength, entrySelector, headOffset, log2, offset, rangeShift, searchRange, sum, table, tableCount, tableData, tag;
  17924. tableCount = Object.keys(tables).length;
  17925. log2 = Math.log(2);
  17926. searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
  17927. entrySelector = Math.floor(searchRange / log2);
  17928. rangeShift = tableCount * 16 - searchRange;
  17929. directory = new Data;
  17930. directory.writeInt(this.scalarType);
  17931. directory.writeShort(tableCount);
  17932. directory.writeShort(searchRange);
  17933. directory.writeShort(entrySelector);
  17934. directory.writeShort(rangeShift);
  17935. directoryLength = tableCount * 16;
  17936. offset = directory.pos + directoryLength;
  17937. headOffset = null;
  17938. tableData = [];
  17939. for (tag in tables) {
  17940. table = tables[tag];
  17941. directory.writeString(tag);
  17942. directory.writeInt(checksum(table));
  17943. directory.writeInt(offset);
  17944. directory.writeInt(table.length);
  17945. tableData = tableData.concat(table);
  17946. if (tag === 'head') {
  17947. headOffset = offset;
  17948. }
  17949. offset += table.length;
  17950. while (offset % 4) {
  17951. tableData.push(0);
  17952. offset++;
  17953. }
  17954. }
  17955. directory.write(tableData);
  17956. sum = checksum(directory.data);
  17957. adjustment = 0xB1B0AFBA - sum;
  17958. directory.pos = headOffset + 8;
  17959. directory.writeUInt32(adjustment);
  17960. return directory.data;
  17961. };
  17962. /***************************************************************/
  17963. /* function : checksum */
  17964. /* comment : Duplicate the table for the tag. */
  17965. /***************************************************************/
  17966. checksum = function (data) {
  17967. var i, sum, tmp, _i, _ref;
  17968. data = __slice.call(data);
  17969. while (data.length % 4) {
  17970. data.push(0);
  17971. }
  17972. tmp = new Data(data);
  17973. sum = 0;
  17974. for (i = _i = 0, _ref = data.length; _i < _ref; i = _i += 4) {
  17975. sum += tmp.readUInt32();
  17976. }
  17977. return sum & 0xFFFFFFFF;
  17978. };
  17979. return Directory;
  17980. })();
  17981. var Table, __hasProp = {}.hasOwnProperty
  17982. , __extends = function (child, parent) {
  17983. for (var key in parent) {
  17984. if (__hasProp.call(parent, key)) child[key] = parent[key];
  17985. }
  17986. function ctor() {
  17987. this.constructor = child;
  17988. }
  17989. ctor.prototype = parent.prototype;
  17990. child.prototype = new ctor();
  17991. child.__super__ = parent.prototype;
  17992. return child;
  17993. };
  17994. /***************************************************************/
  17995. /* function : Table */
  17996. /* comment : Save info for each table, and parse the table. */
  17997. /***************************************************************/
  17998. Table = (function () {
  17999. function Table(file) {
  18000. var info;
  18001. this.file = file;
  18002. info = this.file.directory.tables[this.tag];
  18003. this.exists = !!info;
  18004. if (info) {
  18005. this.offset = info.offset, this.length = info.length;
  18006. this.parse(this.file.contents);
  18007. }
  18008. }
  18009. Table.prototype.parse = function () {};
  18010. Table.prototype.encode = function () {};
  18011. Table.prototype.raw = function () {
  18012. if (!this.exists) {
  18013. return null;
  18014. }
  18015. this.file.contents.pos = this.offset;
  18016. return this.file.contents.read(this.length);
  18017. };
  18018. return Table;
  18019. })();
  18020. var HeadTable = (function (_super) {
  18021. __extends(HeadTable, _super);
  18022. function HeadTable() {
  18023. return HeadTable.__super__.constructor.apply(this, arguments);
  18024. }
  18025. HeadTable.prototype.tag = 'head';
  18026. HeadTable.prototype.parse = function (data) {
  18027. data.pos = this.offset;
  18028. this.version = data.readInt();
  18029. this.revision = data.readInt();
  18030. this.checkSumAdjustment = data.readInt();
  18031. this.magicNumber = data.readInt();
  18032. this.flags = data.readShort();
  18033. this.unitsPerEm = data.readShort();
  18034. this.created = data.readLongLong();
  18035. this.modified = data.readLongLong();
  18036. this.xMin = data.readShort();
  18037. this.yMin = data.readShort();
  18038. this.xMax = data.readShort();
  18039. this.yMax = data.readShort();
  18040. this.macStyle = data.readShort();
  18041. this.lowestRecPPEM = data.readShort();
  18042. this.fontDirectionHint = data.readShort();
  18043. this.indexToLocFormat = data.readShort();
  18044. return this.glyphDataFormat = data.readShort();
  18045. };
  18046. /*HeadTable.prototype.encode = function (loca) {
  18047. var table;
  18048. table = new Data;
  18049. table.writeInt(this.version);
  18050. table.writeInt(this.revision);
  18051. table.writeInt(this.checkSumAdjustment);
  18052. table.writeInt(this.magicNumber);
  18053. table.writeShort(this.flags);
  18054. table.writeShort(this.unitsPerEm);
  18055. table.writeLongLong(this.created);
  18056. table.writeLongLong(this.modified);
  18057. table.writeShort(this.xMin);
  18058. table.writeShort(this.yMin);
  18059. table.writeShort(this.xMax);
  18060. table.writeShort(this.yMax);
  18061. table.writeShort(this.macStyle);
  18062. table.writeShort(this.lowestRecPPEM);
  18063. table.writeShort(this.fontDirectionHint);
  18064. table.writeShort(loca.type);
  18065. table.writeShort(this.glyphDataFormat);
  18066. return table.data;
  18067. };*/
  18068. return HeadTable;
  18069. })(Table);
  18070. /************************************************************************************/
  18071. /* function : CmapEntry */
  18072. /* comment : Cmap Initializes and encodes object information (required by pdf spec).*/
  18073. /************************************************************************************/
  18074. var CmapEntry = (function () {
  18075. function CmapEntry(data, offset) {
  18076. var code, count, endCode, glyphId, glyphIds, i, idDelta, idRangeOffset, index, saveOffset, segCount, segCountX2, start, startCode, tail, _i, _j, _k, _len;
  18077. this.platformID = data.readUInt16();
  18078. this.encodingID = data.readShort();
  18079. this.offset = offset + data.readInt();
  18080. saveOffset = data.pos;
  18081. data.pos = this.offset;
  18082. this.format = data.readUInt16();
  18083. this.length = data.readUInt16();
  18084. this.language = data.readUInt16();
  18085. this.isUnicode = (this.platformID === 3 && this.encodingID === 1 && this.format === 4) || this.platformID === 0 && this.format === 4;
  18086. this.codeMap = {};
  18087. switch (this.format) {
  18088. case 0:
  18089. for (i = _i = 0; _i < 256; i = ++_i) {
  18090. this.codeMap[i] = data.readByte();
  18091. }
  18092. break;
  18093. case 4:
  18094. segCountX2 = data.readUInt16();
  18095. segCount = segCountX2 / 2;
  18096. data.pos += 6;
  18097. endCode = (function () {
  18098. var _j, _results;
  18099. _results = [];
  18100. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  18101. _results.push(data.readUInt16());
  18102. }
  18103. return _results;
  18104. })();
  18105. data.pos += 2;
  18106. startCode = (function () {
  18107. var _j, _results;
  18108. _results = [];
  18109. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  18110. _results.push(data.readUInt16());
  18111. }
  18112. return _results;
  18113. })();
  18114. idDelta = (function () {
  18115. var _j, _results;
  18116. _results = [];
  18117. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  18118. _results.push(data.readUInt16());
  18119. }
  18120. return _results;
  18121. })();
  18122. idRangeOffset = (function () {
  18123. var _j, _results;
  18124. _results = [];
  18125. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  18126. _results.push(data.readUInt16());
  18127. }
  18128. return _results;
  18129. })();
  18130. count = (this.length - data.pos + this.offset) / 2;
  18131. glyphIds = (function () {
  18132. var _j, _results;
  18133. _results = [];
  18134. for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
  18135. _results.push(data.readUInt16());
  18136. }
  18137. return _results;
  18138. })();
  18139. for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
  18140. tail = endCode[i];
  18141. start = startCode[i];
  18142. for (code = _k = start; start <= tail ? _k <= tail : _k >= tail; code = start <= tail ? ++_k : --_k) {
  18143. if (idRangeOffset[i] === 0) {
  18144. glyphId = code + idDelta[i];
  18145. }
  18146. else {
  18147. index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
  18148. glyphId = glyphIds[index] || 0;
  18149. if (glyphId !== 0) {
  18150. glyphId += idDelta[i];
  18151. }
  18152. }
  18153. this.codeMap[code] = glyphId & 0xFFFF;
  18154. }
  18155. }
  18156. }
  18157. data.pos = saveOffset;
  18158. }
  18159. CmapEntry.encode = function (charmap, encoding) {
  18160. var charMap, code, codeMap, codes, delta, deltas, diff, endCode, endCodes, entrySelector, glyphIDs, i, id, indexes, last, map, nextID, offset, old, rangeOffsets, rangeShift, result, searchRange, segCount, segCountX2, startCode, startCodes, startGlyph, subtable, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _len6, _len7, _m, _n, _name, _o, _p, _q;
  18161. subtable = new Data;
  18162. codes = Object.keys(charmap).sort(function (a, b) {
  18163. return a - b;
  18164. });
  18165. switch (encoding) {
  18166. case 'macroman':
  18167. id = 0;
  18168. indexes = (function () {
  18169. var _i, _results;
  18170. _results = [];
  18171. for (i = _i = 0; _i < 256; i = ++_i) {
  18172. _results.push(0);
  18173. }
  18174. return _results;
  18175. })();
  18176. map = {
  18177. 0: 0
  18178. };
  18179. codeMap = {};
  18180. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  18181. code = codes[_i];
  18182. if (map[_name = charmap[code]] == null) {
  18183. map[_name] = ++id;
  18184. }
  18185. codeMap[code] = {
  18186. old: charmap[code]
  18187. , "new": map[charmap[code]]
  18188. };
  18189. indexes[code] = map[charmap[code]];
  18190. }
  18191. subtable.writeUInt16(1);
  18192. subtable.writeUInt16(0);
  18193. subtable.writeUInt32(12);
  18194. subtable.writeUInt16(0);
  18195. subtable.writeUInt16(262);
  18196. subtable.writeUInt16(0);
  18197. subtable.write(indexes);
  18198. return result = {
  18199. charMap: codeMap
  18200. , subtable: subtable.data
  18201. , maxGlyphID: id + 1
  18202. };
  18203. case 'unicode':
  18204. startCodes = [];
  18205. endCodes = [];
  18206. nextID = 0;
  18207. map = {};
  18208. charMap = {};
  18209. last = diff = null;
  18210. for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
  18211. code = codes[_j];
  18212. old = charmap[code];
  18213. if (map[old] == null) {
  18214. map[old] = ++nextID;
  18215. }
  18216. charMap[code] = {
  18217. old: old
  18218. , "new": map[old]
  18219. };
  18220. delta = map[old] - code;
  18221. if ((last == null) || delta !== diff) {
  18222. if (last) {
  18223. endCodes.push(last);
  18224. }
  18225. startCodes.push(code);
  18226. diff = delta;
  18227. }
  18228. last = code;
  18229. }
  18230. if (last) {
  18231. endCodes.push(last);
  18232. }
  18233. endCodes.push(0xFFFF);
  18234. startCodes.push(0xFFFF);
  18235. segCount = startCodes.length;
  18236. segCountX2 = segCount * 2;
  18237. searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
  18238. entrySelector = Math.log(searchRange / 2) / Math.LN2;
  18239. rangeShift = 2 * segCount - searchRange;
  18240. deltas = [];
  18241. rangeOffsets = [];
  18242. glyphIDs = [];
  18243. for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
  18244. startCode = startCodes[i];
  18245. endCode = endCodes[i];
  18246. if (startCode === 0xFFFF) {
  18247. deltas.push(0);
  18248. rangeOffsets.push(0);
  18249. break;
  18250. }
  18251. startGlyph = charMap[startCode]["new"];
  18252. if (startCode - startGlyph >= 0x8000) {
  18253. deltas.push(0);
  18254. rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
  18255. for (code = _l = startCode; startCode <= endCode ? _l <= endCode : _l >= endCode; code = startCode <= endCode ? ++_l : --_l) {
  18256. glyphIDs.push(charMap[code]["new"]);
  18257. }
  18258. }
  18259. else {
  18260. deltas.push(startGlyph - startCode);
  18261. rangeOffsets.push(0);
  18262. }
  18263. }
  18264. subtable.writeUInt16(3);
  18265. subtable.writeUInt16(1);
  18266. subtable.writeUInt32(12);
  18267. subtable.writeUInt16(4);
  18268. subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
  18269. subtable.writeUInt16(0);
  18270. subtable.writeUInt16(segCountX2);
  18271. subtable.writeUInt16(searchRange);
  18272. subtable.writeUInt16(entrySelector);
  18273. subtable.writeUInt16(rangeShift);
  18274. for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
  18275. code = endCodes[_m];
  18276. subtable.writeUInt16(code);
  18277. }
  18278. subtable.writeUInt16(0);
  18279. for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
  18280. code = startCodes[_n];
  18281. subtable.writeUInt16(code);
  18282. }
  18283. for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
  18284. delta = deltas[_o];
  18285. subtable.writeUInt16(delta);
  18286. }
  18287. for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
  18288. offset = rangeOffsets[_p];
  18289. subtable.writeUInt16(offset);
  18290. }
  18291. for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
  18292. id = glyphIDs[_q];
  18293. subtable.writeUInt16(id);
  18294. }
  18295. return result = {
  18296. charMap: charMap
  18297. , subtable: subtable.data
  18298. , maxGlyphID: nextID + 1
  18299. };
  18300. }
  18301. };
  18302. return CmapEntry;
  18303. })();
  18304. var CmapTable = (function (_super) {
  18305. __extends(CmapTable, _super);
  18306. function CmapTable() {
  18307. return CmapTable.__super__.constructor.apply(this, arguments);
  18308. }
  18309. CmapTable.prototype.tag = 'cmap';
  18310. CmapTable.prototype.parse = function (data) {
  18311. var entry, i, tableCount, _i;
  18312. data.pos = this.offset;
  18313. this.version = data.readUInt16();
  18314. tableCount = data.readUInt16();
  18315. this.tables = [];
  18316. this.unicode = null;
  18317. for (i = _i = 0; 0 <= tableCount ? _i < tableCount : _i > tableCount; i = 0 <= tableCount ? ++_i : --_i) {
  18318. entry = new CmapEntry(data, this.offset);
  18319. this.tables.push(entry);
  18320. if (entry.isUnicode) {
  18321. if (this.unicode == null) {
  18322. this.unicode = entry;
  18323. }
  18324. }
  18325. }
  18326. return true;
  18327. };
  18328. /*************************************************************************/
  18329. /* function : encode */
  18330. /* comment : Encode the cmap table corresponding to the input character. */
  18331. /*************************************************************************/
  18332. CmapTable.encode = function (charmap, encoding) {
  18333. var result, table;
  18334. if (encoding == null) {
  18335. encoding = 'macroman';
  18336. }
  18337. result = CmapEntry.encode(charmap, encoding);
  18338. table = new Data;
  18339. table.writeUInt16(0);
  18340. table.writeUInt16(1);
  18341. result.table = table.data.concat(result.subtable);
  18342. return result;
  18343. };
  18344. return CmapTable;
  18345. })(Table);
  18346. var HheaTable = (function (_super) {
  18347. __extends(HheaTable, _super);
  18348. function HheaTable() {
  18349. return HheaTable.__super__.constructor.apply(this, arguments);
  18350. }
  18351. HheaTable.prototype.tag = 'hhea';
  18352. HheaTable.prototype.parse = function (data) {
  18353. data.pos = this.offset;
  18354. this.version = data.readInt();
  18355. this.ascender = data.readShort();
  18356. this.decender = data.readShort();
  18357. this.lineGap = data.readShort();
  18358. this.advanceWidthMax = data.readShort();
  18359. this.minLeftSideBearing = data.readShort();
  18360. this.minRightSideBearing = data.readShort();
  18361. this.xMaxExtent = data.readShort();
  18362. this.caretSlopeRise = data.readShort();
  18363. this.caretSlopeRun = data.readShort();
  18364. this.caretOffset = data.readShort();
  18365. data.pos += 4 * 2;
  18366. this.metricDataFormat = data.readShort();
  18367. return this.numberOfMetrics = data.readUInt16();
  18368. };
  18369. /*HheaTable.prototype.encode = function (ids) {
  18370. var i, table, _i, _ref;
  18371. table = new Data;
  18372. table.writeInt(this.version);
  18373. table.writeShort(this.ascender);
  18374. table.writeShort(this.decender);
  18375. table.writeShort(this.lineGap);
  18376. table.writeShort(this.advanceWidthMax);
  18377. table.writeShort(this.minLeftSideBearing);
  18378. table.writeShort(this.minRightSideBearing);
  18379. table.writeShort(this.xMaxExtent);
  18380. table.writeShort(this.caretSlopeRise);
  18381. table.writeShort(this.caretSlopeRun);
  18382. table.writeShort(this.caretOffset);
  18383. for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  18384. table.writeByte(0);
  18385. }
  18386. table.writeShort(this.metricDataFormat);
  18387. table.writeUInt16(ids.length);
  18388. return table.data;
  18389. };*/
  18390. return HheaTable;
  18391. })(Table);
  18392. var OS2Table = (function (_super) {
  18393. __extends(OS2Table, _super);
  18394. function OS2Table() {
  18395. return OS2Table.__super__.constructor.apply(this, arguments);
  18396. }
  18397. OS2Table.prototype.tag = 'OS/2';
  18398. OS2Table.prototype.parse = function (data) {
  18399. var i;
  18400. data.pos = this.offset;
  18401. this.version = data.readUInt16();
  18402. this.averageCharWidth = data.readShort();
  18403. this.weightClass = data.readUInt16();
  18404. this.widthClass = data.readUInt16();
  18405. this.type = data.readShort();
  18406. this.ySubscriptXSize = data.readShort();
  18407. this.ySubscriptYSize = data.readShort();
  18408. this.ySubscriptXOffset = data.readShort();
  18409. this.ySubscriptYOffset = data.readShort();
  18410. this.ySuperscriptXSize = data.readShort();
  18411. this.ySuperscriptYSize = data.readShort();
  18412. this.ySuperscriptXOffset = data.readShort();
  18413. this.ySuperscriptYOffset = data.readShort();
  18414. this.yStrikeoutSize = data.readShort();
  18415. this.yStrikeoutPosition = data.readShort();
  18416. this.familyClass = data.readShort();
  18417. this.panose = (function () {
  18418. var _i, _results;
  18419. _results = [];
  18420. for (i = _i = 0; _i < 10; i = ++_i) {
  18421. _results.push(data.readByte());
  18422. }
  18423. return _results;
  18424. })();
  18425. this.charRange = (function () {
  18426. var _i, _results;
  18427. _results = [];
  18428. for (i = _i = 0; _i < 4; i = ++_i) {
  18429. _results.push(data.readInt());
  18430. }
  18431. return _results;
  18432. })();
  18433. this.vendorID = data.readString(4);
  18434. this.selection = data.readShort();
  18435. this.firstCharIndex = data.readShort();
  18436. this.lastCharIndex = data.readShort();
  18437. if (this.version > 0) {
  18438. this.ascent = data.readShort();
  18439. this.descent = data.readShort();
  18440. this.lineGap = data.readShort();
  18441. this.winAscent = data.readShort();
  18442. this.winDescent = data.readShort();
  18443. this.codePageRange = (function () {
  18444. var _i, _results;
  18445. _results = [];
  18446. for (i = _i = 0; _i < 2; i = ++_i) {
  18447. _results.push(data.readInt());
  18448. }
  18449. return _results;
  18450. })();
  18451. if (this.version > 1) {
  18452. this.xHeight = data.readShort();
  18453. this.capHeight = data.readShort();
  18454. this.defaultChar = data.readShort();
  18455. this.breakChar = data.readShort();
  18456. return this.maxContext = data.readShort();
  18457. }
  18458. }
  18459. };
  18460. /*OS2Table.prototype.encode = function () {
  18461. return this.raw();
  18462. };*/
  18463. return OS2Table;
  18464. })(Table);
  18465. var PostTable = (function (_super) {
  18466. __extends(PostTable, _super);
  18467. function PostTable() {
  18468. return PostTable.__super__.constructor.apply(this, arguments);
  18469. }
  18470. PostTable.prototype.tag = 'post';
  18471. PostTable.prototype.parse = function (data) {
  18472. var i, length, numberOfGlyphs, _i, _results;
  18473. data.pos = this.offset;
  18474. this.format = data.readInt();
  18475. this.italicAngle = data.readInt();
  18476. this.underlinePosition = data.readShort();
  18477. this.underlineThickness = data.readShort();
  18478. this.isFixedPitch = data.readInt();
  18479. this.minMemType42 = data.readInt();
  18480. this.maxMemType42 = data.readInt();
  18481. this.minMemType1 = data.readInt();
  18482. this.maxMemType1 = data.readInt();
  18483. switch (this.format) {
  18484. case 0x00010000:
  18485. break;
  18486. case 0x00020000:
  18487. numberOfGlyphs = data.readUInt16();
  18488. this.glyphNameIndex = [];
  18489. for (i = _i = 0; 0 <= numberOfGlyphs ? _i < numberOfGlyphs : _i > numberOfGlyphs; i = 0 <= numberOfGlyphs ? ++_i : --_i) {
  18490. this.glyphNameIndex.push(data.readUInt16());
  18491. }
  18492. this.names = [];
  18493. _results = [];
  18494. while (data.pos < this.offset + this.length) {
  18495. length = data.readByte();
  18496. _results.push(this.names.push(data.readString(length)));
  18497. }
  18498. return _results;
  18499. break;
  18500. case 0x00025000:
  18501. numberOfGlyphs = data.readUInt16();
  18502. return this.offsets = data.read(numberOfGlyphs);
  18503. case 0x00030000:
  18504. break;
  18505. case 0x00040000:
  18506. return this.map = (function () {
  18507. var _j, _ref, _results1;
  18508. _results1 = [];
  18509. for (i = _j = 0, _ref = this.file.maxp.numGlyphs; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
  18510. _results1.push(data.readUInt32());
  18511. }
  18512. return _results1;
  18513. }).call(this);
  18514. }
  18515. };
  18516. return PostTable;
  18517. })(Table);
  18518. /*********************************************************************************************************/
  18519. /* function : NameEntry */
  18520. /* comment : Store copyright information, platformID, encodingID, and languageID in the NameEntry object.*/
  18521. /*********************************************************************************************************/
  18522. var NameEntry = (function () {
  18523. function NameEntry(raw, entry) {
  18524. this.raw = raw;
  18525. this.length = raw.length;
  18526. this.platformID = entry.platformID;
  18527. this.encodingID = entry.encodingID;
  18528. this.languageID = entry.languageID;
  18529. }
  18530. return NameEntry;
  18531. })();
  18532. var NameTable = (function (_super) {
  18533. __extends(NameTable, _super);
  18534. function NameTable() {
  18535. return NameTable.__super__.constructor.apply(this, arguments);
  18536. }
  18537. NameTable.prototype.tag = 'name';
  18538. NameTable.prototype.parse = function (data) {
  18539. var count, entries, entry, format, i, name, stringOffset, strings, text, _i, _j, _len, _name;
  18540. data.pos = this.offset;
  18541. format = data.readShort();
  18542. count = data.readShort();
  18543. stringOffset = data.readShort();
  18544. entries = [];
  18545. for (i = _i = 0; 0 <= count ? _i < count : _i > count; i = 0 <= count ? ++_i : --_i) {
  18546. entries.push({
  18547. platformID: data.readShort()
  18548. , encodingID: data.readShort()
  18549. , languageID: data.readShort()
  18550. , nameID: data.readShort()
  18551. , length: data.readShort()
  18552. , offset: this.offset + stringOffset + data.readShort()
  18553. });
  18554. }
  18555. strings = {};
  18556. for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
  18557. entry = entries[i];
  18558. data.pos = entry.offset;
  18559. text = data.readString(entry.length);
  18560. name = new NameEntry(text, entry);
  18561. if (strings[_name = entry.nameID] == null) {
  18562. strings[_name] = [];
  18563. }
  18564. strings[entry.nameID].push(name);
  18565. }
  18566. this.strings = strings;
  18567. this.copyright = strings[0];
  18568. this.fontFamily = strings[1];
  18569. this.fontSubfamily = strings[2];
  18570. this.uniqueSubfamily = strings[3];
  18571. this.fontName = strings[4];
  18572. this.version = strings[5];
  18573. this.postscriptName = strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
  18574. this.trademark = strings[7];
  18575. this.manufacturer = strings[8];
  18576. this.designer = strings[9];
  18577. this.description = strings[10];
  18578. this.vendorUrl = strings[11];
  18579. this.designerUrl = strings[12];
  18580. this.license = strings[13];
  18581. this.licenseUrl = strings[14];
  18582. this.preferredFamily = strings[15];
  18583. this.preferredSubfamily = strings[17];
  18584. this.compatibleFull = strings[18];
  18585. return this.sampleText = strings[19];
  18586. };
  18587. /*NameTable.prototype.encode = function () {
  18588. var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
  18589. strings = {};
  18590. _ref = this.strings;
  18591. for (id in _ref) {
  18592. val = _ref[id];
  18593. strings[id] = val;
  18594. }
  18595. postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
  18596. platformID: 1
  18597. , encodingID: 0
  18598. , languageID: 0
  18599. });
  18600. strings[6] = [postscriptName];
  18601. subsetTag = successorOf(subsetTag);
  18602. strCount = 0;
  18603. for (id in strings) {
  18604. list = strings[id];
  18605. if (list != null) {
  18606. strCount += list.length;
  18607. }
  18608. }
  18609. table = new Data;
  18610. strTable = new Data;
  18611. table.writeShort(0);
  18612. table.writeShort(strCount);
  18613. table.writeShort(6 + 12 * strCount);
  18614. for (nameID in strings) {
  18615. list = strings[nameID];
  18616. if (list != null) {
  18617. for (_i = 0, _len = list.length; _i < _len; _i++) {
  18618. string = list[_i];
  18619. table.writeShort(string.platformID);
  18620. table.writeShort(string.encodingID);
  18621. table.writeShort(string.languageID);
  18622. table.writeShort(nameID);
  18623. table.writeShort(string.length);
  18624. table.writeShort(strTable.pos);
  18625. strTable.writeString(string.raw);
  18626. }
  18627. }
  18628. }
  18629. return nameTable = {
  18630. postscriptName: postscriptName.raw
  18631. , table: table.data.concat(strTable.data)
  18632. };
  18633. };*/
  18634. return NameTable;
  18635. })(Table);
  18636. var MaxpTable = (function (_super) {
  18637. __extends(MaxpTable, _super);
  18638. function MaxpTable() {
  18639. return MaxpTable.__super__.constructor.apply(this, arguments);
  18640. }
  18641. MaxpTable.prototype.tag = 'maxp';
  18642. MaxpTable.prototype.parse = function (data) {
  18643. data.pos = this.offset;
  18644. this.version = data.readInt();
  18645. this.numGlyphs = data.readUInt16();
  18646. this.maxPoints = data.readUInt16();
  18647. this.maxContours = data.readUInt16();
  18648. this.maxCompositePoints = data.readUInt16();
  18649. this.maxComponentContours = data.readUInt16();
  18650. this.maxZones = data.readUInt16();
  18651. this.maxTwilightPoints = data.readUInt16();
  18652. this.maxStorage = data.readUInt16();
  18653. this.maxFunctionDefs = data.readUInt16();
  18654. this.maxInstructionDefs = data.readUInt16();
  18655. this.maxStackElements = data.readUInt16();
  18656. this.maxSizeOfInstructions = data.readUInt16();
  18657. this.maxComponentElements = data.readUInt16();
  18658. return this.maxComponentDepth = data.readUInt16();
  18659. };
  18660. /*MaxpTable.prototype.encode = function (ids) {
  18661. var table;
  18662. table = new Data;
  18663. table.writeInt(this.version);
  18664. table.writeUInt16(ids.length);
  18665. table.writeUInt16(this.maxPoints);
  18666. table.writeUInt16(this.maxContours);
  18667. table.writeUInt16(this.maxCompositePoints);
  18668. table.writeUInt16(this.maxComponentContours);
  18669. table.writeUInt16(this.maxZones);
  18670. table.writeUInt16(this.maxTwilightPoints);
  18671. table.writeUInt16(this.maxStorage);
  18672. table.writeUInt16(this.maxFunctionDefs);
  18673. table.writeUInt16(this.maxInstructionDefs);
  18674. table.writeUInt16(this.maxStackElements);
  18675. table.writeUInt16(this.maxSizeOfInstructions);
  18676. table.writeUInt16(this.maxComponentElements);
  18677. table.writeUInt16(this.maxComponentDepth);
  18678. return table.data;
  18679. };*/
  18680. return MaxpTable;
  18681. })(Table);
  18682. var HmtxTable = (function (_super) {
  18683. __extends(HmtxTable, _super);
  18684. function HmtxTable() {
  18685. return HmtxTable.__super__.constructor.apply(this, arguments);
  18686. }
  18687. HmtxTable.prototype.tag = 'hmtx';
  18688. HmtxTable.prototype.parse = function (data) {
  18689. var i, last, lsbCount, m, _i, _j, _ref, _results;
  18690. data.pos = this.offset;
  18691. this.metrics = [];
  18692. for (i = _i = 0, _ref = this.file.hhea.numberOfMetrics; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  18693. this.metrics.push({
  18694. advance: data.readUInt16()
  18695. , lsb: data.readInt16()
  18696. });
  18697. }
  18698. lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
  18699. this.leftSideBearings = (function () {
  18700. var _j, _results;
  18701. _results = [];
  18702. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  18703. _results.push(data.readInt16());
  18704. }
  18705. return _results;
  18706. })();
  18707. this.widths = (function () {
  18708. var _j, _len, _ref1, _results;
  18709. _ref1 = this.metrics;
  18710. _results = [];
  18711. for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
  18712. m = _ref1[_j];
  18713. _results.push(m.advance);
  18714. }
  18715. return _results;
  18716. }).call(this);
  18717. last = this.widths[this.widths.length - 1];
  18718. _results = [];
  18719. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  18720. _results.push(this.widths.push(last));
  18721. }
  18722. return _results;
  18723. };
  18724. /***************************************************************/
  18725. /* function : forGlyph */
  18726. /* comment : Returns the advance width and lsb for this glyph. */
  18727. /***************************************************************/
  18728. HmtxTable.prototype.forGlyph = function (id) {
  18729. var metrics;
  18730. if (id in this.metrics) {
  18731. return this.metrics[id];
  18732. }
  18733. return metrics = {
  18734. advance: this.metrics[this.metrics.length - 1].advance
  18735. , lsb: this.leftSideBearings[id - this.metrics.length]
  18736. };
  18737. };
  18738. /*HmtxTable.prototype.encode = function (mapping) {
  18739. var id, metric, table, _i, _len;
  18740. table = new Data;
  18741. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  18742. id = mapping[_i];
  18743. metric = this.forGlyph(id);
  18744. table.writeUInt16(metric.advance);
  18745. table.writeUInt16(metric.lsb);
  18746. }
  18747. return table.data;
  18748. };*/
  18749. return HmtxTable;
  18750. })(Table);
  18751. var __slice = [].slice;
  18752. var GlyfTable = (function (_super) {
  18753. __extends(GlyfTable, _super);
  18754. function GlyfTable() {
  18755. return GlyfTable.__super__.constructor.apply(this, arguments);
  18756. }
  18757. GlyfTable.prototype.tag = 'glyf';
  18758. GlyfTable.prototype.parse = function (data) {
  18759. return this.cache = {};
  18760. };
  18761. GlyfTable.prototype.glyphFor = function (id) {
  18762. id = id;
  18763. var data, index, length, loca, numberOfContours, raw, xMax, xMin, yMax, yMin;
  18764. if (id in this.cache) {
  18765. return this.cache[id];
  18766. }
  18767. loca = this.file.loca;
  18768. data = this.file.contents;
  18769. index = loca.indexOf(id);
  18770. length = loca.lengthOf(id);
  18771. if (length === 0) {
  18772. return this.cache[id] = null;
  18773. }
  18774. data.pos = this.offset + index;
  18775. raw = new Data(data.read(length));
  18776. numberOfContours = raw.readShort();
  18777. xMin = raw.readShort();
  18778. yMin = raw.readShort();
  18779. xMax = raw.readShort();
  18780. yMax = raw.readShort();
  18781. if (numberOfContours === -1) {
  18782. this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
  18783. }
  18784. else {
  18785. this.cache[id] = new SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax);
  18786. }
  18787. return this.cache[id];
  18788. };
  18789. GlyfTable.prototype.encode = function (glyphs, mapping, old2new) {
  18790. var glyph, id, offsets, table, _i, _len;
  18791. table = [];
  18792. offsets = [];
  18793. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  18794. id = mapping[_i];
  18795. glyph = glyphs[id];
  18796. offsets.push(table.length);
  18797. if (glyph) {
  18798. table = table.concat(glyph.encode(old2new));
  18799. }
  18800. }
  18801. offsets.push(table.length);
  18802. return {
  18803. table: table
  18804. , offsets: offsets
  18805. };
  18806. };
  18807. return GlyfTable;
  18808. })(Table);
  18809. var SimpleGlyph = (function () {
  18810. /**************************************************************************/
  18811. /* function : SimpleGlyph */
  18812. /* comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph.*/
  18813. /**************************************************************************/
  18814. function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
  18815. this.raw = raw;
  18816. this.numberOfContours = numberOfContours;
  18817. this.xMin = xMin;
  18818. this.yMin = yMin;
  18819. this.xMax = xMax;
  18820. this.yMax = yMax;
  18821. this.compound = false;
  18822. }
  18823. SimpleGlyph.prototype.encode = function () {
  18824. return this.raw.data;
  18825. };
  18826. return SimpleGlyph;
  18827. })();
  18828. var CompoundGlyph = (function () {
  18829. var ARG_1_AND_2_ARE_WORDS, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_SCALE, WE_HAVE_A_TWO_BY_TWO;
  18830. ARG_1_AND_2_ARE_WORDS = 0x0001;
  18831. WE_HAVE_A_SCALE = 0x0008;
  18832. MORE_COMPONENTS = 0x0020;
  18833. WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
  18834. WE_HAVE_A_TWO_BY_TWO = 0x0080;
  18835. /********************************************************************************************************************/
  18836. /* function : CompoundGlypg generator */
  18837. /* comment : It stores raw, xMin, yMin, xMax, yMax, glyph id, and glyph offset for the corresponding compound glyph.*/
  18838. /********************************************************************************************************************/
  18839. function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
  18840. var data, flags;
  18841. this.raw = raw;
  18842. this.xMin = xMin;
  18843. this.yMin = yMin;
  18844. this.xMax = xMax;
  18845. this.yMax = yMax;
  18846. this.compound = true;
  18847. this.glyphIDs = [];
  18848. this.glyphOffsets = [];
  18849. data = this.raw;
  18850. while (true) {
  18851. flags = data.readShort();
  18852. this.glyphOffsets.push(data.pos);
  18853. this.glyphIDs.push(data.readShort());
  18854. if (!(flags & MORE_COMPONENTS)) {
  18855. break;
  18856. }
  18857. if (flags & ARG_1_AND_2_ARE_WORDS) {
  18858. data.pos += 4;
  18859. }
  18860. else {
  18861. data.pos += 2;
  18862. }
  18863. if (flags & WE_HAVE_A_TWO_BY_TWO) {
  18864. data.pos += 8;
  18865. }
  18866. else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
  18867. data.pos += 4;
  18868. }
  18869. else if (flags & WE_HAVE_A_SCALE) {
  18870. data.pos += 2;
  18871. }
  18872. }
  18873. }
  18874. /****************************************************************************************************************/
  18875. /* function : CompoundGlypg encode */
  18876. /* comment : After creating a table for the characters you typed, you call directory.encode to encode the table.*/
  18877. /****************************************************************************************************************/
  18878. CompoundGlyph.prototype.encode = function (mapping) {
  18879. var i, id, result, _i, _len, _ref;
  18880. result = new Data(__slice.call(this.raw.data));
  18881. _ref = this.glyphIDs;
  18882. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  18883. id = _ref[i];
  18884. result.pos = this.glyphOffsets[i];
  18885. }
  18886. return result.data;
  18887. };
  18888. return CompoundGlyph;
  18889. })();
  18890. var LocaTable = (function (_super) {
  18891. __extends(LocaTable, _super);
  18892. function LocaTable() {
  18893. return LocaTable.__super__.constructor.apply(this, arguments);
  18894. }
  18895. LocaTable.prototype.tag = 'loca';
  18896. LocaTable.prototype.parse = function (data) {
  18897. var format, i;
  18898. data.pos = this.offset;
  18899. format = this.file.head.indexToLocFormat;
  18900. if (format === 0) {
  18901. return this.offsets = (function () {
  18902. var _i, _ref, _results;
  18903. _results = [];
  18904. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 2) {
  18905. _results.push(data.readUInt16() * 2);
  18906. }
  18907. return _results;
  18908. }).call(this);
  18909. }
  18910. else {
  18911. return this.offsets = (function () {
  18912. var _i, _ref, _results;
  18913. _results = [];
  18914. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 4) {
  18915. _results.push(data.readUInt32());
  18916. }
  18917. return _results;
  18918. }).call(this);
  18919. }
  18920. };
  18921. LocaTable.prototype.indexOf = function (id) {
  18922. return this.offsets[id];
  18923. };
  18924. LocaTable.prototype.lengthOf = function (id) {
  18925. return this.offsets[id + 1] - this.offsets[id];
  18926. };
  18927. LocaTable.prototype.encode = function (offsets, activeGlyphs) {
  18928. var LocaTable = new Uint32Array(this.offsets.length);
  18929. var glyfPtr = 0;
  18930. var listGlyf = 0;
  18931. for (var k = 0; k < LocaTable.length; ++k) {
  18932. LocaTable[k] = glyfPtr;
  18933. if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
  18934. ++listGlyf;
  18935. LocaTable[k] = glyfPtr;
  18936. var start = this.offsets[k];
  18937. var len = this.offsets[k + 1] - start;
  18938. if (len > 0) {
  18939. glyfPtr += len;
  18940. }
  18941. }
  18942. }
  18943. var newLocaTable = new Array(LocaTable.length * 4);
  18944. for (var j = 0; j < LocaTable.length; ++j) {
  18945. newLocaTable[4 * j + 3] = (LocaTable[j] & 0x000000ff);
  18946. newLocaTable[4 * j + 2] = (LocaTable[j] & 0x0000ff00) >> 8;
  18947. newLocaTable[4 * j + 1] = (LocaTable[j] & 0x00ff0000) >> 16;
  18948. newLocaTable[4 * j] = (LocaTable[j] & 0xff000000) >> 24;
  18949. }
  18950. return newLocaTable;
  18951. };
  18952. return LocaTable;
  18953. })(Table);
  18954. /************************************************************************************/
  18955. /* function : invert */
  18956. /* comment : Change the object's (key: value) to create an object with (value: key).*/
  18957. /************************************************************************************/
  18958. var invert = function (object) {
  18959. var key, ret, val;
  18960. ret = {};
  18961. for (key in object) {
  18962. val = object[key];
  18963. ret[val] = key;
  18964. }
  18965. return ret;
  18966. };
  18967. /*var successorOf = function (input) {
  18968. var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
  18969. alphabet = 'abcdefghijklmnopqrstuvwxyz';
  18970. length = alphabet.length;
  18971. result = input;
  18972. i = input.length;
  18973. while (i >= 0) {
  18974. last = input.charAt(--i);
  18975. if (isNaN(last)) {
  18976. index = alphabet.indexOf(last.toLowerCase());
  18977. if (index === -1) {
  18978. next = last;
  18979. carry = true;
  18980. }
  18981. else {
  18982. next = alphabet.charAt((index + 1) % length);
  18983. isUpperCase = last === last.toUpperCase();
  18984. if (isUpperCase) {
  18985. next = next.toUpperCase();
  18986. }
  18987. carry = index + 1 >= length;
  18988. if (carry && i === 0) {
  18989. added = isUpperCase ? 'A' : 'a';
  18990. result = added + next + result.slice(1);
  18991. break;
  18992. }
  18993. }
  18994. }
  18995. else {
  18996. next = +last + 1;
  18997. carry = next > 9;
  18998. if (carry) {
  18999. next = 0;
  19000. }
  19001. if (carry && i === 0) {
  19002. result = '1' + next + result.slice(1);
  19003. break;
  19004. }
  19005. }
  19006. result = result.slice(0, i) + next + result.slice(i + 1);
  19007. if (!carry) {
  19008. break;
  19009. }
  19010. }
  19011. return result;
  19012. };*/
  19013. var Subset = (function () {
  19014. function Subset(font) {
  19015. this.font = font;
  19016. this.subset = {};
  19017. this.unicodes = {};
  19018. this.next = 33;
  19019. }
  19020. /*Subset.prototype.use = function (character) {
  19021. var i, _i, _ref;
  19022. if (typeof character === 'string') {
  19023. for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19024. this.use(character.charCodeAt(i));
  19025. }
  19026. return;
  19027. }
  19028. if (!this.unicodes[character]) {
  19029. this.subset[this.next] = character;
  19030. return this.unicodes[character] = this.next++;
  19031. }
  19032. };*/
  19033. /*Subset.prototype.encodeText = function (text) {
  19034. var char, i, string, _i, _ref;
  19035. string = '';
  19036. for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19037. char = this.unicodes[text.charCodeAt(i)];
  19038. string += String.fromCharCode(char);
  19039. }
  19040. return string;
  19041. };*/
  19042. /***************************************************************/
  19043. /* function : generateCmap */
  19044. /* comment : Returns the unicode cmap for this font. */
  19045. /***************************************************************/
  19046. Subset.prototype.generateCmap = function () {
  19047. var mapping, roman, unicode, unicodeCmap, _ref;
  19048. unicodeCmap = this.font.cmap.tables[0].codeMap;
  19049. mapping = {};
  19050. _ref = this.subset;
  19051. for (roman in _ref) {
  19052. unicode = _ref[roman];
  19053. mapping[roman] = unicodeCmap[unicode];
  19054. }
  19055. return mapping;
  19056. };
  19057. /*Subset.prototype.glyphIDs = function () {
  19058. var ret, roman, unicode, unicodeCmap, val, _ref;
  19059. unicodeCmap = this.font.cmap.tables[0].codeMap;
  19060. ret = [0];
  19061. _ref = this.subset;
  19062. for (roman in _ref) {
  19063. unicode = _ref[roman];
  19064. val = unicodeCmap[unicode];
  19065. if ((val != null) && __indexOf.call(ret, val) < 0) {
  19066. ret.push(val);
  19067. }
  19068. }
  19069. return ret.sort();
  19070. };*/
  19071. /******************************************************************/
  19072. /* function : glyphsFor */
  19073. /* comment : Returns simple glyph objects for the input character.*/
  19074. /******************************************************************/
  19075. Subset.prototype.glyphsFor = function (glyphIDs) {
  19076. var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
  19077. glyphs = {};
  19078. for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
  19079. id = glyphIDs[_i];
  19080. glyphs[id] = this.font.glyf.glyphFor(id);
  19081. }
  19082. additionalIDs = [];
  19083. for (id in glyphs) {
  19084. glyph = glyphs[id];
  19085. if (glyph != null ? glyph.compound : void 0) {
  19086. additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
  19087. }
  19088. }
  19089. if (additionalIDs.length > 0) {
  19090. _ref = this.glyphsFor(additionalIDs);
  19091. for (id in _ref) {
  19092. glyph = _ref[id];
  19093. glyphs[id] = glyph;
  19094. }
  19095. }
  19096. return glyphs;
  19097. };
  19098. /***************************************************************/
  19099. /* function : encode */
  19100. /* comment : Encode various tables for the characters you use. */
  19101. /***************************************************************/
  19102. Subset.prototype.encode = function (glyID) {
  19103. var cmap, code, glyf, glyphs, id, ids, loca, new2old, newIDs, nextGlyphID, old2new, oldID, oldIDs, tables, _ref;
  19104. cmap = CmapTable.encode(this.generateCmap(), 'unicode');
  19105. glyphs = this.glyphsFor(glyID);
  19106. old2new = {
  19107. 0: 0
  19108. };
  19109. _ref = cmap.charMap;
  19110. for (code in _ref) {
  19111. ids = _ref[code];
  19112. old2new[ids.old] = ids["new"];
  19113. }
  19114. nextGlyphID = cmap.maxGlyphID;
  19115. for (oldID in glyphs) {
  19116. if (!(oldID in old2new)) {
  19117. old2new[oldID] = nextGlyphID++;
  19118. }
  19119. }
  19120. new2old = invert(old2new);
  19121. newIDs = Object.keys(new2old).sort(function (a, b) {
  19122. return a - b;
  19123. });
  19124. oldIDs = (function () {
  19125. var _i, _len, _results;
  19126. _results = [];
  19127. for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
  19128. id = newIDs[_i];
  19129. _results.push(new2old[id]);
  19130. }
  19131. return _results;
  19132. })();
  19133. glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
  19134. loca = this.font.loca.encode(glyf.offsets, oldIDs);
  19135. tables = {
  19136. cmap: this.font.cmap.raw()
  19137. , glyf: glyf.table
  19138. , loca: loca
  19139. , hmtx: this.font.hmtx.raw()
  19140. , hhea: this.font.hhea.raw()
  19141. , maxp: this.font.maxp.raw()
  19142. , post: this.font.post.raw()
  19143. , name: this.font.name.raw()
  19144. , head: this.font.head.raw()
  19145. };
  19146. if (this.font.os2.exists) {
  19147. tables['OS/2'] = this.font.os2.raw();
  19148. }
  19149. return this.font.directory.encode(tables);
  19150. };
  19151. return Subset;
  19152. })();
  19153. jsPDF.API.PDFObject = (function () {
  19154. var pad;
  19155. function PDFObject() {}
  19156. pad = function (str, length) {
  19157. return (Array(length + 1).join('0') + str).slice(-length);
  19158. };
  19159. /*****************************************************************************/
  19160. /* function : convert */
  19161. /* comment :Converts pdf tag's / FontBBox and array values in / W to strings */
  19162. /*****************************************************************************/
  19163. PDFObject.convert = function (object) {
  19164. var e, items, key, out, val;
  19165. if (Array.isArray(object)) {
  19166. items = ((function () {
  19167. var _i, _len, _results;
  19168. _results = [];
  19169. for (_i = 0, _len = object.length; _i < _len; _i++) {
  19170. e = object[_i];
  19171. _results.push(PDFObject.convert(e));
  19172. }
  19173. return _results;
  19174. })()).join(' ');
  19175. return '[' + items + ']';
  19176. }
  19177. else if (typeof object === 'string') {
  19178. return '/' + object;
  19179. }
  19180. else if (object != null ? object.isString : void 0) {
  19181. return '(' + object + ')';
  19182. }
  19183. else if (object instanceof Date) {
  19184. return '(D:' + pad(object.getUTCFullYear(), 4) + pad(object.getUTCMonth(), 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z)';
  19185. }
  19186. else if ({}.toString.call(object) === '[object Object]') {
  19187. out = ['<<'];
  19188. for (key in object) {
  19189. val = object[key];
  19190. out.push('/' + key + ' ' + PDFObject.convert(val));
  19191. }
  19192. out.push('>>');
  19193. return out.join('\n');
  19194. }
  19195. else {
  19196. return '' + object;
  19197. }
  19198. };
  19199. return PDFObject;
  19200. })();
  19201. })(jsPDF);
  19202. // Generated by CoffeeScript 1.4.0
  19203. /*
  19204. # PNG.js
  19205. # Copyright (c) 2011 Devon Govett
  19206. # MIT LICENSE
  19207. #
  19208. #
  19209. */
  19210. (function(global) {
  19211. var PNG;
  19212. PNG = (function() {
  19213. var APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  19214. PNG.load = function(url, canvas, callback) {
  19215. var xhr;
  19216. if (typeof canvas === 'function') {
  19217. callback = canvas;
  19218. }
  19219. xhr = new XMLHttpRequest;
  19220. xhr.open("GET", url, true);
  19221. xhr.responseType = "arraybuffer";
  19222. xhr.onload = function() {
  19223. var data, png;
  19224. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  19225. png = new PNG(data);
  19226. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  19227. png.render(canvas);
  19228. }
  19229. return typeof callback === "function" ? callback(png) : void 0;
  19230. };
  19231. return xhr.send(null);
  19232. };
  19233. APNG_DISPOSE_OP_BACKGROUND = 1;
  19234. APNG_DISPOSE_OP_PREVIOUS = 2;
  19235. APNG_BLEND_OP_SOURCE = 0;
  19236. function PNG(data) {
  19237. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  19238. this.data = data;
  19239. this.pos = 8;
  19240. this.palette = [];
  19241. this.imgData = [];
  19242. this.transparency = {};
  19243. this.animation = null;
  19244. this.text = {};
  19245. frame = null;
  19246. while (true) {
  19247. chunkSize = this.readUInt32();
  19248. section = ((function() {
  19249. var _i, _results;
  19250. _results = [];
  19251. for (i = _i = 0; _i < 4; i = ++_i) {
  19252. _results.push(String.fromCharCode(this.data[this.pos++]));
  19253. }
  19254. return _results;
  19255. }).call(this)).join('');
  19256. switch (section) {
  19257. case 'IHDR':
  19258. this.width = this.readUInt32();
  19259. this.height = this.readUInt32();
  19260. this.bits = this.data[this.pos++];
  19261. this.colorType = this.data[this.pos++];
  19262. this.compressionMethod = this.data[this.pos++];
  19263. this.filterMethod = this.data[this.pos++];
  19264. this.interlaceMethod = this.data[this.pos++];
  19265. break;
  19266. case 'acTL':
  19267. this.animation = {
  19268. numFrames: this.readUInt32(),
  19269. numPlays: this.readUInt32() || Infinity,
  19270. frames: []
  19271. };
  19272. break;
  19273. case 'PLTE':
  19274. this.palette = this.read(chunkSize);
  19275. break;
  19276. case 'fcTL':
  19277. if (frame) {
  19278. this.animation.frames.push(frame);
  19279. }
  19280. this.pos += 4;
  19281. frame = {
  19282. width: this.readUInt32(),
  19283. height: this.readUInt32(),
  19284. xOffset: this.readUInt32(),
  19285. yOffset: this.readUInt32()
  19286. };
  19287. delayNum = this.readUInt16();
  19288. delayDen = this.readUInt16() || 100;
  19289. frame.delay = 1000 * delayNum / delayDen;
  19290. frame.disposeOp = this.data[this.pos++];
  19291. frame.blendOp = this.data[this.pos++];
  19292. frame.data = [];
  19293. break;
  19294. case 'IDAT':
  19295. case 'fdAT':
  19296. if (section === 'fdAT') {
  19297. this.pos += 4;
  19298. chunkSize -= 4;
  19299. }
  19300. data = (frame != null ? frame.data : void 0) || this.imgData;
  19301. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  19302. data.push(this.data[this.pos++]);
  19303. }
  19304. break;
  19305. case 'tRNS':
  19306. this.transparency = {};
  19307. switch (this.colorType) {
  19308. case 3:
  19309. palLen = this.palette.length/3;
  19310. this.transparency.indexed = this.read(chunkSize);
  19311. if(this.transparency.indexed.length > palLen)
  19312. throw new Error('More transparent colors than palette size');
  19313. /*
  19314. * According to the PNG spec trns should be increased to the same size as palette if shorter
  19315. */
  19316. //palShort = 255 - this.transparency.indexed.length;
  19317. palShort = palLen - this.transparency.indexed.length;
  19318. if (palShort > 0) {
  19319. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  19320. this.transparency.indexed.push(255);
  19321. }
  19322. }
  19323. break;
  19324. case 0:
  19325. this.transparency.grayscale = this.read(chunkSize)[0];
  19326. break;
  19327. case 2:
  19328. this.transparency.rgb = this.read(chunkSize);
  19329. }
  19330. break;
  19331. case 'tEXt':
  19332. text = this.read(chunkSize);
  19333. index = text.indexOf(0);
  19334. key = String.fromCharCode.apply(String, text.slice(0, index));
  19335. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  19336. break;
  19337. case 'IEND':
  19338. if (frame) {
  19339. this.animation.frames.push(frame);
  19340. }
  19341. this.colors = (function() {
  19342. switch (this.colorType) {
  19343. case 0:
  19344. case 3:
  19345. case 4:
  19346. return 1;
  19347. case 2:
  19348. case 6:
  19349. return 3;
  19350. }
  19351. }).call(this);
  19352. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  19353. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  19354. this.pixelBitlength = this.bits * colors;
  19355. this.colorSpace = (function() {
  19356. switch (this.colors) {
  19357. case 1:
  19358. return 'DeviceGray';
  19359. case 3:
  19360. return 'DeviceRGB';
  19361. }
  19362. }).call(this);
  19363. this.imgData = new Uint8Array(this.imgData);
  19364. return;
  19365. default:
  19366. this.pos += chunkSize;
  19367. }
  19368. this.pos += 4;
  19369. if (this.pos > this.data.length) {
  19370. throw new Error("Incomplete or corrupt PNG file");
  19371. }
  19372. }
  19373. return;
  19374. }
  19375. PNG.prototype.read = function(bytes) {
  19376. var i, _i, _results;
  19377. _results = [];
  19378. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  19379. _results.push(this.data[this.pos++]);
  19380. }
  19381. return _results;
  19382. };
  19383. PNG.prototype.readUInt32 = function() {
  19384. var b1, b2, b3, b4;
  19385. b1 = this.data[this.pos++] << 24;
  19386. b2 = this.data[this.pos++] << 16;
  19387. b3 = this.data[this.pos++] << 8;
  19388. b4 = this.data[this.pos++];
  19389. return b1 | b2 | b3 | b4;
  19390. };
  19391. PNG.prototype.readUInt16 = function() {
  19392. var b1, b2;
  19393. b1 = this.data[this.pos++] << 8;
  19394. b2 = this.data[this.pos++];
  19395. return b1 | b2;
  19396. };
  19397. PNG.prototype.decodePixels = function(data) {
  19398. var pixelBytes = this.pixelBitlength / 8;
  19399. var fullPixels = new Uint8Array(this.width * this.height * pixelBytes);
  19400. var pos = 0;
  19401. var _this = this;
  19402. if (data == null) {
  19403. data = this.imgData;
  19404. }
  19405. if (data.length === 0) {
  19406. return new Uint8Array(0);
  19407. }
  19408. data = new FlateStream(data);
  19409. data = data.getBytes();
  19410. function pass (x0, y0, dx, dy) {
  19411. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixels, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  19412. var w = Math.ceil((_this.width - x0) / dx), h = Math.ceil((_this.height - y0) / dy);
  19413. var isFull = _this.width == w && _this.height == h;
  19414. scanlineLength = pixelBytes * w;
  19415. pixels = isFull ? fullPixels : new Uint8Array(scanlineLength * h);
  19416. length = data.length;
  19417. row = 0;
  19418. c = 0;
  19419. while (row < h && pos < length) {
  19420. switch (data[pos++]) {
  19421. case 0:
  19422. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  19423. pixels[c++] = data[pos++];
  19424. }
  19425. break;
  19426. case 1:
  19427. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  19428. abyte = data[pos++];
  19429. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  19430. pixels[c++] = (abyte + left) % 256;
  19431. }
  19432. break;
  19433. case 2:
  19434. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  19435. abyte = data[pos++];
  19436. col = (i - (i % pixelBytes)) / pixelBytes;
  19437. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  19438. pixels[c++] = (upper + abyte) % 256;
  19439. }
  19440. break;
  19441. case 3:
  19442. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  19443. abyte = data[pos++];
  19444. col = (i - (i % pixelBytes)) / pixelBytes;
  19445. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  19446. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  19447. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  19448. }
  19449. break;
  19450. case 4:
  19451. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  19452. abyte = data[pos++];
  19453. col = (i - (i % pixelBytes)) / pixelBytes;
  19454. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  19455. if (row === 0) {
  19456. upper = upperLeft = 0;
  19457. } else {
  19458. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
  19459. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
  19460. }
  19461. p = left + upper - upperLeft;
  19462. pa = Math.abs(p - left);
  19463. pb = Math.abs(p - upper);
  19464. pc = Math.abs(p - upperLeft);
  19465. if (pa <= pb && pa <= pc) {
  19466. paeth = left;
  19467. } else if (pb <= pc) {
  19468. paeth = upper;
  19469. } else {
  19470. paeth = upperLeft;
  19471. }
  19472. pixels[c++] = (abyte + paeth) % 256;
  19473. }
  19474. break;
  19475. default:
  19476. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  19477. }
  19478. if (!isFull) {
  19479. var fullPos = ((y0 + row * dy) * _this.width + x0) * pixelBytes;
  19480. var partPos = row * scanlineLength;
  19481. for (i = 0; i < w; i += 1) {
  19482. for (var j = 0; j < pixelBytes; j += 1)
  19483. fullPixels[fullPos++] = pixels[partPos++];
  19484. fullPos += (dx - 1) * pixelBytes;
  19485. }
  19486. }
  19487. row++;
  19488. }
  19489. }
  19490. if (_this.interlaceMethod == 1) {
  19491. /*
  19492. 1 6 4 6 2 6 4 6
  19493. 7 7 7 7 7 7 7 7
  19494. 5 6 5 6 5 6 5 6
  19495. 7 7 7 7 7 7 7 7
  19496. 3 6 4 6 3 6 4 6
  19497. 7 7 7 7 7 7 7 7
  19498. 5 6 5 6 5 6 5 6
  19499. 7 7 7 7 7 7 7 7
  19500. */
  19501. pass(0, 0, 8, 8); // 1
  19502. /* NOTE these seem to follow the pattern:
  19503. * pass(x, 0, 2*x, 2*x);
  19504. * pass(0, x, x, 2*x);
  19505. * with x being 4, 2, 1.
  19506. */
  19507. pass(4, 0, 8, 8); // 2
  19508. pass(0, 4, 4, 8); // 3
  19509. pass(2, 0, 4, 4); // 4
  19510. pass(0, 2, 2, 4); // 5
  19511. pass(1, 0, 2, 2); // 6
  19512. pass(0, 1, 1, 2); // 7
  19513. } else {
  19514. pass(0, 0, 1, 1);
  19515. }
  19516. return fullPixels;
  19517. };
  19518. PNG.prototype.decodePalette = function() {
  19519. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  19520. palette = this.palette;
  19521. transparency = this.transparency.indexed || [];
  19522. ret = new Uint8Array((transparency.length || 0) + palette.length);
  19523. pos = 0;
  19524. length = palette.length;
  19525. c = 0;
  19526. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  19527. ret[pos++] = palette[i];
  19528. ret[pos++] = palette[i + 1];
  19529. ret[pos++] = palette[i + 2];
  19530. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  19531. }
  19532. return ret;
  19533. };
  19534. PNG.prototype.copyToImageData = function(imageData, pixels) {
  19535. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  19536. colors = this.colors;
  19537. palette = null;
  19538. alpha = this.hasAlphaChannel;
  19539. if (this.palette.length) {
  19540. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  19541. colors = 4;
  19542. alpha = true;
  19543. }
  19544. data = imageData.data || imageData;
  19545. length = data.length;
  19546. input = palette || pixels;
  19547. i = j = 0;
  19548. if (colors === 1) {
  19549. while (i < length) {
  19550. k = palette ? pixels[i / 4] * 4 : j;
  19551. v = input[k++];
  19552. data[i++] = v;
  19553. data[i++] = v;
  19554. data[i++] = v;
  19555. data[i++] = alpha ? input[k++] : 255;
  19556. j = k;
  19557. }
  19558. } else {
  19559. while (i < length) {
  19560. k = palette ? pixels[i / 4] * 4 : j;
  19561. data[i++] = input[k++];
  19562. data[i++] = input[k++];
  19563. data[i++] = input[k++];
  19564. data[i++] = alpha ? input[k++] : 255;
  19565. j = k;
  19566. }
  19567. }
  19568. };
  19569. PNG.prototype.decode = function() {
  19570. var ret;
  19571. ret = new Uint8Array(this.width * this.height * 4);
  19572. this.copyToImageData(ret, this.decodePixels());
  19573. return ret;
  19574. };
  19575. try {
  19576. scratchCanvas = global.document.createElement('canvas');
  19577. scratchCtx = scratchCanvas.getContext('2d');
  19578. } catch(e) {
  19579. return -1;
  19580. }
  19581. makeImage = function(imageData) {
  19582. var img;
  19583. scratchCtx.width = imageData.width;
  19584. scratchCtx.height = imageData.height;
  19585. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  19586. scratchCtx.putImageData(imageData, 0, 0);
  19587. img = new Image;
  19588. img.src = scratchCanvas.toDataURL();
  19589. return img;
  19590. };
  19591. PNG.prototype.decodeFrames = function(ctx) {
  19592. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  19593. if (!this.animation) {
  19594. return;
  19595. }
  19596. _ref = this.animation.frames;
  19597. _results = [];
  19598. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  19599. frame = _ref[i];
  19600. imageData = ctx.createImageData(frame.width, frame.height);
  19601. pixels = this.decodePixels(new Uint8Array(frame.data));
  19602. this.copyToImageData(imageData, pixels);
  19603. frame.imageData = imageData;
  19604. _results.push(frame.image = makeImage(imageData));
  19605. }
  19606. return _results;
  19607. };
  19608. PNG.prototype.renderFrame = function(ctx, number) {
  19609. var frame, frames, prev;
  19610. frames = this.animation.frames;
  19611. frame = frames[number];
  19612. prev = frames[number - 1];
  19613. if (number === 0) {
  19614. ctx.clearRect(0, 0, this.width, this.height);
  19615. }
  19616. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  19617. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  19618. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  19619. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  19620. }
  19621. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  19622. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  19623. }
  19624. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  19625. };
  19626. PNG.prototype.animate = function(ctx) {
  19627. var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
  19628. _this = this;
  19629. frameNumber = 0;
  19630. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  19631. return (doFrame = function() {
  19632. var f, frame;
  19633. f = frameNumber++ % numFrames;
  19634. frame = frames[f];
  19635. _this.renderFrame(ctx, f);
  19636. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  19637. return _this.animation._timeout = setTimeout(doFrame, frame.delay);
  19638. }
  19639. })();
  19640. };
  19641. PNG.prototype.stopAnimation = function() {
  19642. var _ref;
  19643. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  19644. };
  19645. PNG.prototype.render = function(canvas) {
  19646. var ctx, data;
  19647. if (canvas._png) {
  19648. canvas._png.stopAnimation();
  19649. }
  19650. canvas._png = this;
  19651. canvas.width = this.width;
  19652. canvas.height = this.height;
  19653. ctx = canvas.getContext("2d");
  19654. if (this.animation) {
  19655. this.decodeFrames(ctx);
  19656. return this.animate(ctx);
  19657. } else {
  19658. data = ctx.createImageData(this.width, this.height);
  19659. this.copyToImageData(data, this.decodePixels());
  19660. return ctx.putImageData(data, 0, 0);
  19661. }
  19662. };
  19663. return PNG;
  19664. })();
  19665. global.PNG = PNG;
  19666. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()));
  19667. // `self` is undefined in Firefox for Android content script context
  19668. // while `this` is nsIContentFrameMessageManager
  19669. // with an attribute `content` that corresponds to the window
  19670. /*
  19671. * Extracted from pdf.js
  19672. * https://github.com/andreasgal/pdf.js
  19673. *
  19674. * Copyright (c) 2011 Mozilla Foundation
  19675. *
  19676. * Contributors: Andreas Gal <gal@mozilla.com>
  19677. * Chris G Jones <cjones@mozilla.com>
  19678. * Shaon Barman <shaon.barman@gmail.com>
  19679. * Vivien Nicolas <21@vingtetun.org>
  19680. * Justin D'Arcangelo <justindarc@gmail.com>
  19681. * Yury Delendik
  19682. *
  19683. *
  19684. */
  19685. var DecodeStream = (function() {
  19686. function constructor() {
  19687. this.pos = 0;
  19688. this.bufferLength = 0;
  19689. this.eof = false;
  19690. this.buffer = null;
  19691. }
  19692. constructor.prototype = {
  19693. ensureBuffer: function decodestream_ensureBuffer(requested) {
  19694. var buffer = this.buffer;
  19695. var current = buffer ? buffer.byteLength : 0;
  19696. if (requested < current)
  19697. return buffer;
  19698. var size = 512;
  19699. while (size < requested)
  19700. size <<= 1;
  19701. var buffer2 = new Uint8Array(size);
  19702. for (var i = 0; i < current; ++i)
  19703. buffer2[i] = buffer[i];
  19704. return this.buffer = buffer2;
  19705. },
  19706. getByte: function decodestream_getByte() {
  19707. var pos = this.pos;
  19708. while (this.bufferLength <= pos) {
  19709. if (this.eof)
  19710. return null;
  19711. this.readBlock();
  19712. }
  19713. return this.buffer[this.pos++];
  19714. },
  19715. getBytes: function decodestream_getBytes(length) {
  19716. var pos = this.pos;
  19717. if (length) {
  19718. this.ensureBuffer(pos + length);
  19719. var end = pos + length;
  19720. while (!this.eof && this.bufferLength < end)
  19721. this.readBlock();
  19722. var bufEnd = this.bufferLength;
  19723. if (end > bufEnd)
  19724. end = bufEnd;
  19725. } else {
  19726. while (!this.eof)
  19727. this.readBlock();
  19728. var end = this.bufferLength;
  19729. }
  19730. this.pos = end;
  19731. return this.buffer.subarray(pos, end);
  19732. },
  19733. lookChar: function decodestream_lookChar() {
  19734. var pos = this.pos;
  19735. while (this.bufferLength <= pos) {
  19736. if (this.eof)
  19737. return null;
  19738. this.readBlock();
  19739. }
  19740. return String.fromCharCode(this.buffer[this.pos]);
  19741. },
  19742. getChar: function decodestream_getChar() {
  19743. var pos = this.pos;
  19744. while (this.bufferLength <= pos) {
  19745. if (this.eof)
  19746. return null;
  19747. this.readBlock();
  19748. }
  19749. return String.fromCharCode(this.buffer[this.pos++]);
  19750. },
  19751. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  19752. var end = start + length;
  19753. while (this.bufferLength <= end && !this.eof)
  19754. this.readBlock();
  19755. return new Stream(this.buffer, start, length, dict);
  19756. },
  19757. skip: function decodestream_skip(n) {
  19758. if (!n)
  19759. n = 1;
  19760. this.pos += n;
  19761. },
  19762. reset: function decodestream_reset() {
  19763. this.pos = 0;
  19764. }
  19765. };
  19766. return constructor;
  19767. })();
  19768. var FlateStream = (function() {
  19769. if (typeof Uint32Array === 'undefined') {
  19770. return undefined;
  19771. }
  19772. var codeLenCodeMap = new Uint32Array([
  19773. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  19774. ]);
  19775. var lengthDecode = new Uint32Array([
  19776. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  19777. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  19778. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  19779. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  19780. ]);
  19781. var distDecode = new Uint32Array([
  19782. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  19783. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  19784. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  19785. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  19786. ]);
  19787. var fixedLitCodeTab = [new Uint32Array([
  19788. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  19789. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  19790. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  19791. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  19792. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  19793. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  19794. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  19795. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  19796. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  19797. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  19798. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  19799. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  19800. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  19801. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  19802. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  19803. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  19804. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  19805. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  19806. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  19807. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  19808. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  19809. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  19810. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  19811. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  19812. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  19813. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  19814. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  19815. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  19816. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  19817. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  19818. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  19819. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  19820. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  19821. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  19822. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  19823. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  19824. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  19825. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  19826. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  19827. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  19828. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  19829. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  19830. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  19831. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  19832. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  19833. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  19834. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  19835. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  19836. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  19837. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  19838. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  19839. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  19840. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  19841. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  19842. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  19843. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  19844. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  19845. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  19846. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  19847. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  19848. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  19849. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  19850. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  19851. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  19852. ]), 9];
  19853. var fixedDistCodeTab = [new Uint32Array([
  19854. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  19855. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  19856. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  19857. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  19858. ]), 5];
  19859. function error(e) {
  19860. throw new Error(e)
  19861. }
  19862. function constructor(bytes) {
  19863. //var bytes = stream.getBytes();
  19864. var bytesPos = 0;
  19865. var cmf = bytes[bytesPos++];
  19866. var flg = bytes[bytesPos++];
  19867. if (cmf == -1 || flg == -1)
  19868. error('Invalid header in flate stream');
  19869. if ((cmf & 0x0f) != 0x08)
  19870. error('Unknown compression method in flate stream');
  19871. if ((((cmf << 8) + flg) % 31) != 0)
  19872. error('Bad FCHECK in flate stream');
  19873. if (flg & 0x20)
  19874. error('FDICT bit set in flate stream');
  19875. this.bytes = bytes;
  19876. this.bytesPos = bytesPos;
  19877. this.codeSize = 0;
  19878. this.codeBuf = 0;
  19879. DecodeStream.call(this);
  19880. }
  19881. constructor.prototype = Object.create(DecodeStream.prototype);
  19882. constructor.prototype.getBits = function(bits) {
  19883. var codeSize = this.codeSize;
  19884. var codeBuf = this.codeBuf;
  19885. var bytes = this.bytes;
  19886. var bytesPos = this.bytesPos;
  19887. var b;
  19888. while (codeSize < bits) {
  19889. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19890. error('Bad encoding in flate stream');
  19891. codeBuf |= b << codeSize;
  19892. codeSize += 8;
  19893. }
  19894. b = codeBuf & ((1 << bits) - 1);
  19895. this.codeBuf = codeBuf >> bits;
  19896. this.codeSize = codeSize -= bits;
  19897. this.bytesPos = bytesPos;
  19898. return b;
  19899. };
  19900. constructor.prototype.getCode = function(table) {
  19901. var codes = table[0];
  19902. var maxLen = table[1];
  19903. var codeSize = this.codeSize;
  19904. var codeBuf = this.codeBuf;
  19905. var bytes = this.bytes;
  19906. var bytesPos = this.bytesPos;
  19907. while (codeSize < maxLen) {
  19908. var b;
  19909. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19910. error('Bad encoding in flate stream');
  19911. codeBuf |= (b << codeSize);
  19912. codeSize += 8;
  19913. }
  19914. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  19915. var codeLen = code >> 16;
  19916. var codeVal = code & 0xffff;
  19917. if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
  19918. error('Bad encoding in flate stream');
  19919. this.codeBuf = (codeBuf >> codeLen);
  19920. this.codeSize = (codeSize - codeLen);
  19921. this.bytesPos = bytesPos;
  19922. return codeVal;
  19923. };
  19924. constructor.prototype.generateHuffmanTable = function(lengths) {
  19925. var n = lengths.length;
  19926. // find max code length
  19927. var maxLen = 0;
  19928. for (var i = 0; i < n; ++i) {
  19929. if (lengths[i] > maxLen)
  19930. maxLen = lengths[i];
  19931. }
  19932. // build the table
  19933. var size = 1 << maxLen;
  19934. var codes = new Uint32Array(size);
  19935. for (var len = 1, code = 0, skip = 2;
  19936. len <= maxLen;
  19937. ++len, code <<= 1, skip <<= 1) {
  19938. for (var val = 0; val < n; ++val) {
  19939. if (lengths[val] == len) {
  19940. // bit-reverse the code
  19941. var code2 = 0;
  19942. var t = code;
  19943. for (var i = 0; i < len; ++i) {
  19944. code2 = (code2 << 1) | (t & 1);
  19945. t >>= 1;
  19946. }
  19947. // fill the table entries
  19948. for (var i = code2; i < size; i += skip)
  19949. codes[i] = (len << 16) | val;
  19950. ++code;
  19951. }
  19952. }
  19953. }
  19954. return [codes, maxLen];
  19955. };
  19956. constructor.prototype.readBlock = function() {
  19957. function repeat(stream, array, len, offset, what) {
  19958. var repeat = stream.getBits(len) + offset;
  19959. while (repeat-- > 0)
  19960. array[i++] = what;
  19961. }
  19962. // read block header
  19963. var hdr = this.getBits(3);
  19964. if (hdr & 1)
  19965. this.eof = true;
  19966. hdr >>= 1;
  19967. if (hdr == 0) { // uncompressed block
  19968. var bytes = this.bytes;
  19969. var bytesPos = this.bytesPos;
  19970. var b;
  19971. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19972. error('Bad block header in flate stream');
  19973. var blockLen = b;
  19974. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19975. error('Bad block header in flate stream');
  19976. blockLen |= (b << 8);
  19977. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19978. error('Bad block header in flate stream');
  19979. var check = b;
  19980. if (typeof (b = bytes[bytesPos++]) == 'undefined')
  19981. error('Bad block header in flate stream');
  19982. check |= (b << 8);
  19983. if (check != (~blockLen & 0xffff))
  19984. error('Bad uncompressed block length in flate stream');
  19985. this.codeBuf = 0;
  19986. this.codeSize = 0;
  19987. var bufferLength = this.bufferLength;
  19988. var buffer = this.ensureBuffer(bufferLength + blockLen);
  19989. var end = bufferLength + blockLen;
  19990. this.bufferLength = end;
  19991. for (var n = bufferLength; n < end; ++n) {
  19992. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  19993. this.eof = true;
  19994. break;
  19995. }
  19996. buffer[n] = b;
  19997. }
  19998. this.bytesPos = bytesPos;
  19999. return;
  20000. }
  20001. var litCodeTable;
  20002. var distCodeTable;
  20003. if (hdr == 1) { // compressed block, fixed codes
  20004. litCodeTable = fixedLitCodeTab;
  20005. distCodeTable = fixedDistCodeTab;
  20006. } else if (hdr == 2) { // compressed block, dynamic codes
  20007. var numLitCodes = this.getBits(5) + 257;
  20008. var numDistCodes = this.getBits(5) + 1;
  20009. var numCodeLenCodes = this.getBits(4) + 4;
  20010. // build the code lengths code table
  20011. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  20012. var i = 0;
  20013. while (i < numCodeLenCodes)
  20014. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  20015. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  20016. // build the literal and distance code tables
  20017. var len = 0;
  20018. var i = 0;
  20019. var codes = numLitCodes + numDistCodes;
  20020. var codeLengths = new Array(codes);
  20021. while (i < codes) {
  20022. var code = this.getCode(codeLenCodeTab);
  20023. if (code == 16) {
  20024. repeat(this, codeLengths, 2, 3, len);
  20025. } else if (code == 17) {
  20026. repeat(this, codeLengths, 3, 3, len = 0);
  20027. } else if (code == 18) {
  20028. repeat(this, codeLengths, 7, 11, len = 0);
  20029. } else {
  20030. codeLengths[i++] = len = code;
  20031. }
  20032. }
  20033. litCodeTable =
  20034. this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  20035. distCodeTable =
  20036. this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  20037. } else {
  20038. error('Unknown block type in flate stream');
  20039. }
  20040. var buffer = this.buffer;
  20041. var limit = buffer ? buffer.length : 0;
  20042. var pos = this.bufferLength;
  20043. while (true) {
  20044. var code1 = this.getCode(litCodeTable);
  20045. if (code1 < 256) {
  20046. if (pos + 1 >= limit) {
  20047. buffer = this.ensureBuffer(pos + 1);
  20048. limit = buffer.length;
  20049. }
  20050. buffer[pos++] = code1;
  20051. continue;
  20052. }
  20053. if (code1 == 256) {
  20054. this.bufferLength = pos;
  20055. return;
  20056. }
  20057. code1 -= 257;
  20058. code1 = lengthDecode[code1];
  20059. var code2 = code1 >> 16;
  20060. if (code2 > 0)
  20061. code2 = this.getBits(code2);
  20062. var len = (code1 & 0xffff) + code2;
  20063. code1 = this.getCode(distCodeTable);
  20064. code1 = distDecode[code1];
  20065. code2 = code1 >> 16;
  20066. if (code2 > 0)
  20067. code2 = this.getBits(code2);
  20068. var dist = (code1 & 0xffff) + code2;
  20069. if (pos + len >= limit) {
  20070. buffer = this.ensureBuffer(pos + len);
  20071. limit = buffer.length;
  20072. }
  20073. for (var k = 0; k < len; ++k, ++pos)
  20074. buffer[pos] = buffer[pos - dist];
  20075. }
  20076. };
  20077. return constructor;
  20078. })();
  20079. /**
  20080. * JavaScript Polyfill functions for jsPDF
  20081. * Collected from public resources by
  20082. * https://github.com/diegocr
  20083. */
  20084. (function (global) {
  20085. if (typeof global.console !== "object") {
  20086. // Console-polyfill. MIT license.
  20087. // https://github.com/paulmillr/console-polyfill
  20088. // Make it safe to do console.log() always.
  20089. global.console = {};
  20090. var con = global.console;
  20091. var prop, method;
  20092. var dummy = function() {};
  20093. var properties = ['memory'];
  20094. var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
  20095. 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
  20096. 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
  20097. while (prop = properties.pop()) if (!con[prop]) con[prop] = {};
  20098. while (method = methods.pop()) if (!con[method]) con[method] = dummy;
  20099. }
  20100. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  20101. if (typeof global.btoa === 'undefined') {
  20102. global.btoa = function(data) {
  20103. // discuss at: http://phpjs.org/functions/base64_encode/
  20104. // original by: Tyler Akins (http://rumkin.com)
  20105. // improved by: Bayron Guevara
  20106. // improved by: Thunder.m
  20107. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  20108. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  20109. // improved by: Rafal Kukawski (http://kukawski.pl)
  20110. // bugfixed by: Pellentesque Malesuada
  20111. // example 1: base64_encode('Kevin van Zonneveld');
  20112. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  20113. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
  20114. if (!data) {
  20115. return data;
  20116. }
  20117. do { // pack three octets into four hexets
  20118. o1 = data.charCodeAt(i++);
  20119. o2 = data.charCodeAt(i++);
  20120. o3 = data.charCodeAt(i++);
  20121. bits = o1 << 16 | o2 << 8 | o3;
  20122. h1 = bits >> 18 & 0x3f;
  20123. h2 = bits >> 12 & 0x3f;
  20124. h3 = bits >> 6 & 0x3f;
  20125. h4 = bits & 0x3f;
  20126. // use hexets to index into b64, and append result to encoded string
  20127. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  20128. } while (i < data.length);
  20129. enc = tmp_arr.join('');
  20130. var r = data.length % 3;
  20131. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  20132. };
  20133. }
  20134. if (typeof global.atob === 'undefined') {
  20135. global.atob = function(data) {
  20136. // discuss at: http://phpjs.org/functions/base64_decode/
  20137. // original by: Tyler Akins (http://rumkin.com)
  20138. // improved by: Thunder.m
  20139. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  20140. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  20141. // input by: Aman Gupta
  20142. // input by: Brett Zamir (http://brett-zamir.me)
  20143. // bugfixed by: Onno Marsman
  20144. // bugfixed by: Pellentesque Malesuada
  20145. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  20146. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  20147. // returns 1: 'Kevin van Zonneveld'
  20148. var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
  20149. if (!data) {
  20150. return data;
  20151. }
  20152. data += '';
  20153. do { // unpack four hexets into three octets using index points in b64
  20154. h1 = b64.indexOf(data.charAt(i++));
  20155. h2 = b64.indexOf(data.charAt(i++));
  20156. h3 = b64.indexOf(data.charAt(i++));
  20157. h4 = b64.indexOf(data.charAt(i++));
  20158. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  20159. o1 = bits >> 16 & 0xff;
  20160. o2 = bits >> 8 & 0xff;
  20161. o3 = bits & 0xff;
  20162. if (h3 == 64) {
  20163. tmp_arr[ac++] = String.fromCharCode(o1);
  20164. } else if (h4 == 64) {
  20165. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  20166. } else {
  20167. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  20168. }
  20169. } while (i < data.length);
  20170. dec = tmp_arr.join('');
  20171. return dec;
  20172. };
  20173. }
  20174. if (!Array.prototype.map) {
  20175. Array.prototype.map = function(fun /*, thisArg */) {
  20176. if (this === void 0 || this === null || typeof fun !== "function")
  20177. throw new TypeError();
  20178. var t = Object(this), len = t.length >>> 0, res = new Array(len);
  20179. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  20180. for (var i = 0; i < len; i++) {
  20181. // NOTE: Absolute correctness would demand Object.defineProperty
  20182. // be used. But this method is fairly new, and failure is
  20183. // possible only if Object.prototype or Array.prototype
  20184. // has a property |i| (very unlikely), so use a less-correct
  20185. // but more portable alternative.
  20186. if (i in t)
  20187. res[i] = fun.call(thisArg, t[i], i, t);
  20188. }
  20189. return res;
  20190. };
  20191. }
  20192. if(!Array.isArray) {
  20193. Array.isArray = function(arg) {
  20194. return Object.prototype.toString.call(arg) === '[object Array]';
  20195. };
  20196. }
  20197. if (!Array.prototype.forEach) {
  20198. Array.prototype.forEach = function(fun, thisArg) {
  20199. if (this === void 0 || this === null || typeof fun !== "function")
  20200. throw new TypeError();
  20201. var t = Object(this), len = t.length >>> 0;
  20202. for (var i = 0; i < len; i++) {
  20203. if (i in t)
  20204. fun.call(thisArg, t[i], i, t);
  20205. }
  20206. };
  20207. }
  20208. if (!Object.keys) {
  20209. Object.keys = (function () {
  20210. var hasOwnProperty = Object.prototype.hasOwnProperty,
  20211. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  20212. dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
  20213. 'isPrototypeOf','propertyIsEnumerable','constructor'],
  20214. dontEnumsLength = dontEnums.length;
  20215. return function (obj) {
  20216. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  20217. throw new TypeError();
  20218. }
  20219. var result = [], prop, i;
  20220. for (prop in obj) {
  20221. if (hasOwnProperty.call(obj, prop)) {
  20222. result.push(prop);
  20223. }
  20224. }
  20225. if (hasDontEnumBug) {
  20226. for (i = 0; i < dontEnumsLength; i++) {
  20227. if (hasOwnProperty.call(obj, dontEnums[i])) {
  20228. result.push(dontEnums[i]);
  20229. }
  20230. }
  20231. }
  20232. return result;
  20233. };
  20234. }());
  20235. }
  20236. if (typeof Object.assign != 'function') {
  20237. Object.assign = function(target) {
  20238. if (target == null) {
  20239. throw new TypeError('Cannot convert undefined or null to object');
  20240. }
  20241. target = Object(target);
  20242. for (var index = 1; index < arguments.length; index++) {
  20243. var source = arguments[index];
  20244. if (source != null) {
  20245. for (var key in source) {
  20246. if (Object.prototype.hasOwnProperty.call(source, key)) {
  20247. target[key] = source[key];
  20248. }
  20249. }
  20250. }
  20251. }
  20252. return target;
  20253. };
  20254. }
  20255. if (!String.prototype.trim) {
  20256. String.prototype.trim = function () {
  20257. return this.replace(/^\s+|\s+$/g, '');
  20258. };
  20259. }
  20260. if (!String.prototype.trimLeft) {
  20261. String.prototype.trimLeft = function() {
  20262. return this.replace(/^\s+/g, "");
  20263. };
  20264. }
  20265. if (!String.prototype.trimRight) {
  20266. String.prototype.trimRight = function() {
  20267. return this.replace(/\s+$/g, "");
  20268. };
  20269. }
  20270. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()));
  20271. // `self` is undefined in Firefox for Android content script context
  20272. // while `this` is nsIContentFrameMessageManager
  20273. // with an attribute `content` that corresponds to the window
  20274. return jsPDF;
  20275. })));