25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

jspdf.debug.js 860 KiB

3 yıl önce
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664
  1. (function (factory) {
  2. typeof define === 'function' && define.amd ? define(factory) :
  3. factory();
  4. }(function () { 'use strict';
  5. /** @license
  6. * jsPDF - PDF Document creation from JavaScript
  7. * Version 1.5.3 Built on 2018-12-27T14:11:42.696Z
  8. * CommitID d93d28db14
  9. *
  10. * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  11. * 2010 Aaron Spike, https://github.com/acspike
  12. * 2012 Willow Systems Corporation, willow-systems.com
  13. * 2012 Pablo Hess, https://github.com/pablohess
  14. * 2012 Florian Jenett, https://github.com/fjenett
  15. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  16. * 2013 Youssef Beddad, https://github.com/lifof
  17. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  18. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  19. * 2013 Jeremy Morel, https://github.com/jmorel
  20. * 2013 Christoph Hartmann, https://github.com/chris-rock
  21. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  22. * 2014 James Makes, https://github.com/dollaruw
  23. * 2014 Diego Casorran, https://github.com/diegocr
  24. * 2014 Steven Spungin, https://github.com/Flamenco
  25. * 2014 Kenneth Glassey, https://github.com/Gavvers
  26. *
  27. * Licensed under the MIT License
  28. *
  29. * Contributor(s):
  30. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  31. * kim3er, mfo, alnorth, Flamenco
  32. */
  33. function _typeof(obj) {
  34. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  35. _typeof = function (obj) {
  36. return typeof obj;
  37. };
  38. } else {
  39. _typeof = function (obj) {
  40. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  41. };
  42. }
  43. return _typeof(obj);
  44. }
  45. /**
  46. * JavaScript Polyfill functions for jsPDF
  47. * Collected from public resources by
  48. * https://github.com/diegocr
  49. */
  50. (function (global) {
  51. if (_typeof(global.console) !== "object") {
  52. // Console-polyfill. MIT license.
  53. // https://github.com/paulmillr/console-polyfill
  54. // Make it safe to do console.log() always.
  55. global.console = {};
  56. var con = global.console;
  57. var prop, method;
  58. var dummy = function dummy() {};
  59. var properties = ['memory'];
  60. var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
  61. while (prop = properties.pop()) {
  62. if (!con[prop]) con[prop] = {};
  63. }
  64. while (method = methods.pop()) {
  65. if (!con[method]) con[method] = dummy;
  66. }
  67. }
  68. var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  69. if (typeof global.btoa === 'undefined') {
  70. global.btoa = function (data) {
  71. // discuss at: http://phpjs.org/functions/base64_encode/
  72. // original by: Tyler Akins (http://rumkin.com)
  73. // improved by: Bayron Guevara
  74. // improved by: Thunder.m
  75. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  76. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  77. // improved by: Rafal Kukawski (http://kukawski.pl)
  78. // bugfixed by: Pellentesque Malesuada
  79. // example 1: base64_encode('Kevin van Zonneveld');
  80. // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  81. var o1,
  82. o2,
  83. o3,
  84. h1,
  85. h2,
  86. h3,
  87. h4,
  88. bits,
  89. i = 0,
  90. ac = 0,
  91. enc = '',
  92. tmp_arr = [];
  93. if (!data) {
  94. return data;
  95. }
  96. do {
  97. // pack three octets into four hexets
  98. o1 = data.charCodeAt(i++);
  99. o2 = data.charCodeAt(i++);
  100. o3 = data.charCodeAt(i++);
  101. bits = o1 << 16 | o2 << 8 | o3;
  102. h1 = bits >> 18 & 0x3f;
  103. h2 = bits >> 12 & 0x3f;
  104. h3 = bits >> 6 & 0x3f;
  105. h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string
  106. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  107. } while (i < data.length);
  108. enc = tmp_arr.join('');
  109. var r = data.length % 3;
  110. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  111. };
  112. }
  113. if (typeof global.atob === 'undefined') {
  114. global.atob = function (data) {
  115. // discuss at: http://phpjs.org/functions/base64_decode/
  116. // original by: Tyler Akins (http://rumkin.com)
  117. // improved by: Thunder.m
  118. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  119. // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  120. // input by: Aman Gupta
  121. // input by: Brett Zamir (http://brett-zamir.me)
  122. // bugfixed by: Onno Marsman
  123. // bugfixed by: Pellentesque Malesuada
  124. // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  125. // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  126. // returns 1: 'Kevin van Zonneveld'
  127. var o1,
  128. o2,
  129. o3,
  130. h1,
  131. h2,
  132. h3,
  133. h4,
  134. bits,
  135. i = 0,
  136. ac = 0,
  137. dec = '',
  138. tmp_arr = [];
  139. if (!data) {
  140. return data;
  141. }
  142. data += '';
  143. do {
  144. // unpack four hexets into three octets using index points in b64
  145. h1 = b64.indexOf(data.charAt(i++));
  146. h2 = b64.indexOf(data.charAt(i++));
  147. h3 = b64.indexOf(data.charAt(i++));
  148. h4 = b64.indexOf(data.charAt(i++));
  149. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  150. o1 = bits >> 16 & 0xff;
  151. o2 = bits >> 8 & 0xff;
  152. o3 = bits & 0xff;
  153. if (h3 == 64) {
  154. tmp_arr[ac++] = String.fromCharCode(o1);
  155. } else if (h4 == 64) {
  156. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  157. } else {
  158. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  159. }
  160. } while (i < data.length);
  161. dec = tmp_arr.join('');
  162. return dec;
  163. };
  164. }
  165. if (!Array.prototype.map) {
  166. Array.prototype.map = function (fun
  167. /*, thisArg */
  168. ) {
  169. if (this === void 0 || this === null || typeof fun !== "function") throw new TypeError();
  170. var t = Object(this),
  171. len = t.length >>> 0,
  172. res = new Array(len);
  173. var thisArg = arguments.length > 1 ? arguments[1] : void 0;
  174. for (var i = 0; i < len; i++) {
  175. // NOTE: Absolute correctness would demand Object.defineProperty
  176. // be used. But this method is fairly new, and failure is
  177. // possible only if Object.prototype or Array.prototype
  178. // has a property |i| (very unlikely), so use a less-correct
  179. // but more portable alternative.
  180. if (i in t) res[i] = fun.call(thisArg, t[i], i, t);
  181. }
  182. return res;
  183. };
  184. }
  185. if (!Array.isArray) {
  186. Array.isArray = function (arg) {
  187. return Object.prototype.toString.call(arg) === '[object Array]';
  188. };
  189. }
  190. if (!Array.prototype.forEach) {
  191. Array.prototype.forEach = function (fun, thisArg) {
  192. if (this === void 0 || this === null || typeof fun !== "function") throw new TypeError();
  193. var t = Object(this),
  194. len = t.length >>> 0;
  195. for (var i = 0; i < len; i++) {
  196. if (i in t) fun.call(thisArg, t[i], i, t);
  197. }
  198. };
  199. } // https://tc39.github.io/ecma262/#sec-array.prototype.find
  200. if (!Array.prototype.find) {
  201. Object.defineProperty(Array.prototype, 'find', {
  202. value: function value(predicate) {
  203. // 1. Let O be ? ToObject(this value).
  204. if (this == null) {
  205. throw new TypeError('"this" is null or not defined');
  206. }
  207. var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")).
  208. var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception.
  209. if (typeof predicate !== 'function') {
  210. throw new TypeError('predicate must be a function');
  211. } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
  212. var thisArg = arguments[1]; // 5. Let k be 0.
  213. var k = 0; // 6. Repeat, while k < len
  214. while (k < len) {
  215. // a. Let Pk be ! ToString(k).
  216. // b. Let kValue be ? Get(O, Pk).
  217. // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
  218. // d. If testResult is true, return kValue.
  219. var kValue = o[k];
  220. if (predicate.call(thisArg, kValue, k, o)) {
  221. return kValue;
  222. } // e. Increase k by 1.
  223. k++;
  224. } // 7. Return undefined.
  225. return undefined;
  226. },
  227. configurable: true,
  228. writable: true
  229. });
  230. }
  231. if (!Object.keys) {
  232. Object.keys = function () {
  233. var hasOwnProperty = Object.prototype.hasOwnProperty,
  234. hasDontEnumBug = !{
  235. toString: null
  236. }.propertyIsEnumerable('toString'),
  237. dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'],
  238. dontEnumsLength = dontEnums.length;
  239. return function (obj) {
  240. if (_typeof(obj) !== 'object' && (typeof obj !== 'function' || obj === null)) {
  241. throw new TypeError();
  242. }
  243. var result = [],
  244. prop,
  245. i;
  246. for (prop in obj) {
  247. if (hasOwnProperty.call(obj, prop)) {
  248. result.push(prop);
  249. }
  250. }
  251. if (hasDontEnumBug) {
  252. for (i = 0; i < dontEnumsLength; i++) {
  253. if (hasOwnProperty.call(obj, dontEnums[i])) {
  254. result.push(dontEnums[i]);
  255. }
  256. }
  257. }
  258. return result;
  259. };
  260. }();
  261. }
  262. if (typeof Object.assign != 'function') {
  263. Object.assign = function (target) {
  264. if (target == null) {
  265. throw new TypeError('Cannot convert undefined or null to object');
  266. }
  267. target = Object(target);
  268. for (var index = 1; index < arguments.length; index++) {
  269. var source = arguments[index];
  270. if (source != null) {
  271. for (var key in source) {
  272. if (Object.prototype.hasOwnProperty.call(source, key)) {
  273. target[key] = source[key];
  274. }
  275. }
  276. }
  277. }
  278. return target;
  279. };
  280. }
  281. if (!String.prototype.trim) {
  282. String.prototype.trim = function () {
  283. return this.replace(/^\s+|\s+$/g, '');
  284. };
  285. }
  286. if (!String.prototype.trimLeft) {
  287. String.prototype.trimLeft = function () {
  288. return this.replace(/^\s+/g, "");
  289. };
  290. }
  291. if (!String.prototype.trimRight) {
  292. String.prototype.trimRight = function () {
  293. return this.replace(/\s+$/g, "");
  294. };
  295. }
  296. Number.isInteger = Number.isInteger || function (value) {
  297. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  298. };
  299. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  300. // while `this` is nsIContentFrameMessageManager
  301. // with an attribute `content` that corresponds to the window
  302. /**
  303. * Creates new jsPDF document object instance.
  304. * @name jsPDF
  305. * @class
  306. * @param orientation {string/Object} Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").<br />
  307. * Can also be an options object.
  308. * @param unit {string} Measurement unit to be used when coordinates are specified.<br />
  309. * Possible values are "pt" (points), "mm" (Default), "cm", "in" or "px".
  310. * @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>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 />
  311. * 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]
  312. * @returns {jsPDF} jsPDF-instance
  313. * @description
  314. * If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
  315. * ```
  316. * {
  317. * orientation: 'p',
  318. * unit: 'mm',
  319. * format: 'a4',
  320. * hotfixes: [] // an array of hotfix strings to enable
  321. * }
  322. * ```
  323. */
  324. var jsPDF = function (global) {
  325. /**
  326. * jsPDF's Internal PubSub Implementation.
  327. * Backward compatible rewritten on 2014 by
  328. * Diego Casorran, https://github.com/diegocr
  329. *
  330. * @class
  331. * @name PubSub
  332. * @ignore
  333. */
  334. function PubSub(context) {
  335. if (_typeof(context) !== 'object') {
  336. throw new Error('Invalid Context passed to initialize PubSub (jsPDF-module)');
  337. }
  338. var topics = {};
  339. this.subscribe = function (topic, callback, once) {
  340. once = once || false;
  341. if (typeof topic !== 'string' || typeof callback !== 'function' || typeof once !== 'boolean') {
  342. throw new Error('Invalid arguments passed to PubSub.subscribe (jsPDF-module)');
  343. }
  344. if (!topics.hasOwnProperty(topic)) {
  345. topics[topic] = {};
  346. }
  347. var token = Math.random().toString(35);
  348. topics[topic][token] = [callback, !!once];
  349. return token;
  350. };
  351. this.unsubscribe = function (token) {
  352. for (var topic in topics) {
  353. if (topics[topic][token]) {
  354. delete topics[topic][token];
  355. if (Object.keys(topics[topic]).length === 0) {
  356. delete topics[topic];
  357. }
  358. return true;
  359. }
  360. }
  361. return false;
  362. };
  363. this.publish = function (topic) {
  364. if (topics.hasOwnProperty(topic)) {
  365. var args = Array.prototype.slice.call(arguments, 1),
  366. tokens = [];
  367. for (var token in topics[topic]) {
  368. var sub = topics[topic][token];
  369. try {
  370. sub[0].apply(context, args);
  371. } catch (ex) {
  372. if (global.console) {
  373. console.error('jsPDF PubSub Error', ex.message, ex);
  374. }
  375. }
  376. if (sub[1]) tokens.push(token);
  377. }
  378. if (tokens.length) tokens.forEach(this.unsubscribe);
  379. }
  380. };
  381. this.getTopics = function () {
  382. return topics;
  383. };
  384. }
  385. /**
  386. * @constructor
  387. * @private
  388. */
  389. function jsPDF(orientation, unit, format, compressPdf) {
  390. var options = {};
  391. var filters = [];
  392. var userUnit = 1.0;
  393. if (_typeof(orientation) === 'object') {
  394. options = orientation;
  395. orientation = options.orientation;
  396. unit = options.unit || unit;
  397. format = options.format || format;
  398. compressPdf = options.compress || options.compressPdf || compressPdf;
  399. filters = options.filters || (compressPdf === true ? ['FlateEncode'] : filters);
  400. userUnit = typeof options.userUnit === "number" ? Math.abs(options.userUnit) : 1.0;
  401. }
  402. unit = unit || 'mm';
  403. orientation = ('' + (orientation || 'P')).toLowerCase();
  404. var putOnlyUsedFonts = options.putOnlyUsedFonts || true;
  405. var usedFonts = {};
  406. var API = {
  407. internal: {},
  408. __private__: {}
  409. };
  410. API.__private__.PubSub = PubSub;
  411. var pdfVersion = '1.3';
  412. var getPdfVersion = API.__private__.getPdfVersion = function () {
  413. return pdfVersion;
  414. };
  415. var setPdfVersion = API.__private__.setPdfVersion = function (value) {
  416. pdfVersion = value;
  417. }; // Size in pt of various paper formats
  418. var pageFormats = {
  419. 'a0': [2383.94, 3370.39],
  420. 'a1': [1683.78, 2383.94],
  421. 'a2': [1190.55, 1683.78],
  422. 'a3': [841.89, 1190.55],
  423. 'a4': [595.28, 841.89],
  424. 'a5': [419.53, 595.28],
  425. 'a6': [297.64, 419.53],
  426. 'a7': [209.76, 297.64],
  427. 'a8': [147.40, 209.76],
  428. 'a9': [104.88, 147.40],
  429. 'a10': [73.70, 104.88],
  430. 'b0': [2834.65, 4008.19],
  431. 'b1': [2004.09, 2834.65],
  432. 'b2': [1417.32, 2004.09],
  433. 'b3': [1000.63, 1417.32],
  434. 'b4': [708.66, 1000.63],
  435. 'b5': [498.90, 708.66],
  436. 'b6': [354.33, 498.90],
  437. 'b7': [249.45, 354.33],
  438. 'b8': [175.75, 249.45],
  439. 'b9': [124.72, 175.75],
  440. 'b10': [87.87, 124.72],
  441. 'c0': [2599.37, 3676.54],
  442. 'c1': [1836.85, 2599.37],
  443. 'c2': [1298.27, 1836.85],
  444. 'c3': [918.43, 1298.27],
  445. 'c4': [649.13, 918.43],
  446. 'c5': [459.21, 649.13],
  447. 'c6': [323.15, 459.21],
  448. 'c7': [229.61, 323.15],
  449. 'c8': [161.57, 229.61],
  450. 'c9': [113.39, 161.57],
  451. 'c10': [79.37, 113.39],
  452. 'dl': [311.81, 623.62],
  453. 'letter': [612, 792],
  454. 'government-letter': [576, 756],
  455. 'legal': [612, 1008],
  456. 'junior-legal': [576, 360],
  457. 'ledger': [1224, 792],
  458. 'tabloid': [792, 1224],
  459. 'credit-card': [153, 243]
  460. };
  461. var getPageFormats = API.__private__.getPageFormats = function () {
  462. return pageFormats;
  463. };
  464. var getPageFormat = API.__private__.getPageFormat = function (value) {
  465. return pageFormats[value];
  466. };
  467. if (typeof format === "string") {
  468. format = getPageFormat(format);
  469. }
  470. format = format || getPageFormat('a4');
  471. var f2 = API.f2 = API.__private__.f2 = function (number) {
  472. if (isNaN(number)) {
  473. throw new Error('Invalid argument passed to jsPDF.f2');
  474. }
  475. return number.toFixed(2); // Ie, %.2f
  476. };
  477. var f3 = API.__private__.f3 = function (number) {
  478. if (isNaN(number)) {
  479. throw new Error('Invalid argument passed to jsPDF.f3');
  480. }
  481. return number.toFixed(3); // Ie, %.3f
  482. };
  483. var fileId = '00000000000000000000000000000000';
  484. var getFileId = API.__private__.getFileId = function () {
  485. return fileId;
  486. };
  487. var setFileId = API.__private__.setFileId = function (value) {
  488. value = value || "12345678901234567890123456789012".split('').map(function () {
  489. return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16));
  490. }).join('');
  491. fileId = value;
  492. return fileId;
  493. };
  494. /**
  495. * @name setFileId
  496. * @memberOf jsPDF
  497. * @function
  498. * @instance
  499. * @param {string} value GUID.
  500. * @returns {jsPDF}
  501. */
  502. API.setFileId = function (value) {
  503. setFileId(value);
  504. return this;
  505. };
  506. /**
  507. * @name getFileId
  508. * @memberOf jsPDF
  509. * @function
  510. * @instance
  511. *
  512. * @returns {string} GUID.
  513. */
  514. API.getFileId = function () {
  515. return getFileId();
  516. };
  517. var creationDate;
  518. var convertDateToPDFDate = API.__private__.convertDateToPDFDate = function (parmDate) {
  519. var result = '';
  520. var tzoffset = parmDate.getTimezoneOffset(),
  521. tzsign = tzoffset < 0 ? '+' : '-',
  522. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  523. tzmin = Math.abs(tzoffset % 60),
  524. timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  525. result = ['D:', parmDate.getFullYear(), padd2(parmDate.getMonth() + 1), padd2(parmDate.getDate()), padd2(parmDate.getHours()), padd2(parmDate.getMinutes()), padd2(parmDate.getSeconds()), timeZoneString].join('');
  526. return result;
  527. };
  528. var convertPDFDateToDate = API.__private__.convertPDFDateToDate = function (parmPDFDate) {
  529. var year = parseInt(parmPDFDate.substr(2, 4), 10);
  530. var month = parseInt(parmPDFDate.substr(6, 2), 10) - 1;
  531. var date = parseInt(parmPDFDate.substr(8, 2), 10);
  532. var hour = parseInt(parmPDFDate.substr(10, 2), 10);
  533. var minutes = parseInt(parmPDFDate.substr(12, 2), 10);
  534. var seconds = parseInt(parmPDFDate.substr(14, 2), 10);
  535. var timeZoneHour = parseInt(parmPDFDate.substr(16, 2), 10);
  536. var timeZoneMinutes = parseInt(parmPDFDate.substr(20, 2), 10);
  537. var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);
  538. return resultingDate;
  539. };
  540. var setCreationDate = API.__private__.setCreationDate = function (date) {
  541. var tmpCreationDateString;
  542. 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])\'?$/;
  543. if (typeof date === "undefined") {
  544. date = new Date();
  545. }
  546. if (_typeof(date) === "object" && Object.prototype.toString.call(date) === "[object Date]") {
  547. tmpCreationDateString = convertDateToPDFDate(date);
  548. } else if (regexPDFCreationDate.test(date)) {
  549. tmpCreationDateString = date;
  550. } else {
  551. throw new Error('Invalid argument passed to jsPDF.setCreationDate');
  552. }
  553. creationDate = tmpCreationDateString;
  554. return creationDate;
  555. };
  556. var getCreationDate = API.__private__.getCreationDate = function (type) {
  557. var result = creationDate;
  558. if (type === "jsDate") {
  559. result = convertPDFDateToDate(creationDate);
  560. }
  561. return result;
  562. };
  563. /**
  564. * @name setCreationDate
  565. * @memberOf jsPDF
  566. * @function
  567. * @instance
  568. * @param {Object} date
  569. * @returns {jsPDF}
  570. */
  571. API.setCreationDate = function (date) {
  572. setCreationDate(date);
  573. return this;
  574. };
  575. /**
  576. * @name getCreationDate
  577. * @memberOf jsPDF
  578. * @function
  579. * @instance
  580. * @param {Object} type
  581. * @returns {Object}
  582. */
  583. API.getCreationDate = function (type) {
  584. return getCreationDate(type);
  585. };
  586. var padd2 = API.__private__.padd2 = function (number) {
  587. return ('0' + parseInt(number)).slice(-2);
  588. };
  589. var outToPages = !1; // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  590. var pages = [];
  591. var content = [];
  592. var currentPage;
  593. var content_length = 0;
  594. var customOutputDestination;
  595. var setOutputDestination = API.__private__.setCustomOutputDestination = function (destination) {
  596. customOutputDestination = destination;
  597. };
  598. var resetOutputDestination = API.__private__.resetCustomOutputDestination = function (destination) {
  599. customOutputDestination = undefined;
  600. };
  601. var out = API.__private__.out = function (string) {
  602. var writeArray;
  603. string = typeof string === "string" ? string : string.toString();
  604. if (typeof customOutputDestination === "undefined") {
  605. writeArray = outToPages ? pages[currentPage] : content;
  606. } else {
  607. writeArray = customOutputDestination;
  608. }
  609. writeArray.push(string);
  610. if (!outToPages) {
  611. content_length += string.length + 1;
  612. }
  613. return writeArray;
  614. };
  615. var write = API.__private__.write = function (value) {
  616. return out(arguments.length === 1 ? value.toString() : Array.prototype.join.call(arguments, ' '));
  617. };
  618. var getArrayBuffer = API.__private__.getArrayBuffer = function (data) {
  619. var len = data.length,
  620. ab = new ArrayBuffer(len),
  621. u8 = new Uint8Array(ab);
  622. while (len--) {
  623. u8[len] = data.charCodeAt(len);
  624. }
  625. return ab;
  626. };
  627. var standardFonts = [['Helvetica', "helvetica", "normal", 'WinAnsiEncoding'], ['Helvetica-Bold', "helvetica", "bold", 'WinAnsiEncoding'], ['Helvetica-Oblique', "helvetica", "italic", 'WinAnsiEncoding'], ['Helvetica-BoldOblique', "helvetica", "bolditalic", 'WinAnsiEncoding'], ['Courier', "courier", "normal", 'WinAnsiEncoding'], ['Courier-Bold', "courier", "bold", 'WinAnsiEncoding'], ['Courier-Oblique', "courier", "italic", 'WinAnsiEncoding'], ['Courier-BoldOblique', "courier", "bolditalic", 'WinAnsiEncoding'], ['Times-Roman', "times", "normal", 'WinAnsiEncoding'], ['Times-Bold', "times", "bold", 'WinAnsiEncoding'], ['Times-Italic', "times", "italic", 'WinAnsiEncoding'], ['Times-BoldItalic', "times", "bolditalic", 'WinAnsiEncoding'], ['ZapfDingbats', "zapfdingbats", "normal", null], ['Symbol', "symbol", "normal", null]];
  628. var getStandardFonts = API.__private__.getStandardFonts = function (data) {
  629. return standardFonts;
  630. };
  631. var activeFontSize = options.fontSize || 16;
  632. /**
  633. * Sets font size for upcoming text elements.
  634. *
  635. * @param {number} size Font size in points.
  636. * @function
  637. * @instance
  638. * @returns {jsPDF}
  639. * @memberOf jsPDF
  640. * @name setFontSize
  641. */
  642. var setFontSize = API.__private__.setFontSize = API.setFontSize = function (size) {
  643. activeFontSize = size;
  644. return this;
  645. };
  646. /**
  647. * Gets the fontsize for upcoming text elements.
  648. *
  649. * @function
  650. * @instance
  651. * @returns {number}
  652. * @memberOf jsPDF
  653. * @name getFontSize
  654. */
  655. var getFontSize = API.__private__.getFontSize = API.getFontSize = function () {
  656. return activeFontSize;
  657. };
  658. var R2L = options.R2L || false;
  659. /**
  660. * Set value of R2L functionality.
  661. *
  662. * @param {boolean} value
  663. * @function
  664. * @instance
  665. * @returns {jsPDF} jsPDF-instance
  666. * @memberOf jsPDF
  667. * @name setR2L
  668. */
  669. var setR2L = API.__private__.setR2L = API.setR2L = function (value) {
  670. R2L = value;
  671. return this;
  672. };
  673. /**
  674. * Get value of R2L functionality.
  675. *
  676. * @function
  677. * @instance
  678. * @returns {boolean} jsPDF-instance
  679. * @memberOf jsPDF
  680. * @name getR2L
  681. */
  682. var getR2L = API.__private__.getR2L = API.getR2L = function (value) {
  683. return R2L;
  684. };
  685. var zoomMode; // default: 1;
  686. var setZoomMode = API.__private__.setZoomMode = function (zoom) {
  687. var validZoomModes = [undefined, null, 'fullwidth', 'fullheight', 'fullpage', 'original'];
  688. if (/^\d*\.?\d*\%$/.test(zoom)) {
  689. zoomMode = zoom;
  690. } else if (!isNaN(zoom)) {
  691. zoomMode = parseInt(zoom, 10);
  692. } else if (validZoomModes.indexOf(zoom) !== -1) {
  693. zoomMode = zoom;
  694. } else {
  695. throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "' + zoom + '" is not recognized.');
  696. }
  697. };
  698. var getZoomMode = API.__private__.getZoomMode = function () {
  699. return zoomMode;
  700. };
  701. var pageMode; // default: 'UseOutlines';
  702. var setPageMode = API.__private__.setPageMode = function (pmode) {
  703. var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
  704. if (validPageModes.indexOf(pmode) == -1) {
  705. throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
  706. }
  707. pageMode = pmode;
  708. };
  709. var getPageMode = API.__private__.getPageMode = function () {
  710. return pageMode;
  711. };
  712. var layoutMode; // default: 'continuous';
  713. var setLayoutMode = API.__private__.setLayoutMode = function (layout) {
  714. var validLayoutModes = [undefined, null, 'continuous', 'single', 'twoleft', 'tworight', 'two'];
  715. if (validLayoutModes.indexOf(layout) == -1) {
  716. throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "' + layout + '" is not recognized.');
  717. }
  718. layoutMode = layout;
  719. };
  720. var getLayoutMode = API.__private__.getLayoutMode = function () {
  721. return layoutMode;
  722. };
  723. /**
  724. * Set the display mode options of the page like zoom and layout.
  725. *
  726. * @name setDisplayMode
  727. * @memberOf jsPDF
  728. * @function
  729. * @instance
  730. * @param {integer|String} zoom You can pass an integer or percentage as
  731. * a string. 2 will scale the document up 2x, '200%' will scale up by the
  732. * same amount. You can also set it to 'fullwidth', 'fullheight',
  733. * 'fullpage', or 'original'.
  734. *
  735. * Only certain PDF readers support this, such as Adobe Acrobat.
  736. *
  737. * @param {string} layout Layout mode can be: 'continuous' - this is the
  738. * default continuous scroll. 'single' - the single page mode only shows one
  739. * page at a time. 'twoleft' - two column left mode, first page starts on
  740. * the left, and 'tworight' - pages are laid out in two columns, with the
  741. * first page on the right. This would be used for books.
  742. * @param {string} pmode 'UseOutlines' - it shows the
  743. * outline of the document on the left. 'UseThumbs' - shows thumbnails along
  744. * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
  745. *
  746. * @returns {jsPDF}
  747. */
  748. var setDisplayMode = API.__private__.setDisplayMode = API.setDisplayMode = function (zoom, layout, pmode) {
  749. setZoomMode(zoom);
  750. setLayoutMode(layout);
  751. setPageMode(pmode);
  752. return this;
  753. };
  754. var documentProperties = {
  755. 'title': '',
  756. 'subject': '',
  757. 'author': '',
  758. 'keywords': '',
  759. 'creator': ''
  760. };
  761. var getDocumentProperty = API.__private__.getDocumentProperty = function (key) {
  762. if (Object.keys(documentProperties).indexOf(key) === -1) {
  763. throw new Error('Invalid argument passed to jsPDF.getDocumentProperty');
  764. }
  765. return documentProperties[key];
  766. };
  767. var getDocumentProperties = API.__private__.getDocumentProperties = function (properties) {
  768. return documentProperties;
  769. };
  770. /**
  771. * Adds a properties to the PDF document.
  772. *
  773. * @param {Object} A property_name-to-property_value object structure.
  774. * @function
  775. * @instance
  776. * @returns {jsPDF}
  777. * @memberOf jsPDF
  778. * @name setDocumentProperties
  779. */
  780. var setDocumentProperties = API.__private__.setDocumentProperties = API.setProperties = API.setDocumentProperties = function (properties) {
  781. // copying only those properties we can render.
  782. for (var property in documentProperties) {
  783. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  784. documentProperties[property] = properties[property];
  785. }
  786. }
  787. return this;
  788. };
  789. var setDocumentProperty = API.__private__.setDocumentProperty = function (key, value) {
  790. if (Object.keys(documentProperties).indexOf(key) === -1) {
  791. throw new Error('Invalid arguments passed to jsPDF.setDocumentProperty');
  792. }
  793. return documentProperties[key] = value;
  794. };
  795. var objectNumber = 0; // 'n' Current object number
  796. var offsets = []; // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  797. var fonts = {}; // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  798. var fontmap = {}; // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  799. var activeFontKey; // will be string representing the KEY of the font as combination of fontName + fontStyle
  800. var k; // Scale factor
  801. var page = 0;
  802. var pagesContext = [];
  803. var additionalObjects = [];
  804. var events = new PubSub(API);
  805. var hotfixes = options.hotfixes || [];
  806. var newObject = API.__private__.newObject = function () {
  807. var oid = newObjectDeferred();
  808. newObjectDeferredBegin(oid, true);
  809. return oid;
  810. }; // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  811. var newObjectDeferred = API.__private__.newObjectDeferred = function () {
  812. objectNumber++;
  813. offsets[objectNumber] = function () {
  814. return content_length;
  815. };
  816. return objectNumber;
  817. };
  818. var newObjectDeferredBegin = function newObjectDeferredBegin(oid, doOutput) {
  819. doOutput = typeof doOutput === 'boolean' ? doOutput : false;
  820. offsets[oid] = content_length;
  821. if (doOutput) {
  822. out(oid + ' 0 obj');
  823. }
  824. return oid;
  825. }; // Does not output the object until after the pages have been output.
  826. // Returns an object containing the objectId and content.
  827. // All pages have been added so the object ID can be estimated to start right after.
  828. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  829. var newAdditionalObject = API.__private__.newAdditionalObject = function () {
  830. var objId = newObjectDeferred();
  831. var obj = {
  832. objId: objId,
  833. content: ''
  834. };
  835. additionalObjects.push(obj);
  836. return obj;
  837. };
  838. var rootDictionaryObjId = newObjectDeferred();
  839. var resourceDictionaryObjId = newObjectDeferred(); /////////////////////
  840. // Private functions
  841. /////////////////////
  842. var decodeColorString = API.__private__.decodeColorString = function (color) {
  843. var colorEncoded = color.split(' ');
  844. if (colorEncoded.length === 2 && (colorEncoded[1] === 'g' || colorEncoded[1] === 'G')) {
  845. // convert grayscale value to rgb so that it can be converted to hex for consistency
  846. var floatVal = parseFloat(colorEncoded[0]);
  847. colorEncoded = [floatVal, floatVal, floatVal, 'r'];
  848. }
  849. var colorAsRGB = '#';
  850. for (var i = 0; i < 3; i++) {
  851. colorAsRGB += ('0' + Math.floor(parseFloat(colorEncoded[i]) * 255).toString(16)).slice(-2);
  852. }
  853. return colorAsRGB;
  854. };
  855. var encodeColorString = API.__private__.encodeColorString = function (options) {
  856. var color;
  857. if (typeof options === "string") {
  858. options = {
  859. ch1: options
  860. };
  861. }
  862. var ch1 = options.ch1;
  863. var ch2 = options.ch2;
  864. var ch3 = options.ch3;
  865. var ch4 = options.ch4;
  866. var precision = options.precision;
  867. var letterArray = options.pdfColorType === "draw" ? ['G', 'RG', 'K'] : ['g', 'rg', 'k'];
  868. if (typeof ch1 === "string" && ch1.charAt(0) !== '#') {
  869. var rgbColor = new RGBColor(ch1);
  870. if (rgbColor.ok) {
  871. ch1 = rgbColor.toHex();
  872. } else if (!/^\d*\.?\d*$/.test(ch1)) {
  873. throw new Error('Invalid color "' + ch1 + '" passed to jsPDF.encodeColorString.');
  874. }
  875. } //convert short rgb to long form
  876. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{3}$/.test(ch1)) {
  877. ch1 = '#' + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];
  878. }
  879. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{6}$/.test(ch1)) {
  880. var hex = parseInt(ch1.substr(1), 16);
  881. ch1 = hex >> 16 & 255;
  882. ch2 = hex >> 8 & 255;
  883. ch3 = hex & 255;
  884. }
  885. if (typeof ch2 === "undefined" || typeof ch4 === "undefined" && ch1 === ch2 && ch2 === ch3) {
  886. // Gray color space.
  887. if (typeof ch1 === "string") {
  888. color = ch1 + " " + letterArray[0];
  889. } else {
  890. switch (options.precision) {
  891. case 2:
  892. color = f2(ch1 / 255) + " " + letterArray[0];
  893. break;
  894. case 3:
  895. default:
  896. color = f3(ch1 / 255) + " " + letterArray[0];
  897. }
  898. }
  899. } else if (typeof ch4 === "undefined" || _typeof(ch4) === "object") {
  900. // assume RGBA
  901. if (ch4 && !isNaN(ch4.a)) {
  902. //TODO Implement transparency.
  903. //WORKAROUND use white for now, if transparent, otherwise handle as rgb
  904. if (ch4.a === 0) {
  905. color = ['1.000', '1.000', '1.000', letterArray[1]].join(" ");
  906. return color;
  907. }
  908. } // assume RGB
  909. if (typeof ch1 === "string") {
  910. color = [ch1, ch2, ch3, letterArray[1]].join(" ");
  911. } else {
  912. switch (options.precision) {
  913. case 2:
  914. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), letterArray[1]].join(" ");
  915. break;
  916. default:
  917. case 3:
  918. color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), letterArray[1]].join(" ");
  919. }
  920. }
  921. } else {
  922. // assume CMYK
  923. if (typeof ch1 === 'string') {
  924. color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");
  925. } else {
  926. switch (options.precision) {
  927. case 2:
  928. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), f2(ch4 / 255), letterArray[2]].join(" ");
  929. break;
  930. case 3:
  931. default:
  932. color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), f3(ch4 / 255), letterArray[2]].join(" ");
  933. }
  934. }
  935. }
  936. return color;
  937. };
  938. var getFilters = API.__private__.getFilters = function () {
  939. return filters;
  940. };
  941. var putStream = API.__private__.putStream = function (options) {
  942. options = options || {};
  943. var data = options.data || '';
  944. var filters = options.filters || getFilters();
  945. var alreadyAppliedFilters = options.alreadyAppliedFilters || [];
  946. var addLength1 = options.addLength1 || false;
  947. var valueOfLength1 = data.length;
  948. var processedData = {};
  949. if (filters === true) {
  950. filters = ['FlateEncode'];
  951. }
  952. var keyValues = options.additionalKeyValues || [];
  953. if (typeof jsPDF.API.processDataByFilters !== 'undefined') {
  954. processedData = jsPDF.API.processDataByFilters(data, filters);
  955. } else {
  956. processedData = {
  957. data: data,
  958. reverseChain: []
  959. };
  960. }
  961. var filterAsString = processedData.reverseChain + (Array.isArray(alreadyAppliedFilters) ? alreadyAppliedFilters.join(' ') : alreadyAppliedFilters.toString());
  962. if (processedData.data.length !== 0) {
  963. keyValues.push({
  964. key: 'Length',
  965. value: processedData.data.length
  966. });
  967. if (addLength1 === true) {
  968. keyValues.push({
  969. key: 'Length1',
  970. value: valueOfLength1
  971. });
  972. }
  973. }
  974. if (filterAsString.length != 0) {
  975. //if (filters.length === 0 && alreadyAppliedFilters.length === 1 && typeof alreadyAppliedFilters !== "undefined") {
  976. if (filterAsString.split('/').length - 1 === 1) {
  977. keyValues.push({
  978. key: 'Filter',
  979. value: filterAsString
  980. });
  981. } else {
  982. keyValues.push({
  983. key: 'Filter',
  984. value: '[' + filterAsString + ']'
  985. });
  986. }
  987. }
  988. out('<<');
  989. for (var i = 0; i < keyValues.length; i++) {
  990. out('/' + keyValues[i].key + ' ' + keyValues[i].value);
  991. }
  992. out('>>');
  993. if (processedData.data.length !== 0) {
  994. out('stream');
  995. out(processedData.data);
  996. out('endstream');
  997. }
  998. };
  999. var putPage = API.__private__.putPage = function (page) {
  1000. var mediaBox = page.mediaBox;
  1001. var pageNumber = page.number;
  1002. var data = page.data;
  1003. var pageObjectNumber = page.objId;
  1004. var pageContentsObjId = page.contentsObjId;
  1005. newObjectDeferredBegin(pageObjectNumber, true);
  1006. var wPt = pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX;
  1007. var hPt = pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY;
  1008. out('<</Type /Page');
  1009. out('/Parent ' + page.rootDictionaryObjId + ' 0 R');
  1010. out('/Resources ' + page.resourceDictionaryObjId + ' 0 R');
  1011. out('/MediaBox [' + parseFloat(f2(page.mediaBox.bottomLeftX)) + ' ' + parseFloat(f2(page.mediaBox.bottomLeftY)) + ' ' + f2(page.mediaBox.topRightX) + ' ' + f2(page.mediaBox.topRightY) + ']');
  1012. if (page.cropBox !== null) {
  1013. out('/CropBox [' + f2(page.cropBox.bottomLeftX) + ' ' + f2(page.cropBox.bottomLeftY) + ' ' + f2(page.cropBox.topRightX) + ' ' + f2(page.cropBox.topRightY) + ']');
  1014. }
  1015. if (page.bleedBox !== null) {
  1016. out('/BleedBox [' + f2(page.bleedBox.bottomLeftX) + ' ' + f2(page.bleedBox.bottomLeftY) + ' ' + f2(page.bleedBox.topRightX) + ' ' + f2(page.bleedBox.topRightY) + ']');
  1017. }
  1018. if (page.trimBox !== null) {
  1019. out('/TrimBox [' + f2(page.trimBox.bottomLeftX) + ' ' + f2(page.trimBox.bottomLeftY) + ' ' + f2(page.trimBox.topRightX) + ' ' + f2(page.trimBox.topRightY) + ']');
  1020. }
  1021. if (page.artBox !== null) {
  1022. out('/ArtBox [' + f2(page.artBox.bottomLeftX) + ' ' + f2(page.artBox.bottomLeftY) + ' ' + f2(page.artBox.topRightX) + ' ' + f2(page.artBox.topRightY) + ']');
  1023. }
  1024. if (typeof page.userUnit === "number" && page.userUnit !== 1.0) {
  1025. out('/UserUnit ' + page.userUnit);
  1026. }
  1027. events.publish('putPage', {
  1028. objId: pageObjectNumber,
  1029. pageContext: pagesContext[pageNumber],
  1030. pageNumber: pageNumber,
  1031. page: data
  1032. });
  1033. out('/Contents ' + pageContentsObjId + ' 0 R');
  1034. out('>>');
  1035. out('endobj'); // Page content
  1036. var pageContent = data.join('\n');
  1037. newObjectDeferredBegin(pageContentsObjId, true);
  1038. putStream({
  1039. data: pageContent,
  1040. filters: getFilters()
  1041. });
  1042. out('endobj');
  1043. return pageObjectNumber;
  1044. };
  1045. var putPages = API.__private__.putPages = function () {
  1046. var n,
  1047. i,
  1048. pageObjectNumbers = [];
  1049. for (n = 1; n <= page; n++) {
  1050. pagesContext[n].objId = newObjectDeferred();
  1051. pagesContext[n].contentsObjId = newObjectDeferred();
  1052. }
  1053. for (n = 1; n <= page; n++) {
  1054. pageObjectNumbers.push(putPage({
  1055. number: n,
  1056. data: pages[n],
  1057. objId: pagesContext[n].objId,
  1058. contentsObjId: pagesContext[n].contentsObjId,
  1059. mediaBox: pagesContext[n].mediaBox,
  1060. cropBox: pagesContext[n].cropBox,
  1061. bleedBox: pagesContext[n].bleedBox,
  1062. trimBox: pagesContext[n].trimBox,
  1063. artBox: pagesContext[n].artBox,
  1064. userUnit: pagesContext[n].userUnit,
  1065. rootDictionaryObjId: rootDictionaryObjId,
  1066. resourceDictionaryObjId: resourceDictionaryObjId
  1067. }));
  1068. }
  1069. newObjectDeferredBegin(rootDictionaryObjId, true);
  1070. out('<</Type /Pages');
  1071. var kids = '/Kids [';
  1072. for (i = 0; i < page; i++) {
  1073. kids += pageObjectNumbers[i] + ' 0 R ';
  1074. }
  1075. out(kids + ']');
  1076. out('/Count ' + page);
  1077. out('>>');
  1078. out('endobj');
  1079. events.publish('postPutPages');
  1080. };
  1081. var putFont = function putFont(font) {
  1082. events.publish('putFont', {
  1083. font: font,
  1084. out: out,
  1085. newObject: newObject,
  1086. putStream: putStream
  1087. });
  1088. if (font.isAlreadyPutted !== true) {
  1089. font.objectNumber = newObject();
  1090. out('<<');
  1091. out('/Type /Font');
  1092. out('/BaseFont /' + font.postScriptName);
  1093. out('/Subtype /Type1');
  1094. if (typeof font.encoding === 'string') {
  1095. out('/Encoding /' + font.encoding);
  1096. }
  1097. out('/FirstChar 32');
  1098. out('/LastChar 255');
  1099. out('>>');
  1100. out('endobj');
  1101. }
  1102. };
  1103. var putFonts = function putFonts() {
  1104. for (var fontKey in fonts) {
  1105. if (fonts.hasOwnProperty(fontKey)) {
  1106. if (putOnlyUsedFonts === false || putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey)) {
  1107. putFont(fonts[fontKey]);
  1108. }
  1109. }
  1110. }
  1111. };
  1112. var putResourceDictionary = function putResourceDictionary() {
  1113. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  1114. out('/Font <<'); // Do this for each font, the '1' bit is the index of the font
  1115. for (var fontKey in fonts) {
  1116. if (fonts.hasOwnProperty(fontKey)) {
  1117. if (putOnlyUsedFonts === false || putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey)) {
  1118. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  1119. }
  1120. }
  1121. }
  1122. out('>>');
  1123. out('/XObject <<');
  1124. events.publish('putXobjectDict');
  1125. out('>>');
  1126. };
  1127. var putResources = function putResources() {
  1128. putFonts();
  1129. events.publish('putResources');
  1130. newObjectDeferredBegin(resourceDictionaryObjId, true);
  1131. out('<<');
  1132. putResourceDictionary();
  1133. out('>>');
  1134. out('endobj');
  1135. events.publish('postPutResources');
  1136. };
  1137. var putAdditionalObjects = function putAdditionalObjects() {
  1138. events.publish('putAdditionalObjects');
  1139. for (var i = 0; i < additionalObjects.length; i++) {
  1140. var obj = additionalObjects[i];
  1141. newObjectDeferredBegin(obj.objId, true);
  1142. out(obj.content);
  1143. out('endobj');
  1144. }
  1145. events.publish('postPutAdditionalObjects');
  1146. };
  1147. var addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  1148. // this is mapping structure for quick font key lookup.
  1149. // returns the KEY of the font (ex: "F1") for a given
  1150. // pair of font name and type (ex: "Arial". "Italic")
  1151. if (!fontmap.hasOwnProperty(fontName)) {
  1152. fontmap[fontName] = {};
  1153. }
  1154. fontmap[fontName][fontStyle] = fontKey;
  1155. };
  1156. var addFont = function addFont(postScriptName, fontName, fontStyle, encoding, isStandardFont) {
  1157. isStandardFont = isStandardFont || false;
  1158. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  1159. // This is FontObject
  1160. font = {
  1161. 'id': fontKey,
  1162. 'postScriptName': postScriptName,
  1163. 'fontName': fontName,
  1164. 'fontStyle': fontStyle,
  1165. 'encoding': encoding,
  1166. 'isStandardFont': isStandardFont,
  1167. 'metadata': {}
  1168. };
  1169. var instance = this;
  1170. events.publish('addFont', {
  1171. font: font,
  1172. instance: instance
  1173. });
  1174. if (fontKey !== undefined) {
  1175. fonts[fontKey] = font;
  1176. addToFontDictionary(fontKey, fontName, fontStyle);
  1177. }
  1178. return fontKey;
  1179. };
  1180. var addFonts = function addFonts(arrayOfFonts) {
  1181. for (var i = 0, l = standardFonts.length; i < l; i++) {
  1182. var fontKey = addFont(arrayOfFonts[i][0], arrayOfFonts[i][1], arrayOfFonts[i][2], standardFonts[i][3], true);
  1183. usedFonts[fontKey] = true; // adding aliases for standard fonts, this time matching the capitalization
  1184. var parts = arrayOfFonts[i][0].split('-');
  1185. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  1186. }
  1187. events.publish('addFonts', {
  1188. fonts: fonts,
  1189. dictionary: fontmap
  1190. });
  1191. };
  1192. var SAFE = function __safeCall(fn) {
  1193. fn.foo = function __safeCallWrapper() {
  1194. try {
  1195. return fn.apply(this, arguments);
  1196. } catch (e) {
  1197. var stack = e.stack || '';
  1198. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  1199. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  1200. if (global.console) {
  1201. global.console.error(m, e);
  1202. if (global.alert) alert(m);
  1203. } else {
  1204. throw new Error(m);
  1205. }
  1206. }
  1207. };
  1208. fn.foo.bar = fn;
  1209. return fn.foo;
  1210. };
  1211. var to8bitStream = function to8bitStream(text, flags) {
  1212. /**
  1213. * PDF 1.3 spec:
  1214. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  1215. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  1216. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  1217. * to be a meaningful beginning of a word or phrase.) The remainder of the
  1218. * string consists of Unicode character codes, according to the UTF-16 encoding
  1219. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  1220. * are represented as 2 bytes per character, with the high-order byte appearing first
  1221. * in the string."
  1222. *
  1223. * In other words, if there are chars in a string with char code above 255, we
  1224. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  1225. *
  1226. * HOWEVER!
  1227. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  1228. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  1229. *
  1230. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  1231. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  1232. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  1233. * code page. There, however, all characters in the stream are treated as GIDs,
  1234. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  1235. * that is tied to a font).
  1236. *
  1237. * To signal this "special" PDFEscape / to8bitStream handling mode,
  1238. * API.text() function sets (unless you overwrite it with manual values
  1239. * given to API.text(.., flags) )
  1240. * flags.autoencode = true
  1241. * flags.noBOM = true
  1242. *
  1243. * ===================================================================================
  1244. * `flags` properties relied upon:
  1245. * .sourceEncoding = string with encoding label.
  1246. * "Unicode" by default. = encoding of the incoming text.
  1247. * pass some non-existing encoding name
  1248. * (ex: 'Do not touch my strings! I know what I am doing.')
  1249. * to make encoding code skip the encoding step.
  1250. * .outputEncoding = Either valid PDF encoding name
  1251. * (must be supported by jsPDF font metrics, otherwise no encoding)
  1252. * or a JS object, where key = sourceCharCode, value = outputCharCode
  1253. * missing keys will be treated as: sourceCharCode === outputCharCode
  1254. * .noBOM
  1255. * See comment higher above for explanation for why this is important
  1256. * .autoencode
  1257. * See comment higher above for explanation for why this is important
  1258. */
  1259. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  1260. flags = flags || {};
  1261. sourceEncoding = flags.sourceEncoding || 'Unicode';
  1262. outputEncoding = flags.outputEncoding; // This 'encoding' section relies on font metrics format
  1263. // attached to font objects by, among others,
  1264. // "Willow Systems' standard_font_metrics plugin"
  1265. // see jspdf.plugin.standard_font_metrics.js for format
  1266. // of the font.metadata.encoding Object.
  1267. // It should be something like
  1268. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  1269. // .widths = {0:width, code:width, ..., 'fof':divisor}
  1270. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  1271. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  1272. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding; // each font has default encoding. Some have it clearly defined.
  1273. if (!outputEncoding && fonts[activeFontKey].encoding) {
  1274. outputEncoding = fonts[activeFontKey].encoding;
  1275. } // Hmmm, the above did not work? Let's try again, in different place.
  1276. if (!outputEncoding && encodingBlock.codePages) {
  1277. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  1278. }
  1279. if (typeof outputEncoding === 'string') {
  1280. outputEncoding = encodingBlock[outputEncoding];
  1281. } // we want output encoding to be a JS Object, where
  1282. // key = sourceEncoding's character code and
  1283. // value = outputEncoding's character code.
  1284. if (outputEncoding) {
  1285. isUnicode = false;
  1286. newtext = [];
  1287. for (i = 0, l = text.length; i < l; i++) {
  1288. ch = outputEncoding[text.charCodeAt(i)];
  1289. if (ch) {
  1290. newtext.push(String.fromCharCode(ch));
  1291. } else {
  1292. newtext.push(text[i]);
  1293. } // since we are looping over chars anyway, might as well
  1294. // check for residual unicodeness
  1295. if (newtext[i].charCodeAt(0) >> 8) {
  1296. /* more than 255 */
  1297. isUnicode = true;
  1298. }
  1299. }
  1300. text = newtext.join('');
  1301. }
  1302. }
  1303. i = text.length; // isUnicode may be set to false above. Hence the triple-equal to undefined
  1304. while (isUnicode === undefined && i !== 0) {
  1305. if (text.charCodeAt(i - 1) >> 8) {
  1306. /* more than 255 */
  1307. isUnicode = true;
  1308. }
  1309. i--;
  1310. }
  1311. if (!isUnicode) {
  1312. return text;
  1313. }
  1314. newtext = flags.noBOM ? [] : [254, 255];
  1315. for (i = 0, l = text.length; i < l; i++) {
  1316. ch = text.charCodeAt(i);
  1317. bch = ch >> 8; // divide by 256
  1318. if (bch >> 8) {
  1319. /* something left after dividing by 256 second time */
  1320. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  1321. }
  1322. newtext.push(bch);
  1323. newtext.push(ch - (bch << 8));
  1324. }
  1325. return String.fromCharCode.apply(undefined, newtext);
  1326. };
  1327. var pdfEscape = API.__private__.pdfEscape = API.pdfEscape = function (text, flags) {
  1328. /**
  1329. * Replace '/', '(', and ')' with pdf-safe versions
  1330. *
  1331. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  1332. * we also need to reference a unicode font and embed it - royal pain in the rear.
  1333. *
  1334. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  1335. * which JavaScript Strings are happy to provide. So, while we still cannot display
  1336. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  1337. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  1338. * is still parseable.
  1339. * This will allow immediate support for unicode in document properties strings.
  1340. */
  1341. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  1342. };
  1343. var beginPage = API.__private__.beginPage = function (width, height) {
  1344. var tmp; // Dimensions are stored as user units and converted to points on output
  1345. var orientation = typeof height === 'string' && height.toLowerCase();
  1346. if (typeof width === 'string') {
  1347. if (tmp = getPageFormat(width.toLowerCase())) {
  1348. width = tmp[0];
  1349. height = tmp[1];
  1350. }
  1351. }
  1352. if (Array.isArray(width)) {
  1353. height = width[1];
  1354. width = width[0];
  1355. }
  1356. if (isNaN(width) || isNaN(height)) {
  1357. width = format[0];
  1358. height = format[1];
  1359. }
  1360. if (orientation) {
  1361. switch (orientation.substr(0, 1)) {
  1362. case 'l':
  1363. if (height > width) orientation = 's';
  1364. break;
  1365. case 'p':
  1366. if (width > height) orientation = 's';
  1367. break;
  1368. }
  1369. if (orientation === 's') {
  1370. tmp = width;
  1371. width = height;
  1372. height = tmp;
  1373. }
  1374. }
  1375. if (width > 14400 || height > 14400) {
  1376. console.warn('A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400');
  1377. width = Math.min(14400, width);
  1378. height = Math.min(14400, height);
  1379. }
  1380. format = [width, height];
  1381. outToPages = true;
  1382. pages[++page] = [];
  1383. pagesContext[page] = {
  1384. objId: 0,
  1385. contentsObjId: 0,
  1386. userUnit: Number(userUnit),
  1387. artBox: null,
  1388. bleedBox: null,
  1389. cropBox: null,
  1390. trimBox: null,
  1391. mediaBox: {
  1392. bottomLeftX: 0,
  1393. bottomLeftY: 0,
  1394. topRightX: Number(width),
  1395. topRightY: Number(height)
  1396. }
  1397. };
  1398. _setPage(page);
  1399. };
  1400. var _addPage = function _addPage() {
  1401. beginPage.apply(this, arguments); // Set line width
  1402. setLineWidth(lineWidth); // Set draw color
  1403. out(strokeColor); // resurrecting non-default line caps, joins
  1404. if (lineCapID !== 0) {
  1405. out(lineCapID + ' J');
  1406. }
  1407. if (lineJoinID !== 0) {
  1408. out(lineJoinID + ' j');
  1409. }
  1410. events.publish('addPage', {
  1411. pageNumber: page
  1412. });
  1413. };
  1414. var _deletePage = function _deletePage(n) {
  1415. if (n > 0 && n <= page) {
  1416. pages.splice(n, 1);
  1417. page--;
  1418. if (currentPage > page) {
  1419. currentPage = page;
  1420. }
  1421. this.setPage(currentPage);
  1422. }
  1423. };
  1424. var _setPage = function _setPage(n) {
  1425. if (n > 0 && n <= page) {
  1426. currentPage = n;
  1427. }
  1428. };
  1429. var getNumberOfPages = API.__private__.getNumberOfPages = API.getNumberOfPages = function () {
  1430. return pages.length - 1;
  1431. };
  1432. /**
  1433. * Returns a document-specific font key - a label assigned to a
  1434. * font name + font type combination at the time the font was added
  1435. * to the font inventory.
  1436. *
  1437. * Font key is used as label for the desired font for a block of text
  1438. * to be added to the PDF document stream.
  1439. * @private
  1440. * @function
  1441. * @param fontName {string} can be undefined on "falthy" to indicate "use current"
  1442. * @param fontStyle {string} can be undefined on "falthy" to indicate "use current"
  1443. * @returns {string} Font key.
  1444. * @ignore
  1445. */
  1446. var _getFont = function getFont(fontName, fontStyle, options) {
  1447. var key = undefined,
  1448. fontNameLowerCase;
  1449. options = options || {};
  1450. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  1451. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  1452. fontNameLowerCase = fontName.toLowerCase();
  1453. if (fontmap[fontNameLowerCase] !== undefined && fontmap[fontNameLowerCase][fontStyle] !== undefined) {
  1454. key = fontmap[fontNameLowerCase][fontStyle];
  1455. } else if (fontmap[fontName] !== undefined && fontmap[fontName][fontStyle] !== undefined) {
  1456. key = fontmap[fontName][fontStyle];
  1457. } else {
  1458. if (options.disableWarning === false) {
  1459. console.warn("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
  1460. }
  1461. }
  1462. if (!key && !options.noFallback) {
  1463. key = fontmap['times'][fontStyle];
  1464. if (key == null) {
  1465. key = fontmap['times']['normal'];
  1466. }
  1467. }
  1468. return key;
  1469. };
  1470. var putInfo = API.__private__.putInfo = function () {
  1471. newObject();
  1472. out('<<');
  1473. out('/Producer (jsPDF ' + jsPDF.version + ')');
  1474. for (var key in documentProperties) {
  1475. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  1476. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  1477. }
  1478. }
  1479. out('/CreationDate (' + creationDate + ')');
  1480. out('>>');
  1481. out('endobj');
  1482. };
  1483. var putCatalog = API.__private__.putCatalog = function (options) {
  1484. options = options || {};
  1485. var tmpRootDictionaryObjId = options.rootDictionaryObjId || rootDictionaryObjId;
  1486. newObject();
  1487. out('<<');
  1488. out('/Type /Catalog');
  1489. out('/Pages ' + tmpRootDictionaryObjId + ' 0 R'); // PDF13ref Section 7.2.1
  1490. if (!zoomMode) zoomMode = 'fullwidth';
  1491. switch (zoomMode) {
  1492. case 'fullwidth':
  1493. out('/OpenAction [3 0 R /FitH null]');
  1494. break;
  1495. case 'fullheight':
  1496. out('/OpenAction [3 0 R /FitV null]');
  1497. break;
  1498. case 'fullpage':
  1499. out('/OpenAction [3 0 R /Fit]');
  1500. break;
  1501. case 'original':
  1502. out('/OpenAction [3 0 R /XYZ null null 1]');
  1503. break;
  1504. default:
  1505. var pcn = '' + zoomMode;
  1506. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  1507. if (typeof zoomMode === 'number') {
  1508. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  1509. }
  1510. }
  1511. if (!layoutMode) layoutMode = 'continuous';
  1512. switch (layoutMode) {
  1513. case 'continuous':
  1514. out('/PageLayout /OneColumn');
  1515. break;
  1516. case 'single':
  1517. out('/PageLayout /SinglePage');
  1518. break;
  1519. case 'two':
  1520. case 'twoleft':
  1521. out('/PageLayout /TwoColumnLeft');
  1522. break;
  1523. case 'tworight':
  1524. out('/PageLayout /TwoColumnRight');
  1525. break;
  1526. }
  1527. if (pageMode) {
  1528. /**
  1529. * A name object specifying how the document should be displayed when opened:
  1530. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  1531. * UseOutlines : Document outline visible
  1532. * UseThumbs : Thumbnail images visible
  1533. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  1534. */
  1535. out('/PageMode /' + pageMode);
  1536. }
  1537. events.publish('putCatalog');
  1538. out('>>');
  1539. out('endobj');
  1540. };
  1541. var putTrailer = API.__private__.putTrailer = function () {
  1542. out('trailer');
  1543. out('<<');
  1544. out('/Size ' + (objectNumber + 1));
  1545. out('/Root ' + objectNumber + ' 0 R');
  1546. out('/Info ' + (objectNumber - 1) + ' 0 R');
  1547. out("/ID [ <" + fileId + "> <" + fileId + "> ]");
  1548. out('>>');
  1549. };
  1550. var putHeader = API.__private__.putHeader = function () {
  1551. out('%PDF-' + pdfVersion);
  1552. out("%\xBA\xDF\xAC\xE0");
  1553. };
  1554. var putXRef = API.__private__.putXRef = function () {
  1555. var i = 1;
  1556. var p = "0000000000";
  1557. out('xref');
  1558. out('0 ' + (objectNumber + 1));
  1559. out('0000000000 65535 f ');
  1560. for (i = 1; i <= objectNumber; i++) {
  1561. var offset = offsets[i];
  1562. if (typeof offset === 'function') {
  1563. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  1564. } else {
  1565. if (typeof offsets[i] !== "undefined") {
  1566. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  1567. } else {
  1568. out('0000000000 00000 n ');
  1569. }
  1570. }
  1571. }
  1572. };
  1573. var buildDocument = API.__private__.buildDocument = function () {
  1574. outToPages = false; // switches out() to content
  1575. //reset fields relevant for objectNumber generation and xref.
  1576. objectNumber = 0;
  1577. content_length = 0;
  1578. content = [];
  1579. offsets = [];
  1580. additionalObjects = [];
  1581. rootDictionaryObjId = newObjectDeferred();
  1582. resourceDictionaryObjId = newObjectDeferred();
  1583. events.publish('buildDocument');
  1584. putHeader();
  1585. putPages();
  1586. putAdditionalObjects();
  1587. putResources();
  1588. putInfo();
  1589. putCatalog();
  1590. var offsetOfXRef = content_length;
  1591. putXRef();
  1592. putTrailer();
  1593. out('startxref');
  1594. out('' + offsetOfXRef);
  1595. out('%%EOF');
  1596. outToPages = true;
  1597. return content.join('\n');
  1598. };
  1599. var getBlob = API.__private__.getBlob = function (data) {
  1600. return new Blob([getArrayBuffer(data)], {
  1601. type: "application/pdf"
  1602. });
  1603. };
  1604. /**
  1605. * Generates the PDF document.
  1606. *
  1607. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1608. *
  1609. * @param {string} type A string identifying one of the possible output types. Possible values are 'arraybuffer', 'blob', 'bloburi'/'bloburl', 'datauristring'/'dataurlstring', 'datauri'/'dataurl', 'dataurlnewwindow'.
  1610. * @param {Object} options An object providing some additional signalling to PDF generator. Possible options are 'filename'.
  1611. *
  1612. * @function
  1613. * @instance
  1614. * @returns {jsPDF}
  1615. * @memberOf jsPDF
  1616. * @name output
  1617. */
  1618. var output = API.output = API.__private__.output = SAFE(function output(type, options) {
  1619. options = options || {};
  1620. var pdfDocument = buildDocument();
  1621. if (typeof options === "string") {
  1622. options = {
  1623. filename: options
  1624. };
  1625. } else {
  1626. options.filename = options.filename || 'generated.pdf';
  1627. }
  1628. switch (type) {
  1629. case undefined:
  1630. return pdfDocument;
  1631. case 'save':
  1632. API.save(options.filename);
  1633. break;
  1634. case 'arraybuffer':
  1635. return getArrayBuffer(pdfDocument);
  1636. case 'blob':
  1637. return getBlob(pdfDocument);
  1638. case 'bloburi':
  1639. case 'bloburl':
  1640. // Developer is responsible of calling revokeObjectURL
  1641. if (typeof global.URL !== "undefined" && typeof global.URL.createObjectURL === "function") {
  1642. return global.URL && global.URL.createObjectURL(getBlob(pdfDocument)) || void 0;
  1643. } else {
  1644. console.warn('bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.');
  1645. }
  1646. break;
  1647. case 'datauristring':
  1648. case 'dataurlstring':
  1649. return 'data:application/pdf;filename=' + options.filename + ';base64,' + btoa(pdfDocument);
  1650. case 'dataurlnewwindow':
  1651. var htmlForNewWindow = '<html>' + '<style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style>' + '<body>' + '<iframe src="' + this.output('datauristring') + '"></iframe>' + '</body></html>';
  1652. var nW = global.open();
  1653. if (nW !== null) {
  1654. nW.document.write(htmlForNewWindow);
  1655. }
  1656. if (nW || typeof safari === "undefined") return nW;
  1657. /* pass through */
  1658. case 'datauri':
  1659. case 'dataurl':
  1660. return global.document.location.href = 'data:application/pdf;filename=' + options.filename + ';base64,' + btoa(pdfDocument);
  1661. default:
  1662. return null;
  1663. }
  1664. });
  1665. /**
  1666. * Used to see if a supplied hotfix was requested when the pdf instance was created.
  1667. * @param {string} hotfixName - The name of the hotfix to check.
  1668. * @returns {boolean}
  1669. */
  1670. var hasHotfix = function hasHotfix(hotfixName) {
  1671. return Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1;
  1672. };
  1673. switch (unit) {
  1674. case 'pt':
  1675. k = 1;
  1676. break;
  1677. case 'mm':
  1678. k = 72 / 25.4;
  1679. break;
  1680. case 'cm':
  1681. k = 72 / 2.54;
  1682. break;
  1683. case 'in':
  1684. k = 72;
  1685. break;
  1686. case 'px':
  1687. if (hasHotfix('px_scaling') == true) {
  1688. k = 72 / 96;
  1689. } else {
  1690. k = 96 / 72;
  1691. }
  1692. break;
  1693. case 'pc':
  1694. k = 12;
  1695. break;
  1696. case 'em':
  1697. k = 12;
  1698. break;
  1699. case 'ex':
  1700. k = 6;
  1701. break;
  1702. default:
  1703. throw new Error('Invalid unit: ' + unit);
  1704. }
  1705. setCreationDate();
  1706. setFileId(); //---------------------------------------
  1707. // Public API
  1708. var getPageInfo = API.__private__.getPageInfo = function (pageNumberOneBased) {
  1709. if (isNaN(pageNumberOneBased) || pageNumberOneBased % 1 !== 0) {
  1710. throw new Error('Invalid argument passed to jsPDF.getPageInfo');
  1711. }
  1712. var objId = pagesContext[pageNumberOneBased].objId;
  1713. return {
  1714. objId: objId,
  1715. pageNumber: pageNumberOneBased,
  1716. pageContext: pagesContext[pageNumberOneBased]
  1717. };
  1718. };
  1719. var getPageInfoByObjId = API.__private__.getPageInfoByObjId = function (objId) {
  1720. for (var pageNumber in pagesContext) {
  1721. if (pagesContext[pageNumber].objId === objId) {
  1722. break;
  1723. }
  1724. }
  1725. if (isNaN(objId) || objId % 1 !== 0) {
  1726. throw new Error('Invalid argument passed to jsPDF.getPageInfoByObjId');
  1727. }
  1728. return getPageInfo(pageNumber);
  1729. };
  1730. var getCurrentPageInfo = API.__private__.getCurrentPageInfo = function () {
  1731. return {
  1732. objId: pagesContext[currentPage].objId,
  1733. pageNumber: currentPage,
  1734. pageContext: pagesContext[currentPage]
  1735. };
  1736. };
  1737. /**
  1738. * Adds (and transfers the focus to) new page to the PDF document.
  1739. * @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>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 />
  1740. * 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]
  1741. * @param orientation {string} Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").
  1742. * @function
  1743. * @instance
  1744. * @returns {jsPDF}
  1745. *
  1746. * @memberOf jsPDF
  1747. * @name addPage
  1748. */
  1749. API.addPage = function () {
  1750. _addPage.apply(this, arguments);
  1751. return this;
  1752. };
  1753. /**
  1754. * Adds (and transfers the focus to) new page to the PDF document.
  1755. * @function
  1756. * @instance
  1757. * @returns {jsPDF}
  1758. *
  1759. * @memberOf jsPDF
  1760. * @name setPage
  1761. * @param {number} page Switch the active page to the page number specified.
  1762. * @example
  1763. * doc = jsPDF()
  1764. * doc.addPage()
  1765. * doc.addPage()
  1766. * doc.text('I am on page 3', 10, 10)
  1767. * doc.setPage(1)
  1768. * doc.text('I am on page 1', 10, 10)
  1769. */
  1770. API.setPage = function () {
  1771. _setPage.apply(this, arguments);
  1772. return this;
  1773. };
  1774. /**
  1775. * @name insertPage
  1776. * @memberOf jsPDF
  1777. *
  1778. * @function
  1779. * @instance
  1780. * @param {Object} beforePage
  1781. * @returns {jsPDF}
  1782. */
  1783. API.insertPage = function (beforePage) {
  1784. this.addPage();
  1785. this.movePage(currentPage, beforePage);
  1786. return this;
  1787. };
  1788. /**
  1789. * @name movePage
  1790. * @memberOf jsPDF
  1791. * @function
  1792. * @instance
  1793. * @param {Object} targetPage
  1794. * @param {Object} beforePage
  1795. * @returns {jsPDF}
  1796. */
  1797. API.movePage = function (targetPage, beforePage) {
  1798. if (targetPage > beforePage) {
  1799. var tmpPages = pages[targetPage];
  1800. var tmpPagesContext = pagesContext[targetPage];
  1801. for (var i = targetPage; i > beforePage; i--) {
  1802. pages[i] = pages[i - 1];
  1803. pagesContext[i] = pagesContext[i - 1];
  1804. }
  1805. pages[beforePage] = tmpPages;
  1806. pagesContext[beforePage] = tmpPagesContext;
  1807. this.setPage(beforePage);
  1808. } else if (targetPage < beforePage) {
  1809. var tmpPages = pages[targetPage];
  1810. var tmpPagesContext = pagesContext[targetPage];
  1811. for (var i = targetPage; i < beforePage; i++) {
  1812. pages[i] = pages[i + 1];
  1813. pagesContext[i] = pagesContext[i + 1];
  1814. }
  1815. pages[beforePage] = tmpPages;
  1816. pagesContext[beforePage] = tmpPagesContext;
  1817. this.setPage(beforePage);
  1818. }
  1819. return this;
  1820. };
  1821. /**
  1822. * Deletes a page from the PDF.
  1823. * @name deletePage
  1824. * @memberOf jsPDF
  1825. * @function
  1826. * @instance
  1827. * @returns {jsPDF}
  1828. */
  1829. API.deletePage = function () {
  1830. _deletePage.apply(this, arguments);
  1831. return this;
  1832. };
  1833. /**
  1834. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1835. *
  1836. * @function
  1837. * @instance
  1838. * @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.
  1839. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  1840. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  1841. * @param {Object} [options] - Collection of settings signaling how the text must be encoded.
  1842. * @param {string} [options.align=left] - The alignment of the text, possible values: left, center, right, justify.
  1843. * @param {string} [options.baseline=alphabetic] - Sets text baseline used when drawing the text, possible values: alphabetic, ideographic, bottom, top, middle.
  1844. * @param {string} [options.angle=0] - Rotate the text counterclockwise. Expects the angle in degree.
  1845. * @param {string} [options.charSpace=0] - The space between each letter.
  1846. * @param {string} [options.lineHeightFactor=1.15] - The lineheight of each line.
  1847. * @param {string} [options.flags] - Flags for to8bitStream.
  1848. * @param {string} [options.flags.noBOM=true] - Don't add BOM to Unicode-text.
  1849. * @param {string} [options.flags.autoencode=true] - Autoencode the Text.
  1850. * @param {string} [options.maxWidth=0] - Split the text by given width, 0 = no split.
  1851. * @param {string} [options.renderingMode=fill] - Set how the text should be rendered, possible values: fill, stroke, fillThenStroke, invisible, fillAndAddForClipping, strokeAndAddPathForClipping, fillThenStrokeAndAddToPathForClipping, addToPathForClipping.
  1852. * @returns {jsPDF}
  1853. * @memberOf jsPDF
  1854. * @name text
  1855. */
  1856. var text = API.__private__.text = API.text = function (text, x, y, options) {
  1857. /**
  1858. * Inserts something like this into PDF
  1859. * BT
  1860. * /F1 16 Tf % Font name + size
  1861. * 16 TL % How many units down for next line in multiline text
  1862. * 0 g % color
  1863. * 28.35 813.54 Td % position
  1864. * (line one) Tj
  1865. * T* (line two) Tj
  1866. * T* (line three) Tj
  1867. * ET
  1868. */
  1869. //backwardsCompatibility
  1870. var tmp; // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1871. // in effort to make all calls have similar signature like
  1872. // function(data, coordinates... , miscellaneous)
  1873. // this method had its args flipped.
  1874. // code below allows backward compatibility with old arg order.
  1875. if (typeof text === 'number' && typeof x === 'number' && (typeof y === 'string' || Array.isArray(y))) {
  1876. tmp = y;
  1877. y = x;
  1878. x = text;
  1879. text = tmp;
  1880. }
  1881. var flags = arguments[3];
  1882. var angle = arguments[4];
  1883. var align = arguments[5];
  1884. if (_typeof(flags) !== "object" || flags === null) {
  1885. if (typeof angle === 'string') {
  1886. align = angle;
  1887. angle = null;
  1888. }
  1889. if (typeof flags === 'string') {
  1890. align = flags;
  1891. flags = null;
  1892. }
  1893. if (typeof flags === 'number') {
  1894. angle = flags;
  1895. flags = null;
  1896. }
  1897. options = {
  1898. flags: flags,
  1899. angle: angle,
  1900. align: align
  1901. };
  1902. }
  1903. flags = flags || {};
  1904. flags.noBOM = flags.noBOM || true;
  1905. flags.autoencode = flags.autoencode || true;
  1906. if (isNaN(x) || isNaN(y) || typeof text === "undefined" || text === null) {
  1907. throw new Error('Invalid arguments passed to jsPDF.text');
  1908. }
  1909. if (text.length === 0) {
  1910. return scope;
  1911. }
  1912. var xtra = '';
  1913. var isHex = false;
  1914. var lineHeight = typeof options.lineHeightFactor === 'number' ? options.lineHeightFactor : lineHeightFactor;
  1915. var scope = options.scope || this;
  1916. function ESC(s) {
  1917. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1918. return pdfEscape(s, flags);
  1919. }
  1920. function transformTextToSpecialArray(text) {
  1921. //we don't want to destroy original text array, so cloning it
  1922. var sa = text.concat();
  1923. var da = [];
  1924. var len = sa.length;
  1925. var curDa; //we do array.join('text that must not be PDFescaped")
  1926. //thus, pdfEscape each component separately
  1927. while (len--) {
  1928. curDa = sa.shift();
  1929. if (typeof curDa === "string") {
  1930. da.push(curDa);
  1931. } else {
  1932. if (Array.isArray(text) && curDa.length === 1) {
  1933. da.push(curDa[0]);
  1934. } else {
  1935. da.push([curDa[0], curDa[1], curDa[2]]);
  1936. }
  1937. }
  1938. }
  1939. return da;
  1940. }
  1941. function processTextByFunction(text, processingFunction) {
  1942. var result;
  1943. if (typeof text === 'string') {
  1944. result = processingFunction(text)[0];
  1945. } else if (Array.isArray(text)) {
  1946. //we don't want to destroy original text array, so cloning it
  1947. var sa = text.concat();
  1948. var da = [];
  1949. var len = sa.length;
  1950. var curDa;
  1951. var tmpResult; //we do array.join('text that must not be PDFescaped")
  1952. //thus, pdfEscape each component separately
  1953. while (len--) {
  1954. curDa = sa.shift();
  1955. if (typeof curDa === "string") {
  1956. da.push(processingFunction(curDa)[0]);
  1957. } else if (Array.isArray(curDa) && curDa[0] === "string") {
  1958. tmpResult = processingFunction(curDa[0], curDa[1], curDa[2]);
  1959. da.push([tmpResult[0], tmpResult[1], tmpResult[2]]);
  1960. }
  1961. }
  1962. result = da;
  1963. }
  1964. return result;
  1965. } //Check if text is of type String
  1966. var textIsOfTypeString = false;
  1967. var tmpTextIsOfTypeString = true;
  1968. if (typeof text === 'string') {
  1969. textIsOfTypeString = true;
  1970. } else if (Array.isArray(text)) {
  1971. //we don't want to destroy original text array, so cloning it
  1972. var sa = text.concat();
  1973. var da = [];
  1974. var len = sa.length;
  1975. var curDa; //we do array.join('text that must not be PDFescaped")
  1976. //thus, pdfEscape each component separately
  1977. while (len--) {
  1978. curDa = sa.shift();
  1979. if (typeof curDa !== "string" || Array.isArray(curDa) && typeof curDa[0] !== "string") {
  1980. tmpTextIsOfTypeString = false;
  1981. }
  1982. }
  1983. textIsOfTypeString = tmpTextIsOfTypeString;
  1984. }
  1985. if (textIsOfTypeString === false) {
  1986. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1987. } //Escaping
  1988. var activeFontEncoding = fonts[activeFontKey].encoding;
  1989. if (activeFontEncoding === "WinAnsiEncoding" || activeFontEncoding === "StandardEncoding") {
  1990. text = processTextByFunction(text, function (text, posX, posY) {
  1991. return [ESC(text), posX, posY];
  1992. });
  1993. } //If there are any newlines in text, we assume
  1994. //the user wanted to print multiple lines, so break the
  1995. //text up into an array. If the text is already an array,
  1996. //we assume the user knows what they are doing.
  1997. //Convert text into an array anyway to simplify
  1998. //later code.
  1999. if (typeof text === 'string') {
  2000. if (text.match(/[\r?\n]/)) {
  2001. text = text.split(/\r\n|\r|\n/g);
  2002. } else {
  2003. text = [text];
  2004. }
  2005. } //baseline
  2006. var height = activeFontSize / scope.internal.scaleFactor;
  2007. var descent = height * (lineHeightFactor - 1);
  2008. switch (options.baseline) {
  2009. case 'bottom':
  2010. y -= descent;
  2011. break;
  2012. case 'top':
  2013. y += height - descent;
  2014. break;
  2015. case 'hanging':
  2016. y += height - 2 * descent;
  2017. break;
  2018. case 'middle':
  2019. y += height / 2 - descent;
  2020. break;
  2021. case 'ideographic':
  2022. case 'alphabetic':
  2023. default:
  2024. // do nothing, everything is fine
  2025. break;
  2026. } //multiline
  2027. var maxWidth = options.maxWidth || 0;
  2028. if (maxWidth > 0) {
  2029. if (typeof text === 'string') {
  2030. text = scope.splitTextToSize(text, maxWidth);
  2031. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  2032. text = scope.splitTextToSize(text.join(" "), maxWidth);
  2033. }
  2034. } //creating Payload-Object to make text byRef
  2035. var payload = {
  2036. text: text,
  2037. x: x,
  2038. y: y,
  2039. options: options,
  2040. mutex: {
  2041. pdfEscape: pdfEscape,
  2042. activeFontKey: activeFontKey,
  2043. fonts: fonts,
  2044. activeFontSize: activeFontSize
  2045. }
  2046. };
  2047. events.publish('preProcessText', payload);
  2048. text = payload.text;
  2049. options = payload.options; //angle
  2050. var angle = options.angle;
  2051. var k = scope.internal.scaleFactor;
  2052. var transformationMatrix = [];
  2053. if (angle) {
  2054. angle *= Math.PI / 180;
  2055. var c = Math.cos(angle),
  2056. s = Math.sin(angle);
  2057. transformationMatrix = [f2(c), f2(s), f2(s * -1), f2(c)];
  2058. } //charSpace
  2059. var charSpace = options.charSpace;
  2060. if (typeof charSpace !== 'undefined') {
  2061. xtra += f3(charSpace * k) + " Tc\n";
  2062. } //lang
  2063. var lang = options.lang;
  2064. var tmpRenderingMode = -1;
  2065. var parmRenderingMode = typeof options.renderingMode !== "undefined" ? options.renderingMode : options.stroke;
  2066. var pageContext = scope.internal.getCurrentPageInfo().pageContext;
  2067. switch (parmRenderingMode) {
  2068. case 0:
  2069. case false:
  2070. case 'fill':
  2071. tmpRenderingMode = 0;
  2072. break;
  2073. case 1:
  2074. case true:
  2075. case 'stroke':
  2076. tmpRenderingMode = 1;
  2077. break;
  2078. case 2:
  2079. case 'fillThenStroke':
  2080. tmpRenderingMode = 2;
  2081. break;
  2082. case 3:
  2083. case 'invisible':
  2084. tmpRenderingMode = 3;
  2085. break;
  2086. case 4:
  2087. case 'fillAndAddForClipping':
  2088. tmpRenderingMode = 4;
  2089. break;
  2090. case 5:
  2091. case 'strokeAndAddPathForClipping':
  2092. tmpRenderingMode = 5;
  2093. break;
  2094. case 6:
  2095. case 'fillThenStrokeAndAddToPathForClipping':
  2096. tmpRenderingMode = 6;
  2097. break;
  2098. case 7:
  2099. case 'addToPathForClipping':
  2100. tmpRenderingMode = 7;
  2101. break;
  2102. }
  2103. var usedRenderingMode = typeof pageContext.usedRenderingMode !== 'undefined' ? pageContext.usedRenderingMode : -1; //if the coder wrote it explicitly to use a specific
  2104. //renderingMode, then use it
  2105. if (tmpRenderingMode !== -1) {
  2106. xtra += tmpRenderingMode + " Tr\n"; //otherwise check if we used the rendering Mode already
  2107. //if so then set the rendering Mode...
  2108. } else if (usedRenderingMode !== -1) {
  2109. xtra += "0 Tr\n";
  2110. }
  2111. if (tmpRenderingMode !== -1) {
  2112. pageContext.usedRenderingMode = tmpRenderingMode;
  2113. } //align
  2114. var align = options.align || 'left';
  2115. var leading = activeFontSize * lineHeight;
  2116. var pageWidth = scope.internal.pageSize.getWidth();
  2117. var k = scope.internal.scaleFactor;
  2118. var activeFont = fonts[activeFontKey];
  2119. var charSpace = options.charSpace || activeCharSpace;
  2120. var maxWidth = options.maxWidth || 0;
  2121. var lineWidths;
  2122. var flags = {};
  2123. var wordSpacingPerLine = [];
  2124. if (Object.prototype.toString.call(text) === '[object Array]') {
  2125. var da = transformTextToSpecialArray(text);
  2126. var newY;
  2127. var maxLineLength;
  2128. var lineWidths;
  2129. if (align !== "left") {
  2130. lineWidths = da.map(function (v) {
  2131. return scope.getStringUnitWidth(v, {
  2132. font: activeFont,
  2133. charSpace: charSpace,
  2134. fontSize: activeFontSize
  2135. }) * activeFontSize / k;
  2136. });
  2137. }
  2138. var maxLineLength = Math.max.apply(Math, lineWidths); //The first line uses the "main" Td setting,
  2139. //and the subsequent lines are offset by the
  2140. //previous line's x coordinate.
  2141. var prevWidth = 0;
  2142. var delta;
  2143. var newX;
  2144. if (align === "right") {
  2145. x -= lineWidths[0];
  2146. text = [];
  2147. for (var i = 0, len = da.length; i < len; i++) {
  2148. delta = maxLineLength - lineWidths[i];
  2149. if (i === 0) {
  2150. newX = getHorizontalCoordinate(x);
  2151. newY = getVerticalCoordinate(y);
  2152. } else {
  2153. newX = (prevWidth - lineWidths[i]) * k;
  2154. newY = -leading;
  2155. }
  2156. text.push([da[i], newX, newY]);
  2157. prevWidth = lineWidths[i];
  2158. }
  2159. } else if (align === "center") {
  2160. x -= lineWidths[0] / 2;
  2161. text = [];
  2162. for (var i = 0, len = da.length; i < len; i++) {
  2163. delta = (maxLineLength - lineWidths[i]) / 2;
  2164. if (i === 0) {
  2165. newX = getHorizontalCoordinate(x);
  2166. newY = getVerticalCoordinate(y);
  2167. } else {
  2168. newX = (prevWidth - lineWidths[i]) / 2 * k;
  2169. newY = -leading;
  2170. }
  2171. text.push([da[i], newX, newY]);
  2172. prevWidth = lineWidths[i];
  2173. }
  2174. } else if (align === "left") {
  2175. text = [];
  2176. for (var i = 0, len = da.length; i < len; i++) {
  2177. newY = i === 0 ? getVerticalCoordinate(y) : -leading;
  2178. newX = i === 0 ? getHorizontalCoordinate(x) : 0; //text.push([da[i], newX, newY]);
  2179. text.push(da[i]);
  2180. }
  2181. } else if (align === "justify") {
  2182. text = [];
  2183. var maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;
  2184. for (var i = 0, len = da.length; i < len; i++) {
  2185. newY = i === 0 ? getVerticalCoordinate(y) : -leading;
  2186. newX = i === 0 ? getHorizontalCoordinate(x) : 0;
  2187. if (i < len - 1) {
  2188. wordSpacingPerLine.push(((maxWidth - lineWidths[i]) / (da[i].split(" ").length - 1) * k).toFixed(2));
  2189. }
  2190. text.push([da[i], newX, newY]);
  2191. }
  2192. } else {
  2193. throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".');
  2194. }
  2195. } //R2L
  2196. var doReversing = typeof options.R2L === "boolean" ? options.R2L : R2L;
  2197. if (doReversing === true) {
  2198. text = processTextByFunction(text, function (text, posX, posY) {
  2199. return [text.split("").reverse().join(""), posX, posY];
  2200. });
  2201. } //creating Payload-Object to make text byRef
  2202. var payload = {
  2203. text: text,
  2204. x: x,
  2205. y: y,
  2206. options: options,
  2207. mutex: {
  2208. pdfEscape: pdfEscape,
  2209. activeFontKey: activeFontKey,
  2210. fonts: fonts,
  2211. activeFontSize: activeFontSize
  2212. }
  2213. };
  2214. events.publish('postProcessText', payload);
  2215. text = payload.text;
  2216. isHex = payload.mutex.isHex;
  2217. var da = transformTextToSpecialArray(text);
  2218. text = [];
  2219. var variant = 0;
  2220. var len = da.length;
  2221. var posX;
  2222. var posY;
  2223. var content;
  2224. var wordSpacing = '';
  2225. for (var i = 0; i < len; i++) {
  2226. wordSpacing = '';
  2227. if (!Array.isArray(da[i])) {
  2228. posX = getHorizontalCoordinate(x);
  2229. posY = getVerticalCoordinate(y);
  2230. content = (isHex ? "<" : "(") + da[i] + (isHex ? ">" : ")");
  2231. } else {
  2232. posX = parseFloat(da[i][1]);
  2233. posY = parseFloat(da[i][2]);
  2234. content = (isHex ? "<" : "(") + da[i][0] + (isHex ? ">" : ")");
  2235. variant = 1;
  2236. }
  2237. if (wordSpacingPerLine !== undefined && wordSpacingPerLine[i] !== undefined) {
  2238. wordSpacing = wordSpacingPerLine[i] + " Tw\n";
  2239. }
  2240. if (transformationMatrix.length !== 0 && i === 0) {
  2241. text.push(wordSpacing + transformationMatrix.join(" ") + " " + posX.toFixed(2) + " " + posY.toFixed(2) + " Tm\n" + content);
  2242. } else if (variant === 1 || variant === 0 && i === 0) {
  2243. text.push(wordSpacing + posX.toFixed(2) + " " + posY.toFixed(2) + " Td\n" + content);
  2244. } else {
  2245. text.push(wordSpacing + content);
  2246. }
  2247. }
  2248. if (variant === 0) {
  2249. text = text.join(" Tj\nT* ");
  2250. } else {
  2251. text = text.join(" Tj\n");
  2252. }
  2253. text += " Tj\n";
  2254. var result = 'BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  2255. (activeFontSize * lineHeight).toFixed(2) + ' TL\n' + // line spacing
  2256. textColor + '\n';
  2257. result += xtra;
  2258. result += text;
  2259. result += "ET";
  2260. out(result);
  2261. usedFonts[activeFontKey] = true;
  2262. return scope;
  2263. };
  2264. /**
  2265. * Letter spacing method to print text with gaps
  2266. *
  2267. * @function
  2268. * @instance
  2269. * @param {String|Array} text String to be added to the page.
  2270. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  2271. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  2272. * @param {number} spacing Spacing (in units declared at inception)
  2273. * @returns {jsPDF}
  2274. * @memberOf jsPDF
  2275. * @name lstext
  2276. * @deprecated We'll be removing this function. It doesn't take character width into account.
  2277. */
  2278. var lstext = API.__private__.lstext = API.lstext = function (text, x, y, charSpace) {
  2279. console.warn('jsPDF.lstext is deprecated');
  2280. return this.text(text, x, y, {
  2281. charSpace: charSpace
  2282. });
  2283. };
  2284. /**
  2285. *
  2286. * @name clip
  2287. * @function
  2288. * @instance
  2289. * @param {string} rule
  2290. * @returns {jsPDF}
  2291. * @memberOf jsPDF
  2292. * @description All .clip() after calling drawing ops with a style argument of null.
  2293. */
  2294. var clip = API.__private__.clip = API.clip = function (rule) {
  2295. // Call .clip() after calling drawing ops with a style argument of null
  2296. // W is the PDF clipping op
  2297. if ('evenodd' === rule) {
  2298. out('W*');
  2299. } else {
  2300. out('W');
  2301. } // End the path object without filling or stroking it.
  2302. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  2303. // (see Section 4.4.3, “Clipping Path Operators”)
  2304. out('n');
  2305. };
  2306. /**
  2307. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  2308. * We introduce the fixed version so as to not break API.
  2309. * @param fillRule
  2310. * @ignore
  2311. */
  2312. var clip_fixed = API.__private__.clip_fixed = API.clip_fixed = function (rule) {
  2313. console.log("clip_fixed is deprecated");
  2314. API.clip(rule);
  2315. };
  2316. var isValidStyle = API.__private__.isValidStyle = function (style) {
  2317. var validStyleVariants = [undefined, null, 'S', 'F', 'DF', 'FD', 'f', 'f*', 'B', 'B*'];
  2318. var result = false;
  2319. if (validStyleVariants.indexOf(style) !== -1) {
  2320. result = true;
  2321. }
  2322. return result;
  2323. };
  2324. var getStyle = API.__private__.getStyle = function (style) {
  2325. // see path-painting operators in PDF spec
  2326. var op = 'S'; // stroke
  2327. if (style === 'F') {
  2328. op = 'f'; // fill
  2329. } else if (style === 'FD' || style === 'DF') {
  2330. op = 'B'; // both
  2331. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  2332. /*
  2333. Allow direct use of these PDF path-painting operators:
  2334. - f fill using nonzero winding number rule
  2335. - f* fill using even-odd rule
  2336. - B fill then stroke with fill using non-zero winding number rule
  2337. - B* fill then stroke with fill using even-odd rule
  2338. */
  2339. op = style;
  2340. }
  2341. return op;
  2342. };
  2343. /**
  2344. * Draw a line on the current page.
  2345. *
  2346. * @name line
  2347. * @function
  2348. * @instance
  2349. * @param {number} x1
  2350. * @param {number} y1
  2351. * @param {number} x2
  2352. * @param {number} y2
  2353. * @returns {jsPDF}
  2354. * @memberOf jsPDF
  2355. */
  2356. var line = API.__private__.line = API.line = function (x1, y1, x2, y2) {
  2357. if (isNaN(x1) || isNaN(y1) || isNaN(x2) || isNaN(y2)) {
  2358. throw new Error('Invalid arguments passed to jsPDF.line');
  2359. }
  2360. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  2361. };
  2362. /**
  2363. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  2364. * All data points in `lines` are relative to last line origin.
  2365. * `x`, `y` become x1,y1 for first line / curve in the set.
  2366. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  2367. * 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.
  2368. *
  2369. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, [1,1], 'F', false) // line, line, bezier curve, line
  2370. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  2371. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2372. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2373. * @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.
  2374. * @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.
  2375. * @param {boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  2376. * @function
  2377. * @instance
  2378. * @returns {jsPDF}
  2379. * @memberOf jsPDF
  2380. * @name lines
  2381. */
  2382. var lines = API.__private__.lines = API.lines = function (lines, x, y, scale, style, closed) {
  2383. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4, tmp; // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  2384. // in effort to make all calls have similar signature like
  2385. // function(content, coordinateX, coordinateY , miscellaneous)
  2386. // this method had its args flipped.
  2387. // code below allows backward compatibility with old arg order.
  2388. if (typeof lines === 'number') {
  2389. tmp = y;
  2390. y = x;
  2391. x = lines;
  2392. lines = tmp;
  2393. }
  2394. scale = scale || [1, 1];
  2395. closed = closed || false;
  2396. if (isNaN(x) || isNaN(y) || !Array.isArray(lines) || !Array.isArray(scale) || !isValidStyle(style) || typeof closed !== 'boolean') {
  2397. throw new Error('Invalid arguments passed to jsPDF.lines');
  2398. } // starting point
  2399. out(f3(getHorizontalCoordinate(x)) + ' ' + f3(getVerticalCoordinate(y)) + ' m ');
  2400. scalex = scale[0];
  2401. scaley = scale[1];
  2402. l = lines.length; //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  2403. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  2404. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  2405. x4 = x; // last / ending point = starting point for first item.
  2406. y4 = y; // last / ending point = starting point for first item.
  2407. for (i = 0; i < l; i++) {
  2408. leg = lines[i];
  2409. if (leg.length === 2) {
  2410. // simple line
  2411. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  2412. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  2413. out(f3(getHorizontalCoordinate(x4)) + ' ' + f3(getVerticalCoordinate(y4)) + ' l');
  2414. } else {
  2415. // bezier curve
  2416. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  2417. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  2418. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  2419. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  2420. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  2421. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  2422. out(f3(getHorizontalCoordinate(x2)) + ' ' + f3(getVerticalCoordinate(y2)) + ' ' + f3(getHorizontalCoordinate(x3)) + ' ' + f3(getVerticalCoordinate(y3)) + ' ' + f3(getHorizontalCoordinate(x4)) + ' ' + f3(getVerticalCoordinate(y4)) + ' c');
  2423. }
  2424. }
  2425. if (closed) {
  2426. out(' h');
  2427. } // stroking / filling / both the path
  2428. if (style !== null) {
  2429. out(getStyle(style));
  2430. }
  2431. return this;
  2432. };
  2433. /**
  2434. * Adds a rectangle to PDF.
  2435. *
  2436. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2437. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2438. * @param {number} w Width (in units declared at inception of PDF document).
  2439. * @param {number} h Height (in units declared at inception of PDF document).
  2440. * @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.
  2441. * @function
  2442. * @instance
  2443. * @returns {jsPDF}
  2444. * @memberOf jsPDF
  2445. * @name rect
  2446. */
  2447. var rect = API.__private__.rect = API.rect = function (x, y, w, h, style) {
  2448. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || !isValidStyle(style)) {
  2449. throw new Error('Invalid arguments passed to jsPDF.rect');
  2450. }
  2451. out([f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y)), f2(w * k), f2(-h * k), 're'].join(' '));
  2452. if (style !== null) {
  2453. out(getStyle(style));
  2454. }
  2455. return this;
  2456. };
  2457. /**
  2458. * Adds a triangle to PDF.
  2459. *
  2460. * @param {number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2461. * @param {number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2462. * @param {number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2463. * @param {number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2464. * @param {number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2465. * @param {number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2466. * @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.
  2467. * @function
  2468. * @instance
  2469. * @returns {jsPDF}
  2470. * @memberOf jsPDF
  2471. * @name triangle
  2472. */
  2473. var triangle = API.__private__.triangle = API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  2474. if (isNaN(x1) || isNaN(y1) || isNaN(x2) || isNaN(y2) || isNaN(x3) || isNaN(y3) || !isValidStyle(style)) {
  2475. throw new Error('Invalid arguments passed to jsPDF.triangle');
  2476. }
  2477. this.lines([[x2 - x1, y2 - y1], // vector to point 2
  2478. [x3 - x2, y3 - y2], // vector to point 3
  2479. [x1 - x3, y1 - y3] // closing vector back to point 1
  2480. ], x1, y1, // start of path
  2481. [1, 1], style, true);
  2482. return this;
  2483. };
  2484. /**
  2485. * Adds a rectangle with rounded corners to PDF.
  2486. *
  2487. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2488. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2489. * @param {number} w Width (in units declared at inception of PDF document).
  2490. * @param {number} h Height (in units declared at inception of PDF document).
  2491. * @param {number} rx Radius along x axis (in units declared at inception of PDF document).
  2492. * @param {number} ry Radius along y axis (in units declared at inception of PDF document).
  2493. * @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.
  2494. * @function
  2495. * @instance
  2496. * @returns {jsPDF}
  2497. * @memberOf jsPDF
  2498. * @name roundedRect
  2499. */
  2500. var roundedRect = API.__private__.roundedRect = API.roundedRect = function (x, y, w, h, rx, ry, style) {
  2501. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || isNaN(rx) || isNaN(ry) || !isValidStyle(style)) {
  2502. throw new Error('Invalid arguments passed to jsPDF.roundedRect');
  2503. }
  2504. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  2505. 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
  2506. [1, 1], style);
  2507. return this;
  2508. };
  2509. /**
  2510. * Adds an ellipse to PDF.
  2511. *
  2512. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2513. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2514. * @param {number} rx Radius along x axis (in units declared at inception of PDF document).
  2515. * @param {number} ry Radius along y axis (in units declared at inception of PDF document).
  2516. * @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.
  2517. * @function
  2518. * @instance
  2519. * @returns {jsPDF}
  2520. * @memberOf jsPDF
  2521. * @name ellipse
  2522. */
  2523. var ellise = API.__private__.ellipse = API.ellipse = function (x, y, rx, ry, style) {
  2524. if (isNaN(x) || isNaN(y) || isNaN(rx) || isNaN(ry) || !isValidStyle(style)) {
  2525. throw new Error('Invalid arguments passed to jsPDF.ellipse');
  2526. }
  2527. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  2528. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  2529. out([f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y)), 'm', f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y - ly)), f2(getHorizontalCoordinate(x + lx)), f2(getVerticalCoordinate(y - ry)), f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y - ry)), 'c'].join(' '));
  2530. out([f2(getHorizontalCoordinate(x - lx)), f2(getVerticalCoordinate(y - ry)), f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y - ly)), f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y)), 'c'].join(' '));
  2531. out([f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y + ly)), f2(getHorizontalCoordinate(x - lx)), f2(getVerticalCoordinate(y + ry)), f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y + ry)), 'c'].join(' '));
  2532. out([f2(getHorizontalCoordinate(x + lx)), f2(getVerticalCoordinate(y + ry)), f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y + ly)), f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y)), 'c'].join(' '));
  2533. if (style !== null) {
  2534. out(getStyle(style));
  2535. }
  2536. return this;
  2537. };
  2538. /**
  2539. * Adds an circle to PDF.
  2540. *
  2541. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2542. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2543. * @param {number} r Radius (in units declared at inception of PDF document).
  2544. * @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.
  2545. * @function
  2546. * @instance
  2547. * @returns {jsPDF}
  2548. * @memberOf jsPDF
  2549. * @name circle
  2550. */
  2551. var circle = API.__private__.circle = API.circle = function (x, y, r, style) {
  2552. if (isNaN(x) || isNaN(y) || isNaN(r) || !isValidStyle(style)) {
  2553. throw new Error('Invalid arguments passed to jsPDF.circle');
  2554. }
  2555. return this.ellipse(x, y, r, r, style);
  2556. };
  2557. /**
  2558. * Sets text font face, variant for upcoming text elements.
  2559. * See output of jsPDF.getFontList() for possible font names, styles.
  2560. *
  2561. * @param {string} fontName Font name or family. Example: "times".
  2562. * @param {string} fontStyle Font style or variant. Example: "italic".
  2563. * @function
  2564. * @instance
  2565. * @returns {jsPDF}
  2566. * @memberOf jsPDF
  2567. * @name setFont
  2568. */
  2569. API.setFont = function (fontName, fontStyle) {
  2570. activeFontKey = _getFont(fontName, fontStyle, {
  2571. disableWarning: false
  2572. });
  2573. return this;
  2574. };
  2575. /**
  2576. * Switches font style or variant for upcoming text elements,
  2577. * while keeping the font face or family same.
  2578. * See output of jsPDF.getFontList() for possible font names, styles.
  2579. *
  2580. * @param {string} style Font style or variant. Example: "italic".
  2581. * @function
  2582. * @instance
  2583. * @returns {jsPDF}
  2584. * @memberOf jsPDF
  2585. * @name setFontStyle
  2586. */
  2587. API.setFontStyle = API.setFontType = function (style) {
  2588. activeFontKey = _getFont(undefined, style); // if font is not found, the above line blows up and we never go further
  2589. return this;
  2590. };
  2591. /**
  2592. * Returns an object - a tree of fontName to fontStyle relationships available to
  2593. * active PDF document.
  2594. *
  2595. * @public
  2596. * @function
  2597. * @instance
  2598. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  2599. * @memberOf jsPDF
  2600. * @name getFontList
  2601. */
  2602. var getFontList = API.__private__.getFontList = API.getFontList = function () {
  2603. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  2604. var list = {},
  2605. fontName,
  2606. fontStyle,
  2607. tmp;
  2608. for (fontName in fontmap) {
  2609. if (fontmap.hasOwnProperty(fontName)) {
  2610. list[fontName] = tmp = [];
  2611. for (fontStyle in fontmap[fontName]) {
  2612. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  2613. tmp.push(fontStyle);
  2614. }
  2615. }
  2616. }
  2617. }
  2618. return list;
  2619. };
  2620. /**
  2621. * Add a custom font to the current instance.
  2622. *
  2623. * @property {string} postScriptName PDF specification full name for the font.
  2624. * @property {string} id PDF-document-instance-specific label assinged to the font.
  2625. * @property {string} fontStyle Style of the Font.
  2626. * @property {Object} encoding Encoding_name-to-Font_metrics_object mapping.
  2627. * @function
  2628. * @instance
  2629. * @memberOf jsPDF
  2630. * @name addFont
  2631. */
  2632. API.addFont = function (postScriptName, fontName, fontStyle, encoding) {
  2633. encoding = encoding || 'Identity-H';
  2634. addFont.call(this, postScriptName, fontName, fontStyle, encoding);
  2635. };
  2636. var lineWidth = options.lineWidth || 0.200025; // 2mm
  2637. /**
  2638. * Sets line width for upcoming lines.
  2639. *
  2640. * @param {number} width Line width (in units declared at inception of PDF document).
  2641. * @function
  2642. * @instance
  2643. * @returns {jsPDF}
  2644. * @memberOf jsPDF
  2645. * @name setLineWidth
  2646. */
  2647. var setLineWidth = API.__private__.setLineWidth = API.setLineWidth = function (width) {
  2648. out((width * k).toFixed(2) + ' w');
  2649. return this;
  2650. };
  2651. /**
  2652. * Sets the dash pattern for upcoming lines.
  2653. *
  2654. * To reset the settings simply call the method without any parameters.
  2655. * @param {array} dashArray The pattern of the line, expects numbers.
  2656. * @param {number} dashPhase The phase at which the dash pattern starts.
  2657. * @function
  2658. * @instance
  2659. * @returns {jsPDF}
  2660. * @memberOf jsPDF
  2661. * @name setLineDash
  2662. */
  2663. var setLineDash = API.__private__.setLineDash = jsPDF.API.setLineDash = function (dashArray, dashPhase) {
  2664. dashArray = dashArray || [];
  2665. dashPhase = dashPhase || 0;
  2666. if (isNaN(dashPhase) || !Array.isArray(dashArray)) {
  2667. throw new Error('Invalid arguments passed to jsPDF.setLineDash');
  2668. }
  2669. dashArray = dashArray.map(function (x) {
  2670. return (x * k).toFixed(3);
  2671. }).join(' ');
  2672. dashPhase = parseFloat((dashPhase * k).toFixed(3));
  2673. out('[' + dashArray + '] ' + dashPhase + ' d');
  2674. return this;
  2675. };
  2676. var lineHeightFactor;
  2677. var getLineHeight = API.__private__.getLineHeight = API.getLineHeight = function () {
  2678. return activeFontSize * lineHeightFactor;
  2679. };
  2680. var lineHeightFactor;
  2681. var getLineHeight = API.__private__.getLineHeight = API.getLineHeight = function () {
  2682. return activeFontSize * lineHeightFactor;
  2683. };
  2684. /**
  2685. * Sets the LineHeightFactor of proportion.
  2686. *
  2687. * @param {number} value LineHeightFactor value. Default: 1.15.
  2688. * @function
  2689. * @instance
  2690. * @returns {jsPDF}
  2691. * @memberOf jsPDF
  2692. * @name setLineHeightFactor
  2693. */
  2694. var setLineHeightFactor = API.__private__.setLineHeightFactor = API.setLineHeightFactor = function (value) {
  2695. value = value || 1.15;
  2696. if (typeof value === "number") {
  2697. lineHeightFactor = value;
  2698. }
  2699. return this;
  2700. };
  2701. /**
  2702. * Gets the LineHeightFactor, default: 1.15.
  2703. *
  2704. * @function
  2705. * @instance
  2706. * @returns {number} lineHeightFactor
  2707. * @memberOf jsPDF
  2708. * @name getLineHeightFactor
  2709. */
  2710. var getLineHeightFactor = API.__private__.getLineHeightFactor = API.getLineHeightFactor = function () {
  2711. return lineHeightFactor;
  2712. };
  2713. setLineHeightFactor(options.lineHeight);
  2714. var getHorizontalCoordinate = API.__private__.getHorizontalCoordinate = function (value) {
  2715. return value * k;
  2716. };
  2717. var getVerticalCoordinate = API.__private__.getVerticalCoordinate = function (value) {
  2718. return pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY - value * k;
  2719. };
  2720. var getHorizontalCoordinateString = API.__private__.getHorizontalCoordinateString = function (value) {
  2721. return f2(value * k);
  2722. };
  2723. var getVerticalCoordinateString = API.__private__.getVerticalCoordinateString = function (value) {
  2724. return f2(pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY - value * k);
  2725. };
  2726. var strokeColor = options.strokeColor || '0 G';
  2727. /**
  2728. * Gets the stroke color for upcoming elements.
  2729. *
  2730. * @function
  2731. * @instance
  2732. * @returns {string} colorAsHex
  2733. * @memberOf jsPDF
  2734. * @name getDrawColor
  2735. */
  2736. var getStrokeColor = API.__private__.getStrokeColor = API.getDrawColor = function () {
  2737. return decodeColorString(strokeColor);
  2738. };
  2739. /**
  2740. * Sets the stroke color for upcoming elements.
  2741. *
  2742. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2743. * color space is implied.
  2744. *
  2745. * When only ch1 is given, "Gray" color space is implied and it
  2746. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2747. * if values are communicated as String types, or in range from 0 (black)
  2748. * to 255 (white) if communicated as Number type.
  2749. * The RGB-like 0-255 range is provided for backward compatibility.
  2750. *
  2751. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2752. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2753. * (max intensity) if values are communicated as String types, or
  2754. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2755. * as Number types.
  2756. * The RGB-like 0-255 range is provided for backward compatibility.
  2757. *
  2758. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2759. * value must be a in the range from 0.00 (0% concentration) to to
  2760. * 1.00 (100% concentration)
  2761. *
  2762. * Because JavaScript treats fixed point numbers badly (rounds to
  2763. * floating point nearest to binary representation) it is highly advised to
  2764. * communicate the fractional numbers as String types, not JavaScript Number type.
  2765. *
  2766. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2767. * @param {Number|String} ch2 Color channel value.
  2768. * @param {Number|String} ch3 Color channel value.
  2769. * @param {Number|String} ch4 Color channel value.
  2770. *
  2771. * @function
  2772. * @instance
  2773. * @returns {jsPDF}
  2774. * @memberOf jsPDF
  2775. * @name setDrawColor
  2776. */
  2777. var setStrokeColor = API.__private__.setStrokeColor = API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  2778. var options = {
  2779. "ch1": ch1,
  2780. "ch2": ch2,
  2781. "ch3": ch3,
  2782. "ch4": ch4,
  2783. "pdfColorType": "draw",
  2784. "precision": 2
  2785. };
  2786. strokeColor = encodeColorString(options);
  2787. out(strokeColor);
  2788. return this;
  2789. };
  2790. var fillColor = options.fillColor || '0 g';
  2791. /**
  2792. * Gets the fill color for upcoming elements.
  2793. *
  2794. * @function
  2795. * @instance
  2796. * @returns {string} colorAsHex
  2797. * @memberOf jsPDF
  2798. * @name getFillColor
  2799. */
  2800. var getFillColor = API.__private__.getFillColor = API.getFillColor = function () {
  2801. return decodeColorString(fillColor);
  2802. };
  2803. /**
  2804. * Sets the fill color for upcoming elements.
  2805. *
  2806. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2807. * color space is implied.
  2808. *
  2809. * When only ch1 is given, "Gray" color space is implied and it
  2810. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2811. * if values are communicated as String types, or in range from 0 (black)
  2812. * to 255 (white) if communicated as Number type.
  2813. * The RGB-like 0-255 range is provided for backward compatibility.
  2814. *
  2815. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2816. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2817. * (max intensity) if values are communicated as String types, or
  2818. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2819. * as Number types.
  2820. * The RGB-like 0-255 range is provided for backward compatibility.
  2821. *
  2822. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2823. * value must be a in the range from 0.00 (0% concentration) to to
  2824. * 1.00 (100% concentration)
  2825. *
  2826. * Because JavaScript treats fixed point numbers badly (rounds to
  2827. * floating point nearest to binary representation) it is highly advised to
  2828. * communicate the fractional numbers as String types, not JavaScript Number type.
  2829. *
  2830. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2831. * @param {Number|String} ch2 Color channel value.
  2832. * @param {Number|String} ch3 Color channel value.
  2833. * @param {Number|String} ch4 Color channel value.
  2834. *
  2835. * @function
  2836. * @instance
  2837. * @returns {jsPDF}
  2838. * @memberOf jsPDF
  2839. * @name setFillColor
  2840. */
  2841. var setFillColor = API.__private__.setFillColor = API.setFillColor = function (ch1, ch2, ch3, ch4) {
  2842. var options = {
  2843. "ch1": ch1,
  2844. "ch2": ch2,
  2845. "ch3": ch3,
  2846. "ch4": ch4,
  2847. "pdfColorType": "fill",
  2848. "precision": 2
  2849. };
  2850. fillColor = encodeColorString(options);
  2851. out(fillColor);
  2852. return this;
  2853. };
  2854. var textColor = options.textColor || '0 g';
  2855. /**
  2856. * Gets the text color for upcoming elements.
  2857. *
  2858. * @function
  2859. * @instance
  2860. * @returns {string} colorAsHex
  2861. * @memberOf jsPDF
  2862. * @name getTextColor
  2863. */
  2864. var getTextColor = API.__private__.getTextColor = API.getTextColor = function () {
  2865. return decodeColorString(textColor);
  2866. };
  2867. /**
  2868. * Sets the text color for upcoming elements.
  2869. *
  2870. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2871. * color space is implied.
  2872. *
  2873. * When only ch1 is given, "Gray" color space is implied and it
  2874. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2875. * if values are communicated as String types, or in range from 0 (black)
  2876. * to 255 (white) if communicated as Number type.
  2877. * The RGB-like 0-255 range is provided for backward compatibility.
  2878. *
  2879. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2880. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2881. * (max intensity) if values are communicated as String types, or
  2882. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2883. * as Number types.
  2884. * The RGB-like 0-255 range is provided for backward compatibility.
  2885. *
  2886. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2887. * value must be a in the range from 0.00 (0% concentration) to to
  2888. * 1.00 (100% concentration)
  2889. *
  2890. * Because JavaScript treats fixed point numbers badly (rounds to
  2891. * floating point nearest to binary representation) it is highly advised to
  2892. * communicate the fractional numbers as String types, not JavaScript Number type.
  2893. *
  2894. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2895. * @param {Number|String} ch2 Color channel value.
  2896. * @param {Number|String} ch3 Color channel value.
  2897. * @param {Number|String} ch4 Color channel value.
  2898. *
  2899. * @function
  2900. * @instance
  2901. * @returns {jsPDF}
  2902. * @memberOf jsPDF
  2903. * @name setTextColor
  2904. */
  2905. var setTextColor = API.__private__.setTextColor = API.setTextColor = function (ch1, ch2, ch3, ch4) {
  2906. var options = {
  2907. "ch1": ch1,
  2908. "ch2": ch2,
  2909. "ch3": ch3,
  2910. "ch4": ch4,
  2911. "pdfColorType": "text",
  2912. "precision": 3
  2913. };
  2914. textColor = encodeColorString(options);
  2915. return this;
  2916. };
  2917. var activeCharSpace = options.charSpace || 0;
  2918. /**
  2919. * Get global value of CharSpace.
  2920. *
  2921. * @function
  2922. * @instance
  2923. * @returns {number} charSpace
  2924. * @memberOf jsPDF
  2925. * @name getCharSpace
  2926. */
  2927. var getCharSpace = API.__private__.getCharSpace = API.getCharSpace = function () {
  2928. return activeCharSpace;
  2929. };
  2930. /**
  2931. * Set global value of CharSpace.
  2932. *
  2933. * @param {number} charSpace
  2934. * @function
  2935. * @instance
  2936. * @returns {jsPDF} jsPDF-instance
  2937. * @memberOf jsPDF
  2938. * @name setCharSpace
  2939. */
  2940. var setCharSpace = API.__private__.setCharSpace = API.setCharSpace = function (charSpace) {
  2941. if (isNaN(charSpace)) {
  2942. throw new Error('Invalid argument passed to jsPDF.setCharSpace');
  2943. }
  2944. activeCharSpace = charSpace;
  2945. return this;
  2946. };
  2947. var lineCapID = 0;
  2948. /**
  2949. * Is an Object providing a mapping from human-readable to
  2950. * integer flag values designating the varieties of line cap
  2951. * and join styles.
  2952. *
  2953. * @memberOf jsPDF
  2954. * @name CapJoinStyles
  2955. */
  2956. API.CapJoinStyles = {
  2957. 0: 0,
  2958. 'butt': 0,
  2959. 'but': 0,
  2960. 'miter': 0,
  2961. 1: 1,
  2962. 'round': 1,
  2963. 'rounded': 1,
  2964. 'circle': 1,
  2965. 2: 2,
  2966. 'projecting': 2,
  2967. 'project': 2,
  2968. 'square': 2,
  2969. 'bevel': 2
  2970. };
  2971. /**
  2972. * Sets the line cap styles.
  2973. * See {jsPDF.CapJoinStyles} for variants.
  2974. *
  2975. * @param {String|Number} style A string or number identifying the type of line cap.
  2976. * @function
  2977. * @instance
  2978. * @returns {jsPDF}
  2979. * @memberOf jsPDF
  2980. * @name setLineCap
  2981. */
  2982. var setLineCap = API.__private__.setLineCap = API.setLineCap = function (style) {
  2983. var id = API.CapJoinStyles[style];
  2984. if (id === undefined) {
  2985. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2986. }
  2987. lineCapID = id;
  2988. out(id + ' J');
  2989. return this;
  2990. };
  2991. var lineJoinID = 0;
  2992. /**
  2993. * Sets the line join styles.
  2994. * See {jsPDF.CapJoinStyles} for variants.
  2995. *
  2996. * @param {String|Number} style A string or number identifying the type of line join.
  2997. * @function
  2998. * @instance
  2999. * @returns {jsPDF}
  3000. * @memberOf jsPDF
  3001. * @name setLineJoin
  3002. */
  3003. var setLineJoin = API.__private__.setLineJoin = API.setLineJoin = function (style) {
  3004. var id = API.CapJoinStyles[style];
  3005. if (id === undefined) {
  3006. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  3007. }
  3008. lineJoinID = id;
  3009. out(id + ' j');
  3010. return this;
  3011. };
  3012. var miterLimit;
  3013. /**
  3014. * Sets the miterLimit property, which effects the maximum miter length.
  3015. *
  3016. * @param {number} length The length of the miter
  3017. * @function
  3018. * @instance
  3019. * @returns {jsPDF}
  3020. * @memberOf jsPDF
  3021. * @name setMiterLimit
  3022. */
  3023. var setMiterLimit = API.__private__.setMiterLimit = API.setMiterLimit = function (length) {
  3024. length = length || 0;
  3025. if (isNaN(length)) {
  3026. throw new Error('Invalid argument passed to jsPDF.setMiterLimit');
  3027. }
  3028. miterLimit = parseFloat(f2(length * k));
  3029. out(miterLimit + ' M');
  3030. return this;
  3031. };
  3032. /**
  3033. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').
  3034. * Uses FileSaver.js-method saveAs.
  3035. *
  3036. * @memberOf jsPDF
  3037. * @name save
  3038. * @function
  3039. * @instance
  3040. * @param {string} filename The filename including extension.
  3041. * @param {Object} options An Object with additional options, possible options: 'returnPromise'.
  3042. * @returns {jsPDF} jsPDF-instance
  3043. */
  3044. API.save = function (filename, options) {
  3045. filename = filename || 'generated.pdf';
  3046. options = options || {};
  3047. options.returnPromise = options.returnPromise || false;
  3048. if (options.returnPromise === false) {
  3049. saveAs(getBlob(buildDocument()), filename);
  3050. if (typeof saveAs.unload === 'function') {
  3051. if (global.setTimeout) {
  3052. setTimeout(saveAs.unload, 911);
  3053. }
  3054. }
  3055. } else {
  3056. return new Promise(function (resolve, reject) {
  3057. try {
  3058. var result = saveAs(getBlob(buildDocument()), filename);
  3059. if (typeof saveAs.unload === 'function') {
  3060. if (global.setTimeout) {
  3061. setTimeout(saveAs.unload, 911);
  3062. }
  3063. }
  3064. resolve(result);
  3065. } catch (e) {
  3066. reject(e.message);
  3067. }
  3068. });
  3069. }
  3070. }; // applying plugins (more methods) ON TOP of built-in API.
  3071. // this is intentional as we allow plugins to override
  3072. // built-ins
  3073. for (var plugin in jsPDF.API) {
  3074. if (jsPDF.API.hasOwnProperty(plugin)) {
  3075. if (plugin === 'events' && jsPDF.API.events.length) {
  3076. (function (events, newEvents) {
  3077. // jsPDF.API.events is a JS Array of Arrays
  3078. // where each Array is a pair of event name, handler
  3079. // Events were added by plugins to the jsPDF instantiator.
  3080. // These are always added to the new instance and some ran
  3081. // during instantiation.
  3082. var eventname, handler_and_args, i;
  3083. for (i = newEvents.length - 1; i !== -1; i--) {
  3084. // subscribe takes 3 args: 'topic', function, runonce_flag
  3085. // if undefined, runonce is false.
  3086. // users can attach callback directly,
  3087. // or they can attach an array with [callback, runonce_flag]
  3088. // that's what the "apply" magic is for below.
  3089. eventname = newEvents[i][0];
  3090. handler_and_args = newEvents[i][1];
  3091. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  3092. }
  3093. })(events, jsPDF.API.events);
  3094. } else {
  3095. API[plugin] = jsPDF.API[plugin];
  3096. }
  3097. }
  3098. }
  3099. /**
  3100. * Object exposing internal API to plugins
  3101. * @public
  3102. * @ignore
  3103. */
  3104. API.internal = {
  3105. 'pdfEscape': pdfEscape,
  3106. 'getStyle': getStyle,
  3107. 'getFont': function getFont() {
  3108. return fonts[_getFont.apply(API, arguments)];
  3109. },
  3110. 'getFontSize': getFontSize,
  3111. 'getCharSpace': getCharSpace,
  3112. 'getTextColor': getTextColor,
  3113. 'getLineHeight': getLineHeight,
  3114. 'getLineHeightFactor': getLineHeightFactor,
  3115. 'write': write,
  3116. 'getHorizontalCoordinate': getHorizontalCoordinate,
  3117. 'getVerticalCoordinate': getVerticalCoordinate,
  3118. 'getCoordinateString': getHorizontalCoordinateString,
  3119. 'getVerticalCoordinateString': getVerticalCoordinateString,
  3120. 'collections': {},
  3121. 'newObject': newObject,
  3122. 'newAdditionalObject': newAdditionalObject,
  3123. 'newObjectDeferred': newObjectDeferred,
  3124. 'newObjectDeferredBegin': newObjectDeferredBegin,
  3125. 'getFilters': getFilters,
  3126. 'putStream': putStream,
  3127. 'events': events,
  3128. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  3129. // units of measurement.
  3130. // scaleFactor is set at initialization of the document and calculated against the stated
  3131. // default measurement units for the document.
  3132. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  3133. // through multiplication.
  3134. 'scaleFactor': k,
  3135. 'pageSize': {
  3136. getWidth: function getWidth() {
  3137. return (pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX) / k;
  3138. },
  3139. setWidth: function setWidth(value) {
  3140. pagesContext[currentPage].mediaBox.topRightX = value * k + pagesContext[currentPage].mediaBox.bottomLeftX;
  3141. },
  3142. getHeight: function getHeight() {
  3143. return (pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY) / k;
  3144. },
  3145. setHeight: function setHeight(value) {
  3146. pagesContext[currentPage].mediaBox.topRightY = value * k + pagesContext[currentPage].mediaBox.bottomLeftY;
  3147. }
  3148. },
  3149. 'output': output,
  3150. 'getNumberOfPages': getNumberOfPages,
  3151. 'pages': pages,
  3152. 'out': out,
  3153. 'f2': f2,
  3154. 'f3': f3,
  3155. 'getPageInfo': getPageInfo,
  3156. 'getPageInfoByObjId': getPageInfoByObjId,
  3157. 'getCurrentPageInfo': getCurrentPageInfo,
  3158. 'getPDFVersion': getPdfVersion,
  3159. 'hasHotfix': hasHotfix //Expose the hasHotfix check so plugins can also check them.
  3160. };
  3161. Object.defineProperty(API.internal.pageSize, 'width', {
  3162. get: function get() {
  3163. return (pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX) / k;
  3164. },
  3165. set: function set(value) {
  3166. pagesContext[currentPage].mediaBox.topRightX = value * k + pagesContext[currentPage].mediaBox.bottomLeftX;
  3167. },
  3168. enumerable: true,
  3169. configurable: true
  3170. });
  3171. Object.defineProperty(API.internal.pageSize, 'height', {
  3172. get: function get() {
  3173. return (pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY) / k;
  3174. },
  3175. set: function set(value) {
  3176. pagesContext[currentPage].mediaBox.topRightY = value * k + pagesContext[currentPage].mediaBox.bottomLeftY;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. }); //////////////////////////////////////////////////////
  3181. // continuing initialization of jsPDF Document object
  3182. //////////////////////////////////////////////////////
  3183. // Add the first page automatically
  3184. addFonts(standardFonts);
  3185. activeFontKey = 'F1';
  3186. _addPage(format, orientation);
  3187. events.publish('initialized');
  3188. return API;
  3189. }
  3190. /**
  3191. * jsPDF.API is a STATIC property of jsPDF class.
  3192. * jsPDF.API is an object you can add methods and properties to.
  3193. * The methods / properties you add will show up in new jsPDF objects.
  3194. *
  3195. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  3196. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  3197. *
  3198. * @static
  3199. * @public
  3200. * @memberOf jsPDF
  3201. * @name API
  3202. *
  3203. * @example
  3204. * jsPDF.API.mymethod = function(){
  3205. * // 'this' will be ref to internal API object. see jsPDF source
  3206. * // , so you can refer to built-in methods like so:
  3207. * // this.line(....)
  3208. * // this.text(....)
  3209. * }
  3210. * var pdfdoc = new jsPDF()
  3211. * pdfdoc.mymethod() // <- !!!!!!
  3212. */
  3213. jsPDF.API = {
  3214. events: []
  3215. };
  3216. /**
  3217. * The version of jsPDF.
  3218. * @name version
  3219. * @type {string}
  3220. * @memberOf jsPDF
  3221. */
  3222. jsPDF.version = '1.5.3';
  3223. if (typeof define === 'function' && define.amd) {
  3224. define('jsPDF', function () {
  3225. return jsPDF;
  3226. });
  3227. } else if (typeof module !== 'undefined' && module.exports) {
  3228. module.exports = jsPDF;
  3229. module.exports.jsPDF = jsPDF;
  3230. } else {
  3231. global.jsPDF = jsPDF;
  3232. }
  3233. return jsPDF;
  3234. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  3235. // while `this` is nsIContentFrameMessageManager
  3236. // with an attribute `content` that corresponds to the window
  3237. /*rollup-keeper-start*/
  3238. window.tmp = jsPDF;
  3239. /*rollup-keeper-end*/
  3240. /**
  3241. * @license
  3242. * Copyright (c) 2016 Alexander Weidt,
  3243. * https://github.com/BiggA94
  3244. *
  3245. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  3246. */
  3247. /**
  3248. * jsPDF AcroForm Plugin
  3249. * @module AcroForm
  3250. */
  3251. (function (jsPDFAPI, globalObj) {
  3252. var scope;
  3253. var scaleFactor = 1;
  3254. var pdfEscape = function pdfEscape(value) {
  3255. return value.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  3256. };
  3257. var pdfUnescape = function pdfUnescape(value) {
  3258. return value.replace(/\\\\/g, '\\').replace(/\\\(/g, '(').replace(/\\\)/g, ')');
  3259. };
  3260. var f2 = function f2(number) {
  3261. if (isNaN(number)) {
  3262. throw new Error('Invalid argument passed to jsPDF.f2');
  3263. }
  3264. return number.toFixed(2); // Ie, %.2f
  3265. };
  3266. var f5 = function f5(number) {
  3267. if (isNaN(number)) {
  3268. throw new Error('Invalid argument passed to jsPDF.f2');
  3269. }
  3270. return number.toFixed(5); // Ie, %.2f
  3271. };
  3272. jsPDFAPI.__acroform__ = {};
  3273. var inherit = function inherit(child, parent) {
  3274. child.prototype = Object.create(parent.prototype);
  3275. child.prototype.constructor = child;
  3276. };
  3277. var scale = function scale(x) {
  3278. return x * scaleFactor;
  3279. };
  3280. var antiScale = function antiScale(x) {
  3281. return x / scaleFactor;
  3282. };
  3283. var createFormXObject = function createFormXObject(formObject) {
  3284. var xobj = new AcroFormXObject();
  3285. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  3286. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  3287. xobj.BBox = [0, 0, Number(f2(width)), Number(f2(height))];
  3288. return xobj;
  3289. };
  3290. /**
  3291. * Bit-Operations
  3292. */
  3293. var setBit = jsPDFAPI.__acroform__.setBit = function (number, bitPosition) {
  3294. number = number || 0;
  3295. bitPosition = bitPosition || 0;
  3296. if (isNaN(number) || isNaN(bitPosition)) {
  3297. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.setBit');
  3298. }
  3299. var bitMask = 1 << bitPosition;
  3300. number |= bitMask;
  3301. return number;
  3302. };
  3303. var clearBit = jsPDFAPI.__acroform__.clearBit = function (number, bitPosition) {
  3304. number = number || 0;
  3305. bitPosition = bitPosition || 0;
  3306. if (isNaN(number) || isNaN(bitPosition)) {
  3307. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.clearBit');
  3308. }
  3309. var bitMask = 1 << bitPosition;
  3310. number &= ~bitMask;
  3311. return number;
  3312. };
  3313. var getBit = jsPDFAPI.__acroform__.getBit = function (number, bitPosition) {
  3314. if (isNaN(number) || isNaN(bitPosition)) {
  3315. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.getBit');
  3316. }
  3317. return (number & 1 << bitPosition) === 0 ? 0 : 1;
  3318. };
  3319. /*
  3320. * Ff starts counting the bit position at 1 and not like javascript at 0
  3321. */
  3322. var getBitForPdf = jsPDFAPI.__acroform__.getBitForPdf = function (number, bitPosition) {
  3323. if (isNaN(number) || isNaN(bitPosition)) {
  3324. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.getBitForPdf');
  3325. }
  3326. return getBit(number, bitPosition - 1);
  3327. };
  3328. var setBitForPdf = jsPDFAPI.__acroform__.setBitForPdf = function (number, bitPosition) {
  3329. if (isNaN(number) || isNaN(bitPosition)) {
  3330. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.setBitForPdf');
  3331. }
  3332. return setBit(number, bitPosition - 1);
  3333. };
  3334. var clearBitForPdf = jsPDFAPI.__acroform__.clearBitForPdf = function (number, bitPosition, value) {
  3335. if (isNaN(number) || isNaN(bitPosition)) {
  3336. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.clearBitForPdf');
  3337. }
  3338. return clearBit(number, bitPosition - 1);
  3339. };
  3340. var calculateCoordinates = jsPDFAPI.__acroform__.calculateCoordinates = function (args) {
  3341. var getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
  3342. var getVerticalCoordinate = this.internal.getVerticalCoordinate;
  3343. var x = args[0];
  3344. var y = args[1];
  3345. var w = args[2];
  3346. var h = args[3];
  3347. var coordinates = {};
  3348. coordinates.lowerLeft_X = getHorizontalCoordinate(x) || 0;
  3349. coordinates.lowerLeft_Y = getVerticalCoordinate(y + h) || 0;
  3350. coordinates.upperRight_X = getHorizontalCoordinate(x + w) || 0;
  3351. coordinates.upperRight_Y = getVerticalCoordinate(y) || 0;
  3352. return [Number(f2(coordinates.lowerLeft_X)), Number(f2(coordinates.lowerLeft_Y)), Number(f2(coordinates.upperRight_X)), Number(f2(coordinates.upperRight_Y))];
  3353. };
  3354. var calculateAppearanceStream = function calculateAppearanceStream(formObject) {
  3355. if (formObject.appearanceStreamContent) {
  3356. return formObject.appearanceStreamContent;
  3357. }
  3358. if (!formObject.V && !formObject.DV) {
  3359. return;
  3360. } // else calculate it
  3361. var stream = [];
  3362. var text = formObject.V || formObject.DV;
  3363. var calcRes = calculateX(formObject, text);
  3364. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id; //PDF 32000-1:2008, page 444
  3365. stream.push('/Tx BMC');
  3366. stream.push('q');
  3367. stream.push('BT'); // Begin Text
  3368. stream.push(scope.__private__.encodeColorString(formObject.color));
  3369. stream.push('/' + fontKey + ' ' + f2(calcRes.fontSize) + ' Tf');
  3370. stream.push('1 0 0 1 0 0 Tm'); // Transformation Matrix
  3371. stream.push(calcRes.text);
  3372. stream.push('ET'); // End Text
  3373. stream.push('Q');
  3374. stream.push('EMC');
  3375. var appearanceStreamContent = new createFormXObject(formObject);
  3376. appearanceStreamContent.stream = stream.join("\n");
  3377. return appearanceStreamContent;
  3378. };
  3379. var calculateX = function calculateX(formObject, text) {
  3380. var maxFontSize = formObject.maxFontSize || 12;
  3381. var font = formObject.fontName;
  3382. var returnValue = {
  3383. text: "",
  3384. fontSize: ""
  3385. }; // Remove Brackets
  3386. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  3387. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text; // split into array of words
  3388. var textSplit = text.split(' ');
  3389. var color = scope.__private__.encodeColorString(formObject.color);
  3390. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3391. var lineSpacing = 2;
  3392. var borderPadding = 2;
  3393. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  3394. height = height < 0 ? -height : height;
  3395. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  3396. width = width < 0 ? -width : width;
  3397. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3398. if (i + 1 < textSplit.length) {
  3399. var tmp = lastLine + " " + textSplit[i + 1];
  3400. var TextWidth = calculateFontSpace(tmp, formObject, fontSize).width;
  3401. var FieldWidth = width - 2 * borderPadding;
  3402. return TextWidth <= FieldWidth;
  3403. } else {
  3404. return false;
  3405. }
  3406. };
  3407. fontSize++;
  3408. FontSize: while (true) {
  3409. var text = "";
  3410. fontSize--;
  3411. var textHeight = calculateFontSpace("3", formObject, fontSize).height;
  3412. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3413. startY += lineSpacing;
  3414. var startX = -borderPadding;
  3415. var lastY = startY;
  3416. var firstWordInLine = 0,
  3417. lastWordInLine = 0;
  3418. var lastLength = 0;
  3419. if (fontSize <= 0) {
  3420. // In case, the Text doesn't fit at all
  3421. fontSize = 12;
  3422. text = "(...) Tj\n";
  3423. text += "% Width of Text: " + calculateFontSpace(text, formObject, fontSize).width + ", FieldWidth:" + width + "\n";
  3424. break;
  3425. }
  3426. lastLength = calculateFontSpace(textSplit[0] + " ", formObject, fontSize).width;
  3427. var lastLine = "";
  3428. var lineCount = 0;
  3429. Line: for (var i in textSplit) {
  3430. if (textSplit.hasOwnProperty(i)) {
  3431. lastLine += textSplit[i] + " "; // Remove last blank
  3432. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3433. var key = parseInt(i);
  3434. lastLength = calculateFontSpace(lastLine + " ", formObject, fontSize).width;
  3435. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3436. var isLastWord = i >= textSplit.length - 1;
  3437. if (nextLineIsSmaller && !isLastWord) {
  3438. lastLine += " ";
  3439. continue; // Line
  3440. } else if (!nextLineIsSmaller && !isLastWord) {
  3441. if (!formObject.multiline) {
  3442. continue FontSize;
  3443. } else {
  3444. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3445. // If the Text is higher than the
  3446. // FieldObject
  3447. continue FontSize;
  3448. }
  3449. lastWordInLine = key; // go on
  3450. }
  3451. } else if (isLastWord) {
  3452. lastWordInLine = key;
  3453. } else {
  3454. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3455. // If the Text is higher than the FieldObject
  3456. continue FontSize;
  3457. }
  3458. }
  3459. var line = '';
  3460. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3461. line += textSplit[x] + ' ';
  3462. } // Remove last blank
  3463. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line; // lastLength -= blankSpace.width;
  3464. lastLength = calculateFontSpace(line, formObject, fontSize).width; // Calculate startX
  3465. switch (formObject.textAlign) {
  3466. case 'right':
  3467. startX = width - lastLength - borderPadding;
  3468. break;
  3469. case 'center':
  3470. startX = (width - lastLength) / 2;
  3471. break;
  3472. case 'left':
  3473. default:
  3474. startX = borderPadding;
  3475. break;
  3476. }
  3477. text += f2(startX) + ' ' + f2(lastY) + ' Td\n';
  3478. text += '(' + pdfEscape(line) + ') Tj\n'; // reset X in PDF
  3479. text += -f2(startX) + ' 0 Td\n'; // After a Line, adjust y position
  3480. lastY = -(fontSize + lineSpacing);
  3481. lastLength = 0;
  3482. firstWordInLine = lastWordInLine + 1;
  3483. lineCount++;
  3484. lastLine = "";
  3485. continue Line;
  3486. }
  3487. }
  3488. break;
  3489. }
  3490. returnValue.text = text;
  3491. returnValue.fontSize = fontSize;
  3492. return returnValue;
  3493. };
  3494. /**
  3495. * Small workaround for calculating the TextMetric approximately.
  3496. *
  3497. * @param text
  3498. * @param fontsize
  3499. * @returns {TextMetrics} (Has Height and Width)
  3500. */
  3501. var calculateFontSpace = function calculateFontSpace(text, formObject, fontSize) {
  3502. var font = scope.internal.getFont(formObject.fontName, formObject.fontStyle);
  3503. var width = scope.getStringUnitWidth(text, {
  3504. font: font,
  3505. fontSize: parseFloat(fontSize),
  3506. charSpace: 0
  3507. }) * parseFloat(fontSize);
  3508. var height = scope.getStringUnitWidth("3", {
  3509. font: font,
  3510. fontSize: parseFloat(fontSize),
  3511. charSpace: 0
  3512. }) * parseFloat(fontSize) * 1.5;
  3513. return {
  3514. height: height,
  3515. width: width
  3516. };
  3517. };
  3518. var acroformPluginTemplate = {
  3519. fields: [],
  3520. xForms: [],
  3521. /**
  3522. * acroFormDictionaryRoot contains information about the AcroForm
  3523. * Dictionary 0: The Event-Token, the AcroFormDictionaryCallback has
  3524. * 1: The Object ID of the Root
  3525. */
  3526. acroFormDictionaryRoot: null,
  3527. /**
  3528. * After the PDF gets evaluated, the reference to the root has to be
  3529. * reset, this indicates, whether the root has already been printed
  3530. * out
  3531. */
  3532. printedOut: false,
  3533. internal: null,
  3534. isInitialized: false
  3535. };
  3536. var annotReferenceCallback = function annotReferenceCallback() {
  3537. //set objId to undefined and force it to get a new objId on buildDocument
  3538. scope.internal.acroformPlugin.acroFormDictionaryRoot.objId = undefined;
  3539. var fields = scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields;
  3540. for (var i in fields) {
  3541. if (fields.hasOwnProperty(i)) {
  3542. var formObject = fields[i]; //set objId to undefined and force it to get a new objId on buildDocument
  3543. formObject.objId = undefined; // add Annot Reference!
  3544. if (formObject.hasAnnotation) {
  3545. // If theres an Annotation Widget in the Form Object, put the
  3546. // Reference in the /Annot array
  3547. createAnnotationReference.call(scope, formObject);
  3548. }
  3549. }
  3550. }
  3551. };
  3552. var putForm = function putForm(formObject) {
  3553. if (scope.internal.acroformPlugin.printedOut) {
  3554. scope.internal.acroformPlugin.printedOut = false;
  3555. scope.internal.acroformPlugin.acroFormDictionaryRoot = null;
  3556. }
  3557. if (!scope.internal.acroformPlugin.acroFormDictionaryRoot) {
  3558. initializeAcroForm.call(scope);
  3559. }
  3560. scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  3561. };
  3562. /**
  3563. * Create the Reference to the widgetAnnotation, so that it gets referenced
  3564. * in the Annot[] int the+ (Requires the Annotation Plugin)
  3565. */
  3566. var createAnnotationReference = function createAnnotationReference(object) {
  3567. var options = {
  3568. type: 'reference',
  3569. object: object
  3570. };
  3571. var findEntry = function findEntry(entry) {
  3572. return entry.type === options.type && entry.object === options.object;
  3573. };
  3574. if (scope.internal.getPageInfo(object.page).pageContext.annotations.find(findEntry) === undefined) {
  3575. scope.internal.getPageInfo(object.page).pageContext.annotations.push(options);
  3576. }
  3577. }; // Callbacks
  3578. var putCatalogCallback = function putCatalogCallback() {
  3579. // Put reference to AcroForm to DocumentCatalog
  3580. if (typeof scope.internal.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  3581. // for safety, shouldn't normally be the case
  3582. scope.internal.write('/AcroForm ' + scope.internal.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  3583. } else {
  3584. throw new Error('putCatalogCallback: Root missing.');
  3585. }
  3586. };
  3587. /**
  3588. * Adds /Acroform X 0 R to Document Catalog, and creates the AcroForm
  3589. * Dictionary
  3590. */
  3591. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  3592. // Remove event
  3593. scope.internal.events.unsubscribe(scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID);
  3594. delete scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID;
  3595. scope.internal.acroformPlugin.printedOut = true;
  3596. };
  3597. /**
  3598. * Creates the single Fields and writes them into the Document
  3599. *
  3600. * If fieldArray is set, use the fields that are inside it instead of the
  3601. * fields from the AcroRoot (for the FormXObjects...)
  3602. */
  3603. var createFieldCallback = function createFieldCallback(fieldArray) {
  3604. var standardFields = !fieldArray;
  3605. if (!fieldArray) {
  3606. // in case there is no fieldArray specified, we want to print out
  3607. // the Fields of the AcroForm
  3608. // Print out Root
  3609. scope.internal.newObjectDeferredBegin(scope.internal.acroformPlugin.acroFormDictionaryRoot.objId, true);
  3610. scope.internal.acroformPlugin.acroFormDictionaryRoot.putStream();
  3611. }
  3612. var fieldArray = fieldArray || scope.internal.acroformPlugin.acroFormDictionaryRoot.Kids;
  3613. for (var i in fieldArray) {
  3614. if (fieldArray.hasOwnProperty(i)) {
  3615. var fieldObject = fieldArray[i];
  3616. var keyValueList = [];
  3617. var oldRect = fieldObject.Rect;
  3618. if (fieldObject.Rect) {
  3619. fieldObject.Rect = calculateCoordinates.call(this, fieldObject.Rect);
  3620. } // Start Writing the Object
  3621. scope.internal.newObjectDeferredBegin(fieldObject.objId, true);
  3622. fieldObject.DA = AcroFormAppearance.createDefaultAppearanceStream(fieldObject);
  3623. if (_typeof(fieldObject) === "object" && typeof fieldObject.getKeyValueListForStream === "function") {
  3624. keyValueList = fieldObject.getKeyValueListForStream();
  3625. }
  3626. fieldObject.Rect = oldRect;
  3627. if (fieldObject.hasAppearanceStream && !fieldObject.appearanceStreamContent) {
  3628. // Calculate Appearance
  3629. var appearance = calculateAppearanceStream.call(this, fieldObject);
  3630. keyValueList.push({
  3631. key: 'AP',
  3632. value: "<</N " + appearance + ">>"
  3633. });
  3634. scope.internal.acroformPlugin.xForms.push(appearance);
  3635. } // Assume AppearanceStreamContent is a Array with N,R,D (at least
  3636. // one of them!)
  3637. if (fieldObject.appearanceStreamContent) {
  3638. var appearanceStreamString = ""; // Iterate over N,R and D
  3639. for (var k in fieldObject.appearanceStreamContent) {
  3640. if (fieldObject.appearanceStreamContent.hasOwnProperty(k)) {
  3641. var value = fieldObject.appearanceStreamContent[k];
  3642. appearanceStreamString += "/" + k + " ";
  3643. appearanceStreamString += "<<";
  3644. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  3645. // appearanceStream is an Array or Object!
  3646. for (var i in value) {
  3647. if (value.hasOwnProperty(i)) {
  3648. var obj = value[i];
  3649. if (typeof obj === 'function') {
  3650. // if Function is referenced, call it in order
  3651. // to get the FormXObject
  3652. obj = obj.call(this, fieldObject);
  3653. }
  3654. appearanceStreamString += "/" + i + " " + obj + " "; // In case the XForm is already used, e.g. OffState
  3655. // of CheckBoxes, don't add it
  3656. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  3657. }
  3658. }
  3659. } else {
  3660. var obj = value;
  3661. if (typeof obj === 'function') {
  3662. // if Function is referenced, call it in order to
  3663. // get the FormXObject
  3664. obj = obj.call(this, fieldObject);
  3665. }
  3666. appearanceStreamString += "/" + i + " " + obj;
  3667. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  3668. }
  3669. appearanceStreamString += ">>";
  3670. }
  3671. } // appearance stream is a normal Object..
  3672. keyValueList.push({
  3673. key: 'AP',
  3674. value: "<<\n" + appearanceStreamString + ">>"
  3675. });
  3676. }
  3677. scope.internal.putStream({
  3678. additionalKeyValues: keyValueList
  3679. });
  3680. scope.internal.out("endobj");
  3681. }
  3682. }
  3683. if (standardFields) {
  3684. createXFormObjectCallback.call(this, scope.internal.acroformPlugin.xForms);
  3685. }
  3686. };
  3687. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  3688. for (var i in fieldArray) {
  3689. if (fieldArray.hasOwnProperty(i)) {
  3690. var key = i;
  3691. var fieldObject = fieldArray[i]; // Start Writing the Object
  3692. scope.internal.newObjectDeferredBegin(fieldObject && fieldObject.objId, true);
  3693. if (_typeof(fieldObject) === "object" && typeof fieldObject.putStream === "function") {
  3694. fieldObject.putStream();
  3695. }
  3696. delete fieldArray[key];
  3697. }
  3698. }
  3699. };
  3700. var initializeAcroForm = function initializeAcroForm() {
  3701. if (this.internal !== undefined && (this.internal.acroformPlugin === undefined || this.internal.acroformPlugin.isInitialized === false)) {
  3702. scope = this;
  3703. AcroFormField.FieldNum = 0;
  3704. this.internal.acroformPlugin = JSON.parse(JSON.stringify(acroformPluginTemplate));
  3705. if (this.internal.acroformPlugin.acroFormDictionaryRoot) {
  3706. throw new Error("Exception while creating AcroformDictionary");
  3707. }
  3708. scaleFactor = scope.internal.scaleFactor; // The Object Number of the AcroForm Dictionary
  3709. scope.internal.acroformPlugin.acroFormDictionaryRoot = new AcroFormDictionary(); // add Callback for creating the AcroForm Dictionary
  3710. scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID = scope.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  3711. scope.internal.events.subscribe('buildDocument', annotReferenceCallback); // buildDocument
  3712. // Register event, that is triggered when the DocumentCatalog is
  3713. // written, in order to add /AcroForm
  3714. scope.internal.events.subscribe('putCatalog', putCatalogCallback); // Register event, that creates all Fields
  3715. scope.internal.events.subscribe('postPutPages', createFieldCallback);
  3716. scope.internal.acroformPlugin.isInitialized = true;
  3717. }
  3718. }; //PDF 32000-1:2008, page 26, 7.3.6
  3719. var arrayToPdfArray = jsPDFAPI.__acroform__.arrayToPdfArray = function (array) {
  3720. if (Array.isArray(array)) {
  3721. var content = '[';
  3722. for (var i = 0; i < array.length; i++) {
  3723. if (i !== 0) {
  3724. content += ' ';
  3725. }
  3726. switch (_typeof(array[i])) {
  3727. case 'boolean':
  3728. case 'number':
  3729. case 'object':
  3730. content += array[i].toString();
  3731. break;
  3732. case 'string':
  3733. if (array[i].substr(0, 1) !== '/') {
  3734. content += '(' + pdfEscape(array[i].toString()) + ')';
  3735. } else {
  3736. content += array[i].toString();
  3737. }
  3738. break;
  3739. }
  3740. }
  3741. content += ']';
  3742. return content;
  3743. }
  3744. throw new Error('Invalid argument passed to jsPDF.__acroform__.arrayToPdfArray');
  3745. };
  3746. function getMatches(string, regex, index) {
  3747. index || (index = 1); // default to the first capturing group
  3748. var matches = [];
  3749. var match;
  3750. while (match = regex.exec(string)) {
  3751. matches.push(match[index]);
  3752. }
  3753. return matches;
  3754. }
  3755. var pdfArrayToStringArray = function pdfArrayToStringArray(array) {
  3756. var result = [];
  3757. if (typeof array === "string") {
  3758. result = getMatches(array, /\((.*?)\)/g);
  3759. }
  3760. return result;
  3761. };
  3762. var toPdfString = function toPdfString(string) {
  3763. string = string || "";
  3764. string.toString();
  3765. string = '(' + pdfEscape(string) + ')';
  3766. return string;
  3767. }; // ##########################
  3768. // Classes
  3769. // ##########################
  3770. /**
  3771. * @class AcroFormPDFObject
  3772. * @classdesc A AcroFormPDFObject
  3773. */
  3774. var AcroFormPDFObject = function AcroFormPDFObject() {
  3775. var _objId;
  3776. /** *
  3777. * @name AcroFormPDFObject#objId
  3778. * @type {any}
  3779. */
  3780. Object.defineProperty(this, 'objId', {
  3781. configurable: true,
  3782. get: function get() {
  3783. if (!_objId) {
  3784. _objId = scope.internal.newObjectDeferred();
  3785. }
  3786. if (!_objId) {
  3787. throw new Error("AcroFormPDFObject: Couldn't create Object ID");
  3788. }
  3789. return _objId;
  3790. },
  3791. set: function set(value) {
  3792. _objId = value;
  3793. }
  3794. });
  3795. };
  3796. /**
  3797. * @function AcroFormPDFObject.toString
  3798. */
  3799. AcroFormPDFObject.prototype.toString = function () {
  3800. return this.objId + " 0 R";
  3801. };
  3802. AcroFormPDFObject.prototype.putStream = function () {
  3803. var keyValueList = this.getKeyValueListForStream();
  3804. scope.internal.putStream({
  3805. data: this.stream,
  3806. additionalKeyValues: keyValueList
  3807. });
  3808. scope.internal.out("endobj");
  3809. };
  3810. /**
  3811. * Returns an key-value-List of all non-configurable Variables from the Object
  3812. *
  3813. * @name getKeyValueListForStream
  3814. * @returns {string}
  3815. */
  3816. AcroFormPDFObject.prototype.getKeyValueListForStream = function () {
  3817. var createKeyValueListFromFieldObject = function createKeyValueListFromFieldObject(fieldObject) {
  3818. var keyValueList = [];
  3819. var keys = Object.getOwnPropertyNames(fieldObject).filter(function (key) {
  3820. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  3821. });
  3822. for (var i in keys) {
  3823. if (Object.getOwnPropertyDescriptor(fieldObject, keys[i]).configurable === false) {
  3824. var key = keys[i];
  3825. var value = fieldObject[key];
  3826. if (value) {
  3827. if (Array.isArray(value)) {
  3828. keyValueList.push({
  3829. key: key,
  3830. value: arrayToPdfArray(value)
  3831. });
  3832. } else if (value instanceof AcroFormPDFObject) {
  3833. // In case it is a reference to another PDFObject,
  3834. // take the reference number
  3835. keyValueList.push({
  3836. key: key,
  3837. value: value.objId + " 0 R"
  3838. });
  3839. } else if (typeof value !== "function") {
  3840. keyValueList.push({
  3841. key: key,
  3842. value: value
  3843. });
  3844. }
  3845. }
  3846. }
  3847. }
  3848. return keyValueList;
  3849. };
  3850. return createKeyValueListFromFieldObject(this);
  3851. };
  3852. var AcroFormXObject = function AcroFormXObject() {
  3853. AcroFormPDFObject.call(this);
  3854. Object.defineProperty(this, 'Type', {
  3855. value: "/XObject",
  3856. configurable: false,
  3857. writeable: true
  3858. });
  3859. Object.defineProperty(this, 'Subtype', {
  3860. value: "/Form",
  3861. configurable: false,
  3862. writeable: true
  3863. });
  3864. Object.defineProperty(this, 'FormType', {
  3865. value: 1,
  3866. configurable: false,
  3867. writeable: true
  3868. });
  3869. var _BBox = [];
  3870. Object.defineProperty(this, 'BBox', {
  3871. configurable: false,
  3872. writeable: true,
  3873. get: function get() {
  3874. return _BBox;
  3875. },
  3876. set: function set(value) {
  3877. _BBox = value;
  3878. }
  3879. });
  3880. Object.defineProperty(this, 'Resources', {
  3881. value: "2 0 R",
  3882. configurable: false,
  3883. writeable: true
  3884. });
  3885. var _stream;
  3886. Object.defineProperty(this, 'stream', {
  3887. enumerable: false,
  3888. configurable: true,
  3889. set: function set(value) {
  3890. _stream = value.trim();
  3891. },
  3892. get: function get() {
  3893. if (_stream) {
  3894. return _stream;
  3895. } else {
  3896. return null;
  3897. }
  3898. }
  3899. });
  3900. };
  3901. inherit(AcroFormXObject, AcroFormPDFObject);
  3902. var AcroFormDictionary = function AcroFormDictionary() {
  3903. AcroFormPDFObject.call(this);
  3904. var _Kids = [];
  3905. Object.defineProperty(this, 'Kids', {
  3906. enumerable: false,
  3907. configurable: true,
  3908. get: function get() {
  3909. if (_Kids.length > 0) {
  3910. return _Kids;
  3911. } else {
  3912. return;
  3913. }
  3914. }
  3915. });
  3916. Object.defineProperty(this, 'Fields', {
  3917. enumerable: false,
  3918. configurable: false,
  3919. get: function get() {
  3920. return _Kids;
  3921. }
  3922. }); // Default Appearance
  3923. var _DA;
  3924. Object.defineProperty(this, 'DA', {
  3925. enumerable: false,
  3926. configurable: false,
  3927. get: function get() {
  3928. if (!_DA) {
  3929. return;
  3930. }
  3931. return '(' + _DA + ')';
  3932. },
  3933. set: function set(value) {
  3934. _DA = value;
  3935. }
  3936. });
  3937. };
  3938. inherit(AcroFormDictionary, AcroFormPDFObject);
  3939. /**
  3940. * The Field Object contains the Variables, that every Field needs
  3941. *
  3942. * @class AcroFormField
  3943. * @classdesc An AcroForm FieldObject
  3944. */
  3945. var AcroFormField = function AcroFormField() {
  3946. AcroFormPDFObject.call(this); //Annotation-Flag See Table 165
  3947. var _F = 4;
  3948. Object.defineProperty(this, 'F', {
  3949. enumerable: false,
  3950. configurable: false,
  3951. get: function get() {
  3952. return _F;
  3953. },
  3954. set: function set(value) {
  3955. if (!isNaN(value)) {
  3956. _F = value;
  3957. } else {
  3958. throw new Error('Invalid value "' + value + '" for attribute F supplied.');
  3959. }
  3960. }
  3961. });
  3962. /**
  3963. * (PDF 1.2) If set, print the annotation when the page is printed. If clear, never print the annotation, regardless of wether is is displayed on the screen.
  3964. * NOTE 2 This can be useful for annotations representing interactive pushbuttons, which would serve no meaningful purpose on the printed page.
  3965. *
  3966. * @name AcroFormField#showWhenPrinted
  3967. * @default true
  3968. * @type {boolean}
  3969. */
  3970. Object.defineProperty(this, 'showWhenPrinted', {
  3971. enumerable: true,
  3972. configurable: true,
  3973. get: function get() {
  3974. return Boolean(getBitForPdf(_F, 3));
  3975. },
  3976. set: function set(value) {
  3977. if (Boolean(value) === true) {
  3978. this.F = setBitForPdf(_F, 3);
  3979. } else {
  3980. this.F = clearBitForPdf(_F, 3);
  3981. }
  3982. }
  3983. });
  3984. var _Ff = 0;
  3985. Object.defineProperty(this, 'Ff', {
  3986. enumerable: false,
  3987. configurable: false,
  3988. get: function get() {
  3989. return _Ff;
  3990. },
  3991. set: function set(value) {
  3992. if (!isNaN(value)) {
  3993. _Ff = value;
  3994. } else {
  3995. throw new Error('Invalid value "' + value + '" for attribute Ff supplied.');
  3996. }
  3997. }
  3998. });
  3999. var _Rect = [];
  4000. Object.defineProperty(this, 'Rect', {
  4001. enumerable: false,
  4002. configurable: false,
  4003. get: function get() {
  4004. if (_Rect.length === 0) {
  4005. return;
  4006. }
  4007. return _Rect;
  4008. },
  4009. set: function set(value) {
  4010. if (typeof value !== "undefined") {
  4011. _Rect = value;
  4012. } else {
  4013. _Rect = [];
  4014. }
  4015. }
  4016. });
  4017. /**
  4018. * The x-position of the field.
  4019. *
  4020. * @name AcroFormField#x
  4021. * @default null
  4022. * @type {number}
  4023. */
  4024. Object.defineProperty(this, 'x', {
  4025. enumerable: true,
  4026. configurable: true,
  4027. get: function get() {
  4028. if (!_Rect || isNaN(_Rect[0])) {
  4029. return 0;
  4030. }
  4031. return antiScale(_Rect[0]);
  4032. },
  4033. set: function set(value) {
  4034. _Rect[0] = scale(value);
  4035. }
  4036. });
  4037. /**
  4038. * The y-position of the field.
  4039. *
  4040. * @name AcroFormField#y
  4041. * @default null
  4042. * @type {number}
  4043. */
  4044. Object.defineProperty(this, 'y', {
  4045. enumerable: true,
  4046. configurable: true,
  4047. get: function get() {
  4048. if (!_Rect || isNaN(_Rect[1])) {
  4049. return 0;
  4050. }
  4051. return antiScale(_Rect[1]);
  4052. },
  4053. set: function set(value) {
  4054. _Rect[1] = scale(value);
  4055. }
  4056. });
  4057. /**
  4058. * The width of the field.
  4059. *
  4060. * @name AcroFormField#width
  4061. * @default null
  4062. * @type {number}
  4063. */
  4064. Object.defineProperty(this, 'width', {
  4065. enumerable: true,
  4066. configurable: true,
  4067. get: function get() {
  4068. if (!_Rect || isNaN(_Rect[2])) {
  4069. return 0;
  4070. }
  4071. return antiScale(_Rect[2]);
  4072. },
  4073. set: function set(value) {
  4074. _Rect[2] = scale(value);
  4075. }
  4076. });
  4077. /**
  4078. * The height of the field.
  4079. *
  4080. * @name AcroFormField#height
  4081. * @default null
  4082. * @type {number}
  4083. */
  4084. Object.defineProperty(this, 'height', {
  4085. enumerable: true,
  4086. configurable: true,
  4087. get: function get() {
  4088. if (!_Rect || isNaN(_Rect[3])) {
  4089. return 0;
  4090. }
  4091. return antiScale(_Rect[3]);
  4092. },
  4093. set: function set(value) {
  4094. _Rect[3] = scale(value);
  4095. }
  4096. });
  4097. var _FT = "";
  4098. Object.defineProperty(this, 'FT', {
  4099. enumerable: true,
  4100. configurable: false,
  4101. get: function get() {
  4102. return _FT;
  4103. },
  4104. set: function set(value) {
  4105. switch (value) {
  4106. case '/Btn':
  4107. case '/Tx':
  4108. case '/Ch':
  4109. case '/Sig':
  4110. _FT = value;
  4111. break;
  4112. default:
  4113. throw new Error('Invalid value "' + value + '" for attribute FT supplied.');
  4114. }
  4115. }
  4116. });
  4117. var _T = null;
  4118. Object.defineProperty(this, 'T', {
  4119. enumerable: true,
  4120. configurable: false,
  4121. get: function get() {
  4122. if (!_T || _T.length < 1) {
  4123. // In case of a Child from a Radio´Group, you don't need a FieldName
  4124. if (this instanceof AcroFormChildClass) {
  4125. return;
  4126. }
  4127. _T = "FieldObject" + AcroFormField.FieldNum++;
  4128. }
  4129. return '(' + pdfEscape(_T) + ')';
  4130. },
  4131. set: function set(value) {
  4132. _T = value.toString();
  4133. }
  4134. });
  4135. /**
  4136. * (Optional) The partial field name (see 12.7.3.2, “Field Names”).
  4137. *
  4138. * @name AcroFormField#fieldName
  4139. * @default null
  4140. * @type {string}
  4141. */
  4142. Object.defineProperty(this, 'fieldName', {
  4143. configurable: true,
  4144. enumerable: true,
  4145. get: function get() {
  4146. return _T;
  4147. },
  4148. set: function set(value) {
  4149. _T = value;
  4150. }
  4151. });
  4152. var _fontName = 'helvetica';
  4153. /**
  4154. * The fontName of the font to be used.
  4155. *
  4156. * @name AcroFormField#fontName
  4157. * @default 'helvetica'
  4158. * @type {string}
  4159. */
  4160. Object.defineProperty(this, 'fontName', {
  4161. enumerable: true,
  4162. configurable: true,
  4163. get: function get() {
  4164. return _fontName;
  4165. },
  4166. set: function set(value) {
  4167. _fontName = value;
  4168. }
  4169. });
  4170. var _fontStyle = 'normal';
  4171. /**
  4172. * The fontStyle of the font to be used.
  4173. *
  4174. * @name AcroFormField#fontStyle
  4175. * @default 'normal'
  4176. * @type {string}
  4177. */
  4178. Object.defineProperty(this, 'fontStyle', {
  4179. enumerable: true,
  4180. configurable: true,
  4181. get: function get() {
  4182. return _fontStyle;
  4183. },
  4184. set: function set(value) {
  4185. _fontStyle = value;
  4186. }
  4187. });
  4188. var _fontSize = 0;
  4189. /**
  4190. * The fontSize of the font to be used.
  4191. *
  4192. * @name AcroFormField#fontSize
  4193. * @default 0 (for auto)
  4194. * @type {number}
  4195. */
  4196. Object.defineProperty(this, 'fontSize', {
  4197. enumerable: true,
  4198. configurable: true,
  4199. get: function get() {
  4200. return antiScale(_fontSize);
  4201. },
  4202. set: function set(value) {
  4203. _fontSize = scale(value);
  4204. }
  4205. });
  4206. var _maxFontSize = 50;
  4207. /**
  4208. * The maximum fontSize of the font to be used.
  4209. *
  4210. * @name AcroFormField#maxFontSize
  4211. * @default 0 (for auto)
  4212. * @type {number}
  4213. */
  4214. Object.defineProperty(this, 'maxFontSize', {
  4215. enumerable: true,
  4216. configurable: true,
  4217. get: function get() {
  4218. return antiScale(_maxFontSize);
  4219. },
  4220. set: function set(value) {
  4221. _maxFontSize = scale(value);
  4222. }
  4223. });
  4224. var _color = 'black';
  4225. /**
  4226. * The color of the text
  4227. *
  4228. * @name AcroFormField#color
  4229. * @default 'black'
  4230. * @type {string|rgba}
  4231. */
  4232. Object.defineProperty(this, 'color', {
  4233. enumerable: true,
  4234. configurable: true,
  4235. get: function get() {
  4236. return _color;
  4237. },
  4238. set: function set(value) {
  4239. _color = value;
  4240. }
  4241. });
  4242. var _DA = '/F1 0 Tf 0 g'; // Defines the default appearance (Needed for variable Text)
  4243. Object.defineProperty(this, 'DA', {
  4244. enumerable: true,
  4245. configurable: false,
  4246. get: function get() {
  4247. if (!_DA || this instanceof AcroFormChildClass || this instanceof AcroFormTextField) {
  4248. return;
  4249. }
  4250. return toPdfString(_DA);
  4251. },
  4252. set: function set(value) {
  4253. value = value.toString();
  4254. _DA = value;
  4255. }
  4256. });
  4257. var _DV = null;
  4258. Object.defineProperty(this, 'DV', {
  4259. enumerable: false,
  4260. configurable: false,
  4261. get: function get() {
  4262. if (!_DV) {
  4263. return;
  4264. }
  4265. if (this instanceof AcroFormButton === false) {
  4266. return toPdfString(_DV);
  4267. }
  4268. return _DV;
  4269. },
  4270. set: function set(value) {
  4271. value = value.toString();
  4272. if (this instanceof AcroFormButton === false) {
  4273. if (value.substr(0, 1) === '(') {
  4274. _DV = pdfUnescape(value.substr(1, value.length - 2));
  4275. } else {
  4276. _DV = pdfUnescape(value);
  4277. }
  4278. } else {
  4279. _DV = value;
  4280. }
  4281. }
  4282. });
  4283. /**
  4284. * (Optional; inheritable) The default value to which the field reverts when a reset-form action is executed (see 12.7.5.3, “Reset-Form Action”). The format of this value is the same as that of value.
  4285. *
  4286. * @name AcroFormField#defaultValue
  4287. * @default null
  4288. * @type {any}
  4289. */
  4290. Object.defineProperty(this, 'defaultValue', {
  4291. enumerable: true,
  4292. configurable: true,
  4293. get: function get() {
  4294. if (this instanceof AcroFormButton === true) {
  4295. return pdfUnescape(_DV.substr(1, _DV.length - 1));
  4296. } else {
  4297. return _DV;
  4298. }
  4299. },
  4300. set: function set(value) {
  4301. value = value.toString();
  4302. if (this instanceof AcroFormButton === true) {
  4303. _DV = '/' + value;
  4304. } else {
  4305. _DV = value;
  4306. }
  4307. }
  4308. });
  4309. var _V = null;
  4310. Object.defineProperty(this, 'V', {
  4311. enumerable: false,
  4312. configurable: false,
  4313. get: function get() {
  4314. if (!_V) {
  4315. return;
  4316. }
  4317. if (this instanceof AcroFormButton === false) {
  4318. return toPdfString(_V);
  4319. }
  4320. return _V;
  4321. },
  4322. set: function set(value) {
  4323. value = value.toString();
  4324. if (this instanceof AcroFormButton === false) {
  4325. if (value.substr(0, 1) === '(') {
  4326. _V = pdfUnescape(value.substr(1, value.length - 2));
  4327. } else {
  4328. _V = pdfUnescape(value);
  4329. }
  4330. } else {
  4331. _V = value;
  4332. }
  4333. }
  4334. });
  4335. /**
  4336. * (Optional; inheritable) The field’s value, whose format varies depending on the field type. See the descriptions of individual field types for further information.
  4337. *
  4338. * @name AcroFormField#value
  4339. * @default null
  4340. * @type {any}
  4341. */
  4342. Object.defineProperty(this, 'value', {
  4343. enumerable: true,
  4344. configurable: true,
  4345. get: function get() {
  4346. if (this instanceof AcroFormButton === true) {
  4347. return pdfUnescape(_V.substr(1, _V.length - 1));
  4348. } else {
  4349. return _V;
  4350. }
  4351. },
  4352. set: function set(value) {
  4353. value = value.toString();
  4354. if (this instanceof AcroFormButton === true) {
  4355. _V = '/' + value;
  4356. } else {
  4357. _V = value;
  4358. }
  4359. }
  4360. });
  4361. /**
  4362. * Check if field has annotations
  4363. *
  4364. * @name AcroFormField#hasAnnotation
  4365. * @readonly
  4366. * @type {boolean}
  4367. */
  4368. Object.defineProperty(this, 'hasAnnotation', {
  4369. enumerable: true,
  4370. configurable: true,
  4371. get: function get() {
  4372. return this.Rect;
  4373. }
  4374. });
  4375. Object.defineProperty(this, 'Type', {
  4376. enumerable: true,
  4377. configurable: false,
  4378. get: function get() {
  4379. return this.hasAnnotation ? "/Annot" : null;
  4380. }
  4381. });
  4382. Object.defineProperty(this, 'Subtype', {
  4383. enumerable: true,
  4384. configurable: false,
  4385. get: function get() {
  4386. return this.hasAnnotation ? "/Widget" : null;
  4387. }
  4388. });
  4389. var _hasAppearanceStream = false;
  4390. /**
  4391. * true if field has an appearanceStream
  4392. *
  4393. * @name AcroFormField#hasAppearanceStream
  4394. * @readonly
  4395. * @type {boolean}
  4396. */
  4397. Object.defineProperty(this, 'hasAppearanceStream', {
  4398. enumerable: true,
  4399. configurable: true,
  4400. writeable: true,
  4401. get: function get() {
  4402. return _hasAppearanceStream;
  4403. },
  4404. set: function set(value) {
  4405. value = Boolean(value);
  4406. _hasAppearanceStream = value;
  4407. }
  4408. });
  4409. /**
  4410. * The page on which the AcroFormField is placed
  4411. *
  4412. * @name AcroFormField#page
  4413. * @type {number}
  4414. */
  4415. var _page;
  4416. Object.defineProperty(this, 'page', {
  4417. enumerable: true,
  4418. configurable: true,
  4419. writeable: true,
  4420. get: function get() {
  4421. if (!_page) {
  4422. return;
  4423. }
  4424. return _page;
  4425. },
  4426. set: function set(value) {
  4427. _page = value;
  4428. }
  4429. });
  4430. /**
  4431. * If set, the user may not change the value of the field. Any associated widget annotations will not interact with the user; that is, they will not respond to mouse clicks or change their appearance in response to mouse motions. This flag is useful for fields whose values are computed or imported from a database.
  4432. *
  4433. * @name AcroFormField#readOnly
  4434. * @default false
  4435. * @type {boolean}
  4436. */
  4437. Object.defineProperty(this, 'readOnly', {
  4438. enumerable: true,
  4439. configurable: true,
  4440. get: function get() {
  4441. return Boolean(getBitForPdf(this.Ff, 1));
  4442. },
  4443. set: function set(value) {
  4444. if (Boolean(value) === true) {
  4445. this.Ff = setBitForPdf(this.Ff, 1);
  4446. } else {
  4447. this.Ff = clearBitForPdf(this.Ff, 1);
  4448. }
  4449. }
  4450. });
  4451. /**
  4452. * If set, the field shall have a value at the time it is exported by a submitform action (see 12.7.5.2, “Submit-Form Action”).
  4453. *
  4454. * @name AcroFormField#required
  4455. * @default false
  4456. * @type {boolean}
  4457. */
  4458. Object.defineProperty(this, 'required', {
  4459. enumerable: true,
  4460. configurable: true,
  4461. get: function get() {
  4462. return Boolean(getBitForPdf(this.Ff, 2));
  4463. },
  4464. set: function set(value) {
  4465. if (Boolean(value) === true) {
  4466. this.Ff = setBitForPdf(this.Ff, 2);
  4467. } else {
  4468. this.Ff = clearBitForPdf(this.Ff, 2);
  4469. }
  4470. }
  4471. });
  4472. /**
  4473. * If set, the field shall not be exported by a submit-form action (see 12.7.5.2, “Submit-Form Action”)
  4474. *
  4475. * @name AcroFormField#noExport
  4476. * @default false
  4477. * @type {boolean}
  4478. */
  4479. Object.defineProperty(this, 'noExport', {
  4480. enumerable: true,
  4481. configurable: true,
  4482. get: function get() {
  4483. return Boolean(getBitForPdf(this.Ff, 3));
  4484. },
  4485. set: function set(value) {
  4486. if (Boolean(value) === true) {
  4487. this.Ff = setBitForPdf(this.Ff, 3);
  4488. } else {
  4489. this.Ff = clearBitForPdf(this.Ff, 3);
  4490. }
  4491. }
  4492. });
  4493. var _Q = null;
  4494. Object.defineProperty(this, 'Q', {
  4495. enumerable: true,
  4496. configurable: false,
  4497. get: function get() {
  4498. if (_Q === null) {
  4499. return;
  4500. }
  4501. return _Q;
  4502. },
  4503. set: function set(value) {
  4504. if ([0, 1, 2].indexOf(value) !== -1) {
  4505. _Q = value;
  4506. } else {
  4507. throw new Error('Invalid value "' + value + '" for attribute Q supplied.');
  4508. }
  4509. }
  4510. });
  4511. /**
  4512. * (Optional; inheritable) A code specifying the form of quadding (justification) that shall be used in displaying the text:
  4513. * 'left', 'center', 'right'
  4514. *
  4515. * @name AcroFormField#textAlign
  4516. * @default 'left'
  4517. * @type {string}
  4518. */
  4519. Object.defineProperty(this, 'textAlign', {
  4520. get: function get() {
  4521. var result = 'left';
  4522. switch (_Q) {
  4523. case 0:
  4524. default:
  4525. result = 'left';
  4526. break;
  4527. case 1:
  4528. result = 'center';
  4529. break;
  4530. case 2:
  4531. result = 'right';
  4532. break;
  4533. }
  4534. return result;
  4535. },
  4536. configurable: true,
  4537. enumerable: true,
  4538. set: function set(value) {
  4539. switch (value) {
  4540. case 'right':
  4541. case 2:
  4542. _Q = 2;
  4543. break;
  4544. case 'center':
  4545. case 1:
  4546. _Q = 1;
  4547. break;
  4548. case 'left':
  4549. case 0:
  4550. default:
  4551. _Q = 0;
  4552. }
  4553. }
  4554. });
  4555. };
  4556. inherit(AcroFormField, AcroFormPDFObject);
  4557. /**
  4558. * @class AcroFormChoiceField
  4559. * @extends AcroFormField
  4560. */
  4561. var AcroFormChoiceField = function AcroFormChoiceField() {
  4562. AcroFormField.call(this); // Field Type = Choice Field
  4563. this.FT = "/Ch"; // options
  4564. this.V = '()';
  4565. this.fontName = 'zapfdingbats'; // Top Index
  4566. var _TI = 0;
  4567. Object.defineProperty(this, 'TI', {
  4568. enumerable: true,
  4569. configurable: false,
  4570. get: function get() {
  4571. return _TI;
  4572. },
  4573. set: function set(value) {
  4574. _TI = value;
  4575. }
  4576. });
  4577. /**
  4578. * (Optional) For scrollable list boxes, the top index (the index in the Opt array of the first option visible in the list). Default value: 0.
  4579. *
  4580. * @name AcroFormChoiceField#topIndex
  4581. * @default 0
  4582. * @type {number}
  4583. */
  4584. Object.defineProperty(this, 'topIndex', {
  4585. enumerable: true,
  4586. configurable: true,
  4587. get: function get() {
  4588. return _TI;
  4589. },
  4590. set: function set(value) {
  4591. _TI = value;
  4592. }
  4593. });
  4594. var _Opt = [];
  4595. Object.defineProperty(this, 'Opt', {
  4596. enumerable: true,
  4597. configurable: false,
  4598. get: function get() {
  4599. return arrayToPdfArray(_Opt);
  4600. },
  4601. set: function set(value) {
  4602. _Opt = pdfArrayToStringArray(value);
  4603. }
  4604. });
  4605. /**
  4606. * @memberof AcroFormChoiceField
  4607. * @name getOptions
  4608. * @function
  4609. * @instance
  4610. * @returns {array} array of Options
  4611. */
  4612. this.getOptions = function () {
  4613. return _Opt;
  4614. };
  4615. /**
  4616. * @memberof AcroFormChoiceField
  4617. * @name setOptions
  4618. * @function
  4619. * @instance
  4620. * @param {array} value
  4621. */
  4622. this.setOptions = function (value) {
  4623. _Opt = value;
  4624. if (this.sort) {
  4625. _Opt.sort();
  4626. }
  4627. };
  4628. /**
  4629. * @memberof AcroFormChoiceField
  4630. * @name addOption
  4631. * @function
  4632. * @instance
  4633. * @param {string} value
  4634. */
  4635. this.addOption = function (value) {
  4636. value = value || "";
  4637. value = value.toString();
  4638. _Opt.push(value);
  4639. if (this.sort) {
  4640. _Opt.sort();
  4641. }
  4642. };
  4643. /**
  4644. * @memberof AcroFormChoiceField
  4645. * @name removeOption
  4646. * @function
  4647. * @instance
  4648. * @param {string} value
  4649. * @param {boolean} allEntries (default: false)
  4650. */
  4651. this.removeOption = function (value, allEntries) {
  4652. allEntries = allEntries || false;
  4653. value = value || "";
  4654. value = value.toString();
  4655. while (_Opt.indexOf(value) !== -1) {
  4656. _Opt.splice(_Opt.indexOf(value), 1);
  4657. if (allEntries === false) {
  4658. break;
  4659. }
  4660. }
  4661. };
  4662. /**
  4663. * If set, the field is a combo box; if clear, the field is a list box.
  4664. *
  4665. * @name AcroFormChoiceField#combo
  4666. * @default false
  4667. * @type {boolean}
  4668. */
  4669. Object.defineProperty(this, 'combo', {
  4670. enumerable: true,
  4671. configurable: true,
  4672. get: function get() {
  4673. return Boolean(getBitForPdf(this.Ff, 18));
  4674. },
  4675. set: function set(value) {
  4676. if (Boolean(value) === true) {
  4677. this.Ff = setBitForPdf(this.Ff, 18);
  4678. } else {
  4679. this.Ff = clearBitForPdf(this.Ff, 18);
  4680. }
  4681. }
  4682. });
  4683. /**
  4684. * If set, the combo box shall include an editable text box as well as a drop-down list; if clear, it shall include only a drop-down list. This flag shall be used only if the Combo flag is set.
  4685. *
  4686. * @name AcroFormChoiceField#edit
  4687. * @default false
  4688. * @type {boolean}
  4689. */
  4690. Object.defineProperty(this, 'edit', {
  4691. enumerable: true,
  4692. configurable: true,
  4693. get: function get() {
  4694. return Boolean(getBitForPdf(this.Ff, 19));
  4695. },
  4696. set: function set(value) {
  4697. //PDF 32000-1:2008, page 444
  4698. if (this.combo === true) {
  4699. if (Boolean(value) === true) {
  4700. this.Ff = setBitForPdf(this.Ff, 19);
  4701. } else {
  4702. this.Ff = clearBitForPdf(this.Ff, 19);
  4703. }
  4704. }
  4705. }
  4706. });
  4707. /**
  4708. * If set, the field’s option items shall be sorted alphabetically. This flag is intended for use by writers, not by readers. Conforming readers shall display the options in the order in which they occur in the Opt array (see Table 231).
  4709. *
  4710. * @name AcroFormChoiceField#sort
  4711. * @default false
  4712. * @type {boolean}
  4713. */
  4714. Object.defineProperty(this, 'sort', {
  4715. enumerable: true,
  4716. configurable: true,
  4717. get: function get() {
  4718. return Boolean(getBitForPdf(this.Ff, 20));
  4719. },
  4720. set: function set(value) {
  4721. if (Boolean(value) === true) {
  4722. this.Ff = setBitForPdf(this.Ff, 20);
  4723. _Opt.sort();
  4724. } else {
  4725. this.Ff = clearBitForPdf(this.Ff, 20);
  4726. }
  4727. }
  4728. });
  4729. /**
  4730. * (PDF 1.4) If set, more than one of the field’s option items may be selected simultaneously; if clear, at most one item shall be selected
  4731. *
  4732. * @name AcroFormChoiceField#multiSelect
  4733. * @default false
  4734. * @type {boolean}
  4735. */
  4736. Object.defineProperty(this, 'multiSelect', {
  4737. enumerable: true,
  4738. configurable: true,
  4739. get: function get() {
  4740. return Boolean(getBitForPdf(this.Ff, 22));
  4741. },
  4742. set: function set(value) {
  4743. if (Boolean(value) === true) {
  4744. this.Ff = setBitForPdf(this.Ff, 22);
  4745. } else {
  4746. this.Ff = clearBitForPdf(this.Ff, 22);
  4747. }
  4748. }
  4749. });
  4750. /**
  4751. * (PDF 1.4) If set, text entered in the field shall not be spellchecked. This flag shall not be used unless the Combo and Edit flags are both set.
  4752. *
  4753. * @name AcroFormChoiceField#doNotSpellCheck
  4754. * @default false
  4755. * @type {boolean}
  4756. */
  4757. Object.defineProperty(this, 'doNotSpellCheck', {
  4758. enumerable: true,
  4759. configurable: true,
  4760. get: function get() {
  4761. return Boolean(getBitForPdf(this.Ff, 23));
  4762. },
  4763. set: function set(value) {
  4764. if (Boolean(value) === true) {
  4765. this.Ff = setBitForPdf(this.Ff, 23);
  4766. } else {
  4767. this.Ff = clearBitForPdf(this.Ff, 23);
  4768. }
  4769. }
  4770. });
  4771. /**
  4772. * (PDF 1.5) If set, the new value shall be committed as soon as a selection is made (commonly with the pointing device). In this case, supplying a value for a field involves three actions: selecting the field for fill-in, selecting a choice for the fill-in value, and leaving that field, which finalizes or “commits” the data choice and triggers any actions associated with the entry or changing of this data. If this flag is on, then processing does not wait for leaving the field action to occur, but immediately proceeds to the third step.
  4773. * This option enables applications to perform an action once a selection is made, without requiring the user to exit the field. If clear, the new value is not committed until the user exits the field.
  4774. *
  4775. * @name AcroFormChoiceField#commitOnSelChange
  4776. * @default false
  4777. * @type {boolean}
  4778. */
  4779. Object.defineProperty(this, 'commitOnSelChange', {
  4780. enumerable: true,
  4781. configurable: true,
  4782. get: function get() {
  4783. return Boolean(getBitForPdf(this.Ff, 27));
  4784. },
  4785. set: function set(value) {
  4786. if (Boolean(value) === true) {
  4787. this.Ff = setBitForPdf(this.Ff, 27);
  4788. } else {
  4789. this.Ff = clearBitForPdf(this.Ff, 27);
  4790. }
  4791. }
  4792. });
  4793. this.hasAppearanceStream = false;
  4794. };
  4795. inherit(AcroFormChoiceField, AcroFormField);
  4796. /**
  4797. * @class AcroFormListBox
  4798. * @extends AcroFormChoiceField
  4799. * @extends AcroFormField
  4800. */
  4801. var AcroFormListBox = function AcroFormListBox() {
  4802. AcroFormChoiceField.call(this);
  4803. this.fontName = 'helvetica'; //PDF 32000-1:2008, page 444
  4804. this.combo = false;
  4805. };
  4806. inherit(AcroFormListBox, AcroFormChoiceField);
  4807. /**
  4808. * @class AcroFormComboBox
  4809. * @extends AcroFormListBox
  4810. * @extends AcroFormChoiceField
  4811. * @extends AcroFormField
  4812. */
  4813. var AcroFormComboBox = function AcroFormComboBox() {
  4814. AcroFormListBox.call(this);
  4815. this.combo = true;
  4816. };
  4817. inherit(AcroFormComboBox, AcroFormListBox);
  4818. /**
  4819. * @class AcroFormEditBox
  4820. * @extends AcroFormComboBox
  4821. * @extends AcroFormListBox
  4822. * @extends AcroFormChoiceField
  4823. * @extends AcroFormField
  4824. */
  4825. var AcroFormEditBox = function AcroFormEditBox() {
  4826. AcroFormComboBox.call(this);
  4827. this.edit = true;
  4828. };
  4829. inherit(AcroFormEditBox, AcroFormComboBox);
  4830. /**
  4831. * @class AcroFormButton
  4832. * @extends AcroFormField
  4833. */
  4834. var AcroFormButton = function AcroFormButton() {
  4835. AcroFormField.call(this);
  4836. this.FT = "/Btn";
  4837. /**
  4838. * (Radio buttons only) If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect. If clear, clicking the selected button deselects it, leaving no button selected.
  4839. *
  4840. * @name AcroFormButton#noToggleToOff
  4841. * @type {boolean}
  4842. */
  4843. Object.defineProperty(this, 'noToggleToOff', {
  4844. enumerable: true,
  4845. configurable: true,
  4846. get: function get() {
  4847. return Boolean(getBitForPdf(this.Ff, 15));
  4848. },
  4849. set: function set(value) {
  4850. if (Boolean(value) === true) {
  4851. this.Ff = setBitForPdf(this.Ff, 15);
  4852. } else {
  4853. this.Ff = clearBitForPdf(this.Ff, 15);
  4854. }
  4855. }
  4856. });
  4857. /**
  4858. * If set, the field is a set of radio buttons; if clear, the field is a checkbox. This flag may be set only if the Pushbutton flag is clear.
  4859. *
  4860. * @name AcroFormButton#radio
  4861. * @type {boolean}
  4862. */
  4863. Object.defineProperty(this, 'radio', {
  4864. enumerable: true,
  4865. configurable: true,
  4866. get: function get() {
  4867. return Boolean(getBitForPdf(this.Ff, 16));
  4868. },
  4869. set: function set(value) {
  4870. if (Boolean(value) === true) {
  4871. this.Ff = setBitForPdf(this.Ff, 16);
  4872. } else {
  4873. this.Ff = clearBitForPdf(this.Ff, 16);
  4874. }
  4875. }
  4876. });
  4877. /**
  4878. * If set, the field is a pushbutton that does not retain a permanent value.
  4879. *
  4880. * @name AcroFormButton#pushButton
  4881. * @type {boolean}
  4882. */
  4883. Object.defineProperty(this, 'pushButton', {
  4884. enumerable: true,
  4885. configurable: true,
  4886. get: function get() {
  4887. return Boolean(getBitForPdf(this.Ff, 17));
  4888. },
  4889. set: function set(value) {
  4890. if (Boolean(value) === true) {
  4891. this.Ff = setBitForPdf(this.Ff, 17);
  4892. } else {
  4893. this.Ff = clearBitForPdf(this.Ff, 17);
  4894. }
  4895. }
  4896. });
  4897. /**
  4898. * (PDF 1.5) If set, a group of radio buttons within a radio button field that use the same value for the on state will turn on and off in unison; that is if one is checked, they are all checked. If clear, the buttons are mutually exclusive (the same behavior as HTML radio buttons).
  4899. *
  4900. * @name AcroFormButton#radioIsUnison
  4901. * @type {boolean}
  4902. */
  4903. Object.defineProperty(this, 'radioIsUnison', {
  4904. enumerable: true,
  4905. configurable: true,
  4906. get: function get() {
  4907. return Boolean(getBitForPdf(this.Ff, 26));
  4908. },
  4909. set: function set(value) {
  4910. if (Boolean(value) === true) {
  4911. this.Ff = setBitForPdf(this.Ff, 26);
  4912. } else {
  4913. this.Ff = clearBitForPdf(this.Ff, 26);
  4914. }
  4915. }
  4916. });
  4917. var _MK = {};
  4918. Object.defineProperty(this, 'MK', {
  4919. enumerable: false,
  4920. configurable: false,
  4921. get: function get() {
  4922. if (Object.keys(_MK).length !== 0) {
  4923. var result = [];
  4924. result.push('<<');
  4925. var key;
  4926. for (key in _MK) {
  4927. result.push('/' + key + ' (' + _MK[key] + ')');
  4928. }
  4929. result.push('>>');
  4930. return result.join('\n');
  4931. }
  4932. return;
  4933. },
  4934. set: function set(value) {
  4935. if (_typeof(value) === "object") {
  4936. _MK = value;
  4937. }
  4938. }
  4939. });
  4940. /**
  4941. * From the PDF reference:
  4942. * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
  4943. * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
  4944. *
  4945. * - '8' = Cross,
  4946. * - 'l' = Circle,
  4947. * - '' = nothing
  4948. * @name AcroFormButton#caption
  4949. * @type {string}
  4950. */
  4951. Object.defineProperty(this, 'caption', {
  4952. enumerable: true,
  4953. configurable: true,
  4954. get: function get() {
  4955. return _MK.CA || '';
  4956. },
  4957. set: function set(value) {
  4958. if (typeof value === "string") {
  4959. _MK.CA = value;
  4960. }
  4961. }
  4962. });
  4963. var _AS;
  4964. Object.defineProperty(this, 'AS', {
  4965. enumerable: false,
  4966. configurable: false,
  4967. get: function get() {
  4968. return _AS;
  4969. },
  4970. set: function set(value) {
  4971. _AS = value;
  4972. }
  4973. });
  4974. /**
  4975. * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
  4976. *
  4977. * @name AcroFormButton#appearanceState
  4978. * @type {any}
  4979. */
  4980. Object.defineProperty(this, 'appearanceState', {
  4981. enumerable: true,
  4982. configurable: true,
  4983. get: function get() {
  4984. return _AS.substr(1, _AS.length - 1);
  4985. },
  4986. set: function set(value) {
  4987. _AS = '/' + value;
  4988. }
  4989. });
  4990. };
  4991. inherit(AcroFormButton, AcroFormField);
  4992. /**
  4993. * @class AcroFormPushButton
  4994. * @extends AcroFormButton
  4995. * @extends AcroFormField
  4996. */
  4997. var AcroFormPushButton = function AcroFormPushButton() {
  4998. AcroFormButton.call(this);
  4999. this.pushButton = true;
  5000. };
  5001. inherit(AcroFormPushButton, AcroFormButton);
  5002. /**
  5003. * @class AcroFormRadioButton
  5004. * @extends AcroFormButton
  5005. * @extends AcroFormField
  5006. */
  5007. var AcroFormRadioButton = function AcroFormRadioButton() {
  5008. AcroFormButton.call(this);
  5009. this.radio = true;
  5010. this.pushButton = false;
  5011. var _Kids = [];
  5012. Object.defineProperty(this, 'Kids', {
  5013. enumerable: true,
  5014. configurable: false,
  5015. get: function get() {
  5016. return _Kids;
  5017. },
  5018. set: function set(value) {
  5019. if (typeof value !== "undefined") {
  5020. _Kids = value;
  5021. } else {
  5022. _Kids = [];
  5023. }
  5024. }
  5025. });
  5026. };
  5027. inherit(AcroFormRadioButton, AcroFormButton);
  5028. /**
  5029. * The Child class of a RadioButton (the radioGroup) -> The single Buttons
  5030. *
  5031. * @class AcroFormChildClass
  5032. * @extends AcroFormField
  5033. * @ignore
  5034. */
  5035. var AcroFormChildClass = function AcroFormChildClass() {
  5036. AcroFormField.call(this);
  5037. var _parent;
  5038. Object.defineProperty(this, 'Parent', {
  5039. enumerable: false,
  5040. configurable: false,
  5041. get: function get() {
  5042. return _parent;
  5043. },
  5044. set: function set(value) {
  5045. _parent = value;
  5046. }
  5047. });
  5048. var _optionName;
  5049. Object.defineProperty(this, 'optionName', {
  5050. enumerable: false,
  5051. configurable: true,
  5052. get: function get() {
  5053. return _optionName;
  5054. },
  5055. set: function set(value) {
  5056. _optionName = value;
  5057. }
  5058. });
  5059. var _MK = {};
  5060. Object.defineProperty(this, 'MK', {
  5061. enumerable: false,
  5062. configurable: false,
  5063. get: function get() {
  5064. var result = [];
  5065. result.push('<<');
  5066. var key;
  5067. for (key in _MK) {
  5068. result.push('/' + key + ' (' + _MK[key] + ')');
  5069. }
  5070. result.push('>>');
  5071. return result.join('\n');
  5072. },
  5073. set: function set(value) {
  5074. if (_typeof(value) === "object") {
  5075. _MK = value;
  5076. }
  5077. }
  5078. });
  5079. /**
  5080. * From the PDF reference:
  5081. * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
  5082. * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
  5083. *
  5084. * - '8' = Cross,
  5085. * - 'l' = Circle,
  5086. * - '' = nothing
  5087. * @name AcroFormButton#caption
  5088. * @type {string}
  5089. */
  5090. Object.defineProperty(this, 'caption', {
  5091. enumerable: true,
  5092. configurable: true,
  5093. get: function get() {
  5094. return _MK.CA || '';
  5095. },
  5096. set: function set(value) {
  5097. if (typeof value === "string") {
  5098. _MK.CA = value;
  5099. }
  5100. }
  5101. });
  5102. var _AS;
  5103. Object.defineProperty(this, 'AS', {
  5104. enumerable: false,
  5105. configurable: false,
  5106. get: function get() {
  5107. return _AS;
  5108. },
  5109. set: function set(value) {
  5110. _AS = value;
  5111. }
  5112. });
  5113. /**
  5114. * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
  5115. *
  5116. * @name AcroFormButton#appearanceState
  5117. * @type {any}
  5118. */
  5119. Object.defineProperty(this, 'appearanceState', {
  5120. enumerable: true,
  5121. configurable: true,
  5122. get: function get() {
  5123. return _AS.substr(1, _AS.length - 1);
  5124. },
  5125. set: function set(value) {
  5126. _AS = '/' + value;
  5127. }
  5128. });
  5129. this.optionName = name;
  5130. this.caption = 'l';
  5131. this.appearanceState = 'Off'; // todo: set AppearanceType as variable that can be set from the
  5132. // outside...
  5133. this._AppearanceType = AcroFormAppearance.RadioButton.Circle; // The Default appearanceType is the Circle
  5134. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  5135. };
  5136. inherit(AcroFormChildClass, AcroFormField);
  5137. AcroFormRadioButton.prototype.setAppearance = function (appearance) {
  5138. if (!('createAppearanceStream' in appearance && 'getCA' in appearance)) {
  5139. throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  5140. return;
  5141. }
  5142. for (var objId in this.Kids) {
  5143. if (this.Kids.hasOwnProperty(objId)) {
  5144. var child = this.Kids[objId];
  5145. child.appearanceStreamContent = appearance.createAppearanceStream(child.optionName);
  5146. child.caption = appearance.getCA();
  5147. }
  5148. }
  5149. };
  5150. AcroFormRadioButton.prototype.createOption = function (name) {
  5151. var kidCount = this.Kids.length; // Create new Child for RadioGroup
  5152. var child = new AcroFormChildClass();
  5153. child.Parent = this;
  5154. child.optionName = name; // Add to Parent
  5155. this.Kids.push(child);
  5156. addField.call(this, child);
  5157. return child;
  5158. };
  5159. /**
  5160. * @class AcroFormCheckBox
  5161. * @extends AcroFormButton
  5162. * @extends AcroFormField
  5163. */
  5164. var AcroFormCheckBox = function AcroFormCheckBox() {
  5165. AcroFormButton.call(this);
  5166. this.fontName = 'zapfdingbats';
  5167. this.caption = '3';
  5168. this.appearanceState = 'On';
  5169. this.value = "On";
  5170. this.textAlign = 'center';
  5171. this.appearanceStreamContent = AcroFormAppearance.CheckBox.createAppearanceStream();
  5172. };
  5173. inherit(AcroFormCheckBox, AcroFormButton);
  5174. /**
  5175. * @class AcroFormTextField
  5176. * @extends AcroFormField
  5177. */
  5178. var AcroFormTextField = function AcroFormTextField() {
  5179. AcroFormField.call(this);
  5180. this.FT = '/Tx';
  5181. /**
  5182. * If set, the field may contain multiple lines of text; if clear, the field’s text shall be restricted to a single line.
  5183. *
  5184. * @name AcroFormTextField#multiline
  5185. * @type {boolean}
  5186. */
  5187. Object.defineProperty(this, 'multiline', {
  5188. enumerable: true,
  5189. configurable: true,
  5190. get: function get() {
  5191. return Boolean(getBitForPdf(this.Ff, 13));
  5192. },
  5193. set: function set(value) {
  5194. if (Boolean(value) === true) {
  5195. this.Ff = setBitForPdf(this.Ff, 13);
  5196. } else {
  5197. this.Ff = clearBitForPdf(this.Ff, 13);
  5198. }
  5199. }
  5200. });
  5201. /**
  5202. * (PDF 1.4) If set, the text entered in the field represents the pathname of a file whose contents shall be submitted as the value of the field.
  5203. *
  5204. * @name AcroFormTextField#fileSelect
  5205. * @type {boolean}
  5206. */
  5207. Object.defineProperty(this, 'fileSelect', {
  5208. enumerable: true,
  5209. configurable: true,
  5210. get: function get() {
  5211. return Boolean(getBitForPdf(this.Ff, 21));
  5212. },
  5213. set: function set(value) {
  5214. if (Boolean(value) === true) {
  5215. this.Ff = setBitForPdf(this.Ff, 21);
  5216. } else {
  5217. this.Ff = clearBitForPdf(this.Ff, 21);
  5218. }
  5219. }
  5220. });
  5221. /**
  5222. * (PDF 1.4) If set, text entered in the field shall not be spell-checked.
  5223. *
  5224. * @name AcroFormTextField#doNotSpellCheck
  5225. * @type {boolean}
  5226. */
  5227. Object.defineProperty(this, 'doNotSpellCheck', {
  5228. enumerable: true,
  5229. configurable: true,
  5230. get: function get() {
  5231. return Boolean(getBitForPdf(this.Ff, 23));
  5232. },
  5233. set: function set(value) {
  5234. if (Boolean(value) === true) {
  5235. this.Ff = setBitForPdf(this.Ff, 23);
  5236. } else {
  5237. this.Ff = clearBitForPdf(this.Ff, 23);
  5238. }
  5239. }
  5240. });
  5241. /**
  5242. * (PDF 1.4) If set, the field shall not scroll (horizontally for single-line fields, vertically for multiple-line fields) to accommodate more text than fits within its annotation rectangle. Once the field is full, no further text shall be accepted for interactive form filling; for noninteractive form filling, the filler should take care not to add more character than will visibly fit in the defined area.
  5243. *
  5244. * @name AcroFormTextField#doNotScroll
  5245. * @type {boolean}
  5246. */
  5247. Object.defineProperty(this, 'doNotScroll', {
  5248. enumerable: true,
  5249. configurable: true,
  5250. get: function get() {
  5251. return Boolean(getBitForPdf(this.Ff, 24));
  5252. },
  5253. set: function set(value) {
  5254. if (Boolean(value) === true) {
  5255. this.Ff = setBitForPdf(this.Ff, 24);
  5256. } else {
  5257. this.Ff = clearBitForPdf(this.Ff, 24);
  5258. }
  5259. }
  5260. });
  5261. /**
  5262. * (PDF 1.5) May be set only if the MaxLen entry is present in the text field dictionary (see Table 229) and if the Multiline, Password, and FileSelect flags are clear. If set, the field shall be automatically divided into as many equally spaced positions, or combs, as the value of MaxLen, and the text is laid out into those combs.
  5263. *
  5264. * @name AcroFormTextField#comb
  5265. * @type {boolean}
  5266. */
  5267. Object.defineProperty(this, 'comb', {
  5268. enumerable: true,
  5269. configurable: true,
  5270. get: function get() {
  5271. return Boolean(getBitForPdf(this.Ff, 25));
  5272. },
  5273. set: function set(value) {
  5274. if (Boolean(value) === true) {
  5275. this.Ff = setBitForPdf(this.Ff, 25);
  5276. } else {
  5277. this.Ff = clearBitForPdf(this.Ff, 25);
  5278. }
  5279. }
  5280. });
  5281. /**
  5282. * (PDF 1.5) If set, the value of this field shall be a rich text string (see 12.7.3.4, “Rich Text Strings”). If the field has a value, the RV entry of the field dictionary (Table 222) shall specify the rich text string.
  5283. *
  5284. * @name AcroFormTextField#richText
  5285. * @type {boolean}
  5286. */
  5287. Object.defineProperty(this, 'richText', {
  5288. enumerable: true,
  5289. configurable: true,
  5290. get: function get() {
  5291. return Boolean(getBitForPdf(this.Ff, 26));
  5292. },
  5293. set: function set(value) {
  5294. if (Boolean(value) === true) {
  5295. this.Ff = setBitForPdf(this.Ff, 26);
  5296. } else {
  5297. this.Ff = clearBitForPdf(this.Ff, 26);
  5298. }
  5299. }
  5300. });
  5301. var _MaxLen = null;
  5302. Object.defineProperty(this, 'MaxLen', {
  5303. enumerable: true,
  5304. configurable: false,
  5305. get: function get() {
  5306. return _MaxLen;
  5307. },
  5308. set: function set(value) {
  5309. _MaxLen = value;
  5310. }
  5311. });
  5312. /**
  5313. * (Optional; inheritable) The maximum length of the field’s text, in characters.
  5314. *
  5315. * @name AcroFormTextField#maxLength
  5316. * @type {number}
  5317. */
  5318. Object.defineProperty(this, 'maxLength', {
  5319. enumerable: true,
  5320. configurable: true,
  5321. get: function get() {
  5322. return _MaxLen;
  5323. },
  5324. set: function set(value) {
  5325. if (Number.isInteger(value)) {
  5326. _MaxLen = value;
  5327. }
  5328. }
  5329. });
  5330. Object.defineProperty(this, 'hasAppearanceStream', {
  5331. enumerable: true,
  5332. configurable: true,
  5333. get: function get() {
  5334. return this.V || this.DV;
  5335. }
  5336. });
  5337. };
  5338. inherit(AcroFormTextField, AcroFormField);
  5339. /**
  5340. * @class AcroFormPasswordField
  5341. * @extends AcroFormTextField
  5342. * @extends AcroFormField
  5343. */
  5344. var AcroFormPasswordField = function AcroFormPasswordField() {
  5345. AcroFormTextField.call(this);
  5346. /**
  5347. * If set, the field is intended for entering a secure password that should not be echoed visibly to the screen. Characters typed from the keyboard shall instead be echoed in some unreadable form, such as asterisks or bullet characters.
  5348. * NOTE To protect password confidentiality, readers should never store the value of the text field in the PDF file if this flag is set.
  5349. *
  5350. * @name AcroFormTextField#password
  5351. * @type {boolean}
  5352. */
  5353. Object.defineProperty(this, 'password', {
  5354. enumerable: true,
  5355. configurable: true,
  5356. get: function get() {
  5357. return Boolean(getBitForPdf(this.Ff, 14));
  5358. },
  5359. set: function set(value) {
  5360. if (Boolean(value) === true) {
  5361. this.Ff = setBitForPdf(this.Ff, 14);
  5362. } else {
  5363. this.Ff = clearBitForPdf(this.Ff, 14);
  5364. }
  5365. }
  5366. });
  5367. this.password = true;
  5368. };
  5369. inherit(AcroFormPasswordField, AcroFormTextField); // Contains Methods for creating standard appearances
  5370. var AcroFormAppearance = {
  5371. CheckBox: {
  5372. createAppearanceStream: function createAppearanceStream() {
  5373. var appearance = {
  5374. N: {
  5375. On: AcroFormAppearance.CheckBox.YesNormal
  5376. },
  5377. D: {
  5378. On: AcroFormAppearance.CheckBox.YesPushDown,
  5379. Off: AcroFormAppearance.CheckBox.OffPushDown
  5380. }
  5381. };
  5382. return appearance;
  5383. },
  5384. /**
  5385. * Returns the standard On Appearance for a CheckBox
  5386. *
  5387. * @returns {AcroFormXObject}
  5388. */
  5389. YesPushDown: function YesPushDown(formObject) {
  5390. var xobj = createFormXObject(formObject);
  5391. var stream = [];
  5392. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5393. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5394. var calcRes = calculateX(formObject, formObject.caption);
  5395. stream.push("0.749023 g");
  5396. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5397. stream.push("f");
  5398. stream.push("BMC");
  5399. stream.push("q");
  5400. stream.push("0 0 1 rg");
  5401. stream.push("/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor);
  5402. stream.push("BT");
  5403. stream.push(calcRes.text);
  5404. stream.push("ET");
  5405. stream.push("Q");
  5406. stream.push("EMC");
  5407. xobj.stream = stream.join("\n");
  5408. return xobj;
  5409. },
  5410. YesNormal: function YesNormal(formObject) {
  5411. var xobj = createFormXObject(formObject);
  5412. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5413. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5414. var stream = [];
  5415. var height = AcroFormAppearance.internal.getHeight(formObject);
  5416. var width = AcroFormAppearance.internal.getWidth(formObject);
  5417. var calcRes = calculateX(formObject, formObject.caption);
  5418. stream.push("1 g");
  5419. stream.push("0 0 " + f2(width) + " " + f2(height) + " re");
  5420. stream.push("f");
  5421. stream.push("q");
  5422. stream.push("0 0 1 rg");
  5423. stream.push("0 0 " + f2(width - 1) + " " + f2(height - 1) + " re");
  5424. stream.push("W");
  5425. stream.push("n");
  5426. stream.push("0 g");
  5427. stream.push("BT");
  5428. stream.push("/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor);
  5429. stream.push(calcRes.text);
  5430. stream.push("ET");
  5431. stream.push("Q");
  5432. xobj.stream = stream.join("\n");
  5433. return xobj;
  5434. },
  5435. /**
  5436. * Returns the standard Off Appearance for a CheckBox
  5437. *
  5438. * @returns {AcroFormXObject}
  5439. */
  5440. OffPushDown: function OffPushDown(formObject) {
  5441. var xobj = createFormXObject(formObject);
  5442. var stream = [];
  5443. stream.push("0.749023 g");
  5444. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5445. stream.push("f");
  5446. xobj.stream = stream.join("\n");
  5447. return xobj;
  5448. }
  5449. },
  5450. RadioButton: {
  5451. Circle: {
  5452. createAppearanceStream: function createAppearanceStream(name) {
  5453. var appearanceStreamContent = {
  5454. D: {
  5455. 'Off': AcroFormAppearance.RadioButton.Circle.OffPushDown
  5456. },
  5457. N: {}
  5458. };
  5459. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Circle.YesNormal;
  5460. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Circle.YesPushDown;
  5461. return appearanceStreamContent;
  5462. },
  5463. getCA: function getCA() {
  5464. return 'l';
  5465. },
  5466. YesNormal: function YesNormal(formObject) {
  5467. var xobj = createFormXObject(formObject);
  5468. var stream = []; // Make the Radius of the Circle relative to min(height, width) of formObject
  5469. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5470. DotRadius = Number((DotRadius * 0.9).toFixed(5));
  5471. var c = AcroFormAppearance.internal.Bezier_C;
  5472. var DotRadiusBezier = Number((DotRadius * c).toFixed(5));
  5473. /*
  5474. * The Following is a Circle created with Bezier-Curves.
  5475. */
  5476. stream.push("q");
  5477. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5478. stream.push(DotRadius + " 0 m");
  5479. stream.push(DotRadius + " " + DotRadiusBezier + " " + DotRadiusBezier + " " + DotRadius + " 0 " + DotRadius + " c");
  5480. stream.push("-" + DotRadiusBezier + " " + DotRadius + " -" + DotRadius + " " + DotRadiusBezier + " -" + DotRadius + " 0 c");
  5481. stream.push("-" + DotRadius + " -" + DotRadiusBezier + " -" + DotRadiusBezier + " -" + DotRadius + " 0 -" + DotRadius + " c");
  5482. stream.push(DotRadiusBezier + " -" + DotRadius + " " + DotRadius + " -" + DotRadiusBezier + " " + DotRadius + " 0 c");
  5483. stream.push("f");
  5484. stream.push("Q");
  5485. xobj.stream = stream.join("\n");
  5486. return xobj;
  5487. },
  5488. YesPushDown: function YesPushDown(formObject) {
  5489. var xobj = createFormXObject(formObject);
  5490. var stream = [];
  5491. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5492. var DotRadius = Number((DotRadius * 0.9).toFixed(5)); // Save results for later use; no need to waste
  5493. // processor ticks on doing math
  5494. var k = Number((DotRadius * 2).toFixed(5));
  5495. var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5496. var dc = Number((DotRadius * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5497. stream.push("0.749023 g");
  5498. stream.push("q");
  5499. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5500. stream.push(k + " 0 m");
  5501. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  5502. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  5503. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  5504. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  5505. stream.push("f");
  5506. stream.push("Q");
  5507. stream.push("0 g");
  5508. stream.push("q");
  5509. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5510. stream.push(DotRadius + " 0 m");
  5511. stream.push("" + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c");
  5512. stream.push("-" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c");
  5513. stream.push("-" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c");
  5514. stream.push(dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c");
  5515. stream.push("f");
  5516. stream.push("Q");
  5517. xobj.stream = stream.join("\n");
  5518. return xobj;
  5519. },
  5520. OffPushDown: function OffPushDown(formObject) {
  5521. var xobj = createFormXObject(formObject);
  5522. var stream = [];
  5523. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5524. var DotRadius = Number((DotRadius * 0.9).toFixed(5)); // Save results for later use; no need to waste
  5525. // processor ticks on doing math
  5526. var k = Number((DotRadius * 2).toFixed(5));
  5527. var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5528. stream.push("0.749023 g");
  5529. stream.push("q");
  5530. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5531. stream.push(k + " 0 m");
  5532. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  5533. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  5534. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  5535. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  5536. stream.push("f");
  5537. stream.push("Q");
  5538. xobj.stream = stream.join("\n");
  5539. return xobj;
  5540. }
  5541. },
  5542. Cross: {
  5543. /**
  5544. * Creates the Actual AppearanceDictionary-References
  5545. *
  5546. * @param {string} name
  5547. * @returns {Object}
  5548. * @ignore
  5549. */
  5550. createAppearanceStream: function createAppearanceStream(name) {
  5551. var appearanceStreamContent = {
  5552. D: {
  5553. 'Off': AcroFormAppearance.RadioButton.Cross.OffPushDown
  5554. },
  5555. N: {}
  5556. };
  5557. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Cross.YesNormal;
  5558. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Cross.YesPushDown;
  5559. return appearanceStreamContent;
  5560. },
  5561. getCA: function getCA() {
  5562. return '8';
  5563. },
  5564. YesNormal: function YesNormal(formObject) {
  5565. var xobj = createFormXObject(formObject);
  5566. var stream = [];
  5567. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  5568. stream.push("q");
  5569. stream.push("1 1 " + f2(AcroFormAppearance.internal.getWidth(formObject) - 2) + " " + f2(AcroFormAppearance.internal.getHeight(formObject) - 2) + " re");
  5570. stream.push("W");
  5571. stream.push("n");
  5572. stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
  5573. stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
  5574. stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
  5575. stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
  5576. stream.push("s");
  5577. stream.push("Q");
  5578. xobj.stream = stream.join("\n");
  5579. return xobj;
  5580. },
  5581. YesPushDown: function YesPushDown(formObject) {
  5582. var xobj = createFormXObject(formObject);
  5583. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  5584. var stream = [];
  5585. stream.push("0.749023 g");
  5586. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5587. stream.push("f");
  5588. stream.push("q");
  5589. stream.push("1 1 " + f2(AcroFormAppearance.internal.getWidth(formObject) - 2) + " " + f2(AcroFormAppearance.internal.getHeight(formObject) - 2) + " re");
  5590. stream.push("W");
  5591. stream.push("n");
  5592. stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
  5593. stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
  5594. stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
  5595. stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
  5596. stream.push("s");
  5597. stream.push("Q");
  5598. xobj.stream = stream.join("\n");
  5599. return xobj;
  5600. },
  5601. OffPushDown: function OffPushDown(formObject) {
  5602. var xobj = createFormXObject(formObject);
  5603. var stream = [];
  5604. stream.push("0.749023 g");
  5605. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5606. stream.push("f");
  5607. xobj.stream = stream.join("\n");
  5608. return xobj;
  5609. }
  5610. }
  5611. },
  5612. /**
  5613. * Returns the standard Appearance
  5614. *
  5615. * @returns {AcroFormXObject}
  5616. */
  5617. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  5618. // Set Helvetica to Standard Font (size: auto)
  5619. // Color: Black
  5620. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5621. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5622. var fontSize = formObject.fontSize;
  5623. var result = '/' + fontKey + ' ' + fontSize + ' Tf ' + encodedColor;
  5624. return result;
  5625. }
  5626. };
  5627. AcroFormAppearance.internal = {
  5628. Bezier_C: 0.551915024494,
  5629. calculateCross: function calculateCross(formObject) {
  5630. var width = AcroFormAppearance.internal.getWidth(formObject);
  5631. var height = AcroFormAppearance.internal.getHeight(formObject);
  5632. var a = Math.min(width, height);
  5633. var cross = {
  5634. x1: {
  5635. // upperLeft
  5636. x: (width - a) / 2,
  5637. y: (height - a) / 2 + a // height - borderPadding
  5638. },
  5639. x2: {
  5640. // lowerRight
  5641. x: (width - a) / 2 + a,
  5642. y: (height - a) / 2 // borderPadding
  5643. },
  5644. x3: {
  5645. // lowerLeft
  5646. x: (width - a) / 2,
  5647. y: (height - a) / 2 // borderPadding
  5648. },
  5649. x4: {
  5650. // upperRight
  5651. x: (width - a) / 2 + a,
  5652. y: (height - a) / 2 + a // height - borderPadding
  5653. }
  5654. };
  5655. return cross;
  5656. }
  5657. };
  5658. AcroFormAppearance.internal.getWidth = function (formObject) {
  5659. var result = 0;
  5660. if (_typeof(formObject) === "object") {
  5661. result = scale(formObject.Rect[2]);
  5662. }
  5663. return result;
  5664. };
  5665. AcroFormAppearance.internal.getHeight = function (formObject) {
  5666. var result = 0;
  5667. if (_typeof(formObject) === "object") {
  5668. result = scale(formObject.Rect[3]);
  5669. }
  5670. return result;
  5671. }; // Public:
  5672. /**
  5673. * Add an AcroForm-Field to the jsPDF-instance
  5674. *
  5675. * @name addField
  5676. * @function
  5677. * @instance
  5678. * @param {Object} fieldObject
  5679. * @returns {jsPDF}
  5680. */
  5681. var addField = jsPDFAPI.addField = function (fieldObject) {
  5682. initializeAcroForm.call(this);
  5683. if (fieldObject instanceof AcroFormField) {
  5684. putForm.call(this, fieldObject);
  5685. } else {
  5686. throw new Error('Invalid argument passed to jsPDF.addField.');
  5687. }
  5688. fieldObject.page = scope.internal.getCurrentPageInfo().pageNumber;
  5689. return this;
  5690. };
  5691. /**
  5692. * @name addButton
  5693. * @function
  5694. * @instance
  5695. * @param {AcroFormButton} options
  5696. * @returns {jsPDF}
  5697. * @deprecated
  5698. */
  5699. var addButton = jsPDFAPI.addButton = function (button) {
  5700. if (button instanceof AcroFormButton === false) {
  5701. throw new Error('Invalid argument passed to jsPDF.addButton.');
  5702. }
  5703. return addField.call(this, button);
  5704. };
  5705. /**
  5706. * @name addTextField
  5707. * @function
  5708. * @instance
  5709. * @param {AcroFormTextField} textField
  5710. * @returns {jsPDF}
  5711. * @deprecated
  5712. */
  5713. var addTextField = jsPDFAPI.addTextField = function (textField) {
  5714. if (textField instanceof AcroFormTextField === false) {
  5715. throw new Error('Invalid argument passed to jsPDF.addTextField.');
  5716. }
  5717. return addField.call(this, textField);
  5718. };
  5719. /**
  5720. * @name addChoiceField
  5721. * @function
  5722. * @instance
  5723. * @param {AcroFormChoiceField}
  5724. * @returns {jsPDF}
  5725. * @deprecated
  5726. */
  5727. var addChoiceField = jsPDFAPI.addChoiceField = function (choiceField) {
  5728. if (choiceField instanceof AcroFormChoiceField === false) {
  5729. throw new Error('Invalid argument passed to jsPDF.addChoiceField.');
  5730. }
  5731. return addField.call(this, choiceField);
  5732. };
  5733. if (_typeof(globalObj) == "object" && typeof globalObj["ChoiceField"] === "undefined" && typeof globalObj["ListBox"] === "undefined" && typeof globalObj["ComboBox"] === "undefined" && typeof globalObj["EditBox"] === "undefined" && typeof globalObj["Button"] === "undefined" && typeof globalObj["PushButton"] === "undefined" && typeof globalObj["RadioButton"] === "undefined" && typeof globalObj["CheckBox"] === "undefined" && typeof globalObj["TextField"] === "undefined" && typeof globalObj["PasswordField"] === "undefined") {
  5734. globalObj["ChoiceField"] = AcroFormChoiceField;
  5735. globalObj["ListBox"] = AcroFormListBox;
  5736. globalObj["ComboBox"] = AcroFormComboBox;
  5737. globalObj["EditBox"] = AcroFormEditBox;
  5738. globalObj["Button"] = AcroFormButton;
  5739. globalObj["PushButton"] = AcroFormPushButton;
  5740. globalObj["RadioButton"] = AcroFormRadioButton;
  5741. globalObj["CheckBox"] = AcroFormCheckBox;
  5742. globalObj["TextField"] = AcroFormTextField;
  5743. globalObj["PasswordField"] = AcroFormPasswordField; // backwardsCompatibility
  5744. globalObj["AcroForm"] = {
  5745. Appearance: AcroFormAppearance
  5746. };
  5747. } else {
  5748. console.warn("AcroForm-Classes are not populated into global-namespace, because the class-Names exist already.");
  5749. }
  5750. jsPDFAPI.AcroFormChoiceField = AcroFormChoiceField;
  5751. jsPDFAPI.AcroFormListBox = AcroFormListBox;
  5752. jsPDFAPI.AcroFormComboBox = AcroFormComboBox;
  5753. jsPDFAPI.AcroFormEditBox = AcroFormEditBox;
  5754. jsPDFAPI.AcroFormButton = AcroFormButton;
  5755. jsPDFAPI.AcroFormPushButton = AcroFormPushButton;
  5756. jsPDFAPI.AcroFormRadioButton = AcroFormRadioButton;
  5757. jsPDFAPI.AcroFormCheckBox = AcroFormCheckBox;
  5758. jsPDFAPI.AcroFormTextField = AcroFormTextField;
  5759. jsPDFAPI.AcroFormPasswordField = AcroFormPasswordField;
  5760. jsPDFAPI.AcroFormAppearance = AcroFormAppearance;
  5761. jsPDFAPI.AcroForm = {
  5762. ChoiceField: AcroFormChoiceField,
  5763. ListBox: AcroFormListBox,
  5764. ComboBox: AcroFormComboBox,
  5765. EditBox: AcroFormEditBox,
  5766. Button: AcroFormButton,
  5767. PushButton: AcroFormPushButton,
  5768. RadioButton: AcroFormRadioButton,
  5769. CheckBox: AcroFormCheckBox,
  5770. TextField: AcroFormTextField,
  5771. PasswordField: AcroFormPasswordField,
  5772. Appearance: AcroFormAppearance
  5773. };
  5774. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  5775. /** @license
  5776. * jsPDF addImage plugin
  5777. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  5778. * 2013 Chris Dowling, https://github.com/gingerchris
  5779. * 2013 Trinh Ho, https://github.com/ineedfat
  5780. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  5781. * 2013 Norah Smith, https://github.com/burnburnrocket
  5782. * 2014 Diego Casorran, https://github.com/diegocr
  5783. * 2014 James Robb, https://github.com/jamesbrobb
  5784. *
  5785. *
  5786. */
  5787. /**
  5788. * @name addImage
  5789. * @module
  5790. */
  5791. (function (jsPDFAPI) {
  5792. var namespace = 'addImage_';
  5793. var imageFileTypeHeaders = {
  5794. PNG: [[0x89, 0x50, 0x4e, 0x47]],
  5795. TIFF: [[0x4D, 0x4D, 0x00, 0x2A], //Motorola
  5796. [0x49, 0x49, 0x2A, 0x00] //Intel
  5797. ],
  5798. JPEG: [[0xFF, 0xD8, 0xFF, 0xE0, undefined, undefined, 0x4A, 0x46, 0x49, 0x46, 0x00], //JFIF
  5799. [0xFF, 0xD8, 0xFF, 0xE1, undefined, undefined, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00] //Exif
  5800. ],
  5801. JPEG2000: [[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20]],
  5802. GIF87a: [[0x47, 0x49, 0x46, 0x38, 0x37, 0x61]],
  5803. GIF89a: [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61]],
  5804. BMP: [[0x42, 0x4D], //BM - Windows 3.1x, 95, NT, ... etc.
  5805. [0x42, 0x41], //BA - OS/2 struct bitmap array
  5806. [0x43, 0x49], //CI - OS/2 struct color icon
  5807. [0x43, 0x50], //CP - OS/2 const color pointer
  5808. [0x49, 0x43], //IC - OS/2 struct icon
  5809. [0x50, 0x54] //PT - OS/2 pointer
  5810. ]
  5811. };
  5812. /**
  5813. * Recognize filetype of Image by magic-bytes
  5814. *
  5815. * https://en.wikipedia.org/wiki/List_of_file_signatures
  5816. *
  5817. * @name getImageFileTypeByImageData
  5818. * @public
  5819. * @function
  5820. * @param {string|arraybuffer} imageData imageData as binary String or arraybuffer
  5821. * @param {string} format format of file if filetype-recognition fails, e.g. 'JPEG'
  5822. *
  5823. * @returns {string} filetype of Image
  5824. */
  5825. var getImageFileTypeByImageData = jsPDFAPI.getImageFileTypeByImageData = function (imageData, fallbackFormat) {
  5826. fallbackFormat = fallbackFormat || 'UNKNOWN';
  5827. var i;
  5828. var j;
  5829. var result = 'UNKNOWN';
  5830. var headerSchemata;
  5831. var compareResult;
  5832. var fileType;
  5833. if (jsPDFAPI.isArrayBufferView(imageData)) {
  5834. imageData = jsPDFAPI.arrayBufferToBinaryString(imageData);
  5835. }
  5836. for (fileType in imageFileTypeHeaders) {
  5837. headerSchemata = imageFileTypeHeaders[fileType];
  5838. for (i = 0; i < headerSchemata.length; i += 1) {
  5839. compareResult = true;
  5840. for (j = 0; j < headerSchemata[i].length; j += 1) {
  5841. if (headerSchemata[i][j] === undefined) {
  5842. continue;
  5843. }
  5844. if (headerSchemata[i][j] !== imageData.charCodeAt(j)) {
  5845. compareResult = false;
  5846. break;
  5847. }
  5848. }
  5849. if (compareResult === true) {
  5850. result = fileType;
  5851. break;
  5852. }
  5853. }
  5854. }
  5855. if (result === 'UNKNOWN' && fallbackFormat !== 'UNKNOWN') {
  5856. console.warn('FileType of Image not recognized. Processing image as "' + fallbackFormat + '".');
  5857. result = fallbackFormat;
  5858. }
  5859. return result;
  5860. }; // Image functionality ported from pdf.js
  5861. var putImage = function putImage(img) {
  5862. var objectNumber = this.internal.newObject(),
  5863. out = this.internal.write,
  5864. putStream = this.internal.putStream,
  5865. getFilters = this.internal.getFilters;
  5866. var filters = getFilters();
  5867. while (filters.indexOf('FlateEncode') !== -1) {
  5868. filters.splice(filters.indexOf('FlateEncode'), 1);
  5869. }
  5870. img['n'] = objectNumber;
  5871. var additionalKeyValues = [];
  5872. additionalKeyValues.push({
  5873. key: 'Type',
  5874. value: '/XObject'
  5875. });
  5876. additionalKeyValues.push({
  5877. key: 'Subtype',
  5878. value: '/Image'
  5879. });
  5880. additionalKeyValues.push({
  5881. key: 'Width',
  5882. value: img['w']
  5883. });
  5884. additionalKeyValues.push({
  5885. key: 'Height',
  5886. value: img['h']
  5887. });
  5888. if (img['cs'] === this.color_spaces.INDEXED) {
  5889. additionalKeyValues.push({
  5890. key: 'ColorSpace',
  5891. value: '[/Indexed /DeviceRGB ' // if an indexed png defines more than one colour with transparency, we've created a smask
  5892. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]'
  5893. });
  5894. } else {
  5895. additionalKeyValues.push({
  5896. key: 'ColorSpace',
  5897. value: '/' + img['cs']
  5898. });
  5899. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  5900. additionalKeyValues.push({
  5901. key: 'Decode',
  5902. value: '[1 0 1 0 1 0 1 0]'
  5903. });
  5904. }
  5905. }
  5906. additionalKeyValues.push({
  5907. key: 'BitsPerComponent',
  5908. value: img['bpc']
  5909. });
  5910. if ('dp' in img) {
  5911. additionalKeyValues.push({
  5912. key: 'DecodeParms',
  5913. value: '<<' + img['dp'] + '>>'
  5914. });
  5915. }
  5916. if ('trns' in img && img['trns'].constructor == Array) {
  5917. var trns = '',
  5918. i = 0,
  5919. len = img['trns'].length;
  5920. for (; i < len; i++) {
  5921. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  5922. }
  5923. additionalKeyValues.push({
  5924. key: 'Mask',
  5925. value: '[' + trns + ']'
  5926. });
  5927. }
  5928. if ('smask' in img) {
  5929. additionalKeyValues.push({
  5930. key: 'SMask',
  5931. value: objectNumber + 1 + ' 0 R'
  5932. });
  5933. }
  5934. var alreadyAppliedFilters = typeof img['f'] !== "undefined" ? ['/' + img['f']] : undefined;
  5935. putStream({
  5936. data: img['data'],
  5937. additionalKeyValues: additionalKeyValues,
  5938. alreadyAppliedFilters: alreadyAppliedFilters
  5939. });
  5940. out('endobj'); // Soft mask
  5941. if ('smask' in img) {
  5942. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  5943. var smask = {
  5944. 'w': img['w'],
  5945. 'h': img['h'],
  5946. 'cs': 'DeviceGray',
  5947. 'bpc': img['bpc'],
  5948. 'dp': dp,
  5949. 'data': img['smask']
  5950. };
  5951. if ('f' in img) smask.f = img['f'];
  5952. putImage.call(this, smask);
  5953. } //Palette
  5954. if (img['cs'] === this.color_spaces.INDEXED) {
  5955. this.internal.newObject(); //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  5956. //putStream(zlib.compress(img['pal']));
  5957. putStream({
  5958. data: this.arrayBufferToBinaryString(new Uint8Array(img['pal']))
  5959. });
  5960. out('endobj');
  5961. }
  5962. },
  5963. putResourcesCallback = function putResourcesCallback() {
  5964. var images = this.internal.collections[namespace + 'images'];
  5965. for (var i in images) {
  5966. putImage.call(this, images[i]);
  5967. }
  5968. },
  5969. putXObjectsDictCallback = function putXObjectsDictCallback() {
  5970. var images = this.internal.collections[namespace + 'images'],
  5971. out = this.internal.write,
  5972. image;
  5973. for (var i in images) {
  5974. image = images[i];
  5975. out('/I' + image['i'], image['n'], '0', 'R');
  5976. }
  5977. },
  5978. checkCompressValue = function checkCompressValue(value) {
  5979. if (value && typeof value === 'string') value = value.toUpperCase();
  5980. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  5981. },
  5982. getImages = function getImages() {
  5983. var images = this.internal.collections[namespace + 'images']; //first run, so initialise stuff
  5984. if (!images) {
  5985. this.internal.collections[namespace + 'images'] = images = {};
  5986. this.internal.events.subscribe('putResources', putResourcesCallback);
  5987. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  5988. }
  5989. return images;
  5990. },
  5991. getImageIndex = function getImageIndex(images) {
  5992. var imageIndex = 0;
  5993. if (images) {
  5994. // this is NOT the first time this method is ran on this instance of jsPDF object.
  5995. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  5996. var i = 0;
  5997. for (var e in o) {
  5998. if (o.hasOwnProperty(e)) {
  5999. i++;
  6000. }
  6001. }
  6002. return i;
  6003. }(images);
  6004. }
  6005. return imageIndex;
  6006. },
  6007. notDefined = function notDefined(value) {
  6008. return typeof value === 'undefined' || value === null || value.length === 0;
  6009. },
  6010. generateAliasFromImageData = function generateAliasFromImageData(imageData) {
  6011. if (typeof imageData === 'string') {
  6012. return jsPDFAPI.sHashCode(imageData);
  6013. }
  6014. if (jsPDFAPI.isArrayBufferView(imageData)) {
  6015. return jsPDFAPI.sHashCode(jsPDFAPI.arrayBufferToBinaryString(imageData));
  6016. }
  6017. return null;
  6018. },
  6019. isImageTypeSupported = function isImageTypeSupported(type) {
  6020. return typeof jsPDFAPI["process" + type.toUpperCase()] === "function";
  6021. },
  6022. isDOMElement = function isDOMElement(object) {
  6023. return _typeof(object) === 'object' && object.nodeType === 1;
  6024. },
  6025. createDataURIFromElement = function createDataURIFromElement(element, format) {
  6026. //if element is an image which uses data url definition, just return the dataurl
  6027. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  6028. var src = '' + element.getAttribute('src'); //is base64 encoded dataUrl, directly process it
  6029. if (src.indexOf('data:image/') === 0) {
  6030. return unescape(src);
  6031. } //it is probably an url, try to load it
  6032. var tmpImageData = jsPDFAPI.loadFile(src);
  6033. if (tmpImageData !== undefined) {
  6034. return btoa(tmpImageData);
  6035. }
  6036. }
  6037. if (element.nodeName === 'CANVAS') {
  6038. var canvas = element;
  6039. return element.toDataURL('image/jpeg', 1.0);
  6040. } //absolute fallback method
  6041. var canvas = document.createElement('canvas');
  6042. canvas.width = element.clientWidth || element.width;
  6043. canvas.height = element.clientHeight || element.height;
  6044. var ctx = canvas.getContext('2d');
  6045. if (!ctx) {
  6046. throw 'addImage requires canvas to be supported by browser.';
  6047. }
  6048. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  6049. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  6050. },
  6051. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  6052. var cached_info;
  6053. if (images) {
  6054. for (var e in images) {
  6055. if (alias === images[e].alias) {
  6056. cached_info = images[e];
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. return cached_info;
  6062. },
  6063. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  6064. if (!w && !h) {
  6065. w = -96;
  6066. h = -96;
  6067. }
  6068. if (w < 0) {
  6069. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  6070. }
  6071. if (h < 0) {
  6072. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  6073. }
  6074. if (w === 0) {
  6075. w = h * info['w'] / info['h'];
  6076. }
  6077. if (h === 0) {
  6078. h = w * info['h'] / info['w'];
  6079. }
  6080. return [w, h];
  6081. },
  6082. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images, rotation) {
  6083. var dims = determineWidthAndHeight.call(this, w, h, info),
  6084. coord = this.internal.getCoordinateString,
  6085. vcoord = this.internal.getVerticalCoordinateString;
  6086. w = dims[0];
  6087. h = dims[1];
  6088. images[index] = info;
  6089. if (rotation) {
  6090. rotation *= Math.PI / 180;
  6091. var c = Math.cos(rotation);
  6092. var s = Math.sin(rotation); //like in pdf Reference do it 4 digits instead of 2
  6093. var f4 = function f4(number) {
  6094. return number.toFixed(4);
  6095. };
  6096. var rotationTransformationMatrix = [f4(c), f4(s), f4(s * -1), f4(c), 0, 0, 'cm'];
  6097. }
  6098. this.internal.write('q'); //Save graphics state
  6099. if (rotation) {
  6100. this.internal.write([1, '0', '0', 1, coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate
  6101. this.internal.write(rotationTransformationMatrix.join(' ')); //Rotate
  6102. this.internal.write([coord(w), '0', '0', coord(h), '0', '0', 'cm'].join(' ')); //Scale
  6103. } else {
  6104. this.internal.write([coord(w), '0', '0', coord(h), coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate and Scale
  6105. }
  6106. this.internal.write('/I' + info['i'] + ' Do'); //Paint Image
  6107. this.internal.write('Q'); //Restore graphics state
  6108. };
  6109. /**
  6110. * COLOR SPACES
  6111. */
  6112. jsPDFAPI.color_spaces = {
  6113. DEVICE_RGB: 'DeviceRGB',
  6114. DEVICE_GRAY: 'DeviceGray',
  6115. DEVICE_CMYK: 'DeviceCMYK',
  6116. CAL_GREY: 'CalGray',
  6117. CAL_RGB: 'CalRGB',
  6118. LAB: 'Lab',
  6119. ICC_BASED: 'ICCBased',
  6120. INDEXED: 'Indexed',
  6121. PATTERN: 'Pattern',
  6122. SEPARATION: 'Separation',
  6123. DEVICE_N: 'DeviceN'
  6124. };
  6125. /**
  6126. * DECODE METHODS
  6127. */
  6128. jsPDFAPI.decode = {
  6129. DCT_DECODE: 'DCTDecode',
  6130. FLATE_DECODE: 'FlateDecode',
  6131. LZW_DECODE: 'LZWDecode',
  6132. JPX_DECODE: 'JPXDecode',
  6133. JBIG2_DECODE: 'JBIG2Decode',
  6134. ASCII85_DECODE: 'ASCII85Decode',
  6135. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  6136. RUN_LENGTH_DECODE: 'RunLengthDecode',
  6137. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  6138. };
  6139. /**
  6140. * IMAGE COMPRESSION TYPES
  6141. */
  6142. jsPDFAPI.image_compression = {
  6143. NONE: 'NONE',
  6144. FAST: 'FAST',
  6145. MEDIUM: 'MEDIUM',
  6146. SLOW: 'SLOW'
  6147. };
  6148. /**
  6149. * @name sHashCode
  6150. * @function
  6151. * @param {string} str
  6152. * @returns {string}
  6153. */
  6154. jsPDFAPI.sHashCode = function (str) {
  6155. str = str || "";
  6156. var hash = 0,
  6157. i,
  6158. chr;
  6159. if (str.length === 0) return hash;
  6160. for (i = 0; i < str.length; i++) {
  6161. chr = str.charCodeAt(i);
  6162. hash = (hash << 5) - hash + chr;
  6163. hash |= 0; // Convert to 32bit integer
  6164. }
  6165. return hash;
  6166. };
  6167. /**
  6168. * @name isString
  6169. * @function
  6170. * @param {any} object
  6171. * @returns {boolean}
  6172. */
  6173. jsPDFAPI.isString = function (object) {
  6174. return typeof object === 'string';
  6175. };
  6176. /**
  6177. * Validates if given String is a valid Base64-String
  6178. *
  6179. * @name validateStringAsBase64
  6180. * @public
  6181. * @function
  6182. * @param {String} possible Base64-String
  6183. *
  6184. * @returns {boolean}
  6185. */
  6186. jsPDFAPI.validateStringAsBase64 = function (possibleBase64String) {
  6187. possibleBase64String = possibleBase64String || '';
  6188. possibleBase64String.toString().trim();
  6189. var result = true;
  6190. if (possibleBase64String.length === 0) {
  6191. result = false;
  6192. }
  6193. if (possibleBase64String.length % 4 !== 0) {
  6194. result = false;
  6195. }
  6196. if (/^[A-Za-z0-9+\/]+$/.test(possibleBase64String.substr(0, possibleBase64String.length - 2)) === false) {
  6197. result = false;
  6198. }
  6199. if (/^[A-Za-z0-9\/][A-Za-z0-9+\/]|[A-Za-z0-9+\/]=|==$/.test(possibleBase64String.substr(-2)) === false) {
  6200. result = false;
  6201. }
  6202. return result;
  6203. };
  6204. /**
  6205. * Strips out and returns info from a valid base64 data URI
  6206. *
  6207. * @name extractInfoFromBase64DataURI
  6208. * @function
  6209. * @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  6210. * @returns {Array}an Array containing the following
  6211. * [0] the complete data URI
  6212. * [1] <MIME-type>
  6213. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  6214. * [4] <data>
  6215. */
  6216. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  6217. return /^data:([\w]+?\/([\w]+?));\S*;*base64,(.+)$/g.exec(dataURI);
  6218. };
  6219. /**
  6220. * Strips out and returns info from a valid base64 data URI
  6221. *
  6222. * @name extractImageFromDataUrl
  6223. * @function
  6224. * @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  6225. * @returns {Array}an Array containing the following
  6226. * [0] the complete data URI
  6227. * [1] <MIME-type>
  6228. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  6229. * [4] <data>
  6230. */
  6231. jsPDFAPI.extractImageFromDataUrl = function (dataUrl) {
  6232. dataUrl = dataUrl || '';
  6233. var dataUrlParts = dataUrl.split('base64,');
  6234. var result = null;
  6235. if (dataUrlParts.length === 2) {
  6236. var extractedInfo = /^data:(\w*\/\w*);*(charset=[\w=-]*)*;*$/.exec(dataUrlParts[0]);
  6237. if (Array.isArray(extractedInfo)) {
  6238. result = {
  6239. mimeType: extractedInfo[1],
  6240. charset: extractedInfo[2],
  6241. data: dataUrlParts[1]
  6242. };
  6243. }
  6244. }
  6245. return result;
  6246. };
  6247. /**
  6248. * Check to see if ArrayBuffer is supported
  6249. *
  6250. * @name supportsArrayBuffer
  6251. * @function
  6252. * @returns {boolean}
  6253. */
  6254. jsPDFAPI.supportsArrayBuffer = function () {
  6255. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  6256. };
  6257. /**
  6258. * Tests supplied object to determine if ArrayBuffer
  6259. *
  6260. * @name isArrayBuffer
  6261. * @function
  6262. * @param {Object} object an Object
  6263. *
  6264. * @returns {boolean}
  6265. */
  6266. jsPDFAPI.isArrayBuffer = function (object) {
  6267. if (!this.supportsArrayBuffer()) return false;
  6268. return object instanceof ArrayBuffer;
  6269. };
  6270. /**
  6271. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  6272. *
  6273. * @name isArrayBufferView
  6274. * @function
  6275. * @param {Object} object an Object
  6276. * @returns {boolean}
  6277. */
  6278. jsPDFAPI.isArrayBufferView = function (object) {
  6279. if (!this.supportsArrayBuffer()) return false;
  6280. if (typeof Uint32Array === 'undefined') return false;
  6281. 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;
  6282. };
  6283. /**
  6284. * Convert the Buffer to a Binary String
  6285. *
  6286. * @name binaryStringToUint8Array
  6287. * @public
  6288. * @function
  6289. * @param {ArrayBuffer} BinaryString with ImageData
  6290. *
  6291. * @returns {Uint8Array}
  6292. */
  6293. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  6294. /*
  6295. * not sure how efficient this will be will bigger files. Is there a native method?
  6296. */
  6297. var len = binary_string.length;
  6298. var bytes = new Uint8Array(len);
  6299. for (var i = 0; i < len; i++) {
  6300. bytes[i] = binary_string.charCodeAt(i);
  6301. }
  6302. return bytes;
  6303. };
  6304. /**
  6305. * Convert the Buffer to a Binary String
  6306. *
  6307. * @name arrayBufferToBinaryString
  6308. * @public
  6309. * @function
  6310. * @param {ArrayBuffer} ArrayBuffer with ImageData
  6311. *
  6312. * @returns {String}
  6313. */
  6314. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  6315. // if (typeof Uint8Array !== 'undefined' && typeof Uint8Array.prototype.reduce !== 'undefined') {
  6316. // return new Uint8Array(buffer).reduce(function (data, byte) {
  6317. // return data.push(String.fromCharCode(byte)), data;
  6318. // }, []).join('');
  6319. // }
  6320. if (typeof atob === "function") {
  6321. return atob(this.arrayBufferToBase64(buffer));
  6322. }
  6323. };
  6324. /**
  6325. * Converts an ArrayBuffer directly to base64
  6326. *
  6327. * Taken from http://jsperf.com/encoding-xhr-image-data/31
  6328. *
  6329. * Need to test if this is a better solution for larger files
  6330. *
  6331. * @name arrayBufferToBase64
  6332. * @param {arraybuffer} arrayBuffer
  6333. * @public
  6334. * @function
  6335. *
  6336. * @returns {string}
  6337. */
  6338. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  6339. var base64 = '';
  6340. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  6341. var bytes = new Uint8Array(arrayBuffer);
  6342. var byteLength = bytes.byteLength;
  6343. var byteRemainder = byteLength % 3;
  6344. var mainLength = byteLength - byteRemainder;
  6345. var a, b, c, d;
  6346. var chunk; // Main loop deals with bytes in chunks of 3
  6347. for (var i = 0; i < mainLength; i = i + 3) {
  6348. // Combine the three bytes into a single integer
  6349. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2]; // Use bitmasks to extract 6-bit segments from the triplet
  6350. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  6351. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  6352. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  6353. d = chunk & 63; // 63 = 2^6 - 1
  6354. // Convert the raw binary segments to the appropriate ASCII encoding
  6355. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  6356. } // Deal with the remaining bytes and padding
  6357. if (byteRemainder == 1) {
  6358. chunk = bytes[mainLength];
  6359. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  6360. // Set the 4 least significant bits to zero
  6361. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  6362. base64 += encodings[a] + encodings[b] + '==';
  6363. } else if (byteRemainder == 2) {
  6364. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  6365. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  6366. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  6367. // Set the 2 least significant bits to zero
  6368. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  6369. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  6370. }
  6371. return base64;
  6372. };
  6373. /**
  6374. *
  6375. * @name createImageInfo
  6376. * @param {Object} data
  6377. * @param {number} wd width
  6378. * @param {number} ht height
  6379. * @param {Object} cs colorSpace
  6380. * @param {number} bpc bits per channel
  6381. * @param {any} f
  6382. * @param {number} imageIndex
  6383. * @param {string} alias
  6384. * @param {any} dp
  6385. * @param {any} trns
  6386. * @param {any} pal
  6387. * @param {any} smask
  6388. * @param {any} p
  6389. * @public
  6390. * @function
  6391. *
  6392. * @returns {Object}
  6393. */
  6394. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  6395. var info = {
  6396. alias: alias,
  6397. w: wd,
  6398. h: ht,
  6399. cs: cs,
  6400. bpc: bpc,
  6401. i: imageIndex,
  6402. data: data // n: objectNumber will be added by putImage code
  6403. };
  6404. if (f) info.f = f;
  6405. if (dp) info.dp = dp;
  6406. if (trns) info.trns = trns;
  6407. if (pal) info.pal = pal;
  6408. if (smask) info.smask = smask;
  6409. if (p) info.p = p; // predictor parameter for PNG compression
  6410. return info;
  6411. };
  6412. /**
  6413. * Adds an Image to the PDF.
  6414. *
  6415. * @name addImage
  6416. * @public
  6417. * @function
  6418. * @param {string/Image-Element/Canvas-Element/Uint8Array} imageData imageData as base64 encoded DataUrl or Image-HTMLElement or Canvas-HTMLElement
  6419. * @param {string} format format of file if filetype-recognition fails, e.g. 'JPEG'
  6420. * @param {number} x x Coordinate (in units declared at inception of PDF document) against left edge of the page
  6421. * @param {number} y y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  6422. * @param {number} width width of the image (in units declared at inception of PDF document)
  6423. * @param {number} height height of the Image (in units declared at inception of PDF document)
  6424. * @param {string} alias alias of the image (if used multiple times)
  6425. * @param {string} compression compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  6426. * @param {number} rotation rotation of the image in degrees (0-359)
  6427. *
  6428. * @returns jsPDF
  6429. */
  6430. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  6431. var tmpImageData = '';
  6432. if (typeof format !== 'string') {
  6433. var tmp = h;
  6434. h = w;
  6435. w = y;
  6436. y = x;
  6437. x = format;
  6438. format = tmp;
  6439. }
  6440. if (_typeof(imageData) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  6441. var options = imageData;
  6442. imageData = options.imageData;
  6443. format = options.format || format || 'UNKNOWN';
  6444. x = options.x || x || 0;
  6445. y = options.y || y || 0;
  6446. w = options.w || w;
  6447. h = options.h || h;
  6448. alias = options.alias || alias;
  6449. compression = options.compression || compression;
  6450. rotation = options.rotation || options.angle || rotation;
  6451. } //If compression is not explicitly set, determine if we should use compression
  6452. var filters = this.internal.getFilters();
  6453. if (compression === undefined && filters.indexOf('FlateEncode') !== -1) {
  6454. compression = 'SLOW';
  6455. }
  6456. if (typeof imageData === "string") {
  6457. imageData = unescape(imageData);
  6458. }
  6459. if (isNaN(x) || isNaN(y)) {
  6460. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  6461. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  6462. }
  6463. var images = getImages.call(this),
  6464. info,
  6465. dataAsBinaryString;
  6466. if (!(info = checkImagesForAlias(imageData, images))) {
  6467. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format);
  6468. if (notDefined(alias)) alias = generateAliasFromImageData(imageData);
  6469. if (!(info = checkImagesForAlias(alias, images))) {
  6470. if (this.isString(imageData)) {
  6471. tmpImageData = this.convertStringToImageData(imageData);
  6472. if (tmpImageData !== '') {
  6473. imageData = tmpImageData;
  6474. } else {
  6475. tmpImageData = jsPDFAPI.loadFile(imageData);
  6476. if (tmpImageData !== undefined) {
  6477. imageData = tmpImageData;
  6478. }
  6479. }
  6480. }
  6481. format = this.getImageFileTypeByImageData(imageData, format);
  6482. if (!isImageTypeSupported(format)) throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  6483. /**
  6484. * need to test if it's more efficient to convert all binary strings
  6485. * to TypedArray - or should we just leave and process as string?
  6486. */
  6487. if (this.supportsArrayBuffer()) {
  6488. // no need to convert if imageData is already uint8array
  6489. if (!(imageData instanceof Uint8Array)) {
  6490. dataAsBinaryString = imageData;
  6491. imageData = this.binaryStringToUint8Array(imageData);
  6492. }
  6493. }
  6494. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  6495. if (!info) {
  6496. throw new Error('An unknown error occurred whilst processing the image');
  6497. }
  6498. }
  6499. }
  6500. writeImageToPDF.call(this, x, y, w, h, info, info.i, images, rotation);
  6501. return this;
  6502. };
  6503. /**
  6504. * @name convertStringToImageData
  6505. * @function
  6506. * @param {string} stringData
  6507. * @returns {string} binary data
  6508. */
  6509. jsPDFAPI.convertStringToImageData = function (stringData) {
  6510. var base64Info;
  6511. var imageData = '';
  6512. var rawData;
  6513. if (this.isString(stringData)) {
  6514. var base64Info = this.extractImageFromDataUrl(stringData);
  6515. rawData = base64Info !== null ? base64Info.data : stringData;
  6516. try {
  6517. imageData = atob(rawData);
  6518. } catch (e) {
  6519. if (!jsPDFAPI.validateStringAsBase64(rawData)) {
  6520. throw new Error('Supplied Data is not a valid base64-String jsPDF.convertStringToImageData ');
  6521. } else {
  6522. throw new Error('atob-Error in jsPDF.convertStringToImageData ' + e.message);
  6523. }
  6524. }
  6525. }
  6526. return imageData;
  6527. };
  6528. /**
  6529. * JPEG SUPPORT
  6530. **/
  6531. //takes a string imgData containing the raw bytes of
  6532. //a jpeg image and returns [width, height]
  6533. //Algorithm from: http://www.64lines.com/jpeg-width-height
  6534. var getJpegSize = function getJpegSize(imgData) {
  6535. var width, height, numcomponents; // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  6536. if (getImageFileTypeByImageData(imgData) !== 'JPEG') {
  6537. throw new Error('getJpegSize requires a binary string jpeg file');
  6538. }
  6539. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  6540. var i = 4,
  6541. len = imgData.length;
  6542. while (i < len) {
  6543. i += blockLength;
  6544. if (imgData.charCodeAt(i) !== 0xff) {
  6545. throw new Error('getJpegSize could not find the size of the image');
  6546. }
  6547. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  6548. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  6549. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  6550. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  6551. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  6552. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  6553. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  6554. imgData.charCodeAt(i + 1) === 0xc7) {
  6555. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  6556. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  6557. numcomponents = imgData.charCodeAt(i + 9);
  6558. return [width, height, numcomponents];
  6559. } else {
  6560. i += 2;
  6561. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  6562. }
  6563. }
  6564. },
  6565. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  6566. var hdr = data[0] << 8 | data[1];
  6567. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  6568. var len = data.length,
  6569. block = (data[4] << 8) + data[5],
  6570. pos = 4,
  6571. bytes,
  6572. width,
  6573. height,
  6574. numcomponents;
  6575. while (pos < len) {
  6576. pos += block;
  6577. bytes = readBytes(data, pos);
  6578. block = (bytes[2] << 8) + bytes[3];
  6579. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  6580. bytes = readBytes(data, pos + 5);
  6581. width = (bytes[2] << 8) + bytes[3];
  6582. height = (bytes[0] << 8) + bytes[1];
  6583. numcomponents = bytes[4];
  6584. return {
  6585. width: width,
  6586. height: height,
  6587. numcomponents: numcomponents
  6588. };
  6589. }
  6590. pos += 2;
  6591. }
  6592. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  6593. },
  6594. readBytes = function readBytes(data, offset) {
  6595. return data.subarray(offset, offset + 5);
  6596. };
  6597. /**
  6598. * @ignore
  6599. */
  6600. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString, colorSpace) {
  6601. var filter = this.decode.DCT_DECODE,
  6602. bpc = 8,
  6603. dims;
  6604. if (!this.isString(data) && !this.isArrayBuffer(data) && !this.isArrayBufferView(data)) {
  6605. return null;
  6606. }
  6607. if (this.isString(data)) {
  6608. dims = getJpegSize(data);
  6609. }
  6610. if (this.isArrayBuffer(data)) {
  6611. data = new Uint8Array(data);
  6612. }
  6613. if (this.isArrayBufferView(data)) {
  6614. dims = getJpegSizeFromBytes(data); // if we already have a stored binary string rep use that
  6615. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  6616. }
  6617. if (colorSpace === undefined) {
  6618. switch (dims.numcomponents) {
  6619. case 1:
  6620. colorSpace = this.color_spaces.DEVICE_GRAY;
  6621. break;
  6622. case 4:
  6623. colorSpace = this.color_spaces.DEVICE_CMYK;
  6624. break;
  6625. default:
  6626. case 3:
  6627. colorSpace = this.color_spaces.DEVICE_RGB;
  6628. break;
  6629. }
  6630. }
  6631. return this.createImageInfo(data, dims.width, dims.height, colorSpace, bpc, filter, index, alias);
  6632. };
  6633. /**
  6634. * @ignore
  6635. */
  6636. jsPDFAPI.processJPG = function ()
  6637. /*data, index, alias, compression, dataAsBinaryString*/
  6638. {
  6639. return this.processJPEG.apply(this, arguments);
  6640. };
  6641. /**
  6642. * @name getImageProperties
  6643. * @function
  6644. * @param {Object} imageData
  6645. * @returns {Object}
  6646. */
  6647. jsPDFAPI.getImageProperties = function (imageData) {
  6648. var info;
  6649. var tmpImageData = '';
  6650. var format;
  6651. if (isDOMElement(imageData)) {
  6652. imageData = createDataURIFromElement(imageData);
  6653. }
  6654. if (this.isString(imageData)) {
  6655. tmpImageData = this.convertStringToImageData(imageData);
  6656. if (tmpImageData !== '') {
  6657. imageData = tmpImageData;
  6658. } else {
  6659. tmpImageData = jsPDFAPI.loadFile(imageData);
  6660. if (tmpImageData !== undefined) {
  6661. imageData = tmpImageData;
  6662. }
  6663. }
  6664. }
  6665. format = this.getImageFileTypeByImageData(imageData);
  6666. if (!isImageTypeSupported(format)) {
  6667. throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  6668. }
  6669. /**
  6670. * need to test if it's more efficient to convert all binary strings
  6671. * to TypedArray - or should we just leave and process as string?
  6672. */
  6673. if (this.supportsArrayBuffer()) {
  6674. // no need to convert if imageData is already uint8array
  6675. if (!(imageData instanceof Uint8Array)) {
  6676. imageData = this.binaryStringToUint8Array(imageData);
  6677. }
  6678. }
  6679. info = this['process' + format.toUpperCase()](imageData);
  6680. if (!info) {
  6681. throw new Error('An unknown error occurred whilst processing the image');
  6682. }
  6683. return {
  6684. fileType: format,
  6685. width: info.w,
  6686. height: info.h,
  6687. colorSpace: info.cs,
  6688. compressionMode: info.f,
  6689. bitsPerComponent: info.bpc
  6690. };
  6691. };
  6692. })(jsPDF.API);
  6693. /**
  6694. * @license
  6695. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  6696. *
  6697. * Licensed under the MIT License.
  6698. * http://opensource.org/licenses/mit-license
  6699. */
  6700. /**
  6701. * jsPDF Annotations PlugIn
  6702. *
  6703. * There are many types of annotations in a PDF document. Annotations are placed
  6704. * on a page at a particular location. They are not 'attached' to an object.
  6705. * <br />
  6706. * This plugin current supports <br />
  6707. * <li> Goto Page (set pageNumber and top in options)
  6708. * <li> Goto Name (set name and top in options)
  6709. * <li> Goto URL (set url in options)
  6710. * <p>
  6711. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  6712. * (set magFactor in options). XYZ is the default.
  6713. * </p>
  6714. * <p>
  6715. * Links, Text, Popup, and FreeText are supported.
  6716. * </p>
  6717. * <p>
  6718. * Options In PDF spec Not Implemented Yet
  6719. * <li> link border
  6720. * <li> named target
  6721. * <li> page coordinates
  6722. * <li> destination page scaling and layout
  6723. * <li> actions other than URL and GotoPage
  6724. * <li> background / hover actions
  6725. * </p>
  6726. * @name annotations
  6727. * @module
  6728. */
  6729. /*
  6730. Destination Magnification Factors
  6731. See PDF 1.3 Page 386 for meanings and options
  6732. [supported]
  6733. XYZ (options; left top zoom)
  6734. Fit (no options)
  6735. FitH (options: top)
  6736. FitV (options: left)
  6737. [not supported]
  6738. FitR
  6739. FitB
  6740. FitBH
  6741. FitBV
  6742. */
  6743. (function (jsPDFAPI) {
  6744. jsPDF.API.events.push(['addPage', function (addPageData) {
  6745. var pageInfo = this.internal.getPageInfo(addPageData.pageNumber);
  6746. pageInfo.pageContext.annotations = [];
  6747. }]);
  6748. jsPDFAPI.events.push(['putPage', function (putPageData) {
  6749. var pageInfo = this.internal.getPageInfoByObjId(putPageData.objId);
  6750. var pageAnnos = putPageData.pageContext.annotations;
  6751. var notEmpty = function notEmpty(obj) {
  6752. if (typeof obj != 'undefined') {
  6753. if (obj != '') {
  6754. return true;
  6755. }
  6756. }
  6757. };
  6758. var found = false;
  6759. for (var a = 0; a < pageAnnos.length && !found; a++) {
  6760. var anno = pageAnnos[a];
  6761. switch (anno.type) {
  6762. case 'link':
  6763. if (notEmpty(anno.options.url) || notEmpty(anno.options.pageNumber)) {
  6764. found = true;
  6765. break;
  6766. }
  6767. case 'reference':
  6768. case 'text':
  6769. case 'freetext':
  6770. found = true;
  6771. break;
  6772. }
  6773. }
  6774. if (found == false) {
  6775. return;
  6776. }
  6777. this.internal.write("/Annots [");
  6778. var pageHeight = this.internal.pageSize.height;
  6779. var getHorizontalCoordinateString = this.internal.getCoordinateString;
  6780. var getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
  6781. for (var a = 0; a < pageAnnos.length; a++) {
  6782. var anno = pageAnnos[a];
  6783. switch (anno.type) {
  6784. case 'reference':
  6785. // References to Widget Annotations (for AcroForm Fields)
  6786. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  6787. break;
  6788. case 'text':
  6789. // Create a an object for both the text and the popup
  6790. var objText = this.internal.newAdditionalObject();
  6791. var objPopup = this.internal.newAdditionalObject();
  6792. var title = anno.title || 'Note';
  6793. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) + " " + getVerticalCoordinateString(anno.bounds.y) + "] ";
  6794. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  6795. line += ' /Popup ' + objPopup.objId + " 0 R";
  6796. line += ' /P ' + pageInfo.objId + " 0 R";
  6797. line += ' /T (' + title + ') >>';
  6798. objText.content = line;
  6799. var parent = objText.objId + ' 0 R';
  6800. var popoff = 30;
  6801. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x + popoff) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w + popoff) + " " + getVerticalCoordinateString(anno.bounds.y) + "] ";
  6802. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  6803. if (anno.open) {
  6804. line += ' /Open true';
  6805. }
  6806. line += ' >>';
  6807. objPopup.content = line;
  6808. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  6809. break;
  6810. case 'freetext':
  6811. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x) + " " + getVerticalCoordinateString(anno.bounds.y) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + "] ";
  6812. var color = anno.color || '#000000';
  6813. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  6814. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  6815. line += ' /Border [0 0 0]';
  6816. line += ' >>';
  6817. this.internal.write(line);
  6818. break;
  6819. case 'link':
  6820. if (anno.options.name) {
  6821. var loc = this.annotations._nameMap[anno.options.name];
  6822. anno.options.pageNumber = loc.page;
  6823. anno.options.top = loc.y;
  6824. } else {
  6825. if (!anno.options.top) {
  6826. anno.options.top = 0;
  6827. }
  6828. }
  6829. var rect = "/Rect [" + getHorizontalCoordinateString(anno.x) + " " + getVerticalCoordinateString(anno.y) + " " + getHorizontalCoordinateString(anno.x + anno.w) + " " + getVerticalCoordinateString(anno.y + anno.h) + "] ";
  6830. var line = '';
  6831. if (anno.options.url) {
  6832. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  6833. } else if (anno.options.pageNumber) {
  6834. // first page is 0
  6835. var info = this.internal.getPageInfo(anno.options.pageNumber);
  6836. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  6837. anno.options.magFactor = anno.options.magFactor || "XYZ";
  6838. switch (anno.options.magFactor) {
  6839. case 'Fit':
  6840. line += ' /Fit]';
  6841. break;
  6842. case 'FitH':
  6843. line += ' /FitH ' + anno.options.top + ']';
  6844. break;
  6845. case 'FitV':
  6846. anno.options.left = anno.options.left || 0;
  6847. line += ' /FitV ' + anno.options.left + ']';
  6848. break;
  6849. case 'XYZ':
  6850. default:
  6851. var top = getVerticalCoordinateString(anno.options.top);
  6852. anno.options.left = anno.options.left || 0; // 0 or null zoom will not change zoom factor
  6853. if (typeof anno.options.zoom === 'undefined') {
  6854. anno.options.zoom = 0;
  6855. }
  6856. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  6857. break;
  6858. }
  6859. }
  6860. if (line != '') {
  6861. line += " >>";
  6862. this.internal.write(line);
  6863. }
  6864. break;
  6865. }
  6866. }
  6867. this.internal.write("]");
  6868. }]);
  6869. /**
  6870. * @name createAnnotation
  6871. * @function
  6872. * @param {Object} options
  6873. */
  6874. jsPDFAPI.createAnnotation = function (options) {
  6875. var pageInfo = this.internal.getCurrentPageInfo();
  6876. switch (options.type) {
  6877. case 'link':
  6878. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  6879. break;
  6880. case 'text':
  6881. case 'freetext':
  6882. pageInfo.pageContext.annotations.push(options);
  6883. break;
  6884. }
  6885. };
  6886. /**
  6887. * Create a link
  6888. *
  6889. * valid options
  6890. * <li> pageNumber or url [required]
  6891. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  6892. * @name link
  6893. * @function
  6894. * @param {number} x
  6895. * @param {number} y
  6896. * @param {number} w
  6897. * @param {number} h
  6898. * @param {Object} options
  6899. */
  6900. jsPDFAPI.link = function (x, y, w, h, options) {
  6901. var pageInfo = this.internal.getCurrentPageInfo();
  6902. pageInfo.pageContext.annotations.push({
  6903. x: x,
  6904. y: y,
  6905. w: w,
  6906. h: h,
  6907. options: options,
  6908. type: 'link'
  6909. });
  6910. };
  6911. /**
  6912. * Currently only supports single line text.
  6913. * Returns the width of the text/link
  6914. *
  6915. * @name textWithLink
  6916. * @function
  6917. * @param {string} text
  6918. * @param {number} x
  6919. * @param {number} y
  6920. * @param {Object} options
  6921. * @returns {number} width the width of the text/link
  6922. */
  6923. jsPDFAPI.textWithLink = function (text, x, y, options) {
  6924. var width = this.getTextWidth(text);
  6925. var height = this.internal.getLineHeight() / this.internal.scaleFactor;
  6926. this.text(text, x, y); //TODO We really need the text baseline height to do this correctly.
  6927. // Or ability to draw text on top, bottom, center, or baseline.
  6928. y += height * .2;
  6929. this.link(x, y - height, width, height, options);
  6930. return width;
  6931. }; //TODO move into external library
  6932. /**
  6933. * @name getTextWidth
  6934. * @function
  6935. * @param {string} text
  6936. * @returns {number} txtWidth
  6937. */
  6938. jsPDFAPI.getTextWidth = function (text) {
  6939. var fontSize = this.internal.getFontSize();
  6940. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  6941. return txtWidth;
  6942. };
  6943. return this;
  6944. })(jsPDF.API);
  6945. /**
  6946. * @license
  6947. * Copyright (c) 2017 Aras Abbasi
  6948. *
  6949. * Licensed under the MIT License.
  6950. * http://opensource.org/licenses/mit-license
  6951. */
  6952. /**
  6953. * jsPDF arabic parser PlugIn
  6954. *
  6955. * @name arabic
  6956. * @module
  6957. */
  6958. (function (jsPDFAPI) {
  6959. /**
  6960. * Arabic shape substitutions: char code => (isolated, final, initial, medial).
  6961. * Arabic Substition A
  6962. */
  6963. var arabicSubstitionA = {
  6964. 0x0621: [0xFE80],
  6965. // ARABIC LETTER HAMZA
  6966. 0x0622: [0xFE81, 0xFE82],
  6967. // ARABIC LETTER ALEF WITH MADDA ABOVE
  6968. 0x0623: [0xFE83, 0xFE84],
  6969. // ARABIC LETTER ALEF WITH HAMZA ABOVE
  6970. 0x0624: [0xFE85, 0xFE86],
  6971. // ARABIC LETTER WAW WITH HAMZA ABOVE
  6972. 0x0625: [0xFE87, 0xFE88],
  6973. // ARABIC LETTER ALEF WITH HAMZA BELOW
  6974. 0x0626: [0xFE89, 0xFE8A, 0xFE8B, 0xFE8C],
  6975. // ARABIC LETTER YEH WITH HAMZA ABOVE
  6976. 0x0627: [0xFE8D, 0xFE8E],
  6977. // ARABIC LETTER ALEF
  6978. 0x0628: [0xFE8F, 0xFE90, 0xFE91, 0xFE92],
  6979. // ARABIC LETTER BEH
  6980. 0x0629: [0xFE93, 0xFE94],
  6981. // ARABIC LETTER TEH MARBUTA
  6982. 0x062A: [0xFE95, 0xFE96, 0xFE97, 0xFE98],
  6983. // ARABIC LETTER TEH
  6984. 0x062B: [0xFE99, 0xFE9A, 0xFE9B, 0xFE9C],
  6985. // ARABIC LETTER THEH
  6986. 0x062C: [0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0],
  6987. // ARABIC LETTER JEEM
  6988. 0x062D: [0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4],
  6989. // ARABIC LETTER HAH
  6990. 0x062E: [0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8],
  6991. // ARABIC LETTER KHAH
  6992. 0x062F: [0xFEA9, 0xFEAA],
  6993. // ARABIC LETTER DAL
  6994. 0x0630: [0xFEAB, 0xFEAC],
  6995. // ARABIC LETTER THAL
  6996. 0x0631: [0xFEAD, 0xFEAE],
  6997. // ARABIC LETTER REH
  6998. 0x0632: [0xFEAF, 0xFEB0],
  6999. // ARABIC LETTER ZAIN
  7000. 0x0633: [0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4],
  7001. // ARABIC LETTER SEEN
  7002. 0x0634: [0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8],
  7003. // ARABIC LETTER SHEEN
  7004. 0x0635: [0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC],
  7005. // ARABIC LETTER SAD
  7006. 0x0636: [0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0],
  7007. // ARABIC LETTER DAD
  7008. 0x0637: [0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4],
  7009. // ARABIC LETTER TAH
  7010. 0x0638: [0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8],
  7011. // ARABIC LETTER ZAH
  7012. 0x0639: [0xFEC9, 0xFECA, 0xFECB, 0xFECC],
  7013. // ARABIC LETTER AIN
  7014. 0x063A: [0xFECD, 0xFECE, 0xFECF, 0xFED0],
  7015. // ARABIC LETTER GHAIN
  7016. 0x0641: [0xFED1, 0xFED2, 0xFED3, 0xFED4],
  7017. // ARABIC LETTER FEH
  7018. 0x0642: [0xFED5, 0xFED6, 0xFED7, 0xFED8],
  7019. // ARABIC LETTER QAF
  7020. 0x0643: [0xFED9, 0xFEDA, 0xFEDB, 0xFEDC],
  7021. // ARABIC LETTER KAF
  7022. 0x0644: [0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0],
  7023. // ARABIC LETTER LAM
  7024. 0x0645: [0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4],
  7025. // ARABIC LETTER MEEM
  7026. 0x0646: [0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8],
  7027. // ARABIC LETTER NOON
  7028. 0x0647: [0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC],
  7029. // ARABIC LETTER HEH
  7030. 0x0648: [0xFEED, 0xFEEE],
  7031. // ARABIC LETTER WAW
  7032. 0x0649: [0xFEEF, 0xFEF0, 64488, 64489],
  7033. // ARABIC LETTER ALEF MAKSURA
  7034. 0x064A: [0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4],
  7035. // ARABIC LETTER YEH
  7036. 0x0671: [0xFB50, 0xFB51],
  7037. // ARABIC LETTER ALEF WASLA
  7038. 0x0677: [0xFBDD],
  7039. // ARABIC LETTER U WITH HAMZA ABOVE
  7040. 0x0679: [0xFB66, 0xFB67, 0xFB68, 0xFB69],
  7041. // ARABIC LETTER TTEH
  7042. 0x067A: [0xFB5E, 0xFB5F, 0xFB60, 0xFB61],
  7043. // ARABIC LETTER TTEHEH
  7044. 0x067B: [0xFB52, 0xFB53, 0xFB54, 0xFB55],
  7045. // ARABIC LETTER BEEH
  7046. 0x067E: [0xFB56, 0xFB57, 0xFB58, 0xFB59],
  7047. // ARABIC LETTER PEH
  7048. 0x067F: [0xFB62, 0xFB63, 0xFB64, 0xFB65],
  7049. // ARABIC LETTER TEHEH
  7050. 0x0680: [0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D],
  7051. // ARABIC LETTER BEHEH
  7052. 0x0683: [0xFB76, 0xFB77, 0xFB78, 0xFB79],
  7053. // ARABIC LETTER NYEH
  7054. 0x0684: [0xFB72, 0xFB73, 0xFB74, 0xFB75],
  7055. // ARABIC LETTER DYEH
  7056. 0x0686: [0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D],
  7057. // ARABIC LETTER TCHEH
  7058. 0x0687: [0xFB7E, 0xFB7F, 0xFB80, 0xFB81],
  7059. // ARABIC LETTER TCHEHEH
  7060. 0x0688: [0xFB88, 0xFB89],
  7061. // ARABIC LETTER DDAL
  7062. 0x068C: [0xFB84, 0xFB85],
  7063. // ARABIC LETTER DAHAL
  7064. 0x068D: [0xFB82, 0xFB83],
  7065. // ARABIC LETTER DDAHAL
  7066. 0x068E: [0xFB86, 0xFB87],
  7067. // ARABIC LETTER DUL
  7068. 0x0691: [0xFB8C, 0xFB8D],
  7069. // ARABIC LETTER RREH
  7070. 0x0698: [0xFB8A, 0xFB8B],
  7071. // ARABIC LETTER JEH
  7072. 0x06A4: [0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D],
  7073. // ARABIC LETTER VEH
  7074. 0x06A6: [0xFB6E, 0xFB6F, 0xFB70, 0xFB71],
  7075. // ARABIC LETTER PEHEH
  7076. 0x06A9: [0xFB8E, 0xFB8F, 0xFB90, 0xFB91],
  7077. // ARABIC LETTER KEHEH
  7078. 0x06AD: [0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6],
  7079. // ARABIC LETTER NG
  7080. 0x06AF: [0xFB92, 0xFB93, 0xFB94, 0xFB95],
  7081. // ARABIC LETTER GAF
  7082. 0x06B1: [0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D],
  7083. // ARABIC LETTER NGOEH
  7084. 0x06B3: [0xFB96, 0xFB97, 0xFB98, 0xFB99],
  7085. // ARABIC LETTER GUEH
  7086. 0x06BA: [0xFB9E, 0xFB9F],
  7087. // ARABIC LETTER NOON GHUNNA
  7088. 0x06BB: [0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3],
  7089. // ARABIC LETTER RNOON
  7090. 0x06BE: [0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD],
  7091. // ARABIC LETTER HEH DOACHASHMEE
  7092. 0x06C0: [0xFBA4, 0xFBA5],
  7093. // ARABIC LETTER HEH WITH YEH ABOVE
  7094. 0x06C1: [0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9],
  7095. // ARABIC LETTER HEH GOAL
  7096. 0x06C5: [0xFBE0, 0xFBE1],
  7097. // ARABIC LETTER KIRGHIZ OE
  7098. 0x06C6: [0xFBD9, 0xFBDA],
  7099. // ARABIC LETTER OE
  7100. 0x06C7: [0xFBD7, 0xFBD8],
  7101. // ARABIC LETTER U
  7102. 0x06C8: [0xFBDB, 0xFBDC],
  7103. // ARABIC LETTER YU
  7104. 0x06C9: [0xFBE2, 0xFBE3],
  7105. // ARABIC LETTER KIRGHIZ YU
  7106. 0x06CB: [0xFBDE, 0xFBDF],
  7107. // ARABIC LETTER VE
  7108. 0x06CC: [0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF],
  7109. // ARABIC LETTER FARSI YEH
  7110. 0x06D0: [0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7],
  7111. //ARABIC LETTER E
  7112. 0x06D2: [0xFBAE, 0xFBAF],
  7113. // ARABIC LETTER YEH BARREE
  7114. 0x06D3: [0xFBB0, 0xFBB1] // ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
  7115. };
  7116. var ligatures = {
  7117. 0xFEDF: {
  7118. 0xFE82: 0xFEF5,
  7119. // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
  7120. 0xFE84: 0xFEF7,
  7121. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
  7122. 0xFE88: 0xFEF9,
  7123. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM
  7124. 0xFE8E: 0xFEFB // ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
  7125. },
  7126. 0xFEE0: {
  7127. 0xFE82: 0xFEF6,
  7128. // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
  7129. 0xFE84: 0xFEF8,
  7130. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
  7131. 0xFE88: 0xFEFA,
  7132. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM
  7133. 0xFE8E: 0xFEFC // ARABIC LIGATURE LAM WITH ALEF FINAL FORM
  7134. },
  7135. 0xFE8D: {
  7136. 0xFEDF: {
  7137. 0xFEE0: {
  7138. 0xFEEA: 0xFDF2
  7139. }
  7140. }
  7141. },
  7142. // ALLAH
  7143. 0x0651: {
  7144. 0x064C: 0xFC5E,
  7145. // Shadda + Dammatan
  7146. 0x064D: 0xFC5F,
  7147. // Shadda + Kasratan
  7148. 0x064E: 0xFC60,
  7149. // Shadda + Fatha
  7150. 0x064F: 0xFC61,
  7151. // Shadda + Damma
  7152. 0x0650: 0xFC62 // Shadda + Kasra
  7153. }
  7154. };
  7155. var arabic_diacritics = {
  7156. 1612: 64606,
  7157. // Shadda + Dammatan
  7158. 1613: 64607,
  7159. // Shadda + Kasratan
  7160. 1614: 64608,
  7161. // Shadda + Fatha
  7162. 1615: 64609,
  7163. // Shadda + Damma
  7164. 1616: 64610 // Shadda + Kasra
  7165. };
  7166. var alfletter = [1570, 1571, 1573, 1575];
  7167. var noChangeInForm = -1;
  7168. var isolatedForm = 0;
  7169. var finalForm = 1;
  7170. var initialForm = 2;
  7171. var medialForm = 3;
  7172. jsPDFAPI.__arabicParser__ = {}; //private
  7173. var isInArabicSubstitutionA = jsPDFAPI.__arabicParser__.isInArabicSubstitutionA = function (letter) {
  7174. return typeof arabicSubstitionA[letter.charCodeAt(0)] !== "undefined";
  7175. };
  7176. var isArabicLetter = jsPDFAPI.__arabicParser__.isArabicLetter = function (letter) {
  7177. return typeof letter === "string" && /^[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]+$/.test(letter);
  7178. };
  7179. var isArabicEndLetter = jsPDFAPI.__arabicParser__.isArabicEndLetter = function (letter) {
  7180. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length <= 2;
  7181. };
  7182. var isArabicAlfLetter = jsPDFAPI.__arabicParser__.isArabicAlfLetter = function (letter) {
  7183. return isArabicLetter(letter) && alfletter.indexOf(letter.charCodeAt(0)) >= 0;
  7184. };
  7185. var arabicLetterHasIsolatedForm = jsPDFAPI.__arabicParser__.arabicLetterHasIsolatedForm = function (letter) {
  7186. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 1;
  7187. };
  7188. var arabicLetterHasFinalForm = jsPDFAPI.__arabicParser__.arabicLetterHasFinalForm = function (letter) {
  7189. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 2;
  7190. };
  7191. var arabicLetterHasInitialForm = jsPDFAPI.__arabicParser__.arabicLetterHasInitialForm = function (letter) {
  7192. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 3;
  7193. };
  7194. var arabicLetterHasMedialForm = jsPDFAPI.__arabicParser__.arabicLetterHasMedialForm = function (letter) {
  7195. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length == 4;
  7196. };
  7197. var resolveLigatures = jsPDFAPI.__arabicParser__.resolveLigatures = function (letters) {
  7198. var i = 0;
  7199. var tmpLigatures = ligatures;
  7200. var position = isolatedForm;
  7201. var result = '';
  7202. var effectedLetters = 0;
  7203. for (i = 0; i < letters.length; i += 1) {
  7204. if (typeof tmpLigatures[letters.charCodeAt(i)] !== "undefined") {
  7205. effectedLetters++;
  7206. tmpLigatures = tmpLigatures[letters.charCodeAt(i)];
  7207. if (typeof tmpLigatures === "number") {
  7208. position = getCorrectForm(letters.charAt(i), letters.charAt(i - effectedLetters), letters.charAt(i + 1));
  7209. position = position !== -1 ? position : 0;
  7210. result += String.fromCharCode(tmpLigatures);
  7211. tmpLigatures = ligatures;
  7212. effectedLetters = 0;
  7213. }
  7214. if (i === letters.length - 1) {
  7215. tmpLigatures = ligatures;
  7216. result += letters.charAt(i - (effectedLetters - 1));
  7217. i = i - (effectedLetters - 1);
  7218. effectedLetters = 0;
  7219. }
  7220. } else {
  7221. tmpLigatures = ligatures;
  7222. result += letters.charAt(i - effectedLetters);
  7223. i = i - effectedLetters;
  7224. effectedLetters = 0;
  7225. }
  7226. }
  7227. return result;
  7228. };
  7229. var isArabicDiacritic = jsPDFAPI.__arabicParser__.isArabicDiacritic = function (letter) {
  7230. return letter !== undefined && arabic_diacritics[letter.charCodeAt(0)] !== undefined;
  7231. };
  7232. var getCorrectForm = jsPDFAPI.__arabicParser__.getCorrectForm = function (currentChar, beforeChar, nextChar) {
  7233. if (!isArabicLetter(currentChar)) {
  7234. return -1;
  7235. }
  7236. if (isInArabicSubstitutionA(currentChar) === false) {
  7237. return noChangeInForm;
  7238. }
  7239. if (!arabicLetterHasFinalForm(currentChar) || !isArabicLetter(beforeChar) && !isArabicLetter(nextChar) || !isArabicLetter(nextChar) && isArabicEndLetter(beforeChar) || isArabicEndLetter(currentChar) && !isArabicLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicAlfLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicEndLetter(beforeChar)) {
  7240. return isolatedForm;
  7241. }
  7242. if (arabicLetterHasMedialForm(currentChar) && isArabicLetter(beforeChar) && !isArabicEndLetter(beforeChar) && isArabicLetter(nextChar) && arabicLetterHasFinalForm(nextChar)) {
  7243. return medialForm;
  7244. }
  7245. if (isArabicEndLetter(currentChar) || !isArabicLetter(nextChar)) {
  7246. return finalForm;
  7247. }
  7248. return initialForm;
  7249. };
  7250. /**
  7251. * @name processArabic
  7252. * @function
  7253. * @param {string} text
  7254. * @param {boolean} reverse
  7255. * @returns {string}
  7256. */
  7257. var processArabic = jsPDFAPI.__arabicParser__.processArabic = jsPDFAPI.processArabic = function (text) {
  7258. text = text || "";
  7259. var result = "";
  7260. var i = 0;
  7261. var j = 0;
  7262. var position = 0;
  7263. var currentLetter = "";
  7264. var prevLetter = "";
  7265. var nextLetter = "";
  7266. var words = text.split("\\s+");
  7267. var newWords = [];
  7268. for (i = 0; i < words.length; i += 1) {
  7269. newWords.push('');
  7270. for (j = 0; j < words[i].length; j += 1) {
  7271. currentLetter = words[i][j];
  7272. prevLetter = words[i][j - 1];
  7273. nextLetter = words[i][j + 1];
  7274. if (isArabicLetter(currentLetter)) {
  7275. position = getCorrectForm(currentLetter, prevLetter, nextLetter);
  7276. if (position !== -1) {
  7277. newWords[i] += String.fromCharCode(arabicSubstitionA[currentLetter.charCodeAt(0)][position]);
  7278. } else {
  7279. newWords[i] += currentLetter;
  7280. }
  7281. } else {
  7282. newWords[i] += currentLetter;
  7283. }
  7284. }
  7285. newWords[i] = resolveLigatures(newWords[i]);
  7286. }
  7287. result = newWords.join(' ');
  7288. return result;
  7289. };
  7290. var arabicParserFunction = function arabicParserFunction(args) {
  7291. var text = args.text;
  7292. var x = args.x;
  7293. var y = args.y;
  7294. var options = args.options || {};
  7295. var mutex = args.mutex || {};
  7296. var lang = options.lang;
  7297. var tmpText = [];
  7298. if (Object.prototype.toString.call(text) === '[object Array]') {
  7299. var i = 0;
  7300. tmpText = [];
  7301. for (i = 0; i < text.length; i += 1) {
  7302. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  7303. tmpText.push([processArabic(text[i][0]), text[i][1], text[i][2]]);
  7304. } else {
  7305. tmpText.push([processArabic(text[i])]);
  7306. }
  7307. }
  7308. args.text = tmpText;
  7309. } else {
  7310. args.text = processArabic(text);
  7311. }
  7312. };
  7313. jsPDFAPI.events.push(['preProcessText', arabicParserFunction]);
  7314. })(jsPDF.API);
  7315. /** @license
  7316. * jsPDF Autoprint Plugin
  7317. *
  7318. * Licensed under the MIT License.
  7319. * http://opensource.org/licenses/mit-license
  7320. */
  7321. /**
  7322. * @name autoprint
  7323. * @module
  7324. */
  7325. (function (jsPDFAPI) {
  7326. /**
  7327. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  7328. * Reader.
  7329. *
  7330. * @name autoPrint
  7331. * @function
  7332. * @param {Object} options (optional) Set the attribute variant to 'non-conform' (default) or 'javascript' to activate different methods of automatic printing when opening in a PDF-viewer .
  7333. * @returns {jsPDF}
  7334. * @example
  7335. * var doc = new jsPDF();
  7336. * doc.text(10, 10, 'This is a test');
  7337. * doc.autoPrint({variant: 'non-conform'});
  7338. * doc.save('autoprint.pdf');
  7339. */
  7340. jsPDFAPI.autoPrint = function (options) {
  7341. var refAutoPrintTag;
  7342. options = options || {};
  7343. options.variant = options.variant || 'non-conform';
  7344. switch (options.variant) {
  7345. case 'javascript':
  7346. //https://github.com/Rob--W/pdf.js/commit/c676ecb5a0f54677b9f3340c3ef2cf42225453bb
  7347. this.addJS('print({});');
  7348. break;
  7349. case 'non-conform':
  7350. default:
  7351. this.internal.events.subscribe('postPutResources', function () {
  7352. refAutoPrintTag = this.internal.newObject();
  7353. this.internal.out("<<");
  7354. this.internal.out("/S /Named");
  7355. this.internal.out("/Type /Action");
  7356. this.internal.out("/N /Print");
  7357. this.internal.out(">>");
  7358. this.internal.out("endobj");
  7359. });
  7360. this.internal.events.subscribe("putCatalog", function () {
  7361. this.internal.out("/OpenAction " + refAutoPrintTag + " 0 R");
  7362. });
  7363. break;
  7364. }
  7365. return this;
  7366. };
  7367. })(jsPDF.API);
  7368. /**
  7369. * @license
  7370. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7371. *
  7372. * Licensed under the MIT License.
  7373. * http://opensource.org/licenses/mit-license
  7374. */
  7375. /**
  7376. * jsPDF Canvas PlugIn
  7377. * This plugin mimics the HTML5 Canvas
  7378. *
  7379. * The goal is to provide a way for current canvas users to print directly to a PDF.
  7380. * @name canvas
  7381. * @module
  7382. */
  7383. (function (jsPDFAPI) {
  7384. /**
  7385. * @class Canvas
  7386. * @classdesc A Canvas Wrapper for jsPDF
  7387. */
  7388. var Canvas = function Canvas() {
  7389. var jsPdfInstance = undefined;
  7390. Object.defineProperty(this, 'pdf', {
  7391. get: function get() {
  7392. return jsPdfInstance;
  7393. },
  7394. set: function set(value) {
  7395. jsPdfInstance = value;
  7396. }
  7397. });
  7398. var _width = 150;
  7399. /**
  7400. * The height property is a positive integer reflecting the height HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
  7401. * This is one of the two properties, the other being width, that controls the size of the canvas.
  7402. *
  7403. * @name width
  7404. */
  7405. Object.defineProperty(this, 'width', {
  7406. get: function get() {
  7407. return _width;
  7408. },
  7409. set: function set(value) {
  7410. if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
  7411. _width = 150;
  7412. } else {
  7413. _width = value;
  7414. }
  7415. if (this.getContext('2d').pageWrapXEnabled) {
  7416. this.getContext('2d').pageWrapX = _width + 1;
  7417. }
  7418. }
  7419. });
  7420. var _height = 300;
  7421. /**
  7422. * The width property is a positive integer reflecting the width HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
  7423. * This is one of the two properties, the other being height, that controls the size of the canvas.
  7424. *
  7425. * @name height
  7426. */
  7427. Object.defineProperty(this, 'height', {
  7428. get: function get() {
  7429. return _height;
  7430. },
  7431. set: function set(value) {
  7432. if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
  7433. _height = 300;
  7434. } else {
  7435. _height = value;
  7436. }
  7437. if (this.getContext('2d').pageWrapYEnabled) {
  7438. this.getContext('2d').pageWrapY = _height + 1;
  7439. }
  7440. }
  7441. });
  7442. var _childNodes = [];
  7443. Object.defineProperty(this, 'childNodes', {
  7444. get: function get() {
  7445. return _childNodes;
  7446. },
  7447. set: function set(value) {
  7448. _childNodes = value;
  7449. }
  7450. });
  7451. var _style = {};
  7452. Object.defineProperty(this, 'style', {
  7453. get: function get() {
  7454. return _style;
  7455. },
  7456. set: function set(value) {
  7457. _style = value;
  7458. }
  7459. });
  7460. Object.defineProperty(this, 'parentNode', {
  7461. get: function get() {
  7462. return false;
  7463. }
  7464. });
  7465. };
  7466. /**
  7467. * The getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported.
  7468. *
  7469. * @name getContext
  7470. * @function
  7471. * @param {string} contextType Is a String containing the context identifier defining the drawing context associated to the canvas. Possible value is "2d", leading to the creation of a Context2D object representing a two-dimensional rendering context.
  7472. * @param {object} contextAttributes
  7473. */
  7474. Canvas.prototype.getContext = function (contextType, contextAttributes) {
  7475. contextType = contextType || '2d';
  7476. var key;
  7477. if (contextType !== '2d') {
  7478. return null;
  7479. }
  7480. for (key in contextAttributes) {
  7481. if (this.pdf.context2d.hasOwnProperty(key)) {
  7482. this.pdf.context2d[key] = contextAttributes[key];
  7483. }
  7484. }
  7485. this.pdf.context2d._canvas = this;
  7486. return this.pdf.context2d;
  7487. };
  7488. /**
  7489. * The toDataURL() method is just a stub to throw an error if accidently called.
  7490. *
  7491. * @name toDataURL
  7492. * @function
  7493. */
  7494. Canvas.prototype.toDataURL = function () {
  7495. throw new Error('toDataURL is not implemented.');
  7496. };
  7497. jsPDFAPI.events.push(['initialized', function () {
  7498. this.canvas = new Canvas();
  7499. this.canvas.pdf = this;
  7500. }]);
  7501. return this;
  7502. })(jsPDF.API);
  7503. /**
  7504. * @license
  7505. * ====================================================================
  7506. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  7507. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  7508. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  7509. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  7510. * 2014 James Hall, james@parall.ax
  7511. * 2014 Diego Casorran, https://github.com/diegocr
  7512. *
  7513. *
  7514. * ====================================================================
  7515. */
  7516. /**
  7517. * @name cell
  7518. * @module
  7519. */
  7520. (function (jsPDFAPI) {
  7521. /*jslint browser:true */
  7522. /*global document: false, jsPDF */
  7523. var padding = 3,
  7524. margin = 13,
  7525. headerFunction,
  7526. lastCellPos = {
  7527. x: undefined,
  7528. y: undefined,
  7529. w: undefined,
  7530. h: undefined,
  7531. ln: undefined
  7532. },
  7533. pages = 1,
  7534. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  7535. lastCellPos = {
  7536. 'x': x,
  7537. 'y': y,
  7538. 'w': w,
  7539. 'h': h,
  7540. 'ln': ln
  7541. };
  7542. },
  7543. getLastCellPosition = function getLastCellPosition() {
  7544. return lastCellPos;
  7545. },
  7546. NO_MARGINS = {
  7547. left: 0,
  7548. top: 0,
  7549. bottom: 0
  7550. };
  7551. /**
  7552. * @name setHeaderFunction
  7553. * @function
  7554. * @param {function} func
  7555. */
  7556. jsPDFAPI.setHeaderFunction = function (func) {
  7557. headerFunction = func;
  7558. };
  7559. /**
  7560. * @name getTextDimensions
  7561. * @function
  7562. * @param {string} txt
  7563. * @returns {Object} dimensions
  7564. */
  7565. jsPDFAPI.getTextDimensions = function (text, options) {
  7566. var fontSize = this.table_font_size || this.internal.getFontSize();
  7567. var fontStyle = this.internal.getFont().fontStyle;
  7568. options = options || {};
  7569. var scaleFactor = options.scaleFactor || this.internal.scaleFactor;
  7570. var width = 0;
  7571. var amountOfLines = 0;
  7572. var height = 0;
  7573. var tempWidth = 0;
  7574. if (typeof text === 'string') {
  7575. width = this.getStringUnitWidth(text) * fontSize;
  7576. if (width !== 0) {
  7577. amountOfLines = 1;
  7578. }
  7579. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  7580. for (var i = 0; i < text.length; i++) {
  7581. tempWidth = this.getStringUnitWidth(text[i]) * fontSize;
  7582. if (width < tempWidth) {
  7583. width = tempWidth;
  7584. }
  7585. }
  7586. if (width !== 0) {
  7587. amountOfLines = text.length;
  7588. }
  7589. } else {
  7590. throw new Error('getTextDimensions expects text-parameter to be of type String or an Array of Strings.');
  7591. }
  7592. width = width / scaleFactor;
  7593. height = Math.max((amountOfLines * fontSize * this.getLineHeightFactor() - fontSize * (this.getLineHeightFactor() - 1)) / scaleFactor, 0);
  7594. return {
  7595. w: width,
  7596. h: height
  7597. };
  7598. };
  7599. /**
  7600. * @name cellAddPage
  7601. * @function
  7602. */
  7603. jsPDFAPI.cellAddPage = function () {
  7604. var margins = this.margins || NO_MARGINS;
  7605. this.addPage();
  7606. setLastCellPosition(margins.left, margins.top, undefined, undefined); //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  7607. pages += 1;
  7608. };
  7609. /**
  7610. * @name cellInitialize
  7611. * @function
  7612. */
  7613. jsPDFAPI.cellInitialize = function () {
  7614. lastCellPos = {
  7615. x: undefined,
  7616. y: undefined,
  7617. w: undefined,
  7618. h: undefined,
  7619. ln: undefined
  7620. };
  7621. pages = 1;
  7622. };
  7623. /**
  7624. * @name cell
  7625. * @function
  7626. * @param {number} x
  7627. * @param {number} y
  7628. * @param {number} w
  7629. * @param {number} h
  7630. * @param {string} txt
  7631. * @param {number} ln lineNumber
  7632. * @param {string} align
  7633. * @return {jsPDF} jsPDF-instance
  7634. */
  7635. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  7636. var curCell = getLastCellPosition();
  7637. var pgAdded = false; // If this is not the first cell, we must change its position
  7638. if (curCell.ln !== undefined) {
  7639. if (curCell.ln === ln) {
  7640. //Same line
  7641. x = curCell.x + curCell.w;
  7642. y = curCell.y;
  7643. } else {
  7644. //New line
  7645. var margins = this.margins || NO_MARGINS;
  7646. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.getHeight() - margins.bottom) {
  7647. this.cellAddPage();
  7648. pgAdded = true;
  7649. if (this.printHeaders && this.tableHeaderRow) {
  7650. this.printHeaderRow(ln, true);
  7651. }
  7652. } //We ignore the passed y: the lines may have different heights
  7653. y = getLastCellPosition().y + getLastCellPosition().h;
  7654. if (pgAdded) y = margin + 10;
  7655. }
  7656. }
  7657. if (txt[0] !== undefined) {
  7658. if (this.printingHeaderRow) {
  7659. this.rect(x, y, w, h, 'FD');
  7660. } else {
  7661. this.rect(x, y, w, h);
  7662. }
  7663. if (align === 'right') {
  7664. if (!(txt instanceof Array)) {
  7665. txt = [txt];
  7666. }
  7667. for (var i = 0; i < txt.length; i++) {
  7668. var currentLine = txt[i];
  7669. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize() / this.internal.scaleFactor;
  7670. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  7671. }
  7672. } else {
  7673. this.text(txt, x + padding, y + this.internal.getLineHeight());
  7674. }
  7675. }
  7676. setLastCellPosition(x, y, w, h, ln);
  7677. return this;
  7678. };
  7679. /**
  7680. * Return the maximum value from an array
  7681. *
  7682. * @name arrayMax
  7683. * @function
  7684. * @param {Array} array
  7685. * @param comparisonFn
  7686. * @returns {number}
  7687. */
  7688. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  7689. var max = array[0],
  7690. i,
  7691. ln,
  7692. item;
  7693. for (i = 0, ln = array.length; i < ln; i += 1) {
  7694. item = array[i];
  7695. if (comparisonFn) {
  7696. if (comparisonFn(max, item) === -1) {
  7697. max = item;
  7698. }
  7699. } else {
  7700. if (item > max) {
  7701. max = item;
  7702. }
  7703. }
  7704. }
  7705. return max;
  7706. };
  7707. /**
  7708. * Create a table from a set of data.
  7709. * @name table
  7710. * @function
  7711. * @param {Integer} [x] : left-position for top-left corner of table
  7712. * @param {Integer} [y] top-position for top-left corner of table
  7713. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  7714. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  7715. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  7716. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  7717. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  7718. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  7719. * @returns {jsPDF} jsPDF-instance
  7720. */
  7721. jsPDFAPI.table = function (x, y, data, headers, config) {
  7722. if (!data) {
  7723. throw 'No data for PDF table';
  7724. }
  7725. var headerNames = [],
  7726. headerPrompts = [],
  7727. header,
  7728. i,
  7729. ln,
  7730. cln,
  7731. columnMatrix = {},
  7732. columnWidths = {},
  7733. columnData,
  7734. column,
  7735. columnMinWidths = [],
  7736. j,
  7737. tableHeaderConfigs = [],
  7738. model,
  7739. jln,
  7740. func,
  7741. //set up defaults. If a value is provided in config, defaults will be overwritten:
  7742. autoSize = false,
  7743. printHeaders = true,
  7744. fontSize = 12,
  7745. margins = NO_MARGINS;
  7746. margins.width = this.internal.pageSize.getWidth();
  7747. if (config) {
  7748. //override config defaults if the user has specified non-default behavior:
  7749. if (config.autoSize === true) {
  7750. autoSize = true;
  7751. }
  7752. if (config.printHeaders === false) {
  7753. printHeaders = false;
  7754. }
  7755. if (config.fontSize) {
  7756. fontSize = config.fontSize;
  7757. }
  7758. if (config.css && typeof config.css['font-size'] !== "undefined") {
  7759. fontSize = config.css['font-size'] * 16;
  7760. }
  7761. if (config.margins) {
  7762. margins = config.margins;
  7763. }
  7764. }
  7765. /**
  7766. * @property {Number} lnMod
  7767. * Keep track of the current line number modifier used when creating cells
  7768. */
  7769. this.lnMod = 0;
  7770. lastCellPos = {
  7771. x: undefined,
  7772. y: undefined,
  7773. w: undefined,
  7774. h: undefined,
  7775. ln: undefined
  7776. }, pages = 1;
  7777. this.printHeaders = printHeaders;
  7778. this.margins = margins;
  7779. this.setFontSize(fontSize);
  7780. this.table_font_size = fontSize; // Set header values
  7781. if (headers === undefined || headers === null) {
  7782. // No headers defined so we derive from data
  7783. headerNames = Object.keys(data[0]);
  7784. } else if (headers[0] && typeof headers[0] !== 'string') {
  7785. var px2pt = 0.264583 * 72 / 25.4; // Split header configs into names and prompts
  7786. for (i = 0, ln = headers.length; i < ln; i += 1) {
  7787. header = headers[i];
  7788. headerNames.push(header.name);
  7789. headerPrompts.push(header.prompt);
  7790. columnWidths[header.name] = header.width * px2pt;
  7791. }
  7792. } else {
  7793. headerNames = headers;
  7794. }
  7795. if (autoSize) {
  7796. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  7797. func = function func(rec) {
  7798. return rec[header];
  7799. };
  7800. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  7801. header = headerNames[i];
  7802. columnMatrix[header] = data.map(func); // get header width
  7803. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header, {
  7804. scaleFactor: 1
  7805. }).w);
  7806. column = columnMatrix[header]; // get cell widths
  7807. for (j = 0, cln = column.length; j < cln; j += 1) {
  7808. columnData = column[j];
  7809. columnMinWidths.push(this.getTextDimensions(columnData, {
  7810. scaleFactor: 1
  7811. }).w);
  7812. } // get final column width
  7813. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths); //have to reset
  7814. columnMinWidths = [];
  7815. }
  7816. } // -- Construct the table
  7817. if (printHeaders) {
  7818. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames); // Construct the header row
  7819. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  7820. header = headerNames[i];
  7821. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  7822. } // Store the table header config
  7823. this.setTableHeaderRow(tableHeaderConfigs); // Print the header for the start of the table
  7824. this.printHeaderRow(1, false);
  7825. } // Construct the data rows
  7826. for (i = 0, ln = data.length; i < ln; i += 1) {
  7827. var lineHeight;
  7828. model = data[i];
  7829. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  7830. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  7831. header = headerNames[j];
  7832. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  7833. }
  7834. }
  7835. this.lastCellPos = lastCellPos;
  7836. this.table_x = x;
  7837. this.table_y = y;
  7838. return this;
  7839. };
  7840. /**
  7841. * Calculate the height for containing the highest column
  7842. *
  7843. * @name calculateLineHeight
  7844. * @function
  7845. * @param {String[]} headerNames is the header, used as keys to the data
  7846. * @param {Integer[]} columnWidths is size of each column
  7847. * @param {Object[]} model is the line of data we want to calculate the height of
  7848. * @returns {number} lineHeight
  7849. */
  7850. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  7851. var header,
  7852. lineHeight = 0;
  7853. for (var j = 0; j < headerNames.length; j++) {
  7854. header = headerNames[j];
  7855. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  7856. var h = this.internal.getLineHeight() * model[header].length + padding;
  7857. if (h > lineHeight) lineHeight = h;
  7858. }
  7859. return lineHeight;
  7860. };
  7861. /**
  7862. * Store the config for outputting a table header
  7863. *
  7864. * @name setTableHeaderRow
  7865. * @function
  7866. * @param {Object[]} config
  7867. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  7868. * except the ln parameter is excluded
  7869. */
  7870. jsPDFAPI.setTableHeaderRow = function (config) {
  7871. this.tableHeaderRow = config;
  7872. };
  7873. /**
  7874. * Output the store header row
  7875. *
  7876. * @name printHeaderRow
  7877. * @function
  7878. * @param {number} lineNumber The line number to output the header at
  7879. * @param {boolean} new_page
  7880. */
  7881. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  7882. if (!this.tableHeaderRow) {
  7883. throw 'Property tableHeaderRow does not exist.';
  7884. }
  7885. var tableHeaderCell, tmpArray, i, ln;
  7886. this.printingHeaderRow = true;
  7887. if (headerFunction !== undefined) {
  7888. var position = headerFunction(this, pages);
  7889. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  7890. }
  7891. this.setFontStyle('bold');
  7892. var tempHeaderConf = [];
  7893. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  7894. this.setFillColor(200, 200, 200);
  7895. tableHeaderCell = this.tableHeaderRow[i];
  7896. if (new_page) {
  7897. this.margins.top = margin;
  7898. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  7899. tempHeaderConf.push(tableHeaderCell);
  7900. }
  7901. tmpArray = [].concat(tableHeaderCell);
  7902. this.cell.apply(this, tmpArray.concat(lineNumber));
  7903. }
  7904. if (tempHeaderConf.length > 0) {
  7905. this.setTableHeaderRow(tempHeaderConf);
  7906. }
  7907. this.setFontStyle('normal');
  7908. this.printingHeaderRow = false;
  7909. };
  7910. })(jsPDF.API);
  7911. /**
  7912. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7913. *
  7914. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  7915. */
  7916. /**
  7917. * This plugin mimics the HTML5 CanvasRenderingContext2D.
  7918. *
  7919. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  7920. *
  7921. * @name context2d
  7922. * @module
  7923. */
  7924. (function (jsPDFAPI, globalObj) {
  7925. var ContextLayer = function ContextLayer(ctx) {
  7926. ctx = ctx || {};
  7927. this.isStrokeTransparent = ctx.isStrokeTransparent || false;
  7928. this.strokeOpacity = ctx.strokeOpacity || 1;
  7929. this.strokeStyle = ctx.strokeStyle || '#000000';
  7930. this.fillStyle = ctx.fillStyle || '#000000';
  7931. this.isFillTransparent = ctx.isFillTransparent || false;
  7932. this.fillOpacity = ctx.fillOpacity || 1;
  7933. this.font = ctx.font || '10px sans-serif';
  7934. this.textBaseline = ctx.textBaseline || 'alphabetic';
  7935. this.textAlign = ctx.textAlign || 'left';
  7936. this.lineWidth = ctx.lineWidth || 1;
  7937. this.lineJoin = ctx.lineJoin || 'miter';
  7938. this.lineCap = ctx.lineCap || 'butt';
  7939. this.path = ctx.path || [];
  7940. this.transform = typeof ctx.transform !== 'undefined' ? ctx.transform.clone() : new Matrix();
  7941. this.globalCompositeOperation = ctx.globalCompositeOperation || 'normal';
  7942. this.globalAlpha = ctx.globalAlpha || 1.0;
  7943. this.clip_path = ctx.clip_path || [];
  7944. this.currentPoint = ctx.currentPoint || new Point();
  7945. this.miterLimit = ctx.miterLimit || 10.0;
  7946. this.lastPoint = ctx.lastPoint || new Point();
  7947. this.ignoreClearRect = typeof ctx.ignoreClearRect === "boolean" ? ctx.ignoreClearRect : true;
  7948. return this;
  7949. }; //stub
  7950. var f2, f3, getHorizontalCoordinateString, getVerticalCoordinateString, getHorizontalCoordinate, getVerticalCoordinate;
  7951. jsPDFAPI.events.push(['initialized', function () {
  7952. this.context2d = new Context2D(this);
  7953. f2 = this.internal.f2;
  7954. f3 = this.internal.f3;
  7955. getHorizontalCoordinateString = this.internal.getCoordinateString;
  7956. getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
  7957. getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
  7958. getVerticalCoordinate = this.internal.getVerticalCoordinate;
  7959. }]);
  7960. var Context2D = function Context2D(pdf) {
  7961. Object.defineProperty(this, 'canvas', {
  7962. get: function get() {
  7963. return {
  7964. parentNode: false,
  7965. style: false
  7966. };
  7967. }
  7968. });
  7969. Object.defineProperty(this, 'pdf', {
  7970. get: function get() {
  7971. return pdf;
  7972. }
  7973. });
  7974. var _pageWrapXEnabled = false;
  7975. /**
  7976. * @name pageWrapXEnabled
  7977. * @type {boolean}
  7978. * @default false
  7979. */
  7980. Object.defineProperty(this, 'pageWrapXEnabled', {
  7981. get: function get() {
  7982. return _pageWrapXEnabled;
  7983. },
  7984. set: function set(value) {
  7985. _pageWrapXEnabled = Boolean(value);
  7986. }
  7987. });
  7988. var _pageWrapYEnabled = false;
  7989. /**
  7990. * @name pageWrapYEnabled
  7991. * @type {boolean}
  7992. * @default true
  7993. */
  7994. Object.defineProperty(this, 'pageWrapYEnabled', {
  7995. get: function get() {
  7996. return _pageWrapYEnabled;
  7997. },
  7998. set: function set(value) {
  7999. _pageWrapYEnabled = Boolean(value);
  8000. }
  8001. });
  8002. var _posX = 0;
  8003. /**
  8004. * @name posX
  8005. * @type {number}
  8006. * @default 0
  8007. */
  8008. Object.defineProperty(this, 'posX', {
  8009. get: function get() {
  8010. return _posX;
  8011. },
  8012. set: function set(value) {
  8013. if (!isNaN(value)) {
  8014. _posX = value;
  8015. }
  8016. }
  8017. });
  8018. var _posY = 0;
  8019. /**
  8020. * @name posY
  8021. * @type {number}
  8022. * @default 0
  8023. */
  8024. Object.defineProperty(this, 'posY', {
  8025. get: function get() {
  8026. return _posY;
  8027. },
  8028. set: function set(value) {
  8029. if (!isNaN(value)) {
  8030. _posY = value;
  8031. }
  8032. }
  8033. });
  8034. var _autoPaging = false;
  8035. /**
  8036. * @name autoPaging
  8037. * @type {boolean}
  8038. * @default true
  8039. */
  8040. Object.defineProperty(this, 'autoPaging', {
  8041. get: function get() {
  8042. return _autoPaging;
  8043. },
  8044. set: function set(value) {
  8045. _autoPaging = Boolean(value);
  8046. }
  8047. });
  8048. var lastBreak = 0;
  8049. /**
  8050. * @name lastBreak
  8051. * @type {number}
  8052. * @default 0
  8053. */
  8054. Object.defineProperty(this, 'lastBreak', {
  8055. get: function get() {
  8056. return lastBreak;
  8057. },
  8058. set: function set(value) {
  8059. lastBreak = value;
  8060. }
  8061. });
  8062. var pageBreaks = [];
  8063. /**
  8064. * Y Position of page breaks.
  8065. * @name pageBreaks
  8066. * @type {number}
  8067. * @default 0
  8068. */
  8069. Object.defineProperty(this, 'pageBreaks', {
  8070. get: function get() {
  8071. return pageBreaks;
  8072. },
  8073. set: function set(value) {
  8074. pageBreaks = value;
  8075. }
  8076. });
  8077. var _ctx = new ContextLayer();
  8078. /**
  8079. * @name ctx
  8080. * @type {object}
  8081. * @default {}
  8082. */
  8083. Object.defineProperty(this, 'ctx', {
  8084. get: function get() {
  8085. return _ctx;
  8086. },
  8087. set: function set(value) {
  8088. if (value instanceof ContextLayer) {
  8089. _ctx = value;
  8090. }
  8091. }
  8092. });
  8093. /**
  8094. * @name path
  8095. * @type {array}
  8096. * @default []
  8097. */
  8098. Object.defineProperty(this, 'path', {
  8099. get: function get() {
  8100. return _ctx.path;
  8101. },
  8102. set: function set(value) {
  8103. _ctx.path = value;
  8104. }
  8105. });
  8106. /**
  8107. * @name ctxStack
  8108. * @type {array}
  8109. * @default []
  8110. */
  8111. var _ctxStack = [];
  8112. Object.defineProperty(this, 'ctxStack', {
  8113. get: function get() {
  8114. return _ctxStack;
  8115. },
  8116. set: function set(value) {
  8117. _ctxStack = value;
  8118. }
  8119. });
  8120. /**
  8121. * Sets or returns the color, gradient, or pattern used to fill the drawing
  8122. *
  8123. * @name fillStyle
  8124. * @default #000000
  8125. * @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000<br />
  8126. * A gradient object (linear or radial) used to fill the drawing (not supported by context2d)<br />
  8127. * A pattern object to use to fill the drawing (not supported by context2d)
  8128. */
  8129. Object.defineProperty(this, 'fillStyle', {
  8130. get: function get() {
  8131. return this.ctx.fillStyle;
  8132. },
  8133. set: function set(value) {
  8134. var rgba;
  8135. rgba = getRGBA(value);
  8136. this.ctx.fillStyle = rgba.style;
  8137. this.ctx.isFillTransparent = rgba.a === 0;
  8138. this.ctx.fillOpacity = rgba.a;
  8139. this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, {
  8140. a: rgba.a
  8141. });
  8142. this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, {
  8143. a: rgba.a
  8144. });
  8145. }
  8146. });
  8147. /**
  8148. * Sets or returns the color, gradient, or pattern used for strokes
  8149. *
  8150. * @name strokeStyle
  8151. * @default #000000
  8152. * @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)
  8153. * @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)
  8154. * @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)
  8155. */
  8156. Object.defineProperty(this, 'strokeStyle', {
  8157. get: function get() {
  8158. return this.ctx.strokeStyle;
  8159. },
  8160. set: function set(value) {
  8161. var rgba = getRGBA(value);
  8162. this.ctx.strokeStyle = rgba.style;
  8163. this.ctx.isStrokeTransparent = rgba.a === 0;
  8164. this.ctx.strokeOpacity = rgba.a;
  8165. if (rgba.a === 0) {
  8166. this.pdf.setDrawColor(255, 255, 255);
  8167. } else if (rgba.a === 1) {
  8168. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  8169. } else {
  8170. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  8171. }
  8172. }
  8173. });
  8174. /**
  8175. * Sets or returns the style of the end caps for a line
  8176. *
  8177. * @name lineCap
  8178. * @default butt
  8179. * @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line <br/>
  8180. * round A rounded end cap is added to each end of the line<br/>
  8181. * square A square end cap is added to each end of the line<br/>
  8182. */
  8183. Object.defineProperty(this, 'lineCap', {
  8184. get: function get() {
  8185. return this.ctx.lineCap;
  8186. },
  8187. set: function set(value) {
  8188. if (['butt', 'round', 'square'].indexOf(value) !== -1) {
  8189. this.ctx.lineCap = value;
  8190. this.pdf.setLineCap(value);
  8191. }
  8192. }
  8193. });
  8194. /**
  8195. * Sets or returns the current line width
  8196. *
  8197. * @name lineWidth
  8198. * @default 1
  8199. * @property {number} lineWidth The current line width, in pixels
  8200. */
  8201. Object.defineProperty(this, 'lineWidth', {
  8202. get: function get() {
  8203. return this.ctx.lineWidth;
  8204. },
  8205. set: function set(value) {
  8206. if (!isNaN(value)) {
  8207. this.ctx.lineWidth = value;
  8208. this.pdf.setLineWidth(value);
  8209. }
  8210. }
  8211. });
  8212. /**
  8213. * Sets or returns the type of corner created, when two lines meet
  8214. */
  8215. Object.defineProperty(this, 'lineJoin', {
  8216. get: function get() {
  8217. return this.ctx.lineJoin;
  8218. },
  8219. set: function set(value) {
  8220. if (['bevel', 'round', 'miter'].indexOf(value) !== -1) {
  8221. this.ctx.lineJoin = value;
  8222. this.pdf.setLineJoin(value);
  8223. }
  8224. }
  8225. });
  8226. /**
  8227. * A number specifying the miter limit ratio in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0.
  8228. *
  8229. * @name miterLimit
  8230. * @default 10
  8231. */
  8232. Object.defineProperty(this, 'miterLimit', {
  8233. get: function get() {
  8234. return this.ctx.miterLimit;
  8235. },
  8236. set: function set(value) {
  8237. if (!isNaN(value)) {
  8238. this.ctx.miterLimit = value;
  8239. this.pdf.setMiterLimit(value);
  8240. }
  8241. }
  8242. });
  8243. Object.defineProperty(this, 'textBaseline', {
  8244. get: function get() {
  8245. return this.ctx.textBaseline;
  8246. },
  8247. set: function set(value) {
  8248. this.ctx.textBaseline = value;
  8249. }
  8250. });
  8251. Object.defineProperty(this, 'textAlign', {
  8252. get: function get() {
  8253. return this.ctx.textAlign;
  8254. },
  8255. set: function set(value) {
  8256. if (['right', 'end', 'center', 'left', 'start'].indexOf(value) !== -1) {
  8257. this.ctx.textAlign = value;
  8258. }
  8259. }
  8260. });
  8261. Object.defineProperty(this, 'font', {
  8262. get: function get() {
  8263. return this.ctx.font;
  8264. },
  8265. set: function set(value) {
  8266. this.ctx.font = value;
  8267. var rx, matches; //source: https://stackoverflow.com/a/10136041
  8268. rx = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i;
  8269. matches = rx.exec(value);
  8270. if (matches !== null) {
  8271. var fontStyle = matches[1];
  8272. var fontVariant = matches[2];
  8273. var fontWeight = matches[3];
  8274. var fontSize = matches[4];
  8275. var fontSizeUnit = matches[5];
  8276. var fontFamily = matches[6];
  8277. } else {
  8278. return;
  8279. }
  8280. if ('px' === fontSizeUnit) {
  8281. fontSize = Math.floor(parseFloat(fontSize));
  8282. } else if ('em' === fontSizeUnit) {
  8283. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  8284. } else {
  8285. fontSize = Math.floor(parseFloat(fontSize));
  8286. }
  8287. this.pdf.setFontSize(fontSize);
  8288. var style = '';
  8289. if (fontWeight === 'bold' || parseInt(fontWeight, 10) >= 700 || fontStyle === 'bold') {
  8290. style = 'bold';
  8291. }
  8292. if (fontStyle === 'italic') {
  8293. style += 'italic';
  8294. }
  8295. if (style.length === 0) {
  8296. style = 'normal';
  8297. }
  8298. var jsPdfFontName = '';
  8299. var parts = fontFamily.toLowerCase().replace(/"|'/g, '').split(/\s*,\s*/);
  8300. var fallbackFonts = {
  8301. arial: 'Helvetica',
  8302. verdana: 'Helvetica',
  8303. helvetica: 'Helvetica',
  8304. 'sans-serif': 'Helvetica',
  8305. fixed: 'Courier',
  8306. monospace: 'Courier',
  8307. terminal: 'Courier',
  8308. courier: 'Courier',
  8309. times: 'Times',
  8310. cursive: 'Times',
  8311. fantasy: 'Times',
  8312. serif: 'Times'
  8313. };
  8314. for (var i = 0; i < parts.length; i++) {
  8315. if (this.pdf.internal.getFont(parts[i], style, {
  8316. noFallback: true,
  8317. disableWarning: true
  8318. }) !== undefined) {
  8319. jsPdfFontName = parts[i];
  8320. break;
  8321. } else if (style === 'bolditalic' && this.pdf.internal.getFont(parts[i], 'bold', {
  8322. noFallback: true,
  8323. disableWarning: true
  8324. }) !== undefined) {
  8325. jsPdfFontName = parts[i];
  8326. style = 'bold';
  8327. } else if (this.pdf.internal.getFont(parts[i], 'normal', {
  8328. noFallback: true,
  8329. disableWarning: true
  8330. }) !== undefined) {
  8331. jsPdfFontName = parts[i];
  8332. style = 'normal';
  8333. break;
  8334. }
  8335. }
  8336. if (jsPdfFontName === '') {
  8337. for (var i = 0; i < parts.length; i++) {
  8338. if (fallbackFonts[parts[i]]) {
  8339. jsPdfFontName = fallbackFonts[parts[i]];
  8340. break;
  8341. }
  8342. }
  8343. }
  8344. jsPdfFontName = jsPdfFontName === '' ? 'Times' : jsPdfFontName;
  8345. this.pdf.setFont(jsPdfFontName, style);
  8346. }
  8347. });
  8348. Object.defineProperty(this, 'globalCompositeOperation', {
  8349. get: function get() {
  8350. return this.ctx.globalCompositeOperation;
  8351. },
  8352. set: function set(value) {
  8353. this.ctx.globalCompositeOperation = value;
  8354. }
  8355. });
  8356. Object.defineProperty(this, 'globalAlpha', {
  8357. get: function get() {
  8358. return this.ctx.globalAlpha;
  8359. },
  8360. set: function set(value) {
  8361. this.ctx.globalAlpha = value;
  8362. }
  8363. }); // Not HTML API
  8364. Object.defineProperty(this, 'ignoreClearRect', {
  8365. get: function get() {
  8366. return this.ctx.ignoreClearRect;
  8367. },
  8368. set: function set(value) {
  8369. this.ctx.ignoreClearRect = Boolean(value);
  8370. }
  8371. });
  8372. };
  8373. Context2D.prototype.fill = function () {
  8374. pathPreProcess.call(this, 'fill', false);
  8375. };
  8376. /**
  8377. * Actually draws the path you have defined
  8378. *
  8379. * @name stroke
  8380. * @function
  8381. * @description The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.
  8382. */
  8383. Context2D.prototype.stroke = function () {
  8384. pathPreProcess.call(this, 'stroke', false);
  8385. };
  8386. /**
  8387. * Begins a path, or resets the current
  8388. *
  8389. * @name beginPath
  8390. * @function
  8391. * @description The beginPath() method begins a path, or resets the current path.
  8392. */
  8393. Context2D.prototype.beginPath = function () {
  8394. this.path = [{
  8395. type: 'begin'
  8396. }];
  8397. };
  8398. /**
  8399. * Moves the path to the specified point in the canvas, without creating a line
  8400. *
  8401. * @name moveTo
  8402. * @function
  8403. * @param x {Number} The x-coordinate of where to move the path to
  8404. * @param y {Number} The y-coordinate of where to move the path to
  8405. */
  8406. Context2D.prototype.moveTo = function (x, y) {
  8407. if (isNaN(x) || isNaN(y)) {
  8408. console.error('jsPDF.context2d.moveTo: Invalid arguments', arguments);
  8409. throw new Error('Invalid arguments passed to jsPDF.context2d.moveTo');
  8410. }
  8411. var pt = this.ctx.transform.applyToPoint(new Point(x, y));
  8412. this.path.push({
  8413. type: 'mt',
  8414. x: pt.x,
  8415. y: pt.y
  8416. });
  8417. this.ctx.lastPoint = new Point(x, y);
  8418. };
  8419. /**
  8420. * Creates a path from the current point back to the starting point
  8421. *
  8422. * @name closePath
  8423. * @function
  8424. * @description The closePath() method creates a path from the current point back to the starting point.
  8425. */
  8426. Context2D.prototype.closePath = function () {
  8427. var pathBegin = new Point(0, 0);
  8428. var i = 0;
  8429. for (i = this.path.length - 1; i !== -1; i--) {
  8430. if (this.path[i].type === 'begin') {
  8431. if (_typeof(this.path[i + 1]) === 'object' && typeof this.path[i + 1].x === 'number') {
  8432. pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);
  8433. this.path.push({
  8434. type: 'lt',
  8435. x: pathBegin.x,
  8436. y: pathBegin.y
  8437. });
  8438. break;
  8439. }
  8440. }
  8441. }
  8442. if (_typeof(this.path[i + 2]) === 'object' && typeof this.path[i + 2].x === 'number') {
  8443. this.path.push(JSON.parse(JSON.stringify(this.path[i + 2])));
  8444. }
  8445. this.path.push({
  8446. type: 'close'
  8447. });
  8448. this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);
  8449. };
  8450. /**
  8451. * Adds a new point and creates a line to that point from the last specified point in the canvas
  8452. *
  8453. * @name lineTo
  8454. * @function
  8455. * @param x The x-coordinate of where to create the line to
  8456. * @param y The y-coordinate of where to create the line to
  8457. * @description The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).
  8458. */
  8459. Context2D.prototype.lineTo = function (x, y) {
  8460. if (isNaN(x) || isNaN(y)) {
  8461. console.error('jsPDF.context2d.lineTo: Invalid arguments', arguments);
  8462. throw new Error('Invalid arguments passed to jsPDF.context2d.lineTo');
  8463. }
  8464. var pt = this.ctx.transform.applyToPoint(new Point(x, y));
  8465. this.path.push({
  8466. type: 'lt',
  8467. x: pt.x,
  8468. y: pt.y
  8469. });
  8470. this.ctx.lastPoint = new Point(pt.x, pt.y);
  8471. };
  8472. /**
  8473. * Clips a region of any shape and size from the original canvas
  8474. *
  8475. * @name clip
  8476. * @function
  8477. * @description The clip() method clips a region of any shape and size from the original canvas.
  8478. */
  8479. Context2D.prototype.clip = function () {
  8480. this.ctx.clip_path = JSON.parse(JSON.stringify(this.path));
  8481. pathPreProcess.call(this, null, true);
  8482. };
  8483. /**
  8484. * Creates a cubic Bézier curve
  8485. *
  8486. * @name quadraticCurveTo
  8487. * @function
  8488. * @param cpx {Number} The x-coordinate of the Bézier control point
  8489. * @param cpy {Number} The y-coordinate of the Bézier control point
  8490. * @param x {Number} The x-coordinate of the ending point
  8491. * @param y {Number} The y-coordinate of the ending point
  8492. * @description The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.<br /><br /> A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
  8493. */
  8494. Context2D.prototype.quadraticCurveTo = function (cpx, cpy, x, y) {
  8495. if (isNaN(x) || isNaN(y) || isNaN(cpx) || isNaN(cpy)) {
  8496. console.error('jsPDF.context2d.quadraticCurveTo: Invalid arguments', arguments);
  8497. throw new Error('Invalid arguments passed to jsPDF.context2d.quadraticCurveTo');
  8498. }
  8499. var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
  8500. var pt1 = this.ctx.transform.applyToPoint(new Point(cpx, cpy));
  8501. this.path.push({
  8502. type: 'qct',
  8503. x1: pt1.x,
  8504. y1: pt1.y,
  8505. x: pt0.x,
  8506. y: pt0.y
  8507. });
  8508. this.ctx.lastPoint = new Point(pt0.x, pt0.y);
  8509. };
  8510. /**
  8511. * Creates a cubic Bézier curve
  8512. *
  8513. * @name bezierCurveTo
  8514. * @function
  8515. * @param cp1x {Number} The x-coordinate of the first Bézier control point
  8516. * @param cp1y {Number} The y-coordinate of the first Bézier control point
  8517. * @param cp2x {Number} The x-coordinate of the second Bézier control point
  8518. * @param cp2y {Number} The y-coordinate of the second Bézier control point
  8519. * @param x {Number} The x-coordinate of the ending point
  8520. * @param y {Number} The y-coordinate of the ending point
  8521. * @description The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. <br /><br />A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
  8522. */
  8523. Context2D.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  8524. if (isNaN(x) || isNaN(y) || isNaN(cp1x) || isNaN(cp1y) || isNaN(cp2x) || isNaN(cp2y)) {
  8525. console.error('jsPDF.context2d.bezierCurveTo: Invalid arguments', arguments);
  8526. throw new Error('Invalid arguments passed to jsPDF.context2d.bezierCurveTo');
  8527. }
  8528. var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
  8529. var pt1 = this.ctx.transform.applyToPoint(new Point(cp1x, cp1y));
  8530. var pt2 = this.ctx.transform.applyToPoint(new Point(cp2x, cp2y));
  8531. this.path.push({
  8532. type: 'bct',
  8533. x1: pt1.x,
  8534. y1: pt1.y,
  8535. x2: pt2.x,
  8536. y2: pt2.y,
  8537. x: pt0.x,
  8538. y: pt0.y
  8539. });
  8540. this.ctx.lastPoint = new Point(pt0.x, pt0.y);
  8541. };
  8542. /**
  8543. * Creates an arc/curve (used to create circles, or parts of circles)
  8544. *
  8545. * @name arc
  8546. * @function
  8547. * @param x {Number} The x-coordinate of the center of the circle
  8548. * @param y {Number} The y-coordinate of the center of the circle
  8549. * @param radius {Number} The radius of the circle
  8550. * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
  8551. * @param endAngle {Number} The ending angle, in radians
  8552. * @param counterclockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
  8553. * @description The arc() method creates an arc/curve (used to create circles, or parts of circles).
  8554. */
  8555. Context2D.prototype.arc = function (x, y, radius, startAngle, endAngle, counterclockwise) {
  8556. if (isNaN(x) || isNaN(y) || isNaN(radius) || isNaN(startAngle) || isNaN(endAngle)) {
  8557. console.error('jsPDF.context2d.arc: Invalid arguments', arguments);
  8558. throw new Error('Invalid arguments passed to jsPDF.context2d.arc');
  8559. }
  8560. counterclockwise = Boolean(counterclockwise);
  8561. if (!this.ctx.transform.isIdentity) {
  8562. var xpt = this.ctx.transform.applyToPoint(new Point(x, y));
  8563. x = xpt.x;
  8564. y = xpt.y;
  8565. var x_radPt = this.ctx.transform.applyToPoint(new Point(0, radius));
  8566. var x_radPt0 = this.ctx.transform.applyToPoint(new Point(0, 0));
  8567. radius = Math.sqrt(Math.pow(x_radPt.x - x_radPt0.x, 2) + Math.pow(x_radPt.y - x_radPt0.y, 2));
  8568. }
  8569. if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
  8570. startAngle = 0;
  8571. endAngle = 2 * Math.PI;
  8572. }
  8573. this.path.push({
  8574. type: 'arc',
  8575. x: x,
  8576. y: y,
  8577. radius: radius,
  8578. startAngle: startAngle,
  8579. endAngle: endAngle,
  8580. counterclockwise: counterclockwise
  8581. }); // this.ctx.lastPoint(new Point(pt.x,pt.y));
  8582. };
  8583. /**
  8584. * Creates an arc/curve between two tangents
  8585. *
  8586. * @name arcTo
  8587. * @function
  8588. * @param x1 {Number} The x-coordinate of the first tangent
  8589. * @param y1 {Number} The y-coordinate of the first tangent
  8590. * @param x2 {Number} The x-coordinate of the second tangent
  8591. * @param y2 {Number} The y-coordinate of the second tangent
  8592. * @param radius The radius of the arc
  8593. * @description The arcTo() method creates an arc/curve between two tangents on the canvas.
  8594. */
  8595. Context2D.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  8596. throw new Error('arcTo not implemented.');
  8597. };
  8598. /**
  8599. * Creates a rectangle
  8600. *
  8601. * @name rect
  8602. * @function
  8603. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8604. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8605. * @param w {Number} The width of the rectangle, in pixels
  8606. * @param h {Number} The height of the rectangle, in pixels
  8607. * @description The rect() method creates a rectangle.
  8608. */
  8609. Context2D.prototype.rect = function (x, y, w, h) {
  8610. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8611. console.error('jsPDF.context2d.rect: Invalid arguments', arguments);
  8612. throw new Error('Invalid arguments passed to jsPDF.context2d.rect');
  8613. }
  8614. this.moveTo(x, y);
  8615. this.lineTo(x + w, y);
  8616. this.lineTo(x + w, y + h);
  8617. this.lineTo(x, y + h);
  8618. this.lineTo(x, y);
  8619. this.lineTo(x + w, y);
  8620. this.lineTo(x, y);
  8621. };
  8622. /**
  8623. * Draws a "filled" rectangle
  8624. *
  8625. * @name fillRect
  8626. * @function
  8627. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8628. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8629. * @param w {Number} The width of the rectangle, in pixels
  8630. * @param h {Number} The height of the rectangle, in pixels
  8631. * @description The fillRect() method draws a "filled" rectangle. The default color of the fill is black.
  8632. */
  8633. Context2D.prototype.fillRect = function (x, y, w, h) {
  8634. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8635. console.error('jsPDF.context2d.fillRect: Invalid arguments', arguments);
  8636. throw new Error('Invalid arguments passed to jsPDF.context2d.fillRect');
  8637. }
  8638. if (isFillTransparent.call(this)) {
  8639. return;
  8640. }
  8641. var tmp = {};
  8642. if (this.lineCap !== 'butt') {
  8643. tmp.lineCap = this.lineCap;
  8644. this.lineCap = 'butt';
  8645. }
  8646. if (this.lineJoin !== 'miter') {
  8647. tmp.lineJoin = this.lineJoin;
  8648. this.lineJoin = 'miter';
  8649. }
  8650. this.beginPath();
  8651. this.rect(x, y, w, h);
  8652. this.fill();
  8653. if (tmp.hasOwnProperty('lineCap')) {
  8654. this.lineCap = tmp.lineCap;
  8655. }
  8656. if (tmp.hasOwnProperty('lineJoin')) {
  8657. this.lineJoin = tmp.lineJoin;
  8658. }
  8659. };
  8660. /**
  8661. * Draws a rectangle (no fill)
  8662. *
  8663. * @name strokeRect
  8664. * @function
  8665. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8666. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8667. * @param w {Number} The width of the rectangle, in pixels
  8668. * @param h {Number} The height of the rectangle, in pixels
  8669. * @description The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.
  8670. */
  8671. Context2D.prototype.strokeRect = function strokeRect(x, y, w, h) {
  8672. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8673. console.error('jsPDF.context2d.strokeRect: Invalid arguments', arguments);
  8674. throw new Error('Invalid arguments passed to jsPDF.context2d.strokeRect');
  8675. }
  8676. if (isStrokeTransparent.call(this)) {
  8677. return;
  8678. }
  8679. this.beginPath();
  8680. this.rect(x, y, w, h);
  8681. this.stroke();
  8682. };
  8683. /**
  8684. * Clears the specified pixels within a given rectangle
  8685. *
  8686. * @name clearRect
  8687. * @function
  8688. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8689. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8690. * @param w {Number} The width of the rectangle to clear, in pixels
  8691. * @param h {Number} The height of the rectangle to clear, in pixels
  8692. * @description We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  8693. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  8694. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  8695. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  8696. *
  8697. */
  8698. Context2D.prototype.clearRect = function (x, y, w, h) {
  8699. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8700. console.error('jsPDF.context2d.clearRect: Invalid arguments', arguments);
  8701. throw new Error('Invalid arguments passed to jsPDF.context2d.clearRect');
  8702. }
  8703. if (this.ignoreClearRect) {
  8704. return;
  8705. }
  8706. this.fillStyle = '#ffffff';
  8707. this.fillRect(x, y, w, h);
  8708. };
  8709. /**
  8710. * Saves the state of the current context
  8711. *
  8712. * @name save
  8713. * @function
  8714. */
  8715. Context2D.prototype.save = function (doStackPush) {
  8716. doStackPush = typeof doStackPush === 'boolean' ? doStackPush : true;
  8717. var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
  8718. for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
  8719. this.pdf.setPage(i + 1);
  8720. this.pdf.internal.out('q');
  8721. }
  8722. this.pdf.setPage(tmpPageNumber);
  8723. if (doStackPush) {
  8724. this.ctx.fontSize = this.pdf.internal.getFontSize();
  8725. var ctx = new ContextLayer(this.ctx);
  8726. this.ctxStack.push(this.ctx);
  8727. this.ctx = ctx;
  8728. }
  8729. };
  8730. /**
  8731. * Returns previously saved path state and attributes
  8732. *
  8733. * @name restore
  8734. * @function
  8735. */
  8736. Context2D.prototype.restore = function (doStackPop) {
  8737. doStackPop = typeof doStackPop === 'boolean' ? doStackPop : true;
  8738. var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
  8739. for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
  8740. this.pdf.setPage(i + 1);
  8741. this.pdf.internal.out('Q');
  8742. }
  8743. this.pdf.setPage(tmpPageNumber);
  8744. if (doStackPop && this.ctxStack.length !== 0) {
  8745. this.ctx = this.ctxStack.pop();
  8746. this.fillStyle = this.ctx.fillStyle;
  8747. this.strokeStyle = this.ctx.strokeStyle;
  8748. this.font = this.ctx.font;
  8749. this.lineCap = this.ctx.lineCap;
  8750. this.lineWidth = this.ctx.lineWidth;
  8751. this.lineJoin = this.ctx.lineJoin;
  8752. }
  8753. };
  8754. /**
  8755. * @name toDataURL
  8756. * @function
  8757. */
  8758. Context2D.prototype.toDataURL = function () {
  8759. throw new Error('toDataUrl not implemented.');
  8760. }; //helper functions
  8761. /**
  8762. * Get the decimal values of r, g, b and a
  8763. *
  8764. * @name getRGBA
  8765. * @function
  8766. * @private
  8767. * @ignore
  8768. */
  8769. var getRGBA = function getRGBA(style) {
  8770. var rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  8771. var rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  8772. var rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  8773. var r, g, b, a;
  8774. if (style.isCanvasGradient === true) {
  8775. style = style.getColor();
  8776. }
  8777. if (!style) {
  8778. return {
  8779. r: 0,
  8780. g: 0,
  8781. b: 0,
  8782. a: 0,
  8783. style: style
  8784. };
  8785. }
  8786. if (rxTransparent.test(style)) {
  8787. r = 0;
  8788. g = 0;
  8789. b = 0;
  8790. a = 0;
  8791. } else {
  8792. var matches = rxRgb.exec(style);
  8793. if (matches !== null) {
  8794. r = parseInt(matches[1]);
  8795. g = parseInt(matches[2]);
  8796. b = parseInt(matches[3]);
  8797. a = 1;
  8798. } else {
  8799. matches = rxRgba.exec(style);
  8800. if (matches !== null) {
  8801. r = parseInt(matches[1]);
  8802. g = parseInt(matches[2]);
  8803. b = parseInt(matches[3]);
  8804. a = parseFloat(matches[4]);
  8805. } else {
  8806. a = 1;
  8807. if (typeof style === "string" && style.charAt(0) !== '#') {
  8808. var rgbColor = new RGBColor(style);
  8809. if (rgbColor.ok) {
  8810. style = rgbColor.toHex();
  8811. } else {
  8812. style = '#000000';
  8813. }
  8814. }
  8815. if (style.length === 4) {
  8816. r = style.substring(1, 2);
  8817. r += r;
  8818. g = style.substring(2, 3);
  8819. g += g;
  8820. b = style.substring(3, 4);
  8821. b += b;
  8822. } else {
  8823. r = style.substring(1, 3);
  8824. g = style.substring(3, 5);
  8825. b = style.substring(5, 7);
  8826. }
  8827. r = parseInt(r, 16);
  8828. g = parseInt(g, 16);
  8829. b = parseInt(b, 16);
  8830. }
  8831. }
  8832. }
  8833. return {
  8834. r: r,
  8835. g: g,
  8836. b: b,
  8837. a: a,
  8838. style: style
  8839. };
  8840. };
  8841. /**
  8842. * @name isFillTransparent
  8843. * @function
  8844. * @private
  8845. * @ignore
  8846. * @returns {Boolean}
  8847. */
  8848. var isFillTransparent = function isFillTransparent() {
  8849. return this.ctx.isFillTransparent || this.globalAlpha == 0;
  8850. };
  8851. /**
  8852. * @name isStrokeTransparent
  8853. * @function
  8854. * @private
  8855. * @ignore
  8856. * @returns {Boolean}
  8857. */
  8858. var isStrokeTransparent = function isStrokeTransparent() {
  8859. return Boolean(this.ctx.isStrokeTransparent || this.globalAlpha == 0);
  8860. };
  8861. /**
  8862. * Draws "filled" text on the canvas
  8863. *
  8864. * @name fillText
  8865. * @function
  8866. * @param text {String} Specifies the text that will be written on the canvas
  8867. * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
  8868. * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
  8869. * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
  8870. * @description The fillText() method draws filled text on the canvas. The default color of the text is black.
  8871. */
  8872. Context2D.prototype.fillText = function (text, x, y, maxWidth) {
  8873. if (isNaN(x) || isNaN(y) || typeof text !== 'string') {
  8874. console.error('jsPDF.context2d.fillText: Invalid arguments', arguments);
  8875. throw new Error('Invalid arguments passed to jsPDF.context2d.fillText');
  8876. }
  8877. maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
  8878. if (isFillTransparent.call(this)) {
  8879. return;
  8880. }
  8881. y = getBaseline.call(this, y);
  8882. var degs = rad2deg(this.ctx.transform.rotation); // We only use X axis as scale hint
  8883. var scale = this.ctx.transform.scaleX;
  8884. putText.call(this, {
  8885. text: text,
  8886. x: x,
  8887. y: y,
  8888. scale: scale,
  8889. angle: degs,
  8890. align: this.textAlign,
  8891. maxWidth: maxWidth
  8892. });
  8893. };
  8894. /**
  8895. * Draws text on the canvas (no fill)
  8896. *
  8897. * @name strokeText
  8898. * @function
  8899. * @param text {String} Specifies the text that will be written on the canvas
  8900. * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
  8901. * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
  8902. * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
  8903. * @description The strokeText() method draws text (with no fill) on the canvas. The default color of the text is black.
  8904. */
  8905. Context2D.prototype.strokeText = function (text, x, y, maxWidth) {
  8906. if (isNaN(x) || isNaN(y) || typeof text !== 'string') {
  8907. console.error('jsPDF.context2d.strokeText: Invalid arguments', arguments);
  8908. throw new Error('Invalid arguments passed to jsPDF.context2d.strokeText');
  8909. }
  8910. if (isStrokeTransparent.call(this)) {
  8911. return;
  8912. }
  8913. maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
  8914. y = getBaseline.call(this, y);
  8915. var degs = rad2deg(this.ctx.transform.rotation);
  8916. var scale = this.ctx.transform.scaleX;
  8917. putText.call(this, {
  8918. text: text,
  8919. x: x,
  8920. y: y,
  8921. scale: scale,
  8922. renderingMode: 'stroke',
  8923. angle: degs,
  8924. align: this.textAlign,
  8925. maxWidth: maxWidth
  8926. });
  8927. };
  8928. /**
  8929. * Returns an object that contains the width of the specified text
  8930. *
  8931. * @name measureText
  8932. * @function
  8933. * @param text {String} The text to be measured
  8934. * @description The measureText() method returns an object that contains the width of the specified text, in pixels.
  8935. * @returns {Number}
  8936. */
  8937. Context2D.prototype.measureText = function (text) {
  8938. if (typeof text !== 'string') {
  8939. console.error('jsPDF.context2d.measureText: Invalid arguments', arguments);
  8940. throw new Error('Invalid arguments passed to jsPDF.context2d.measureText');
  8941. }
  8942. var pdf = this.pdf;
  8943. var k = this.pdf.internal.scaleFactor;
  8944. var fontSize = pdf.internal.getFontSize();
  8945. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  8946. txtWidth *= Math.round(k * 96 / 72 * 10000) / 10000;
  8947. var TextMetrics = function TextMetrics(options) {
  8948. options = options || {};
  8949. var _width = options.width || 0;
  8950. Object.defineProperty(this, 'width', {
  8951. get: function get() {
  8952. return _width;
  8953. }
  8954. });
  8955. return this;
  8956. };
  8957. return new TextMetrics({
  8958. width: txtWidth
  8959. });
  8960. }; //Transformations
  8961. /**
  8962. * Scales the current drawing bigger or smaller
  8963. *
  8964. * @name scale
  8965. * @function
  8966. * @param scalewidth {Number} Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
  8967. * @param scaleheight {Number} Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
  8968. * @description The scale() method scales the current drawing, bigger or smaller.
  8969. */
  8970. Context2D.prototype.scale = function (scalewidth, scaleheight) {
  8971. if (isNaN(scalewidth) || isNaN(scaleheight)) {
  8972. console.error('jsPDF.context2d.scale: Invalid arguments', arguments);
  8973. throw new Error('Invalid arguments passed to jsPDF.context2d.scale');
  8974. }
  8975. var matrix = new Matrix(scalewidth, 0.0, 0.0, scaleheight, 0.0, 0.0);
  8976. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8977. };
  8978. /**
  8979. * Rotates the current drawing
  8980. *
  8981. * @name rotate
  8982. * @function
  8983. * @param angle {Number} The rotation angle, in radians.
  8984. * @description To calculate from degrees to radians: degrees*Math.PI/180. <br />
  8985. * Example: to rotate 5 degrees, specify the following: 5*Math.PI/180
  8986. */
  8987. Context2D.prototype.rotate = function (angle) {
  8988. if (isNaN(angle)) {
  8989. console.error('jsPDF.context2d.rotate: Invalid arguments', arguments);
  8990. throw new Error('Invalid arguments passed to jsPDF.context2d.rotate');
  8991. }
  8992. var matrix = new Matrix(Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0);
  8993. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8994. };
  8995. /**
  8996. * Remaps the (0,0) position on the canvas
  8997. *
  8998. * @name translate
  8999. * @function
  9000. * @param x {Number} The value to add to horizontal (x) coordinates
  9001. * @param y {Number} The value to add to vertical (y) coordinates
  9002. * @description The translate() method remaps the (0,0) position on the canvas.
  9003. */
  9004. Context2D.prototype.translate = function (x, y) {
  9005. if (isNaN(x) || isNaN(y)) {
  9006. console.error('jsPDF.context2d.translate: Invalid arguments', arguments);
  9007. throw new Error('Invalid arguments passed to jsPDF.context2d.translate');
  9008. }
  9009. var matrix = new Matrix(1.0, 0.0, 0.0, 1.0, x, y);
  9010. this.ctx.transform = this.ctx.transform.multiply(matrix);
  9011. };
  9012. /**
  9013. * Replaces the current transformation matrix for the drawing
  9014. *
  9015. * @name transform
  9016. * @function
  9017. * @param a {Number} Horizontal scaling
  9018. * @param b {Number} Horizontal skewing
  9019. * @param c {Number} Vertical skewing
  9020. * @param d {Number} Vertical scaling
  9021. * @param e {Number} Horizontal moving
  9022. * @param f {Number} Vertical moving
  9023. * @description Each object on the canvas has a current transformation matrix.<br /><br />The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:<br /><br /><br /><br />a c e<br /><br />b d f<br /><br />0 0 1<br /><br />In other words, the transform() method lets you scale, rotate, move, and skew the current context.
  9024. */
  9025. Context2D.prototype.transform = function (a, b, c, d, e, f) {
  9026. if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d) || isNaN(e) || isNaN(f)) {
  9027. console.error('jsPDF.context2d.transform: Invalid arguments', arguments);
  9028. throw new Error('Invalid arguments passed to jsPDF.context2d.transform');
  9029. }
  9030. var matrix = new Matrix(a, b, c, d, e, f);
  9031. this.ctx.transform = this.ctx.transform.multiply(matrix);
  9032. };
  9033. /**
  9034. * Resets the current transform to the identity matrix. Then runs transform()
  9035. *
  9036. * @name setTransform
  9037. * @function
  9038. * @param a {Number} Horizontal scaling
  9039. * @param b {Number} Horizontal skewing
  9040. * @param c {Number} Vertical skewing
  9041. * @param d {Number} Vertical scaling
  9042. * @param e {Number} Horizontal moving
  9043. * @param f {Number} Vertical moving
  9044. * @description Each object on the canvas has a current transformation matrix. <br /><br />The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.<br /><br />In other words, the setTransform() method lets you scale, rotate, move, and skew the current context.
  9045. */
  9046. Context2D.prototype.setTransform = function (a, b, c, d, e, f) {
  9047. a = isNaN(a) ? 1 : a;
  9048. b = isNaN(b) ? 0 : b;
  9049. c = isNaN(c) ? 0 : c;
  9050. d = isNaN(d) ? 1 : d;
  9051. e = isNaN(e) ? 0 : e;
  9052. f = isNaN(f) ? 0 : f;
  9053. this.ctx.transform = new Matrix(a, b, c, d, e, f);
  9054. };
  9055. /**
  9056. * Draws an image, canvas, or video onto the canvas
  9057. *
  9058. * @function
  9059. * @param img {} Specifies the image, canvas, or video element to use
  9060. * @param sx {Number} Optional. The x coordinate where to start clipping
  9061. * @param sy {Number} Optional. The y coordinate where to start clipping
  9062. * @param swidth {Number} Optional. The width of the clipped image
  9063. * @param sheight {Number} Optional. The height of the clipped image
  9064. * @param x {Number} The x coordinate where to place the image on the canvas
  9065. * @param y {Number} The y coordinate where to place the image on the canvas
  9066. * @param width {Number} Optional. The width of the image to use (stretch or reduce the image)
  9067. * @param height {Number} Optional. The height of the image to use (stretch or reduce the image)
  9068. */
  9069. Context2D.prototype.drawImage = function (img, sx, sy, swidth, sheight, x, y, width, height) {
  9070. var imageProperties = this.pdf.getImageProperties(img);
  9071. var factorX = 1;
  9072. var factorY = 1;
  9073. var clipFactorX = 1;
  9074. var clipFactorY = 1;
  9075. var scaleFactorX = 1;
  9076. if (typeof swidth !== 'undefined' && typeof width !== 'undefined') {
  9077. clipFactorX = width / swidth;
  9078. clipFactorY = height / sheight;
  9079. factorX = imageProperties.width / swidth * width / swidth;
  9080. factorY = imageProperties.height / sheight * height / sheight;
  9081. } //is sx and sy are set and x and y not, set x and y with values of sx and sy
  9082. if (typeof x === 'undefined') {
  9083. x = sx;
  9084. y = sy;
  9085. sx = 0;
  9086. sy = 0;
  9087. }
  9088. if (typeof swidth !== 'undefined' && typeof width === 'undefined') {
  9089. width = swidth;
  9090. height = sheight;
  9091. }
  9092. if (typeof swidth === 'undefined' && typeof width === 'undefined') {
  9093. width = imageProperties.width;
  9094. height = imageProperties.height;
  9095. }
  9096. var decomposedTransformationMatrix = this.ctx.transform.decompose();
  9097. var angle = rad2deg(decomposedTransformationMatrix.rotate.shx);
  9098. scaleFactorX = decomposedTransformationMatrix.scale.sx;
  9099. scaleFactorX = decomposedTransformationMatrix.scale.sy;
  9100. var matrix = new Matrix();
  9101. matrix = matrix.multiply(decomposedTransformationMatrix.translate);
  9102. matrix = matrix.multiply(decomposedTransformationMatrix.skew);
  9103. matrix = matrix.multiply(decomposedTransformationMatrix.scale);
  9104. var mP = matrix.applyToPoint(new Point(width, height));
  9105. var xRect = matrix.applyToRectangle(new Rectangle(x - sx * clipFactorX, y - sy * clipFactorY, swidth * factorX, sheight * factorY));
  9106. var pageArray = getPagesByPath.call(this, xRect);
  9107. var pages = [];
  9108. for (var ii = 0; ii < pageArray.length; ii += 1) {
  9109. if (pages.indexOf(pageArray[ii]) === -1) {
  9110. pages.push(pageArray[ii]);
  9111. }
  9112. }
  9113. pages.sort();
  9114. var clipPath;
  9115. if (this.autoPaging) {
  9116. var min = pages[0];
  9117. var max = pages[pages.length - 1];
  9118. for (var i = min; i < max + 1; i++) {
  9119. this.pdf.setPage(i);
  9120. if (this.ctx.clip_path.length !== 0) {
  9121. var tmpPaths = this.path;
  9122. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  9123. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  9124. drawPaths.call(this, 'fill', true);
  9125. this.path = tmpPaths;
  9126. }
  9127. var tmpRect = JSON.parse(JSON.stringify(xRect));
  9128. tmpRect = pathPositionRedo([tmpRect], this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY)[0];
  9129. this.pdf.addImage(img, 'jpg', tmpRect.x, tmpRect.y, tmpRect.w, tmpRect.h, null, null, angle);
  9130. }
  9131. } else {
  9132. this.pdf.addImage(img, 'jpg', xRect.x, xRect.y, xRect.w, xRect.h, null, null, angle);
  9133. }
  9134. };
  9135. var getPagesByPath = function getPagesByPath(path, pageWrapX, pageWrapY) {
  9136. var result = [];
  9137. pageWrapX = pageWrapX || this.pdf.internal.pageSize.width;
  9138. pageWrapY = pageWrapY || this.pdf.internal.pageSize.height;
  9139. switch (path.type) {
  9140. default:
  9141. case 'mt':
  9142. case 'lt':
  9143. result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
  9144. break;
  9145. case 'arc':
  9146. result.push(Math.floor((path.y + this.posY - path.radius) / pageWrapY) + 1);
  9147. result.push(Math.floor((path.y + this.posY + path.radius) / pageWrapY) + 1);
  9148. break;
  9149. case 'qct':
  9150. var rectOfQuadraticCurve = getQuadraticCurveBoundary(this.ctx.lastPoint.x, this.ctx.lastPoint.y, path.x1, path.y1, path.x, path.y);
  9151. result.push(Math.floor(rectOfQuadraticCurve.y / pageWrapY) + 1);
  9152. result.push(Math.floor((rectOfQuadraticCurve.y + rectOfQuadraticCurve.h) / pageWrapY) + 1);
  9153. break;
  9154. case 'bct':
  9155. var rectOfBezierCurve = getBezierCurveBoundary(this.ctx.lastPoint.x, this.ctx.lastPoint.y, path.x1, path.y1, path.x2, path.y2, path.x, path.y);
  9156. result.push(Math.floor(rectOfBezierCurve.y / pageWrapY) + 1);
  9157. result.push(Math.floor((rectOfBezierCurve.y + rectOfBezierCurve.h) / pageWrapY) + 1);
  9158. break;
  9159. case 'rect':
  9160. result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
  9161. result.push(Math.floor((path.y + path.h + this.posY) / pageWrapY) + 1);
  9162. }
  9163. for (var i = 0; i < result.length; i += 1) {
  9164. while (this.pdf.internal.getNumberOfPages() < result[i]) {
  9165. addPage.call(this);
  9166. }
  9167. }
  9168. return result;
  9169. };
  9170. var addPage = function addPage() {
  9171. var fillStyle = this.fillStyle;
  9172. var strokeStyle = this.strokeStyle;
  9173. var font = this.font;
  9174. var lineCap = this.lineCap;
  9175. var lineWidth = this.lineWidth;
  9176. var lineJoin = this.lineJoin;
  9177. this.pdf.addPage();
  9178. this.fillStyle = fillStyle;
  9179. this.strokeStyle = strokeStyle;
  9180. this.font = font;
  9181. this.lineCap = lineCap;
  9182. this.lineWidth = lineWidth;
  9183. this.lineJoin = lineJoin;
  9184. };
  9185. var pathPositionRedo = function pathPositionRedo(paths, x, y) {
  9186. for (var i = 0; i < paths.length; i++) {
  9187. switch (paths[i].type) {
  9188. case 'bct':
  9189. paths[i].x2 += x;
  9190. paths[i].y2 += y;
  9191. case 'qct':
  9192. paths[i].x1 += x;
  9193. paths[i].y1 += y;
  9194. case 'mt':
  9195. case 'lt':
  9196. case 'arc':
  9197. default:
  9198. paths[i].x += x;
  9199. paths[i].y += y;
  9200. }
  9201. }
  9202. return paths;
  9203. };
  9204. var pathPreProcess = function pathPreProcess(rule, isClip) {
  9205. var fillStyle = this.fillStyle;
  9206. var strokeStyle = this.strokeStyle;
  9207. var font = this.font;
  9208. var lineCap = this.lineCap;
  9209. var lineWidth = this.lineWidth;
  9210. var lineJoin = this.lineJoin;
  9211. var origPath = JSON.parse(JSON.stringify(this.path));
  9212. var xPath = JSON.parse(JSON.stringify(this.path));
  9213. var clipPath;
  9214. var tmpPath;
  9215. var pages = [];
  9216. for (var i = 0; i < xPath.length; i++) {
  9217. if (typeof xPath[i].x !== "undefined") {
  9218. var page = getPagesByPath.call(this, xPath[i]);
  9219. for (var ii = 0; ii < page.length; ii += 1) {
  9220. if (pages.indexOf(page[ii]) === -1) {
  9221. pages.push(page[ii]);
  9222. }
  9223. }
  9224. }
  9225. }
  9226. for (var i = 0; i < pages.length; i++) {
  9227. while (this.pdf.internal.getNumberOfPages() < pages[i]) {
  9228. addPage.call(this);
  9229. }
  9230. }
  9231. pages.sort();
  9232. if (this.autoPaging) {
  9233. var min = pages[0];
  9234. var max = pages[pages.length - 1];
  9235. for (var i = min; i < max + 1; i++) {
  9236. this.pdf.setPage(i);
  9237. this.fillStyle = fillStyle;
  9238. this.strokeStyle = strokeStyle;
  9239. this.lineCap = lineCap;
  9240. this.lineWidth = lineWidth;
  9241. this.lineJoin = lineJoin;
  9242. if (this.ctx.clip_path.length !== 0) {
  9243. var tmpPaths = this.path;
  9244. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  9245. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  9246. drawPaths.call(this, rule, true);
  9247. this.path = tmpPaths;
  9248. }
  9249. tmpPath = JSON.parse(JSON.stringify(origPath));
  9250. this.path = pathPositionRedo(tmpPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  9251. if (isClip === false || i === 0) {
  9252. drawPaths.call(this, rule, isClip);
  9253. }
  9254. }
  9255. } else {
  9256. drawPaths.call(this, rule, isClip);
  9257. }
  9258. this.path = origPath;
  9259. };
  9260. /**
  9261. * Processes the paths
  9262. *
  9263. * @function
  9264. * @param rule {String}
  9265. * @param isClip {Boolean}
  9266. * @private
  9267. * @ignore
  9268. */
  9269. var drawPaths = function drawPaths(rule, isClip) {
  9270. if (rule === 'stroke' && !isClip && isStrokeTransparent.call(this)) {
  9271. return;
  9272. }
  9273. if (rule !== 'stroke' && !isClip && isFillTransparent.call(this)) {
  9274. return;
  9275. }
  9276. var moves = [];
  9277. var alpha = this.ctx.globalAlpha;
  9278. if (this.ctx.fillOpacity < 1) {
  9279. alpha = this.ctx.fillOpacity;
  9280. }
  9281. var xPath = this.path;
  9282. for (var i = 0; i < xPath.length; i++) {
  9283. var pt = xPath[i];
  9284. switch (pt.type) {
  9285. case 'begin':
  9286. moves.push({
  9287. begin: true
  9288. });
  9289. break;
  9290. case 'close':
  9291. moves.push({
  9292. close: true
  9293. });
  9294. break;
  9295. case 'mt':
  9296. moves.push({
  9297. start: pt,
  9298. deltas: [],
  9299. abs: []
  9300. });
  9301. break;
  9302. case 'lt':
  9303. var iii = moves.length;
  9304. if (!isNaN(xPath[i - 1].x)) {
  9305. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  9306. if (iii > 0) {
  9307. for (iii; iii >= 0; iii--) {
  9308. if (moves[iii - 1].close !== true && moves[iii - 1].begin !== true) {
  9309. moves[iii - 1].deltas.push(delta);
  9310. moves[iii - 1].abs.push(pt);
  9311. break;
  9312. }
  9313. }
  9314. }
  9315. }
  9316. break;
  9317. case 'bct':
  9318. 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];
  9319. moves[moves.length - 1].deltas.push(delta);
  9320. break;
  9321. case 'qct':
  9322. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  9323. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  9324. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  9325. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  9326. var x3 = pt.x;
  9327. var y3 = pt.y;
  9328. 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];
  9329. moves[moves.length - 1].deltas.push(delta);
  9330. break;
  9331. case 'arc':
  9332. moves.push({
  9333. deltas: [],
  9334. abs: [],
  9335. arc: true
  9336. });
  9337. if (Array.isArray(moves[moves.length - 1].abs)) {
  9338. moves[moves.length - 1].abs.push(pt);
  9339. }
  9340. break;
  9341. }
  9342. }
  9343. var style;
  9344. if (!isClip) {
  9345. if (rule === 'stroke') {
  9346. style = 'stroke';
  9347. } else {
  9348. style = 'fill';
  9349. }
  9350. } else {
  9351. style = null;
  9352. }
  9353. for (var i = 0; i < moves.length; i++) {
  9354. if (moves[i].arc) {
  9355. var arcs = moves[i].abs;
  9356. for (var ii = 0; ii < arcs.length; ii++) {
  9357. var arc = arcs[ii];
  9358. if (typeof arc.startAngle !== 'undefined') {
  9359. var start = rad2deg(arc.startAngle);
  9360. var end = rad2deg(arc.endAngle);
  9361. var x = arc.x;
  9362. var y = arc.y;
  9363. drawArc.call(this, x, y, arc.radius, start, end, arc.counterclockwise, style, isClip);
  9364. } else {
  9365. drawLine.call(this, arc.x, arc.y);
  9366. }
  9367. }
  9368. }
  9369. if (!moves[i].arc) {
  9370. if (moves[i].close !== true && moves[i].begin !== true) {
  9371. var x = moves[i].start.x;
  9372. var y = moves[i].start.y;
  9373. drawLines.call(this, moves[i].deltas, x, y, null, null);
  9374. }
  9375. }
  9376. }
  9377. if (style) {
  9378. putStyle.call(this, style);
  9379. }
  9380. if (isClip) {
  9381. doClip.call(this);
  9382. }
  9383. };
  9384. var getBaseline = function getBaseline(y) {
  9385. var height = this.pdf.internal.getFontSize() / this.pdf.internal.scaleFactor;
  9386. var descent = height * (this.pdf.internal.getLineHeightFactor() - 1);
  9387. switch (this.ctx.textBaseline) {
  9388. case 'bottom':
  9389. return y - descent;
  9390. case 'top':
  9391. return y + height - descent;
  9392. case 'hanging':
  9393. return y + height - 2 * descent;
  9394. case 'middle':
  9395. return y + height / 2 - descent;
  9396. case 'ideographic':
  9397. // TODO not implemented
  9398. return y;
  9399. case 'alphabetic':
  9400. default:
  9401. return y;
  9402. }
  9403. };
  9404. Context2D.prototype.createLinearGradient = function createLinearGradient() {
  9405. var canvasGradient = function canvasGradient() {};
  9406. canvasGradient.colorStops = [];
  9407. canvasGradient.addColorStop = function (offset, color) {
  9408. this.colorStops.push([offset, color]);
  9409. };
  9410. canvasGradient.getColor = function () {
  9411. if (this.colorStops.length === 0) {
  9412. return '#000000';
  9413. }
  9414. return this.colorStops[0][1];
  9415. };
  9416. canvasGradient.isCanvasGradient = true;
  9417. return canvasGradient;
  9418. };
  9419. Context2D.prototype.createPattern = function createPattern() {
  9420. return this.createLinearGradient();
  9421. };
  9422. Context2D.prototype.createRadialGradient = function createRadialGradient() {
  9423. return this.createLinearGradient();
  9424. };
  9425. /**
  9426. *
  9427. * @param x Edge point X
  9428. * @param y Edge point Y
  9429. * @param r Radius
  9430. * @param a1 start angle
  9431. * @param a2 end angle
  9432. * @param counterclockwise
  9433. * @param style
  9434. * @param isClip
  9435. */
  9436. var drawArc = function drawArc(x, y, r, a1, a2, counterclockwise, style, isClip) {
  9437. var k = this.pdf.internal.scaleFactor;
  9438. var a1r = deg2rad(a1);
  9439. var a2r = deg2rad(a2);
  9440. var curves = createArc.call(this, r, a1r, a2r, counterclockwise);
  9441. for (var i = 0; i < curves.length; i++) {
  9442. var curve = curves[i];
  9443. if (i === 0) {
  9444. doMove.call(this, curve.x1 + x, curve.y1 + y);
  9445. }
  9446. drawCurve.call(this, x, y, curve.x2, curve.y2, curve.x3, curve.y3, curve.x4, curve.y4);
  9447. }
  9448. if (!isClip) {
  9449. putStyle.call(this, style);
  9450. } else {
  9451. doClip.call(this);
  9452. }
  9453. };
  9454. var putStyle = function putStyle(style) {
  9455. switch (style) {
  9456. case 'stroke':
  9457. this.pdf.internal.out('S');
  9458. break;
  9459. case 'fill':
  9460. this.pdf.internal.out('f');
  9461. break;
  9462. }
  9463. };
  9464. var doClip = function doClip() {
  9465. this.pdf.clip();
  9466. };
  9467. var doMove = function doMove(x, y) {
  9468. this.pdf.internal.out(getHorizontalCoordinateString(x) + ' ' + getVerticalCoordinateString(y) + ' m');
  9469. };
  9470. var putText = function putText(options) {
  9471. var textAlign;
  9472. switch (options.align) {
  9473. case 'right':
  9474. case 'end':
  9475. textAlign = 'right';
  9476. break;
  9477. case 'center':
  9478. textAlign = 'center';
  9479. break;
  9480. case 'left':
  9481. case 'start':
  9482. default:
  9483. textAlign = 'left';
  9484. break;
  9485. }
  9486. var pt = this.ctx.transform.applyToPoint(new Point(options.x, options.y));
  9487. var decomposedTransformationMatrix = this.ctx.transform.decompose();
  9488. var matrix = new Matrix();
  9489. matrix = matrix.multiply(decomposedTransformationMatrix.translate);
  9490. matrix = matrix.multiply(decomposedTransformationMatrix.skew);
  9491. matrix = matrix.multiply(decomposedTransformationMatrix.scale);
  9492. var textDimensions = this.pdf.getTextDimensions(options.text);
  9493. var textRect = this.ctx.transform.applyToRectangle(new Rectangle(options.x, options.y, textDimensions.w, textDimensions.h));
  9494. var textXRect = matrix.applyToRectangle(new Rectangle(options.x, options.y - textDimensions.h, textDimensions.w, textDimensions.h));
  9495. var pageArray = getPagesByPath.call(this, textXRect);
  9496. var pages = [];
  9497. for (var ii = 0; ii < pageArray.length; ii += 1) {
  9498. if (pages.indexOf(pageArray[ii]) === -1) {
  9499. pages.push(pageArray[ii]);
  9500. }
  9501. }
  9502. pages.sort();
  9503. var clipPath;
  9504. if (this.autoPaging === true) {
  9505. var min = pages[0];
  9506. var max = pages[pages.length - 1];
  9507. for (var i = min; i < max + 1; i++) {
  9508. this.pdf.setPage(i);
  9509. if (this.ctx.clip_path.length !== 0) {
  9510. var tmpPaths = this.path;
  9511. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  9512. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  9513. drawPaths.call(this, 'fill', true);
  9514. this.path = tmpPaths;
  9515. }
  9516. var tmpRect = JSON.parse(JSON.stringify(textRect));
  9517. tmpRect = pathPositionRedo([tmpRect], this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY)[0];
  9518. if (options.scale >= 0.01) {
  9519. var oldSize = this.pdf.internal.getFontSize();
  9520. this.pdf.setFontSize(oldSize * options.scale);
  9521. }
  9522. this.pdf.text(options.text, tmpRect.x, tmpRect.y, {
  9523. angle: options.angle,
  9524. align: textAlign,
  9525. renderingMode: options.renderingMode,
  9526. maxWidth: options.maxWidth
  9527. });
  9528. if (options.scale >= 0.01) {
  9529. this.pdf.setFontSize(oldSize);
  9530. }
  9531. }
  9532. } else {
  9533. if (options.scale >= 0.01) {
  9534. var oldSize = this.pdf.internal.getFontSize();
  9535. this.pdf.setFontSize(oldSize * options.scale);
  9536. }
  9537. this.pdf.text(options.text, pt.x + this.posX, pt.y + this.posY, {
  9538. angle: options.angle,
  9539. align: textAlign,
  9540. renderingMode: options.renderingMode,
  9541. maxWidth: options.maxWidth
  9542. });
  9543. if (options.scale >= 0.01) {
  9544. this.pdf.setFontSize(oldSize);
  9545. }
  9546. }
  9547. };
  9548. var drawLine = function drawLine(x, y, prevX, prevY) {
  9549. prevX = prevX || 0;
  9550. prevY = prevY || 0;
  9551. this.pdf.internal.out(getHorizontalCoordinateString(x + prevX) + ' ' + getVerticalCoordinateString(y + prevY) + ' l');
  9552. };
  9553. var drawLines = function drawLines(lines, x, y) {
  9554. return this.pdf.lines(lines, x, y, null, null);
  9555. };
  9556. var drawCurve = function drawCurve(x, y, x1, y1, x2, y2, x3, y3) {
  9557. this.pdf.internal.out([f2(getHorizontalCoordinate(x1 + x)), f2(getVerticalCoordinate(y1 + y)), f2(getHorizontalCoordinate(x2 + x)), f2(getVerticalCoordinate(y2 + y)), f2(getHorizontalCoordinate(x3 + x)), f2(getVerticalCoordinate(y3 + y)), 'c'].join(' '));
  9558. };
  9559. /**
  9560. * 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.
  9561. *
  9562. * 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.
  9563. * @function createArc
  9564. */
  9565. var createArc = function createArc(radius, startAngle, endAngle, anticlockwise) {
  9566. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below // normalize startAngle, endAngle to [-2PI, 2PI]
  9567. var twoPI = Math.PI * 2;
  9568. var startAngleN = startAngle;
  9569. if (startAngleN < twoPI || startAngleN > twoPI) {
  9570. startAngleN = startAngleN % twoPI;
  9571. }
  9572. var endAngleN = endAngle;
  9573. if (endAngleN < twoPI || endAngleN > twoPI) {
  9574. endAngleN = endAngleN % twoPI;
  9575. } // Compute the sequence of arc curves, up to PI/2 at a time. // Total arc angle is less than 2PI.
  9576. var curves = [];
  9577. var piOverTwo = Math.PI / 2.0; //var sgn = (startAngle < endAngle) ? +1 : -1; // clockwise or counterclockwise
  9578. var sgn = anticlockwise ? -1 : +1;
  9579. var a1 = startAngle;
  9580. for (var totalAngle = Math.min(twoPI, Math.abs(endAngleN - startAngleN)); totalAngle > EPSILON;) {
  9581. var a2 = a1 + sgn * Math.min(totalAngle, piOverTwo);
  9582. curves.push(createSmallArc.call(this, radius, a1, a2));
  9583. totalAngle -= Math.abs(a2 - a1);
  9584. a1 = a2;
  9585. }
  9586. return curves;
  9587. };
  9588. /**
  9589. * 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.
  9590. *
  9591. * 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.
  9592. *
  9593. * 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.
  9594. */
  9595. var createSmallArc = function createSmallArc(r, a1, a2) {
  9596. var a = (a2 - a1) / 2.0;
  9597. var x4 = r * Math.cos(a);
  9598. var y4 = r * Math.sin(a);
  9599. var x1 = x4;
  9600. var y1 = -y4;
  9601. var q1 = x1 * x1 + y1 * y1;
  9602. var q2 = q1 + x1 * x4 + y1 * y4;
  9603. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  9604. var x2 = x1 - k2 * y1;
  9605. var y2 = y1 + k2 * x1;
  9606. var x3 = x2;
  9607. var y3 = -y2;
  9608. var ar = a + a1;
  9609. var cos_ar = Math.cos(ar);
  9610. var sin_ar = Math.sin(ar);
  9611. return {
  9612. x1: r * Math.cos(a1),
  9613. y1: r * Math.sin(a1),
  9614. x2: x2 * cos_ar - y2 * sin_ar,
  9615. y2: x2 * sin_ar + y2 * cos_ar,
  9616. x3: x3 * cos_ar - y3 * sin_ar,
  9617. y3: x3 * sin_ar + y3 * cos_ar,
  9618. x4: r * Math.cos(a2),
  9619. y4: r * Math.sin(a2)
  9620. };
  9621. };
  9622. var rad2deg = function rad2deg(value) {
  9623. return value * 180 / Math.PI;
  9624. };
  9625. var deg2rad = function deg2rad(deg) {
  9626. return deg * Math.PI / 180;
  9627. };
  9628. var getQuadraticCurveBoundary = function getQuadraticCurveBoundary(sx, sy, cpx, cpy, ex, ey) {
  9629. var midX1 = sx + (cpx - sx) * 0.50;
  9630. var midY1 = sy + (cpy - sy) * 0.50;
  9631. var midX2 = ex + (cpx - ex) * 0.50;
  9632. var midY2 = ey + (cpy - ey) * 0.50;
  9633. var resultX1 = Math.min(sx, ex, midX1, midX2);
  9634. var resultX2 = Math.max(sx, ex, midX1, midX2);
  9635. var resultY1 = Math.min(sy, ey, midY1, midY2);
  9636. var resultY2 = Math.max(sy, ey, midY1, midY2);
  9637. return new Rectangle(resultX1, resultY1, resultX2 - resultX1, resultY2 - resultY1);
  9638. }; //De Casteljau algorithm
  9639. var getBezierCurveBoundary = function getBezierCurveBoundary(ax, ay, bx, by, cx, cy, dx, dy) {
  9640. var tobx = bx - ax;
  9641. var toby = by - ay;
  9642. var tocx = cx - bx;
  9643. var tocy = cy - by;
  9644. var todx = dx - cx;
  9645. var tody = dy - cy;
  9646. var precision = 40;
  9647. var d, px, py, qx, qy, rx, ry, tx, ty, sx, sy, x, y, i, minx, miny, maxx, maxy, toqx, toqy, torx, tory, totx, toty;
  9648. for (var i = 0; i < precision + 1; i++) {
  9649. d = i / precision;
  9650. px = ax + d * tobx;
  9651. py = ay + d * toby;
  9652. qx = bx + d * tocx;
  9653. qy = by + d * tocy;
  9654. rx = cx + d * todx;
  9655. ry = cy + d * tody;
  9656. toqx = qx - px;
  9657. toqy = qy - py;
  9658. torx = rx - qx;
  9659. tory = ry - qy;
  9660. sx = px + d * toqx;
  9661. sy = py + d * toqy;
  9662. tx = qx + d * torx;
  9663. ty = qy + d * tory;
  9664. totx = tx - sx;
  9665. toty = ty - sy;
  9666. x = sx + d * totx;
  9667. y = sy + d * toty;
  9668. if (i == 0) {
  9669. minx = x;
  9670. miny = y;
  9671. maxx = x;
  9672. maxy = y;
  9673. } else {
  9674. minx = Math.min(minx, x);
  9675. miny = Math.min(miny, y);
  9676. maxx = Math.max(maxx, x);
  9677. maxy = Math.max(maxy, y);
  9678. }
  9679. }
  9680. return new Rectangle(Math.round(minx), Math.round(miny), Math.round(maxx - minx), Math.round(maxy - miny));
  9681. };
  9682. var Point = function Point(x, y) {
  9683. var _x = x || 0;
  9684. Object.defineProperty(this, 'x', {
  9685. enumerable: true,
  9686. get: function get() {
  9687. return _x;
  9688. },
  9689. set: function set(value) {
  9690. if (!isNaN(value)) {
  9691. _x = parseFloat(value);
  9692. }
  9693. }
  9694. });
  9695. var _y = y || 0;
  9696. Object.defineProperty(this, 'y', {
  9697. enumerable: true,
  9698. get: function get() {
  9699. return _y;
  9700. },
  9701. set: function set(value) {
  9702. if (!isNaN(value)) {
  9703. _y = parseFloat(value);
  9704. }
  9705. }
  9706. });
  9707. var _type = 'pt';
  9708. Object.defineProperty(this, 'type', {
  9709. enumerable: true,
  9710. get: function get() {
  9711. return _type;
  9712. },
  9713. set: function set(value) {
  9714. _type = value.toString();
  9715. }
  9716. });
  9717. return this;
  9718. };
  9719. var Rectangle = function Rectangle(x, y, w, h) {
  9720. Point.call(this, x, y);
  9721. this.type = 'rect';
  9722. var _w = w || 0;
  9723. Object.defineProperty(this, 'w', {
  9724. enumerable: true,
  9725. get: function get() {
  9726. return _w;
  9727. },
  9728. set: function set(value) {
  9729. if (!isNaN(value)) {
  9730. _w = parseFloat(value);
  9731. }
  9732. }
  9733. });
  9734. var _h = h || 0;
  9735. Object.defineProperty(this, 'h', {
  9736. enumerable: true,
  9737. get: function get() {
  9738. return _h;
  9739. },
  9740. set: function set(value) {
  9741. if (!isNaN(value)) {
  9742. _h = parseFloat(value);
  9743. }
  9744. }
  9745. });
  9746. return this;
  9747. };
  9748. var Matrix = function Matrix(sx, shy, shx, sy, tx, ty) {
  9749. var _matrix = [];
  9750. Object.defineProperty(this, 'sx', {
  9751. get: function get() {
  9752. return _matrix[0];
  9753. },
  9754. set: function set(value) {
  9755. _matrix[0] = Math.round(value * 100000) / 100000;
  9756. }
  9757. });
  9758. Object.defineProperty(this, 'shy', {
  9759. get: function get() {
  9760. return _matrix[1];
  9761. },
  9762. set: function set(value) {
  9763. _matrix[1] = Math.round(value * 100000) / 100000;
  9764. }
  9765. });
  9766. Object.defineProperty(this, 'shx', {
  9767. get: function get() {
  9768. return _matrix[2];
  9769. },
  9770. set: function set(value) {
  9771. _matrix[2] = Math.round(value * 100000) / 100000;
  9772. }
  9773. });
  9774. Object.defineProperty(this, 'sy', {
  9775. get: function get() {
  9776. return _matrix[3];
  9777. },
  9778. set: function set(value) {
  9779. _matrix[3] = Math.round(value * 100000) / 100000;
  9780. }
  9781. });
  9782. Object.defineProperty(this, 'tx', {
  9783. get: function get() {
  9784. return _matrix[4];
  9785. },
  9786. set: function set(value) {
  9787. _matrix[4] = Math.round(value * 100000) / 100000;
  9788. }
  9789. });
  9790. Object.defineProperty(this, 'ty', {
  9791. get: function get() {
  9792. return _matrix[5];
  9793. },
  9794. set: function set(value) {
  9795. _matrix[5] = Math.round(value * 100000) / 100000;
  9796. }
  9797. });
  9798. Object.defineProperty(this, 'rotation', {
  9799. get: function get() {
  9800. return Math.atan2(this.shx, this.sx);
  9801. }
  9802. });
  9803. Object.defineProperty(this, 'scaleX', {
  9804. get: function get() {
  9805. return this.decompose().scale.sx;
  9806. }
  9807. });
  9808. Object.defineProperty(this, 'scaleY', {
  9809. get: function get() {
  9810. return this.decompose().scale.sy;
  9811. }
  9812. });
  9813. Object.defineProperty(this, 'isIdentity', {
  9814. get: function get() {
  9815. if (this.sx !== 1) {
  9816. return false;
  9817. }
  9818. if (this.shy !== 0) {
  9819. return false;
  9820. }
  9821. if (this.shx !== 0) {
  9822. return false;
  9823. }
  9824. if (this.sy !== 1) {
  9825. return false;
  9826. }
  9827. if (this.tx !== 0) {
  9828. return false;
  9829. }
  9830. if (this.ty !== 0) {
  9831. return false;
  9832. }
  9833. return true;
  9834. }
  9835. });
  9836. this.sx = !isNaN(sx) ? sx : 1;
  9837. this.shy = !isNaN(shy) ? shy : 0;
  9838. this.shx = !isNaN(shx) ? shx : 0;
  9839. this.sy = !isNaN(sy) ? sy : 1;
  9840. this.tx = !isNaN(tx) ? tx : 0;
  9841. this.ty = !isNaN(ty) ? ty : 0;
  9842. return this;
  9843. };
  9844. /**
  9845. * Multiply the matrix with given Matrix
  9846. *
  9847. * @function multiply
  9848. * @param matrix
  9849. * @returns {Matrix}
  9850. * @private
  9851. * @ignore
  9852. */
  9853. Matrix.prototype.multiply = function (matrix) {
  9854. var sx = matrix.sx * this.sx + matrix.shy * this.shx;
  9855. var shy = matrix.sx * this.shy + matrix.shy * this.sy;
  9856. var shx = matrix.shx * this.sx + matrix.sy * this.shx;
  9857. var sy = matrix.shx * this.shy + matrix.sy * this.sy;
  9858. var tx = matrix.tx * this.sx + matrix.ty * this.shx + this.tx;
  9859. var ty = matrix.tx * this.shy + matrix.ty * this.sy + this.ty;
  9860. return new Matrix(sx, shy, shx, sy, tx, ty);
  9861. };
  9862. /**
  9863. * @function decompose
  9864. * @private
  9865. * @ignore
  9866. */
  9867. Matrix.prototype.decompose = function () {
  9868. var a = this.sx;
  9869. var b = this.shy;
  9870. var c = this.shx;
  9871. var d = this.sy;
  9872. var e = this.tx;
  9873. var f = this.ty;
  9874. var scaleX = Math.sqrt(a * a + b * b);
  9875. a /= scaleX;
  9876. b /= scaleX;
  9877. var shear = a * c + b * d;
  9878. c -= a * shear;
  9879. d -= b * shear;
  9880. var scaleY = Math.sqrt(c * c + d * d);
  9881. c /= scaleY;
  9882. d /= scaleY;
  9883. shear /= scaleY;
  9884. if (a * d < b * c) {
  9885. a = -a;
  9886. b = -b;
  9887. shear = -shear;
  9888. scaleX = -scaleX;
  9889. }
  9890. return {
  9891. scale: new Matrix(scaleX, 0, 0, scaleY, 0, 0),
  9892. translate: new Matrix(1, 0, 0, 1, e, f),
  9893. rotate: new Matrix(a, b, -b, a, 0, 0),
  9894. skew: new Matrix(1, 0, shear, 1, 0, 0)
  9895. };
  9896. };
  9897. /**
  9898. * @function applyToPoint
  9899. * @private
  9900. * @ignore
  9901. */
  9902. Matrix.prototype.applyToPoint = function (pt) {
  9903. var x = pt.x * this.sx + pt.y * this.shx + this.tx;
  9904. var y = pt.x * this.shy + pt.y * this.sy + this.ty;
  9905. return new Point(x, y);
  9906. };
  9907. /**
  9908. * @function applyToRectangle
  9909. * @private
  9910. * @ignore
  9911. */
  9912. Matrix.prototype.applyToRectangle = function (rect) {
  9913. var pt1 = this.applyToPoint(rect);
  9914. var pt2 = this.applyToPoint(new Point(rect.x + rect.w, rect.y + rect.h));
  9915. return new Rectangle(pt1.x, pt1.y, pt2.x - pt1.x, pt2.y - pt1.y);
  9916. };
  9917. /**
  9918. * @function clone
  9919. * @private
  9920. * @ignore
  9921. */
  9922. Matrix.prototype.clone = function () {
  9923. var sx = this.sx;
  9924. var shy = this.shy;
  9925. var shx = this.shx;
  9926. var sy = this.sy;
  9927. var tx = this.tx;
  9928. var ty = this.ty;
  9929. return new Matrix(sx, shy, shx, sy, tx, ty);
  9930. };
  9931. })(jsPDF.API, typeof self !== 'undefined' && self || typeof window !== 'undefined' && window || typeof global !== 'undefined' && global || Function('return typeof this === "object" && this.content')() || Function('return this')());
  9932. /**
  9933. * jsPDF filters PlugIn
  9934. * Copyright (c) 2014 Aras Abbasi
  9935. *
  9936. * Licensed under the MIT License.
  9937. * http://opensource.org/licenses/mit-license
  9938. */
  9939. (function (jsPDFAPI) {
  9940. var ASCII85Encode = function ASCII85Encode(a) {
  9941. var b, c, d, e, f, g, h, i, j, k;
  9942. for (!/[^\x00-\xFF]/.test(a), b = "\x00\x00\x00\x00".slice(a.length % 4 || 4), a += b, c = [], d = 0, e = a.length; e > d; d += 4) {
  9943. f = (a.charCodeAt(d) << 24) + (a.charCodeAt(d + 1) << 16) + (a.charCodeAt(d + 2) << 8) + a.charCodeAt(d + 3), 0 !== f ? (k = f % 85, f = (f - k) / 85, j = f % 85, f = (f - j) / 85, i = f % 85, f = (f - i) / 85, h = f % 85, f = (f - h) / 85, g = f % 85, c.push(g + 33, h + 33, i + 33, j + 33, k + 33)) : c.push(122);
  9944. }
  9945. return function (a, b) {
  9946. for (var c = b; c > 0; c--) {
  9947. a.pop();
  9948. }
  9949. }(c, b.length), String.fromCharCode.apply(String, c) + "~>";
  9950. };
  9951. var ASCII85Decode = function ASCII85Decode(a) {
  9952. var c,
  9953. d,
  9954. e,
  9955. f,
  9956. g,
  9957. h = String,
  9958. l = "length",
  9959. w = 255,
  9960. x = "charCodeAt",
  9961. y = "slice",
  9962. z = "replace";
  9963. for ("~>" === a[y](-2), a = a[y](0, -2)[z](/\s/g, "")[z]("z", "!!!!!"), c = "uuuuu"[y](a[l] % 5 || 5), a += c, e = [], f = 0, g = a[l]; g > f; f += 5) {
  9964. d = 52200625 * (a[x](f) - 33) + 614125 * (a[x](f + 1) - 33) + 7225 * (a[x](f + 2) - 33) + 85 * (a[x](f + 3) - 33) + (a[x](f + 4) - 33), e.push(w & d >> 24, w & d >> 16, w & d >> 8, w & d);
  9965. }
  9966. return function (a, b) {
  9967. for (var c = b; c > 0; c--) {
  9968. a.pop();
  9969. }
  9970. }(e, c[l]), h.fromCharCode.apply(h, e);
  9971. };
  9972. /**
  9973. * TODO: Not Tested:
  9974. //https://gist.github.com/revolunet/843889
  9975. // LZW-compress a string
  9976. var LZWEncode = function(s, options) {
  9977. options = Object.assign({
  9978. predictor: 1,
  9979. colors: 1,
  9980. bitsPerComponent: 8,
  9981. columns: 1,
  9982. earlyChange: 1
  9983. }, options);
  9984. var dict = {};
  9985. var data = (s + "").split("");
  9986. var out = [];
  9987. var currChar;
  9988. var phrase = data[0];
  9989. var code = 256; //0xe000
  9990. for (var i=1; i<data.length; i++) {
  9991. currChar=data[i];
  9992. if (dict['_' + phrase + currChar] != null) {
  9993. phrase += currChar;
  9994. }
  9995. else {
  9996. out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
  9997. dict['_' + phrase + currChar] = code;
  9998. code++;
  9999. phrase=currChar;
  10000. }
  10001. }
  10002. out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
  10003. for (var i=0; i<out.length; i++) {
  10004. out[i] = String.fromCharCode(out[i]);
  10005. }
  10006. return out.join("");
  10007. }
  10008. // Decompress an LZW-encoded string
  10009. var LZWDecode = function(s, options) {
  10010. options = Object.assign({
  10011. predictor: 1,
  10012. colors: 1,
  10013. bitsPerComponent: 8,
  10014. columns: 1,
  10015. earlyChange: 1
  10016. }, options);
  10017. var dict = {};
  10018. var data = (s + "").split("");
  10019. var currChar = data[0];
  10020. var oldPhrase = currChar;
  10021. var out = [currChar];
  10022. var code = 256;
  10023. var phrase;
  10024. for (var i=1; i<data.length; i++) {
  10025. var currCode = data[i].charCodeAt(0);
  10026. if (currCode < 256) {
  10027. phrase = data[i];
  10028. }
  10029. else {
  10030. phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar);
  10031. }
  10032. out.push(phrase);
  10033. currChar = phrase.charAt(0);
  10034. dict['_'+code] = oldPhrase + currChar;
  10035. code++;
  10036. oldPhrase = phrase;
  10037. }
  10038. return out.join("");
  10039. }
  10040. */
  10041. var ASCIIHexEncode = function ASCIIHexEncode(value) {
  10042. var result = '';
  10043. var i;
  10044. for (var i = 0; i < value.length; i += 1) {
  10045. result += ("0" + value.charCodeAt(i).toString(16)).slice(-2);
  10046. }
  10047. result += '>';
  10048. return result;
  10049. };
  10050. var ASCIIHexDecode = function ASCIIHexDecode(value) {
  10051. var regexCheckIfHex = new RegExp(/^([0-9A-Fa-f]{2})+$/);
  10052. value = value.replace(/\s/g, '');
  10053. if (value.indexOf(">") !== -1) {
  10054. value = value.substr(0, value.indexOf(">"));
  10055. }
  10056. if (value.length % 2) {
  10057. value += "0";
  10058. }
  10059. if (regexCheckIfHex.test(value) === false) {
  10060. return "";
  10061. }
  10062. var result = '';
  10063. var i;
  10064. for (var i = 0; i < value.length; i += 2) {
  10065. result += String.fromCharCode("0x" + (value[i] + value[i + 1]));
  10066. }
  10067. return result;
  10068. };
  10069. var FlateEncode = function FlateEncode(data, options) {
  10070. options = Object.assign({
  10071. predictor: 1,
  10072. colors: 1,
  10073. bitsPerComponent: 8,
  10074. columns: 1
  10075. }, options);
  10076. var arr = [];
  10077. var i = data.length;
  10078. var adler32;
  10079. var deflater;
  10080. while (i--) {
  10081. arr[i] = data.charCodeAt(i);
  10082. }
  10083. adler32 = jsPDFAPI.adler32cs.from(data);
  10084. deflater = new Deflater(6);
  10085. deflater.append(new Uint8Array(arr));
  10086. data = deflater.flush();
  10087. arr = new Uint8Array(data.length + 6);
  10088. arr.set(new Uint8Array([120, 156])), arr.set(data, 2);
  10089. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), data.length + 2);
  10090. data = String.fromCharCode.apply(null, arr);
  10091. return data;
  10092. };
  10093. jsPDFAPI.processDataByFilters = function (origData, filterChain) {
  10094. var i = 0;
  10095. var data = origData || '';
  10096. var reverseChain = [];
  10097. filterChain = filterChain || [];
  10098. if (typeof filterChain === "string") {
  10099. filterChain = [filterChain];
  10100. }
  10101. for (i = 0; i < filterChain.length; i += 1) {
  10102. switch (filterChain[i]) {
  10103. case "ASCII85Decode":
  10104. case "/ASCII85Decode":
  10105. data = ASCII85Decode(data);
  10106. reverseChain.push("/ASCII85Encode");
  10107. break;
  10108. case "ASCII85Encode":
  10109. case "/ASCII85Encode":
  10110. data = ASCII85Encode(data);
  10111. reverseChain.push("/ASCII85Decode");
  10112. break;
  10113. case "ASCIIHexDecode":
  10114. case "/ASCIIHexDecode":
  10115. data = ASCIIHexDecode(data);
  10116. reverseChain.push("/ASCIIHexEncode");
  10117. break;
  10118. case "ASCIIHexEncode":
  10119. case "/ASCIIHexEncode":
  10120. data = ASCIIHexEncode(data);
  10121. reverseChain.push("/ASCIIHexDecode");
  10122. break;
  10123. case "FlateEncode":
  10124. case "/FlateEncode":
  10125. data = FlateEncode(data);
  10126. reverseChain.push("/FlateDecode");
  10127. break;
  10128. /**
  10129. case "LZWDecode":
  10130. case "/LZWDecode":
  10131. data = LZWDecode(data);
  10132. reverseChain.push("/LZWEncode");
  10133. break;
  10134. case "LZWEncode":
  10135. case "/LZWEncode":
  10136. data = LZWEncode(data);
  10137. reverseChain.push("/LZWDecode");
  10138. break;
  10139. */
  10140. default:
  10141. throw "The filter: \"" + filterChain[i] + "\" is not implemented";
  10142. }
  10143. }
  10144. return {
  10145. data: data,
  10146. reverseChain: reverseChain.reverse().join(" ")
  10147. };
  10148. };
  10149. })(jsPDF.API);
  10150. /**
  10151. * jsPDF fileloading PlugIn
  10152. * Copyright (c) 2018 Aras Abbasi (aras.abbasi@gmail.com)
  10153. *
  10154. * Licensed under the MIT License.
  10155. * http://opensource.org/licenses/mit-license
  10156. */
  10157. /**
  10158. * @name fileloading
  10159. * @module
  10160. */
  10161. (function (jsPDFAPI) {
  10162. /**
  10163. * @name loadFile
  10164. * @function
  10165. * @param {string} url
  10166. * @param {boolean} sync
  10167. * @param {function} callback
  10168. * @returns {string|undefined} result
  10169. */
  10170. jsPDFAPI.loadFile = function (url, sync, callback) {
  10171. sync = sync || true;
  10172. callback = callback || function () {};
  10173. var result;
  10174. var xhr = function xhr(url, sync, callback) {
  10175. var req = new XMLHttpRequest();
  10176. var byteArray = [];
  10177. var i = 0;
  10178. var sanitizeUnicode = function sanitizeUnicode(data) {
  10179. var dataLength = data.length;
  10180. var StringFromCharCode = String.fromCharCode; //Transform Unicode to ASCII
  10181. for (i = 0; i < dataLength; i += 1) {
  10182. byteArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff));
  10183. }
  10184. return byteArray.join("");
  10185. };
  10186. req.open('GET', url, !sync); // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  10187. req.overrideMimeType('text\/plain; charset=x-user-defined');
  10188. if (sync === false) {
  10189. req.onload = function () {
  10190. return sanitizeUnicode(this.responseText);
  10191. };
  10192. }
  10193. req.send(null);
  10194. if (req.status !== 200) {
  10195. console.warn('Unable to load file "' + url + '"');
  10196. return;
  10197. }
  10198. if (sync) {
  10199. return sanitizeUnicode(req.responseText);
  10200. }
  10201. };
  10202. try {
  10203. result = xhr(url, sync, callback);
  10204. } catch (e) {
  10205. result = undefined;
  10206. }
  10207. return result;
  10208. };
  10209. /**
  10210. * @name loadImageFile
  10211. * @function
  10212. * @param {string} path
  10213. * @param {boolean} sync
  10214. * @param {function} callback
  10215. */
  10216. jsPDFAPI.loadImageFile = jsPDFAPI.loadFile;
  10217. })(jsPDF.API);
  10218. /**
  10219. * Copyright (c) 2018 Erik Koopmans
  10220. * Released under the MIT License.
  10221. *
  10222. * Licensed under the MIT License.
  10223. * http://opensource.org/licenses/mit-license
  10224. */
  10225. /**
  10226. * jsPDF html PlugIn
  10227. *
  10228. * @name html
  10229. * @module
  10230. */
  10231. (function (jsPDFAPI, global) {
  10232. /**
  10233. * Determine the type of a variable/object.
  10234. *
  10235. * @private
  10236. * @ignore
  10237. */
  10238. var objType = function objType(obj) {
  10239. var type = _typeof(obj);
  10240. if (type === 'undefined') return 'undefined';else if (type === 'string' || obj instanceof String) return 'string';else if (type === 'number' || obj instanceof Number) return 'number';else if (type === 'function' || obj instanceof Function) return 'function';else if (!!obj && obj.constructor === Array) return 'array';else if (obj && obj.nodeType === 1) return 'element';else if (type === 'object') return 'object';else return 'unknown';
  10241. };
  10242. /**
  10243. * Create an HTML element with optional className, innerHTML, and style.
  10244. *
  10245. * @private
  10246. * @ignore
  10247. */
  10248. var createElement = function createElement(tagName, opt) {
  10249. var el = document.createElement(tagName);
  10250. if (opt.className) el.className = opt.className;
  10251. if (opt.innerHTML) {
  10252. el.innerHTML = opt.innerHTML;
  10253. var scripts = el.getElementsByTagName('script');
  10254. for (var i = scripts.length; i-- > 0; null) {
  10255. scripts[i].parentNode.removeChild(scripts[i]);
  10256. }
  10257. }
  10258. for (var key in opt.style) {
  10259. el.style[key] = opt.style[key];
  10260. }
  10261. return el;
  10262. };
  10263. /**
  10264. * Deep-clone a node and preserve contents/properties.
  10265. *
  10266. * @private
  10267. * @ignore
  10268. */
  10269. var cloneNode = function cloneNode(node, javascriptEnabled) {
  10270. // Recursively clone the node.
  10271. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  10272. for (var child = node.firstChild; child; child = child.nextSibling) {
  10273. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  10274. clone.appendChild(cloneNode(child, javascriptEnabled));
  10275. }
  10276. }
  10277. if (node.nodeType === 1) {
  10278. // Preserve contents/properties of special nodes.
  10279. if (node.nodeName === 'CANVAS') {
  10280. clone.width = node.width;
  10281. clone.height = node.height;
  10282. clone.getContext('2d').drawImage(node, 0, 0);
  10283. } else if (node.nodeName === 'TEXTAREA' || node.nodeName === 'SELECT') {
  10284. clone.value = node.value;
  10285. } // Preserve the node's scroll position when it loads.
  10286. clone.addEventListener('load', function () {
  10287. clone.scrollTop = node.scrollTop;
  10288. clone.scrollLeft = node.scrollLeft;
  10289. }, true);
  10290. } // Return the cloned node.
  10291. return clone;
  10292. };
  10293. /* ----- CONSTRUCTOR ----- */
  10294. var Worker = function Worker(opt) {
  10295. // Create the root parent for the proto chain, and the starting Worker.
  10296. var root = Object.assign(Worker.convert(Promise.resolve()), JSON.parse(JSON.stringify(Worker.template)));
  10297. var self = Worker.convert(Promise.resolve(), root); // Set progress, optional settings, and return.
  10298. self = self.setProgress(1, Worker, 1, [Worker]);
  10299. self = self.set(opt);
  10300. return self;
  10301. }; // Boilerplate for subclassing Promise.
  10302. Worker.prototype = Object.create(Promise.prototype);
  10303. Worker.prototype.constructor = Worker; // Converts/casts promises into Workers.
  10304. Worker.convert = function convert(promise, inherit) {
  10305. // Uses prototypal inheritance to receive changes made to ancestors' properties.
  10306. promise.__proto__ = inherit || Worker.prototype;
  10307. return promise;
  10308. };
  10309. Worker.template = {
  10310. prop: {
  10311. src: null,
  10312. container: null,
  10313. overlay: null,
  10314. canvas: null,
  10315. img: null,
  10316. pdf: null,
  10317. pageSize: null,
  10318. callback: function callback() {}
  10319. },
  10320. progress: {
  10321. val: 0,
  10322. state: null,
  10323. n: 0,
  10324. stack: []
  10325. },
  10326. opt: {
  10327. filename: 'file.pdf',
  10328. margin: [0, 0, 0, 0],
  10329. enableLinks: true,
  10330. x: 0,
  10331. y: 0,
  10332. html2canvas: {},
  10333. jsPDF: {}
  10334. }
  10335. };
  10336. /* ----- FROM / TO ----- */
  10337. Worker.prototype.from = function from(src, type) {
  10338. function getType(src) {
  10339. switch (objType(src)) {
  10340. case 'string':
  10341. return 'string';
  10342. case 'element':
  10343. return src.nodeName.toLowerCase === 'canvas' ? 'canvas' : 'element';
  10344. default:
  10345. return 'unknown';
  10346. }
  10347. }
  10348. return this.then(function from_main() {
  10349. type = type || getType(src);
  10350. switch (type) {
  10351. case 'string':
  10352. return this.set({
  10353. src: createElement('div', {
  10354. innerHTML: src
  10355. })
  10356. });
  10357. case 'element':
  10358. return this.set({
  10359. src: src
  10360. });
  10361. case 'canvas':
  10362. return this.set({
  10363. canvas: src
  10364. });
  10365. case 'img':
  10366. return this.set({
  10367. img: src
  10368. });
  10369. default:
  10370. return this.error('Unknown source type.');
  10371. }
  10372. });
  10373. };
  10374. Worker.prototype.to = function to(target) {
  10375. // Route the 'to' request to the appropriate method.
  10376. switch (target) {
  10377. case 'container':
  10378. return this.toContainer();
  10379. case 'canvas':
  10380. return this.toCanvas();
  10381. case 'img':
  10382. return this.toImg();
  10383. case 'pdf':
  10384. return this.toPdf();
  10385. default:
  10386. return this.error('Invalid target.');
  10387. }
  10388. };
  10389. Worker.prototype.toContainer = function toContainer() {
  10390. // Set up function prerequisites.
  10391. var prereqs = [function checkSrc() {
  10392. return this.prop.src || this.error('Cannot duplicate - no source HTML.');
  10393. }, function checkPageSize() {
  10394. return this.prop.pageSize || this.setPageSize();
  10395. }];
  10396. return this.thenList(prereqs).then(function toContainer_main() {
  10397. // Define the CSS styles for the container and its overlay parent.
  10398. var overlayCSS = {
  10399. position: 'fixed',
  10400. overflow: 'hidden',
  10401. zIndex: 1000,
  10402. left: '-100000px',
  10403. right: 0,
  10404. bottom: 0,
  10405. top: 0
  10406. };
  10407. var containerCSS = {
  10408. position: 'relative',
  10409. display: 'inline-block',
  10410. width: Math.max(this.prop.src.clientWidth, this.prop.src.scrollWidth, this.prop.src.offsetWidth) + 'px',
  10411. left: 0,
  10412. right: 0,
  10413. top: 0,
  10414. margin: 'auto',
  10415. backgroundColor: 'white'
  10416. }; // Set the overlay to hidden (could be changed in the future to provide a print preview).
  10417. var source = cloneNode(this.prop.src, this.opt.html2canvas.javascriptEnabled);
  10418. if (source.tagName === 'BODY') {
  10419. containerCSS.height = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) + 'px';
  10420. }
  10421. this.prop.overlay = createElement('div', {
  10422. className: 'html2pdf__overlay',
  10423. style: overlayCSS
  10424. });
  10425. this.prop.container = createElement('div', {
  10426. className: 'html2pdf__container',
  10427. style: containerCSS
  10428. });
  10429. this.prop.container.appendChild(source);
  10430. this.prop.container.firstChild.appendChild(createElement('div', {
  10431. style: {
  10432. clear: 'both',
  10433. border: '0 none transparent',
  10434. margin: 0,
  10435. padding: 0,
  10436. height: 0
  10437. }
  10438. }));
  10439. this.prop.container.style.float = 'none';
  10440. this.prop.overlay.appendChild(this.prop.container);
  10441. document.body.appendChild(this.prop.overlay);
  10442. this.prop.container.firstChild.style.position = 'relative';
  10443. this.prop.container.height = Math.max(this.prop.container.firstChild.clientHeight, this.prop.container.firstChild.scrollHeight, this.prop.container.firstChild.offsetHeight) + 'px';
  10444. });
  10445. };
  10446. Worker.prototype.toCanvas = function toCanvas() {
  10447. // Set up function prerequisites.
  10448. var prereqs = [function checkContainer() {
  10449. return document.body.contains(this.prop.container) || this.toContainer();
  10450. }]; // Fulfill prereqs then create the canvas.
  10451. return this.thenList(prereqs).then(function toCanvas_main() {
  10452. // Handle old-fashioned 'onrendered' argument.
  10453. var options = Object.assign({}, this.opt.html2canvas);
  10454. delete options.onrendered;
  10455. if (!this.isHtml2CanvasLoaded()) {
  10456. return;
  10457. }
  10458. return html2canvas(this.prop.container, options);
  10459. }).then(function toCanvas_post(canvas) {
  10460. // Handle old-fashioned 'onrendered' argument.
  10461. var onRendered = this.opt.html2canvas.onrendered || function () {};
  10462. onRendered(canvas);
  10463. this.prop.canvas = canvas;
  10464. document.body.removeChild(this.prop.overlay);
  10465. });
  10466. };
  10467. Worker.prototype.toContext2d = function toContext2d() {
  10468. // Set up function prerequisites.
  10469. var prereqs = [function checkContainer() {
  10470. return document.body.contains(this.prop.container) || this.toContainer();
  10471. }]; // Fulfill prereqs then create the canvas.
  10472. return this.thenList(prereqs).then(function toContext2d_main() {
  10473. // Handle old-fashioned 'onrendered' argument.
  10474. var pdf = this.opt.jsPDF;
  10475. var options = Object.assign({
  10476. async: true,
  10477. allowTaint: true,
  10478. backgroundColor: '#ffffff',
  10479. imageTimeout: 15000,
  10480. logging: true,
  10481. proxy: null,
  10482. removeContainer: true,
  10483. foreignObjectRendering: false,
  10484. useCORS: false
  10485. }, this.opt.html2canvas);
  10486. delete options.onrendered;
  10487. pdf.context2d.autoPaging = true;
  10488. pdf.context2d.posX = this.opt.x;
  10489. pdf.context2d.posY = this.opt.y;
  10490. options.windowHeight = options.windowHeight || 0;
  10491. options.windowHeight = options.windowHeight == 0 ? Math.max(this.prop.container.clientHeight, this.prop.container.scrollHeight, this.prop.container.offsetHeight) : options.windowHeight;
  10492. if (!this.isHtml2CanvasLoaded()) {
  10493. return;
  10494. }
  10495. return html2canvas(this.prop.container, options);
  10496. }).then(function toContext2d_post(canvas) {
  10497. // Handle old-fashioned 'onrendered' argument.
  10498. var onRendered = this.opt.html2canvas.onrendered || function () {};
  10499. onRendered(canvas);
  10500. this.prop.canvas = canvas;
  10501. document.body.removeChild(this.prop.overlay);
  10502. });
  10503. };
  10504. Worker.prototype.toImg = function toImg() {
  10505. // Set up function prerequisites.
  10506. var prereqs = [function checkCanvas() {
  10507. return this.prop.canvas || this.toCanvas();
  10508. }]; // Fulfill prereqs then create the image.
  10509. return this.thenList(prereqs).then(function toImg_main() {
  10510. var imgData = this.prop.canvas.toDataURL('image/' + this.opt.image.type, this.opt.image.quality);
  10511. this.prop.img = document.createElement('img');
  10512. this.prop.img.src = imgData;
  10513. });
  10514. };
  10515. Worker.prototype.toPdf = function toPdf() {
  10516. // Set up function prerequisites.
  10517. var prereqs = [function checkContext2d() {
  10518. return this.toContext2d();
  10519. } //function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
  10520. ]; // Fulfill prereqs then create the image.
  10521. return this.thenList(prereqs).then(function toPdf_main() {
  10522. // Create local copies of frequently used properties.
  10523. this.prop.pdf = this.prop.pdf || this.opt.jsPDF;
  10524. });
  10525. };
  10526. /* ----- OUTPUT / SAVE ----- */
  10527. Worker.prototype.output = function output(type, options, src) {
  10528. // Redirect requests to the correct function (outputPdf / outputImg).
  10529. src = src || 'pdf';
  10530. if (src.toLowerCase() === 'img' || src.toLowerCase() === 'image') {
  10531. return this.outputImg(type, options);
  10532. } else {
  10533. return this.outputPdf(type, options);
  10534. }
  10535. };
  10536. Worker.prototype.outputPdf = function outputPdf(type, options) {
  10537. // Set up function prerequisites.
  10538. var prereqs = [function checkPdf() {
  10539. return this.prop.pdf || this.toPdf();
  10540. }]; // Fulfill prereqs then perform the appropriate output.
  10541. return this.thenList(prereqs).then(function outputPdf_main() {
  10542. /* Currently implemented output types:
  10543. * https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
  10544. * save(options), arraybuffer, blob, bloburi/bloburl,
  10545. * datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
  10546. */
  10547. return this.prop.pdf.output(type, options);
  10548. });
  10549. };
  10550. Worker.prototype.outputImg = function outputImg(type, options) {
  10551. // Set up function prerequisites.
  10552. var prereqs = [function checkImg() {
  10553. return this.prop.img || this.toImg();
  10554. }]; // Fulfill prereqs then perform the appropriate output.
  10555. return this.thenList(prereqs).then(function outputImg_main() {
  10556. switch (type) {
  10557. case undefined:
  10558. case 'img':
  10559. return this.prop.img;
  10560. case 'datauristring':
  10561. case 'dataurlstring':
  10562. return this.prop.img.src;
  10563. case 'datauri':
  10564. case 'dataurl':
  10565. return document.location.href = this.prop.img.src;
  10566. default:
  10567. throw 'Image output type "' + type + '" is not supported.';
  10568. }
  10569. });
  10570. };
  10571. Worker.prototype.isHtml2CanvasLoaded = function () {
  10572. var result = typeof global.html2canvas !== "undefined";
  10573. if (!result) {
  10574. console.error("html2canvas not loaded.");
  10575. }
  10576. return result;
  10577. };
  10578. Worker.prototype.save = function save(filename) {
  10579. // Set up function prerequisites.
  10580. var prereqs = [function checkPdf() {
  10581. return this.prop.pdf || this.toPdf();
  10582. }];
  10583. if (!this.isHtml2CanvasLoaded()) {
  10584. return;
  10585. } // Fulfill prereqs, update the filename (if provided), and save the PDF.
  10586. return this.thenList(prereqs).set(filename ? {
  10587. filename: filename
  10588. } : null).then(function save_main() {
  10589. this.prop.pdf.save(this.opt.filename);
  10590. });
  10591. };
  10592. Worker.prototype.doCallback = function doCallback(filename) {
  10593. // Set up function prerequisites.
  10594. var prereqs = [function checkPdf() {
  10595. return this.prop.pdf || this.toPdf();
  10596. }];
  10597. if (!this.isHtml2CanvasLoaded()) {
  10598. return;
  10599. } // Fulfill prereqs, update the filename (if provided), and save the PDF.
  10600. return this.thenList(prereqs).then(function doCallback_main() {
  10601. this.prop.callback(this.prop.pdf);
  10602. });
  10603. };
  10604. /* ----- SET / GET ----- */
  10605. Worker.prototype.set = function set(opt) {
  10606. // TODO: Implement ordered pairs?
  10607. // Silently ignore invalid or empty input.
  10608. if (objType(opt) !== 'object') {
  10609. return this;
  10610. } // Build an array of setter functions to queue.
  10611. var fns = Object.keys(opt || {}).map(function (key) {
  10612. if (key in Worker.template.prop) {
  10613. // Set pre-defined properties.
  10614. return function set_prop() {
  10615. this.prop[key] = opt[key];
  10616. };
  10617. } else {
  10618. switch (key) {
  10619. case 'margin':
  10620. return this.setMargin.bind(this, opt.margin);
  10621. case 'jsPDF':
  10622. return function set_jsPDF() {
  10623. this.opt.jsPDF = opt.jsPDF;
  10624. return this.setPageSize();
  10625. };
  10626. case 'pageSize':
  10627. return this.setPageSize.bind(this, opt.pageSize);
  10628. default:
  10629. // Set any other properties in opt.
  10630. return function set_opt() {
  10631. this.opt[key] = opt[key];
  10632. };
  10633. }
  10634. }
  10635. }, this); // Set properties within the promise chain.
  10636. return this.then(function set_main() {
  10637. return this.thenList(fns);
  10638. });
  10639. };
  10640. Worker.prototype.get = function get(key, cbk) {
  10641. return this.then(function get_main() {
  10642. // Fetch the requested property, either as a predefined prop or in opt.
  10643. var val = key in Worker.template.prop ? this.prop[key] : this.opt[key];
  10644. return cbk ? cbk(val) : val;
  10645. });
  10646. };
  10647. Worker.prototype.setMargin = function setMargin(margin) {
  10648. return this.then(function setMargin_main() {
  10649. // Parse the margin property.
  10650. switch (objType(margin)) {
  10651. case 'number':
  10652. margin = [margin, margin, margin, margin];
  10653. case 'array':
  10654. if (margin.length === 2) {
  10655. margin = [margin[0], margin[1], margin[0], margin[1]];
  10656. }
  10657. if (margin.length === 4) {
  10658. break;
  10659. }
  10660. default:
  10661. return this.error('Invalid margin array.');
  10662. } // Set the margin property, then update pageSize.
  10663. this.opt.margin = margin;
  10664. }).then(this.setPageSize);
  10665. };
  10666. Worker.prototype.setPageSize = function setPageSize(pageSize) {
  10667. function toPx(val, k) {
  10668. return Math.floor(val * k / 72 * 96);
  10669. }
  10670. return this.then(function setPageSize_main() {
  10671. // Retrieve page-size based on jsPDF settings, if not explicitly provided.
  10672. pageSize = pageSize || jsPDF.getPageSize(this.opt.jsPDF); // Add 'inner' field if not present.
  10673. if (!pageSize.hasOwnProperty('inner')) {
  10674. pageSize.inner = {
  10675. width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
  10676. height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
  10677. };
  10678. pageSize.inner.px = {
  10679. width: toPx(pageSize.inner.width, pageSize.k),
  10680. height: toPx(pageSize.inner.height, pageSize.k)
  10681. };
  10682. pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
  10683. } // Attach pageSize to this.
  10684. this.prop.pageSize = pageSize;
  10685. });
  10686. };
  10687. Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
  10688. // Immediately update all progress values.
  10689. if (val != null) this.progress.val = val;
  10690. if (state != null) this.progress.state = state;
  10691. if (n != null) this.progress.n = n;
  10692. if (stack != null) this.progress.stack = stack;
  10693. this.progress.ratio = this.progress.val / this.progress.state; // Return this for command chaining.
  10694. return this;
  10695. };
  10696. Worker.prototype.updateProgress = function updateProgress(val, state, n, stack) {
  10697. // Immediately update all progress values, using setProgress.
  10698. return this.setProgress(val ? this.progress.val + val : null, state ? state : null, n ? this.progress.n + n : null, stack ? this.progress.stack.concat(stack) : null);
  10699. };
  10700. /* ----- PROMISE MAPPING ----- */
  10701. Worker.prototype.then = function then(onFulfilled, onRejected) {
  10702. // Wrap `this` for encapsulation.
  10703. var self = this;
  10704. return this.thenCore(onFulfilled, onRejected, function then_main(onFulfilled, onRejected) {
  10705. // Update progress while queuing, calling, and resolving `then`.
  10706. self.updateProgress(null, null, 1, [onFulfilled]);
  10707. return Promise.prototype.then.call(this, function then_pre(val) {
  10708. self.updateProgress(null, onFulfilled);
  10709. return val;
  10710. }).then(onFulfilled, onRejected).then(function then_post(val) {
  10711. self.updateProgress(1);
  10712. return val;
  10713. });
  10714. });
  10715. };
  10716. Worker.prototype.thenCore = function thenCore(onFulfilled, onRejected, thenBase) {
  10717. // Handle optional thenBase parameter.
  10718. thenBase = thenBase || Promise.prototype.then; // Wrap `this` for encapsulation and bind it to the promise handlers.
  10719. var self = this;
  10720. if (onFulfilled) {
  10721. onFulfilled = onFulfilled.bind(self);
  10722. }
  10723. if (onRejected) {
  10724. onRejected = onRejected.bind(self);
  10725. } // Cast self into a Promise to avoid polyfills recursively defining `then`.
  10726. var isNative = Promise.toString().indexOf('[native code]') !== -1 && Promise.name === 'Promise';
  10727. var selfPromise = isNative ? self : Worker.convert(Object.assign({}, self), Promise.prototype); // Return the promise, after casting it into a Worker and preserving props.
  10728. var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
  10729. return Worker.convert(returnVal, self.__proto__);
  10730. };
  10731. Worker.prototype.thenExternal = function thenExternal(onFulfilled, onRejected) {
  10732. // Call `then` and return a standard promise (exits the Worker chain).
  10733. return Promise.prototype.then.call(this, onFulfilled, onRejected);
  10734. };
  10735. Worker.prototype.thenList = function thenList(fns) {
  10736. // Queue a series of promise 'factories' into the promise chain.
  10737. var self = this;
  10738. fns.forEach(function thenList_forEach(fn) {
  10739. self = self.thenCore(fn);
  10740. });
  10741. return self;
  10742. };
  10743. Worker.prototype['catch'] = function (onRejected) {
  10744. // Bind `this` to the promise handler, call `catch`, and return a Worker.
  10745. if (onRejected) {
  10746. onRejected = onRejected.bind(this);
  10747. }
  10748. var returnVal = Promise.prototype['catch'].call(this, onRejected);
  10749. return Worker.convert(returnVal, this);
  10750. };
  10751. Worker.prototype.catchExternal = function catchExternal(onRejected) {
  10752. // Call `catch` and return a standard promise (exits the Worker chain).
  10753. return Promise.prototype['catch'].call(this, onRejected);
  10754. };
  10755. Worker.prototype.error = function error(msg) {
  10756. // Throw the error in the Promise chain.
  10757. return this.then(function error_main() {
  10758. throw new Error(msg);
  10759. });
  10760. };
  10761. /* ----- ALIASES ----- */
  10762. Worker.prototype.using = Worker.prototype.set;
  10763. Worker.prototype.saveAs = Worker.prototype.save;
  10764. Worker.prototype.export = Worker.prototype.output;
  10765. Worker.prototype.run = Worker.prototype.then; // Get dimensions of a PDF page, as determined by jsPDF.
  10766. jsPDF.getPageSize = function (orientation, unit, format) {
  10767. // Decode options object
  10768. if (_typeof(orientation) === 'object') {
  10769. var options = orientation;
  10770. orientation = options.orientation;
  10771. unit = options.unit || unit;
  10772. format = options.format || format;
  10773. } // Default options
  10774. unit = unit || 'mm';
  10775. format = format || 'a4';
  10776. orientation = ('' + (orientation || 'P')).toLowerCase();
  10777. var format_as_string = ('' + format).toLowerCase(); // Size in pt of various paper formats
  10778. var pageFormats = {
  10779. 'a0': [2383.94, 3370.39],
  10780. 'a1': [1683.78, 2383.94],
  10781. 'a2': [1190.55, 1683.78],
  10782. 'a3': [841.89, 1190.55],
  10783. 'a4': [595.28, 841.89],
  10784. 'a5': [419.53, 595.28],
  10785. 'a6': [297.64, 419.53],
  10786. 'a7': [209.76, 297.64],
  10787. 'a8': [147.40, 209.76],
  10788. 'a9': [104.88, 147.40],
  10789. 'a10': [73.70, 104.88],
  10790. 'b0': [2834.65, 4008.19],
  10791. 'b1': [2004.09, 2834.65],
  10792. 'b2': [1417.32, 2004.09],
  10793. 'b3': [1000.63, 1417.32],
  10794. 'b4': [708.66, 1000.63],
  10795. 'b5': [498.90, 708.66],
  10796. 'b6': [354.33, 498.90],
  10797. 'b7': [249.45, 354.33],
  10798. 'b8': [175.75, 249.45],
  10799. 'b9': [124.72, 175.75],
  10800. 'b10': [87.87, 124.72],
  10801. 'c0': [2599.37, 3676.54],
  10802. 'c1': [1836.85, 2599.37],
  10803. 'c2': [1298.27, 1836.85],
  10804. 'c3': [918.43, 1298.27],
  10805. 'c4': [649.13, 918.43],
  10806. 'c5': [459.21, 649.13],
  10807. 'c6': [323.15, 459.21],
  10808. 'c7': [229.61, 323.15],
  10809. 'c8': [161.57, 229.61],
  10810. 'c9': [113.39, 161.57],
  10811. 'c10': [79.37, 113.39],
  10812. 'dl': [311.81, 623.62],
  10813. 'letter': [612, 792],
  10814. 'government-letter': [576, 756],
  10815. 'legal': [612, 1008],
  10816. 'junior-legal': [576, 360],
  10817. 'ledger': [1224, 792],
  10818. 'tabloid': [792, 1224],
  10819. 'credit-card': [153, 243]
  10820. }; // Unit conversion
  10821. switch (unit) {
  10822. case 'pt':
  10823. var k = 1;
  10824. break;
  10825. case 'mm':
  10826. var k = 72 / 25.4;
  10827. break;
  10828. case 'cm':
  10829. var k = 72 / 2.54;
  10830. break;
  10831. case 'in':
  10832. var k = 72;
  10833. break;
  10834. case 'px':
  10835. var k = 72 / 96;
  10836. break;
  10837. case 'pc':
  10838. var k = 12;
  10839. break;
  10840. case 'em':
  10841. var k = 12;
  10842. break;
  10843. case 'ex':
  10844. var k = 6;
  10845. break;
  10846. default:
  10847. throw 'Invalid unit: ' + unit;
  10848. } // Dimensions are stored as user units and converted to points on output
  10849. if (pageFormats.hasOwnProperty(format_as_string)) {
  10850. var pageHeight = pageFormats[format_as_string][1] / k;
  10851. var pageWidth = pageFormats[format_as_string][0] / k;
  10852. } else {
  10853. try {
  10854. var pageHeight = format[1];
  10855. var pageWidth = format[0];
  10856. } catch (err) {
  10857. throw new Error('Invalid format: ' + format);
  10858. }
  10859. } // Handle page orientation
  10860. if (orientation === 'p' || orientation === 'portrait') {
  10861. orientation = 'p';
  10862. if (pageWidth > pageHeight) {
  10863. var tmp = pageWidth;
  10864. pageWidth = pageHeight;
  10865. pageHeight = tmp;
  10866. }
  10867. } else if (orientation === 'l' || orientation === 'landscape') {
  10868. orientation = 'l';
  10869. if (pageHeight > pageWidth) {
  10870. var tmp = pageWidth;
  10871. pageWidth = pageHeight;
  10872. pageHeight = tmp;
  10873. }
  10874. } else {
  10875. throw 'Invalid orientation: ' + orientation;
  10876. } // Return information (k is the unit conversion ratio from pts)
  10877. var info = {
  10878. 'width': pageWidth,
  10879. 'height': pageHeight,
  10880. 'unit': unit,
  10881. 'k': k
  10882. };
  10883. return info;
  10884. };
  10885. /**
  10886. * Generate a PDF from an HTML element or string using.
  10887. *
  10888. * @name html
  10889. * @function
  10890. * @param {Element|string} source The source element or HTML string.
  10891. * @param {Object=} options An object of optional settings.
  10892. * @description The Plugin needs html2canvas from niklasvh
  10893. */
  10894. jsPDFAPI.html = function (src, options) {
  10895. options = options || {};
  10896. options.callback = options.callback || function () {};
  10897. options.html2canvas = options.html2canvas || {};
  10898. options.html2canvas.canvas = options.html2canvas.canvas || this.canvas;
  10899. options.jsPDF = options.jsPDF || this; // Create a new worker with the given options.
  10900. var pdf = options.jsPDF;
  10901. var worker = new Worker(options);
  10902. if (!options.worker) {
  10903. // If worker is not set to true, perform the traditional 'simple' operation.
  10904. return worker.from(src).doCallback();
  10905. } else {
  10906. // Otherwise, return the worker for new Promise-based operation.
  10907. return worker;
  10908. }
  10909. return this;
  10910. };
  10911. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  10912. /**
  10913. * @license
  10914. * ====================================================================
  10915. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  10916. *
  10917. *
  10918. * ====================================================================
  10919. */
  10920. /*global jsPDF */
  10921. /**
  10922. * jsPDF JavaScript plugin
  10923. *
  10924. * @name javascript
  10925. * @module
  10926. */
  10927. (function (jsPDFAPI) {
  10928. var jsNamesObj, jsJsObj, text;
  10929. /**
  10930. * @name addJS
  10931. * @function
  10932. * @param {string} javascript The javascript to be embedded into the PDF-file.
  10933. * @returns {jsPDF}
  10934. */
  10935. jsPDFAPI.addJS = function (javascript) {
  10936. text = javascript;
  10937. this.internal.events.subscribe('postPutResources', function (javascript) {
  10938. jsNamesObj = this.internal.newObject();
  10939. this.internal.out('<<');
  10940. this.internal.out('/Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R]');
  10941. this.internal.out('>>');
  10942. this.internal.out('endobj');
  10943. jsJsObj = this.internal.newObject();
  10944. this.internal.out('<<');
  10945. this.internal.out('/S /JavaScript');
  10946. this.internal.out('/JS (' + text + ')');
  10947. this.internal.out('>>');
  10948. this.internal.out('endobj');
  10949. });
  10950. this.internal.events.subscribe('putCatalog', function () {
  10951. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  10952. this.internal.out('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  10953. }
  10954. });
  10955. return this;
  10956. };
  10957. })(jsPDF.API);
  10958. /**
  10959. * @license
  10960. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  10961. *
  10962. * Licensed under the MIT License.
  10963. * http://opensource.org/licenses/mit-license
  10964. */
  10965. (function (jsPDFAPI) {
  10966. jsPDFAPI.events.push(['postPutResources', function () {
  10967. var pdf = this;
  10968. var rx = /^(\d+) 0 obj$/; // Write action goto objects for each page
  10969. // this.outline.destsGoto = [];
  10970. // for (var i = 0; i < totalPages; i++) {
  10971. // var id = pdf.internal.newObject();
  10972. // this.outline.destsGoto.push(id);
  10973. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  10974. // null null]/S/GoTo>> endobj");
  10975. // }
  10976. //
  10977. // for (var i = 0; i < dests.length; i++) {
  10978. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  10979. // R");
  10980. // }
  10981. //
  10982. if (this.outline.root.children.length > 0) {
  10983. var lines = pdf.outline.render().split(/\r\n/);
  10984. for (var i = 0; i < lines.length; i++) {
  10985. var line = lines[i];
  10986. var m = rx.exec(line);
  10987. if (m != null) {
  10988. var oid = m[1];
  10989. pdf.internal.newObjectDeferredBegin(oid, false);
  10990. }
  10991. pdf.internal.write(line);
  10992. }
  10993. } // This code will write named destination for each page reference
  10994. // (page_1, etc)
  10995. if (this.outline.createNamedDestinations) {
  10996. var totalPages = this.internal.pages.length; // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  10997. // follow 5, 7, 9, etc
  10998. // Write destination objects for each page
  10999. var dests = [];
  11000. for (var i = 0; i < totalPages; i++) {
  11001. var id = pdf.internal.newObject();
  11002. dests.push(id);
  11003. var info = pdf.internal.getPageInfo(i + 1);
  11004. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  11005. } // assign a name for each destination
  11006. var names2Oid = pdf.internal.newObject();
  11007. pdf.internal.write('<< /Names [ ');
  11008. for (var i = 0; i < dests.length; i++) {
  11009. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  11010. }
  11011. pdf.internal.write(' ] >>', 'endobj'); // var kids = pdf.internal.newObject();
  11012. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  11013. // pdf.internal.write(' ] >>', 'endobj');
  11014. var namesOid = pdf.internal.newObject();
  11015. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  11016. pdf.internal.write('>>', 'endobj');
  11017. }
  11018. }]);
  11019. jsPDFAPI.events.push(['putCatalog', function () {
  11020. var pdf = this;
  11021. if (pdf.outline.root.children.length > 0) {
  11022. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  11023. if (this.outline.createNamedDestinations) {
  11024. pdf.internal.write("/Names " + namesOid + " 0 R");
  11025. } // Open with Bookmarks showing
  11026. // pdf.internal.write("/PageMode /UseOutlines");
  11027. }
  11028. }]);
  11029. jsPDFAPI.events.push(['initialized', function () {
  11030. var pdf = this;
  11031. pdf.outline = {
  11032. createNamedDestinations: false,
  11033. root: {
  11034. children: []
  11035. }
  11036. };
  11037. /**
  11038. * Options: pageNumber
  11039. */
  11040. pdf.outline.add = function (parent, title, options) {
  11041. var item = {
  11042. title: title,
  11043. options: options,
  11044. children: []
  11045. };
  11046. if (parent == null) {
  11047. parent = this.root;
  11048. }
  11049. parent.children.push(item);
  11050. return item;
  11051. };
  11052. pdf.outline.render = function () {
  11053. this.ctx = {};
  11054. this.ctx.val = '';
  11055. this.ctx.pdf = pdf;
  11056. this.genIds_r(this.root);
  11057. this.renderRoot(this.root);
  11058. this.renderItems(this.root);
  11059. return this.ctx.val;
  11060. };
  11061. pdf.outline.genIds_r = function (node) {
  11062. node.id = pdf.internal.newObjectDeferred();
  11063. for (var i = 0; i < node.children.length; i++) {
  11064. this.genIds_r(node.children[i]);
  11065. }
  11066. };
  11067. pdf.outline.renderRoot = function (node) {
  11068. this.objStart(node);
  11069. this.line('/Type /Outlines');
  11070. if (node.children.length > 0) {
  11071. this.line('/First ' + this.makeRef(node.children[0]));
  11072. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  11073. }
  11074. this.line('/Count ' + this.count_r({
  11075. count: 0
  11076. }, node));
  11077. this.objEnd();
  11078. };
  11079. pdf.outline.renderItems = function (node) {
  11080. var getHorizontalCoordinateString = this.ctx.pdf.internal.getCoordinateString;
  11081. var getVerticalCoordinateString = this.ctx.pdf.internal.getVerticalCoordinateString;
  11082. for (var i = 0; i < node.children.length; i++) {
  11083. var item = node.children[i];
  11084. this.objStart(item);
  11085. this.line('/Title ' + this.makeString(item.title));
  11086. this.line('/Parent ' + this.makeRef(node));
  11087. if (i > 0) {
  11088. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  11089. }
  11090. if (i < node.children.length - 1) {
  11091. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  11092. }
  11093. if (item.children.length > 0) {
  11094. this.line('/First ' + this.makeRef(item.children[0]));
  11095. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  11096. }
  11097. var count = this.count = this.count_r({
  11098. count: 0
  11099. }, item);
  11100. if (count > 0) {
  11101. this.line('/Count ' + count);
  11102. }
  11103. if (item.options) {
  11104. if (item.options.pageNumber) {
  11105. // Explicit Destination
  11106. //WARNING this assumes page ids are 3,5,7, etc.
  11107. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  11108. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + getVerticalCoordinateString(0) + ' 0]'); // this line does not work on all clients (pageNumber instead of page ref)
  11109. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() + ' 0]');
  11110. // Named Destination
  11111. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  11112. // Action Destination
  11113. // var id = pdf.internal.newObject();
  11114. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  11115. // this.line('/A ' + id + ' 0 R' );
  11116. }
  11117. }
  11118. this.objEnd();
  11119. }
  11120. for (var i = 0; i < node.children.length; i++) {
  11121. var item = node.children[i];
  11122. this.renderItems(item);
  11123. }
  11124. };
  11125. pdf.outline.line = function (text) {
  11126. this.ctx.val += text + '\r\n';
  11127. };
  11128. pdf.outline.makeRef = function (node) {
  11129. return node.id + ' 0 R';
  11130. };
  11131. pdf.outline.makeString = function (val) {
  11132. return '(' + pdf.internal.pdfEscape(val) + ')';
  11133. };
  11134. pdf.outline.objStart = function (node) {
  11135. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  11136. };
  11137. pdf.outline.objEnd = function (node) {
  11138. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  11139. };
  11140. pdf.outline.count_r = function (ctx, node) {
  11141. for (var i = 0; i < node.children.length; i++) {
  11142. ctx.count++;
  11143. this.count_r(ctx, node.children[i]);
  11144. }
  11145. return ctx.count;
  11146. };
  11147. }]);
  11148. return this;
  11149. })(jsPDF.API);
  11150. /**
  11151. * @license
  11152. *
  11153. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  11154. *
  11155. *
  11156. * ====================================================================
  11157. */
  11158. /**
  11159. * jsPDF PNG PlugIn
  11160. * @name png_support
  11161. * @module
  11162. */
  11163. (function (jsPDFAPI) {
  11164. /*
  11165. * @see http://www.w3.org/TR/PNG-Chunks.html
  11166. *
  11167. Color Allowed Interpretation
  11168. Type Bit Depths
  11169. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  11170. 2 8,16 Each pixel is an R,G,B triple.
  11171. 3 1,2,4,8 Each pixel is a palette index;
  11172. a PLTE chunk must appear.
  11173. 4 8,16 Each pixel is a grayscale sample,
  11174. followed by an alpha sample.
  11175. 6 8,16 Each pixel is an R,G,B triple,
  11176. followed by an alpha sample.
  11177. */
  11178. /*
  11179. * PNG filter method types
  11180. *
  11181. * @see http://www.w3.org/TR/PNG-Filters.html
  11182. * @see http://www.libpng.org/pub/png/book/chapter09.html
  11183. *
  11184. * This is what the value 'Predictor' in decode params relates to
  11185. *
  11186. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  11187. * 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.
  11188. *
  11189. 0 None
  11190. 1 Sub
  11191. 2 Up
  11192. 3 Average
  11193. 4 Paeth
  11194. */
  11195. var doesNotHavePngJS = function doesNotHavePngJS() {
  11196. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  11197. },
  11198. canCompress = function canCompress(value) {
  11199. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  11200. },
  11201. hasCompressionJS = function hasCompressionJS() {
  11202. var inst = typeof Deflater === 'function';
  11203. if (!inst) throw new Error("requires deflate.js for compression");
  11204. return inst;
  11205. },
  11206. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  11207. var level = 5,
  11208. filter_method = filterUp;
  11209. switch (compression) {
  11210. case jsPDFAPI.image_compression.FAST:
  11211. level = 3;
  11212. filter_method = filterSub;
  11213. break;
  11214. case jsPDFAPI.image_compression.MEDIUM:
  11215. level = 6;
  11216. filter_method = filterAverage;
  11217. break;
  11218. case jsPDFAPI.image_compression.SLOW:
  11219. level = 9;
  11220. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  11221. break;
  11222. }
  11223. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  11224. var header = new Uint8Array(createZlibHeader(level));
  11225. var checksum = adler32(bytes);
  11226. var deflate = new Deflater(level);
  11227. var a = deflate.append(bytes);
  11228. var cBytes = deflate.flush();
  11229. var len = header.length + a.length + cBytes.length;
  11230. var cmpd = new Uint8Array(len + 4);
  11231. cmpd.set(header);
  11232. cmpd.set(a, header.length);
  11233. cmpd.set(cBytes, header.length + a.length);
  11234. cmpd[len++] = checksum >>> 24 & 0xff;
  11235. cmpd[len++] = checksum >>> 16 & 0xff;
  11236. cmpd[len++] = checksum >>> 8 & 0xff;
  11237. cmpd[len++] = checksum & 0xff;
  11238. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  11239. },
  11240. createZlibHeader = function createZlibHeader(bytes, level) {
  11241. /*
  11242. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  11243. */
  11244. var cm = 8;
  11245. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  11246. var cmf = cinfo << 4 | cm;
  11247. var hdr = cmf << 8;
  11248. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  11249. hdr |= flevel << 6;
  11250. hdr |= 0; //FDICT
  11251. hdr += 31 - hdr % 31;
  11252. return [cmf, hdr & 0xff & 0xff];
  11253. },
  11254. adler32 = function adler32(array, param) {
  11255. var adler = 1;
  11256. var s1 = adler & 0xffff,
  11257. s2 = adler >>> 16 & 0xffff;
  11258. var len = array.length;
  11259. var tlen;
  11260. var i = 0;
  11261. while (len > 0) {
  11262. tlen = len > param ? param : len;
  11263. len -= tlen;
  11264. do {
  11265. s1 += array[i++];
  11266. s2 += s1;
  11267. } while (--tlen);
  11268. s1 %= 65521;
  11269. s2 %= 65521;
  11270. }
  11271. return (s2 << 16 | s1) >>> 0;
  11272. },
  11273. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  11274. var lines = bytes.length / lineLength,
  11275. result = new Uint8Array(bytes.length + lines),
  11276. filter_methods = getFilterMethods(),
  11277. i = 0,
  11278. line,
  11279. prevLine,
  11280. offset;
  11281. for (; i < lines; i++) {
  11282. offset = i * lineLength;
  11283. line = bytes.subarray(offset, offset + lineLength);
  11284. if (filter_method) {
  11285. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  11286. } else {
  11287. var j = 0,
  11288. len = filter_methods.length,
  11289. results = [];
  11290. for (; j < len; j++) {
  11291. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  11292. }
  11293. var ind = getIndexOfSmallestSum(results.concat());
  11294. result.set(results[ind], offset + i);
  11295. }
  11296. prevLine = line;
  11297. }
  11298. return result;
  11299. },
  11300. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  11301. /*var result = new Uint8Array(line.length + 1);
  11302. result[0] = 0;
  11303. result.set(line, 1);*/
  11304. var result = Array.apply([], line);
  11305. result.unshift(0);
  11306. return result;
  11307. },
  11308. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  11309. var result = [],
  11310. i = 0,
  11311. len = line.length,
  11312. left;
  11313. result[0] = 1;
  11314. for (; i < len; i++) {
  11315. left = line[i - colorsPerPixel] || 0;
  11316. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  11317. }
  11318. return result;
  11319. },
  11320. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  11321. var result = [],
  11322. i = 0,
  11323. len = line.length,
  11324. up;
  11325. result[0] = 2;
  11326. for (; i < len; i++) {
  11327. up = prevLine && prevLine[i] || 0;
  11328. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  11329. }
  11330. return result;
  11331. },
  11332. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  11333. var result = [],
  11334. i = 0,
  11335. len = line.length,
  11336. left,
  11337. up;
  11338. result[0] = 3;
  11339. for (; i < len; i++) {
  11340. left = line[i - colorsPerPixel] || 0;
  11341. up = prevLine && prevLine[i] || 0;
  11342. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  11343. }
  11344. return result;
  11345. },
  11346. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  11347. var result = [],
  11348. i = 0,
  11349. len = line.length,
  11350. left,
  11351. up,
  11352. upLeft,
  11353. paeth;
  11354. result[0] = 4;
  11355. for (; i < len; i++) {
  11356. left = line[i - colorsPerPixel] || 0;
  11357. up = prevLine && prevLine[i] || 0;
  11358. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  11359. paeth = paethPredictor(left, up, upLeft);
  11360. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  11361. }
  11362. return result;
  11363. },
  11364. paethPredictor = function paethPredictor(left, up, upLeft) {
  11365. var p = left + up - upLeft,
  11366. pLeft = Math.abs(p - left),
  11367. pUp = Math.abs(p - up),
  11368. pUpLeft = Math.abs(p - upLeft);
  11369. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  11370. },
  11371. getFilterMethods = function getFilterMethods() {
  11372. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  11373. },
  11374. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  11375. var i = 0,
  11376. len = arrays.length,
  11377. sum,
  11378. min,
  11379. ind;
  11380. while (i < len) {
  11381. sum = absSum(arrays[i].slice(1));
  11382. if (sum < min || !min) {
  11383. min = sum;
  11384. ind = i;
  11385. }
  11386. i++;
  11387. }
  11388. return ind;
  11389. },
  11390. absSum = function absSum(array) {
  11391. var i = 0,
  11392. len = array.length,
  11393. sum = 0;
  11394. while (i < len) {
  11395. sum += Math.abs(array[i++]);
  11396. }
  11397. return sum;
  11398. },
  11399. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  11400. var predictor;
  11401. switch (compression) {
  11402. case jsPDFAPI.image_compression.FAST:
  11403. predictor = 11;
  11404. break;
  11405. case jsPDFAPI.image_compression.MEDIUM:
  11406. predictor = 13;
  11407. break;
  11408. case jsPDFAPI.image_compression.SLOW:
  11409. predictor = 14;
  11410. break;
  11411. default:
  11412. predictor = 12;
  11413. break;
  11414. }
  11415. return predictor;
  11416. };
  11417. /**
  11418. *
  11419. * @name processPNG
  11420. * @function
  11421. * @ignore
  11422. */
  11423. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11424. var colorSpace = this.color_spaces.DEVICE_RGB,
  11425. decode = this.decode.FLATE_DECODE,
  11426. bpc = 8,
  11427. img,
  11428. dp,
  11429. trns,
  11430. colors,
  11431. pal,
  11432. smask;
  11433. /* if(this.isString(imageData)) {
  11434. }*/
  11435. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  11436. if (this.isArrayBufferView(imageData)) {
  11437. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  11438. img = new PNG(imageData);
  11439. imageData = img.imgData;
  11440. bpc = img.bits;
  11441. colorSpace = img.colorSpace;
  11442. colors = img.colors; //logImg(img);
  11443. /*
  11444. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  11445. *
  11446. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  11447. *
  11448. * Extract alpha to create two separate images, using the alpha as a sMask
  11449. */
  11450. if ([4, 6].indexOf(img.colorType) !== -1) {
  11451. /*
  11452. * processes 8 bit RGBA and grayscale + alpha images
  11453. */
  11454. if (img.bits === 8) {
  11455. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  11456. len = pixels.length,
  11457. imgData = new Uint8Array(len * img.colors),
  11458. alphaData = new Uint8Array(len),
  11459. pDiff = img.pixelBitlength - img.bits,
  11460. i = 0,
  11461. n = 0,
  11462. pixel,
  11463. pbl;
  11464. for (; i < len; i++) {
  11465. pixel = pixels[i];
  11466. pbl = 0;
  11467. while (pbl < pDiff) {
  11468. imgData[n++] = pixel >>> pbl & 0xff;
  11469. pbl = pbl + img.bits;
  11470. }
  11471. alphaData[i] = pixel >>> pbl & 0xff;
  11472. }
  11473. }
  11474. /*
  11475. * processes 16 bit RGBA and grayscale + alpha images
  11476. */
  11477. if (img.bits === 16) {
  11478. var pixels = new Uint32Array(img.decodePixels().buffer),
  11479. len = pixels.length,
  11480. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  11481. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  11482. hasColors = img.colors > 1,
  11483. i = 0,
  11484. n = 0,
  11485. a = 0,
  11486. pixel;
  11487. while (i < len) {
  11488. pixel = pixels[i++];
  11489. imgData[n++] = pixel >>> 0 & 0xFF;
  11490. if (hasColors) {
  11491. imgData[n++] = pixel >>> 16 & 0xFF;
  11492. pixel = pixels[i++];
  11493. imgData[n++] = pixel >>> 0 & 0xFF;
  11494. }
  11495. alphaData[a++] = pixel >>> 16 & 0xFF;
  11496. }
  11497. bpc = 8;
  11498. }
  11499. if (canCompress(compression)) {
  11500. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  11501. smask = compressBytes(alphaData, img.width, 1, compression);
  11502. } else {
  11503. imageData = imgData;
  11504. smask = alphaData;
  11505. decode = null;
  11506. }
  11507. }
  11508. /*
  11509. * Indexed png. Each pixel is a palette index.
  11510. */
  11511. if (img.colorType === 3) {
  11512. colorSpace = this.color_spaces.INDEXED;
  11513. pal = img.palette;
  11514. if (img.transparency.indexed) {
  11515. var trans = img.transparency.indexed;
  11516. var total = 0,
  11517. i = 0,
  11518. len = trans.length;
  11519. for (; i < len; ++i) {
  11520. total += trans[i];
  11521. }
  11522. total = total / 255;
  11523. /*
  11524. * a single color is specified as 100% transparent (0),
  11525. * so we set trns to use a /Mask with that index
  11526. */
  11527. if (total === len - 1 && trans.indexOf(0) !== -1) {
  11528. trns = [trans.indexOf(0)];
  11529. /*
  11530. * there's more than one colour within the palette that specifies
  11531. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  11532. */
  11533. } else if (total !== len) {
  11534. var pixels = img.decodePixels(),
  11535. alphaData = new Uint8Array(pixels.length),
  11536. i = 0,
  11537. len = pixels.length;
  11538. for (; i < len; i++) {
  11539. alphaData[i] = trans[pixels[i]];
  11540. }
  11541. smask = compressBytes(alphaData, img.width, 1);
  11542. }
  11543. }
  11544. }
  11545. var predictor = getPredictorFromCompression(compression);
  11546. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  11547. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  11548. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  11549. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  11550. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  11551. }
  11552. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  11553. };
  11554. })(jsPDF.API);
  11555. /**
  11556. * @license
  11557. * Copyright (c) 2017 Aras Abbasi
  11558. *
  11559. * Licensed under the MIT License.
  11560. * http://opensource.org/licenses/mit-license
  11561. */
  11562. /**
  11563. * jsPDF gif Support PlugIn
  11564. *
  11565. * @name gif_support
  11566. * @module
  11567. */
  11568. (function (jsPDFAPI) {
  11569. jsPDFAPI.processGIF89A = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11570. var reader = new GifReader(imageData);
  11571. var width = reader.width,
  11572. height = reader.height;
  11573. var qu = 100;
  11574. var pixels = [];
  11575. reader.decodeAndBlitFrameRGBA(0, pixels);
  11576. var rawImageData = {
  11577. data: pixels,
  11578. width: width,
  11579. height: height
  11580. };
  11581. var encoder = new JPEGEncoder(qu);
  11582. var data = encoder.encode(rawImageData, qu);
  11583. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  11584. };
  11585. jsPDFAPI.processGIF87A = jsPDFAPI.processGIF89A;
  11586. })(jsPDF.API);
  11587. /**
  11588. * Copyright (c) 2018 Aras Abbasi
  11589. *
  11590. * Licensed under the MIT License.
  11591. * http://opensource.org/licenses/mit-license
  11592. */
  11593. /**
  11594. * jsPDF bmp Support PlugIn
  11595. * @name bmp_support
  11596. * @module
  11597. */
  11598. (function (jsPDFAPI) {
  11599. jsPDFAPI.processBMP = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11600. var reader = new BmpDecoder(imageData, false);
  11601. var width = reader.width,
  11602. height = reader.height;
  11603. var qu = 100;
  11604. var pixels = reader.getData();
  11605. var rawImageData = {
  11606. data: pixels,
  11607. width: width,
  11608. height: height
  11609. };
  11610. var encoder = new JPEGEncoder(qu);
  11611. var data = encoder.encode(rawImageData, qu);
  11612. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  11613. };
  11614. })(jsPDF.API);
  11615. /**
  11616. * @license
  11617. * Licensed under the MIT License.
  11618. * http://opensource.org/licenses/mit-license
  11619. */
  11620. /**
  11621. * jsPDF setLanguage Plugin
  11622. *
  11623. * @name setLanguage
  11624. * @module
  11625. */
  11626. (function (jsPDFAPI) {
  11627. /**
  11628. * Add Language Tag to the generated PDF
  11629. *
  11630. * @name setLanguage
  11631. * @function
  11632. * @param {string} langCode The Language code as ISO-639-1 (e.g. 'en') or as country language code (e.g. 'en-GB').
  11633. * @returns {jsPDF}
  11634. * @example
  11635. * var doc = new jsPDF()
  11636. * doc.text(10, 10, 'This is a test')
  11637. * doc.setLanguage("en-US")
  11638. * doc.save('english.pdf')
  11639. */
  11640. jsPDFAPI.setLanguage = function (langCode) {
  11641. var langCodes = {
  11642. "af": "Afrikaans",
  11643. "sq": "Albanian",
  11644. "ar": "Arabic (Standard)",
  11645. "ar-DZ": "Arabic (Algeria)",
  11646. "ar-BH": "Arabic (Bahrain)",
  11647. "ar-EG": "Arabic (Egypt)",
  11648. "ar-IQ": "Arabic (Iraq)",
  11649. "ar-JO": "Arabic (Jordan)",
  11650. "ar-KW": "Arabic (Kuwait)",
  11651. "ar-LB": "Arabic (Lebanon)",
  11652. "ar-LY": "Arabic (Libya)",
  11653. "ar-MA": "Arabic (Morocco)",
  11654. "ar-OM": "Arabic (Oman)",
  11655. "ar-QA": "Arabic (Qatar)",
  11656. "ar-SA": "Arabic (Saudi Arabia)",
  11657. "ar-SY": "Arabic (Syria)",
  11658. "ar-TN": "Arabic (Tunisia)",
  11659. "ar-AE": "Arabic (U.A.E.)",
  11660. "ar-YE": "Arabic (Yemen)",
  11661. "an": "Aragonese",
  11662. "hy": "Armenian",
  11663. "as": "Assamese",
  11664. "ast": "Asturian",
  11665. "az": "Azerbaijani",
  11666. "eu": "Basque",
  11667. "be": "Belarusian",
  11668. "bn": "Bengali",
  11669. "bs": "Bosnian",
  11670. "br": "Breton",
  11671. "bg": "Bulgarian",
  11672. "my": "Burmese",
  11673. "ca": "Catalan",
  11674. "ch": "Chamorro",
  11675. "ce": "Chechen",
  11676. "zh": "Chinese",
  11677. "zh-HK": "Chinese (Hong Kong)",
  11678. "zh-CN": "Chinese (PRC)",
  11679. "zh-SG": "Chinese (Singapore)",
  11680. "zh-TW": "Chinese (Taiwan)",
  11681. "cv": "Chuvash",
  11682. "co": "Corsican",
  11683. "cr": "Cree",
  11684. "hr": "Croatian",
  11685. "cs": "Czech",
  11686. "da": "Danish",
  11687. "nl": "Dutch (Standard)",
  11688. "nl-BE": "Dutch (Belgian)",
  11689. "en": "English",
  11690. "en-AU": "English (Australia)",
  11691. "en-BZ": "English (Belize)",
  11692. "en-CA": "English (Canada)",
  11693. "en-IE": "English (Ireland)",
  11694. "en-JM": "English (Jamaica)",
  11695. "en-NZ": "English (New Zealand)",
  11696. "en-PH": "English (Philippines)",
  11697. "en-ZA": "English (South Africa)",
  11698. "en-TT": "English (Trinidad & Tobago)",
  11699. "en-GB": "English (United Kingdom)",
  11700. "en-US": "English (United States)",
  11701. "en-ZW": "English (Zimbabwe)",
  11702. "eo": "Esperanto",
  11703. "et": "Estonian",
  11704. "fo": "Faeroese",
  11705. "fj": "Fijian",
  11706. "fi": "Finnish",
  11707. "fr": "French (Standard)",
  11708. "fr-BE": "French (Belgium)",
  11709. "fr-CA": "French (Canada)",
  11710. "fr-FR": "French (France)",
  11711. "fr-LU": "French (Luxembourg)",
  11712. "fr-MC": "French (Monaco)",
  11713. "fr-CH": "French (Switzerland)",
  11714. "fy": "Frisian",
  11715. "fur": "Friulian",
  11716. "gd": "Gaelic (Scots)",
  11717. "gd-IE": "Gaelic (Irish)",
  11718. "gl": "Galacian",
  11719. "ka": "Georgian",
  11720. "de": "German (Standard)",
  11721. "de-AT": "German (Austria)",
  11722. "de-DE": "German (Germany)",
  11723. "de-LI": "German (Liechtenstein)",
  11724. "de-LU": "German (Luxembourg)",
  11725. "de-CH": "German (Switzerland)",
  11726. "el": "Greek",
  11727. "gu": "Gujurati",
  11728. "ht": "Haitian",
  11729. "he": "Hebrew",
  11730. "hi": "Hindi",
  11731. "hu": "Hungarian",
  11732. "is": "Icelandic",
  11733. "id": "Indonesian",
  11734. "iu": "Inuktitut",
  11735. "ga": "Irish",
  11736. "it": "Italian (Standard)",
  11737. "it-CH": "Italian (Switzerland)",
  11738. "ja": "Japanese",
  11739. "kn": "Kannada",
  11740. "ks": "Kashmiri",
  11741. "kk": "Kazakh",
  11742. "km": "Khmer",
  11743. "ky": "Kirghiz",
  11744. "tlh": "Klingon",
  11745. "ko": "Korean",
  11746. "ko-KP": "Korean (North Korea)",
  11747. "ko-KR": "Korean (South Korea)",
  11748. "la": "Latin",
  11749. "lv": "Latvian",
  11750. "lt": "Lithuanian",
  11751. "lb": "Luxembourgish",
  11752. "mk": "FYRO Macedonian",
  11753. "ms": "Malay",
  11754. "ml": "Malayalam",
  11755. "mt": "Maltese",
  11756. "mi": "Maori",
  11757. "mr": "Marathi",
  11758. "mo": "Moldavian",
  11759. "nv": "Navajo",
  11760. "ng": "Ndonga",
  11761. "ne": "Nepali",
  11762. "no": "Norwegian",
  11763. "nb": "Norwegian (Bokmal)",
  11764. "nn": "Norwegian (Nynorsk)",
  11765. "oc": "Occitan",
  11766. "or": "Oriya",
  11767. "om": "Oromo",
  11768. "fa": "Persian",
  11769. "fa-IR": "Persian/Iran",
  11770. "pl": "Polish",
  11771. "pt": "Portuguese",
  11772. "pt-BR": "Portuguese (Brazil)",
  11773. "pa": "Punjabi",
  11774. "pa-IN": "Punjabi (India)",
  11775. "pa-PK": "Punjabi (Pakistan)",
  11776. "qu": "Quechua",
  11777. "rm": "Rhaeto-Romanic",
  11778. "ro": "Romanian",
  11779. "ro-MO": "Romanian (Moldavia)",
  11780. "ru": "Russian",
  11781. "ru-MO": "Russian (Moldavia)",
  11782. "sz": "Sami (Lappish)",
  11783. "sg": "Sango",
  11784. "sa": "Sanskrit",
  11785. "sc": "Sardinian",
  11786. "sd": "Sindhi",
  11787. "si": "Singhalese",
  11788. "sr": "Serbian",
  11789. "sk": "Slovak",
  11790. "sl": "Slovenian",
  11791. "so": "Somani",
  11792. "sb": "Sorbian",
  11793. "es": "Spanish",
  11794. "es-AR": "Spanish (Argentina)",
  11795. "es-BO": "Spanish (Bolivia)",
  11796. "es-CL": "Spanish (Chile)",
  11797. "es-CO": "Spanish (Colombia)",
  11798. "es-CR": "Spanish (Costa Rica)",
  11799. "es-DO": "Spanish (Dominican Republic)",
  11800. "es-EC": "Spanish (Ecuador)",
  11801. "es-SV": "Spanish (El Salvador)",
  11802. "es-GT": "Spanish (Guatemala)",
  11803. "es-HN": "Spanish (Honduras)",
  11804. "es-MX": "Spanish (Mexico)",
  11805. "es-NI": "Spanish (Nicaragua)",
  11806. "es-PA": "Spanish (Panama)",
  11807. "es-PY": "Spanish (Paraguay)",
  11808. "es-PE": "Spanish (Peru)",
  11809. "es-PR": "Spanish (Puerto Rico)",
  11810. "es-ES": "Spanish (Spain)",
  11811. "es-UY": "Spanish (Uruguay)",
  11812. "es-VE": "Spanish (Venezuela)",
  11813. "sx": "Sutu",
  11814. "sw": "Swahili",
  11815. "sv": "Swedish",
  11816. "sv-FI": "Swedish (Finland)",
  11817. "sv-SV": "Swedish (Sweden)",
  11818. "ta": "Tamil",
  11819. "tt": "Tatar",
  11820. "te": "Teluga",
  11821. "th": "Thai",
  11822. "tig": "Tigre",
  11823. "ts": "Tsonga",
  11824. "tn": "Tswana",
  11825. "tr": "Turkish",
  11826. "tk": "Turkmen",
  11827. "uk": "Ukrainian",
  11828. "hsb": "Upper Sorbian",
  11829. "ur": "Urdu",
  11830. "ve": "Venda",
  11831. "vi": "Vietnamese",
  11832. "vo": "Volapuk",
  11833. "wa": "Walloon",
  11834. "cy": "Welsh",
  11835. "xh": "Xhosa",
  11836. "ji": "Yiddish",
  11837. "zu": "Zulu"
  11838. };
  11839. if (this.internal.languageSettings === undefined) {
  11840. this.internal.languageSettings = {};
  11841. this.internal.languageSettings.isSubscribed = false;
  11842. }
  11843. if (langCodes[langCode] !== undefined) {
  11844. this.internal.languageSettings.languageCode = langCode;
  11845. if (this.internal.languageSettings.isSubscribed === false) {
  11846. this.internal.events.subscribe("putCatalog", function () {
  11847. this.internal.write("/Lang (" + this.internal.languageSettings.languageCode + ")");
  11848. });
  11849. this.internal.languageSettings.isSubscribed = true;
  11850. }
  11851. }
  11852. return this;
  11853. };
  11854. })(jsPDF.API);
  11855. /** @license
  11856. * MIT license.
  11857. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  11858. * 2014 Diego Casorran, https://github.com/diegocr
  11859. *
  11860. *
  11861. * ====================================================================
  11862. */
  11863. /**
  11864. * jsPDF split_text_to_size plugin
  11865. *
  11866. * @name split_text_to_size
  11867. * @module
  11868. */
  11869. (function (API) {
  11870. /**
  11871. * Returns an array of length matching length of the 'word' string, with each
  11872. * cell occupied by the width of the char in that position.
  11873. *
  11874. * @name getCharWidthsArray
  11875. * @function
  11876. * @param {string} text
  11877. * @param {Object} options
  11878. * @returns {Array}
  11879. */
  11880. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  11881. options = options || {};
  11882. var activeFont = options.font || this.internal.getFont();
  11883. var fontSize = options.fontSize || this.internal.getFontSize();
  11884. var charSpace = options.charSpace || this.internal.getCharSpace();
  11885. var widths = options.widths ? options.widths : activeFont.metadata.Unicode.widths;
  11886. var widthsFractionOf = widths.fof ? widths.fof : 1;
  11887. var kerning = options.kerning ? options.kerning : activeFont.metadata.Unicode.kerning;
  11888. var kerningFractionOf = kerning.fof ? kerning.fof : 1;
  11889. var i;
  11890. var l;
  11891. var char_code;
  11892. var prior_char_code = 0; //for kerning
  11893. var default_char_width = widths[0] || widthsFractionOf;
  11894. var output = [];
  11895. for (i = 0, l = text.length; i < l; i++) {
  11896. char_code = text.charCodeAt(i);
  11897. if (typeof activeFont.metadata.widthOfString === "function") {
  11898. output.push((activeFont.metadata.widthOfGlyph(activeFont.metadata.characterToGlyph(char_code)) + charSpace * (1000 / fontSize) || 0) / 1000);
  11899. } else {
  11900. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  11901. }
  11902. prior_char_code = char_code;
  11903. }
  11904. return output;
  11905. };
  11906. /**
  11907. * Calculate the sum of a number-array
  11908. *
  11909. * @name getArraySum
  11910. * @public
  11911. * @function
  11912. * @param {Array} array Array of numbers
  11913. * @returns {number}
  11914. */
  11915. var getArraySum = API.getArraySum = function (array) {
  11916. var i = array.length,
  11917. output = 0;
  11918. while (i) {
  11919. i--;
  11920. output += array[i];
  11921. }
  11922. return output;
  11923. };
  11924. /**
  11925. * Returns a widths of string in a given font, if the font size is set as 1 point.
  11926. *
  11927. * In other words, this is "proportional" value. For 1 unit of font size, the length
  11928. * of the string will be that much.
  11929. *
  11930. * Multiply by font size to get actual width in *points*
  11931. * Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  11932. *
  11933. * @name getStringUnitWidth
  11934. * @public
  11935. * @function
  11936. * @param {string} text
  11937. * @param {string} options
  11938. * @returns {number} result
  11939. */
  11940. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  11941. options = options || {};
  11942. var fontSize = options.fontSize || this.internal.getFontSize();
  11943. var font = options.font || this.internal.getFont();
  11944. var charSpace = options.charSpace || this.internal.getCharSpace();
  11945. var result = 0;
  11946. if (typeof font.metadata.widthOfString === "function") {
  11947. result = font.metadata.widthOfString(text, fontSize, charSpace) / fontSize;
  11948. } else {
  11949. result = getArraySum(getCharWidthsArray.apply(this, arguments));
  11950. }
  11951. return result;
  11952. };
  11953. /**
  11954. returns array of lines
  11955. */
  11956. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  11957. var answer = []; // 1st, chop off the piece that can fit on the hanging line.
  11958. var i = 0,
  11959. l = word.length,
  11960. workingLen = 0;
  11961. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  11962. workingLen += widths_array[i];
  11963. i++;
  11964. } // this is first line.
  11965. answer.push(word.slice(0, i)); // 2nd. Split the rest into maxLen pieces.
  11966. var startOfLine = i;
  11967. workingLen = 0;
  11968. while (i !== l) {
  11969. if (workingLen + widths_array[i] > maxLen) {
  11970. answer.push(word.slice(startOfLine, i));
  11971. workingLen = 0;
  11972. startOfLine = i;
  11973. }
  11974. workingLen += widths_array[i];
  11975. i++;
  11976. }
  11977. if (startOfLine !== i) {
  11978. answer.push(word.slice(startOfLine, i));
  11979. }
  11980. return answer;
  11981. }; // Note, all sizing inputs for this function must be in "font measurement units"
  11982. // By default, for PDF, it's "point".
  11983. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  11984. // at this time works only on Western scripts, ones with space char
  11985. // separating the words. Feel free to expand.
  11986. if (!options) {
  11987. options = {};
  11988. }
  11989. var line = [],
  11990. lines = [line],
  11991. line_length = options.textIndent || 0,
  11992. separator_length = 0,
  11993. current_word_length = 0,
  11994. word,
  11995. widths_array,
  11996. words = text.split(' '),
  11997. spaceCharWidth = getCharWidthsArray.apply(this, [' ', options])[0],
  11998. i,
  11999. l,
  12000. tmp,
  12001. lineIndent;
  12002. if (options.lineIndent === -1) {
  12003. lineIndent = words[0].length + 2;
  12004. } else {
  12005. lineIndent = options.lineIndent || 0;
  12006. }
  12007. if (lineIndent) {
  12008. var pad = Array(lineIndent).join(" "),
  12009. wrds = [];
  12010. words.map(function (wrd) {
  12011. wrd = wrd.split(/\s*\n/);
  12012. if (wrd.length > 1) {
  12013. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  12014. return (idx && wrd.length ? "\n" : "") + wrd;
  12015. }));
  12016. } else {
  12017. wrds.push(wrd[0]);
  12018. }
  12019. });
  12020. words = wrds;
  12021. lineIndent = getStringUnitWidth.apply(this, [pad, options]);
  12022. }
  12023. for (i = 0, l = words.length; i < l; i++) {
  12024. var force = 0;
  12025. word = words[i];
  12026. if (lineIndent && word[0] == "\n") {
  12027. word = word.substr(1);
  12028. force = 1;
  12029. }
  12030. widths_array = getCharWidthsArray.apply(this, [word, options]);
  12031. current_word_length = getArraySum(widths_array);
  12032. if (line_length + separator_length + current_word_length > maxlen || force) {
  12033. if (current_word_length > maxlen) {
  12034. // this happens when you have space-less long URLs for example.
  12035. // we just chop these to size. We do NOT insert hiphens
  12036. tmp = splitLongWord.apply(this, [word, widths_array, maxlen - (line_length + separator_length), maxlen]); // first line we add to existing line object
  12037. line.push(tmp.shift()); // it's ok to have extra space indicator there
  12038. // last line we make into new line object
  12039. line = [tmp.pop()]; // lines in the middle we apped to lines object as whole lines
  12040. while (tmp.length) {
  12041. lines.push([tmp.shift()]); // single fragment occupies whole line
  12042. }
  12043. current_word_length = getArraySum(widths_array.slice(word.length - (line[0] ? line[0].length : 0)));
  12044. } else {
  12045. // just put it on a new line
  12046. line = [word];
  12047. } // now we attach new line to lines
  12048. lines.push(line);
  12049. line_length = current_word_length + lineIndent;
  12050. separator_length = spaceCharWidth;
  12051. } else {
  12052. line.push(word);
  12053. line_length += separator_length + current_word_length;
  12054. separator_length = spaceCharWidth;
  12055. }
  12056. }
  12057. if (lineIndent) {
  12058. var postProcess = function postProcess(ln, idx) {
  12059. return (idx ? pad : '') + ln.join(" ");
  12060. };
  12061. } else {
  12062. var postProcess = function postProcess(ln) {
  12063. return ln.join(" ");
  12064. };
  12065. }
  12066. return lines.map(postProcess);
  12067. };
  12068. /**
  12069. * Splits a given string into an array of strings. Uses 'size' value
  12070. * (in measurement units declared as default for the jsPDF instance)
  12071. * and the font's "widths" and "Kerning" tables, where available, to
  12072. * determine display length of a given string for a given font.
  12073. *
  12074. * We use character's 100% of unit size (height) as width when Width
  12075. * table or other default width is not available.
  12076. *
  12077. * @name splitTextToSize
  12078. * @public
  12079. * @function
  12080. * @param {string} text Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  12081. * @param {number} size Nominal number, measured in units default to this instance of jsPDF.
  12082. * @param {Object} options Optional flags needed for chopper to do the right thing.
  12083. * @returns {Array} array Array with strings chopped to size.
  12084. */
  12085. API.splitTextToSize = function (text, maxlen, options) {
  12086. options = options || {};
  12087. var fsize = options.fontSize || this.internal.getFontSize(),
  12088. newOptions = function (options) {
  12089. var widths = {
  12090. 0: 1
  12091. },
  12092. kerning = {};
  12093. if (!options.widths || !options.kerning) {
  12094. var f = this.internal.getFont(options.fontName, options.fontStyle),
  12095. encoding = 'Unicode'; // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  12096. // Actual JavaScript-native String's 16bit char codes used.
  12097. // no multi-byte logic here
  12098. if (f.metadata[encoding]) {
  12099. return {
  12100. widths: f.metadata[encoding].widths || widths,
  12101. kerning: f.metadata[encoding].kerning || kerning
  12102. };
  12103. } else {
  12104. return {
  12105. font: f.metadata,
  12106. fontSize: this.internal.getFontSize(),
  12107. charSpace: this.internal.getCharSpace()
  12108. };
  12109. }
  12110. } else {
  12111. return {
  12112. widths: options.widths,
  12113. kerning: options.kerning
  12114. };
  12115. } // then use default values
  12116. return {
  12117. widths: widths,
  12118. kerning: kerning
  12119. };
  12120. }.call(this, options); // first we split on end-of-line chars
  12121. var paragraphs;
  12122. if (Array.isArray(text)) {
  12123. paragraphs = text;
  12124. } else {
  12125. paragraphs = text.split(/\r?\n/);
  12126. } // now we convert size (max length of line) into "font size units"
  12127. // at present time, the "font size unit" is always 'point'
  12128. // 'proportional' means, "in proportion to font size"
  12129. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize; // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  12130. // this may change in the future?
  12131. // until then, proportional_maxlen is likely to be in 'points'
  12132. // If first line is to be indented (shorter or longer) than maxLen
  12133. // we indicate that by using CSS-style "text-indent" option.
  12134. // here it's in font units too (which is likely 'points')
  12135. // it can be negative (which makes the first line longer than maxLen)
  12136. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  12137. newOptions.lineIndent = options.lineIndent;
  12138. var i,
  12139. l,
  12140. output = [];
  12141. for (i = 0, l = paragraphs.length; i < l; i++) {
  12142. output = output.concat(splitParagraphIntoLines.apply(this, [paragraphs[i], fontUnit_maxLen, newOptions]));
  12143. }
  12144. return output;
  12145. };
  12146. })(jsPDF.API);
  12147. /** @license
  12148. jsPDF standard_fonts_metrics plugin
  12149. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  12150. * MIT license.
  12151. *
  12152. * ====================================================================
  12153. */
  12154. (function (API) {
  12155. /*
  12156. # reference (Python) versions of 'compress' and 'uncompress'
  12157. # only 'uncompress' function is featured lower as JavaScript
  12158. # if you want to unit test "roundtrip", just transcribe the reference
  12159. # 'compress' function from Python into JavaScript
  12160. def compress(data):
  12161. keys = '0123456789abcdef'
  12162. values = 'klmnopqrstuvwxyz'
  12163. mapping = dict(zip(keys, values))
  12164. vals = []
  12165. for key in data.keys():
  12166. value = data[key]
  12167. try:
  12168. keystring = hex(key)[2:]
  12169. keystring = keystring[:-1] + mapping[keystring[-1:]]
  12170. except:
  12171. keystring = key.join(["'","'"])
  12172. #print('Keystring is %s' % keystring)
  12173. try:
  12174. if value < 0:
  12175. valuestring = hex(value)[3:]
  12176. numberprefix = '-'
  12177. else:
  12178. valuestring = hex(value)[2:]
  12179. numberprefix = ''
  12180. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  12181. except:
  12182. if type(value) == dict:
  12183. valuestring = compress(value)
  12184. else:
  12185. raise Exception("Don't know what to do with value type %s" % type(value))
  12186. vals.append(keystring+valuestring)
  12187. return '{' + ''.join(vals) + '}'
  12188. def uncompress(data):
  12189. decoded = '0123456789abcdef'
  12190. encoded = 'klmnopqrstuvwxyz'
  12191. mapping = dict(zip(encoded, decoded))
  12192. sign = +1
  12193. stringmode = False
  12194. stringparts = []
  12195. output = {}
  12196. activeobject = output
  12197. parentchain = []
  12198. keyparts = ''
  12199. valueparts = ''
  12200. key = None
  12201. ending = set(encoded)
  12202. i = 1
  12203. l = len(data) - 1 # stripping starting, ending {}
  12204. while i != l: # stripping {}
  12205. # -, {, }, ' are special.
  12206. ch = data[i]
  12207. i += 1
  12208. if ch == "'":
  12209. if stringmode:
  12210. # end of string mode
  12211. stringmode = False
  12212. key = ''.join(stringparts)
  12213. else:
  12214. # start of string mode
  12215. stringmode = True
  12216. stringparts = []
  12217. elif stringmode == True:
  12218. #print("Adding %s to stringpart" % ch)
  12219. stringparts.append(ch)
  12220. elif ch == '{':
  12221. # start of object
  12222. parentchain.append( [activeobject, key] )
  12223. activeobject = {}
  12224. key = None
  12225. #DEBUG = True
  12226. elif ch == '}':
  12227. # end of object
  12228. parent, key = parentchain.pop()
  12229. parent[key] = activeobject
  12230. key = None
  12231. activeobject = parent
  12232. #DEBUG = False
  12233. elif ch == '-':
  12234. sign = -1
  12235. else:
  12236. # must be number
  12237. if key == None:
  12238. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  12239. if ch in ending:
  12240. #debug("End of key")
  12241. keyparts += mapping[ch]
  12242. key = int(keyparts, 16) * sign
  12243. sign = +1
  12244. keyparts = ''
  12245. else:
  12246. keyparts += ch
  12247. else:
  12248. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  12249. if ch in ending:
  12250. #debug("End of value")
  12251. valueparts += mapping[ch]
  12252. activeobject[key] = int(valueparts, 16) * sign
  12253. sign = +1
  12254. key = None
  12255. valueparts = ''
  12256. else:
  12257. valueparts += ch
  12258. #debug(activeobject)
  12259. return output
  12260. */
  12261. /**
  12262. Uncompresses data compressed into custom, base16-like format.
  12263. @public
  12264. @function
  12265. @param
  12266. @returns {Type}
  12267. */
  12268. var uncompress = function uncompress(data) {
  12269. var decoded = '0123456789abcdef',
  12270. encoded = 'klmnopqrstuvwxyz',
  12271. mapping = {};
  12272. for (var i = 0; i < encoded.length; i++) {
  12273. mapping[encoded[i]] = decoded[i];
  12274. }
  12275. var undef,
  12276. output = {},
  12277. sign = 1,
  12278. stringparts // undef. will be [] in string mode
  12279. ,
  12280. activeobject = output,
  12281. parentchain = [],
  12282. parent_key_pair,
  12283. keyparts = '',
  12284. valueparts = '',
  12285. key // undef. will be Truthy when Key is resolved.
  12286. ,
  12287. datalen = data.length - 1 // stripping ending }
  12288. ,
  12289. ch;
  12290. i = 1; // stripping starting {
  12291. while (i != datalen) {
  12292. // - { } ' are special.
  12293. ch = data[i];
  12294. i += 1;
  12295. if (ch == "'") {
  12296. if (stringparts) {
  12297. // end of string mode
  12298. key = stringparts.join('');
  12299. stringparts = undef;
  12300. } else {
  12301. // start of string mode
  12302. stringparts = [];
  12303. }
  12304. } else if (stringparts) {
  12305. stringparts.push(ch);
  12306. } else if (ch == '{') {
  12307. // start of object
  12308. parentchain.push([activeobject, key]);
  12309. activeobject = {};
  12310. key = undef;
  12311. } else if (ch == '}') {
  12312. // end of object
  12313. parent_key_pair = parentchain.pop();
  12314. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  12315. key = undef;
  12316. activeobject = parent_key_pair[0];
  12317. } else if (ch == '-') {
  12318. sign = -1;
  12319. } else {
  12320. // must be number
  12321. if (key === undef) {
  12322. if (mapping.hasOwnProperty(ch)) {
  12323. keyparts += mapping[ch];
  12324. key = parseInt(keyparts, 16) * sign;
  12325. sign = +1;
  12326. keyparts = '';
  12327. } else {
  12328. keyparts += ch;
  12329. }
  12330. } else {
  12331. if (mapping.hasOwnProperty(ch)) {
  12332. valueparts += mapping[ch];
  12333. activeobject[key] = parseInt(valueparts, 16) * sign;
  12334. sign = +1;
  12335. key = undef;
  12336. valueparts = '';
  12337. } else {
  12338. valueparts += ch;
  12339. }
  12340. }
  12341. }
  12342. } // end while
  12343. return output;
  12344. }; // encoding = 'Unicode'
  12345. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  12346. // Actual 16bit char codes used.
  12347. // no multi-byte logic here
  12348. // Unicode characters to WinAnsiEncoding:
  12349. // {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}
  12350. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  12351. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  12352. // as well as give strings with some (supported by these fonts) Unicode characters and
  12353. // these will be mapped to win cp1252
  12354. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  12355. var encodingBlock = {
  12356. 'codePages': ['WinAnsiEncoding'],
  12357. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  12358. },
  12359. encodings = {
  12360. 'Unicode': {
  12361. 'Courier': encodingBlock,
  12362. 'Courier-Bold': encodingBlock,
  12363. 'Courier-BoldOblique': encodingBlock,
  12364. 'Courier-Oblique': encodingBlock,
  12365. 'Helvetica': encodingBlock,
  12366. 'Helvetica-Bold': encodingBlock,
  12367. 'Helvetica-BoldOblique': encodingBlock,
  12368. 'Helvetica-Oblique': encodingBlock,
  12369. 'Times-Roman': encodingBlock,
  12370. 'Times-Bold': encodingBlock,
  12371. 'Times-BoldItalic': encodingBlock,
  12372. 'Times-Italic': encodingBlock // , 'Symbol'
  12373. // , 'ZapfDingbats'
  12374. }
  12375. },
  12376. fontMetrics = {
  12377. 'Unicode': {
  12378. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  12379. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  12380. // width is 476/1000 or 47.6% of its height (regardless of font size)
  12381. // At this time this value applies to "widths" and "kerning" numbers.
  12382. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  12383. // key 'fof' represents the "fontMetricsFractionOf" value
  12384. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12385. '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}}}"),
  12386. '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}}}"),
  12387. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12388. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12389. '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}}}"),
  12390. 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"),
  12391. '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}}}"),
  12392. '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}}}"),
  12393. 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),
  12394. 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12395. '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}}}"),
  12396. '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}}}"),
  12397. '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}}}")
  12398. }
  12399. };
  12400. /*
  12401. This event handler is fired when a new jsPDF object is initialized
  12402. This event handler appends metrics data to standard fonts within
  12403. that jsPDF instance. The metrics are mapped over Unicode character
  12404. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  12405. standard PDF fonts.
  12406. Future:
  12407. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  12408. char codes to StandardEncoding character codes. The encoding table is to be used
  12409. somewhere around "pdfEscape" call.
  12410. */
  12411. API.events.push(['addFont', function (data) {
  12412. var font = data.font;
  12413. var metrics,
  12414. unicode_section,
  12415. encoding = 'Unicode',
  12416. encodingBlock;
  12417. metrics = fontMetrics[encoding][font.postScriptName];
  12418. if (metrics) {
  12419. if (font.metadata[encoding]) {
  12420. unicode_section = font.metadata[encoding];
  12421. } else {
  12422. unicode_section = font.metadata[encoding] = {};
  12423. }
  12424. unicode_section.widths = metrics.widths;
  12425. unicode_section.kerning = metrics.kerning;
  12426. }
  12427. encodingBlock = encodings[encoding][font.postScriptName];
  12428. if (encodingBlock) {
  12429. if (font.metadata[encoding]) {
  12430. unicode_section = font.metadata[encoding];
  12431. } else {
  12432. unicode_section = font.metadata[encoding] = {};
  12433. }
  12434. unicode_section.encoding = encodingBlock;
  12435. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  12436. font.encoding = encodingBlock.codePages[0];
  12437. }
  12438. }
  12439. }]); // end of adding event handler
  12440. })(jsPDF.API);
  12441. /**
  12442. * @license
  12443. * Licensed under the MIT License.
  12444. * http://opensource.org/licenses/mit-license
  12445. */
  12446. /**
  12447. * @name ttfsupport
  12448. * @module
  12449. */
  12450. (function (jsPDF, global) {
  12451. jsPDF.API.events.push(['addFont', function (data) {
  12452. var font = data.font;
  12453. var instance = data.instance;
  12454. if (typeof instance !== "undefined" && instance.existsFileInVFS(font.postScriptName)) {
  12455. var file = instance.getFileFromVFS(font.postScriptName);
  12456. if (typeof file !== "string") {
  12457. throw new Error("Font is not stored as string-data in vFS, import fonts or remove declaration doc.addFont('" + font.postScriptName + "').");
  12458. }
  12459. font.metadata = jsPDF.API.TTFFont.open(font.postScriptName, font.fontName, file, font.encoding);
  12460. font.metadata.Unicode = font.metadata.Unicode || {
  12461. encoding: {},
  12462. kerning: {},
  12463. widths: []
  12464. };
  12465. font.metadata.glyIdsUsed = [0];
  12466. } else if (font.isStandardFont === false) {
  12467. throw new Error("Font does not exist in vFS, import fonts or remove declaration doc.addFont('" + font.postScriptName + "').");
  12468. }
  12469. }]); // end of adding event handler
  12470. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  12471. /** @license
  12472. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  12473. *
  12474. *
  12475. * ====================================================================
  12476. */
  12477. (function (jsPDFAPI) {
  12478. /**
  12479. * Parses SVG XML and converts only some of the SVG elements into
  12480. * PDF elements.
  12481. *
  12482. * Supports:
  12483. * paths
  12484. *
  12485. * @name addSvg
  12486. * @public
  12487. * @function
  12488. * @param {string} SVG-Data as Text
  12489. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  12490. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  12491. * @param {number} width of SVG (in units declared at inception of PDF document)
  12492. * @param {number} height of SVG (in units declared at inception of PDF document)
  12493. * @returns {Object} jsPDF-instance
  12494. */
  12495. jsPDFAPI.addSvg = function (svgtext, x, y, w, h) {
  12496. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  12497. var undef;
  12498. if (x === undef || y === undef) {
  12499. throw new Error("addSVG needs values for 'x' and 'y'");
  12500. }
  12501. function InjectCSS(cssbody, document) {
  12502. var styletag = document.createElement('style');
  12503. styletag.type = 'text/css';
  12504. if (styletag.styleSheet) {
  12505. // ie
  12506. styletag.styleSheet.cssText = cssbody;
  12507. } else {
  12508. // others
  12509. styletag.appendChild(document.createTextNode(cssbody));
  12510. }
  12511. document.getElementsByTagName("head")[0].appendChild(styletag);
  12512. }
  12513. function createWorkerNode(document) {
  12514. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  12515. ,
  12516. frame = document.createElement('iframe');
  12517. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  12518. frame.name = frameID;
  12519. frame.setAttribute("width", 0);
  12520. frame.setAttribute("height", 0);
  12521. frame.setAttribute("frameborder", "0");
  12522. frame.setAttribute("scrolling", "no");
  12523. frame.setAttribute("seamless", "seamless");
  12524. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  12525. document.body.appendChild(frame);
  12526. return frame;
  12527. }
  12528. function attachSVGToWorkerNode(svgtext, frame) {
  12529. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  12530. framedoc.write(svgtext);
  12531. framedoc.close();
  12532. return framedoc.getElementsByTagName('svg')[0];
  12533. }
  12534. function convertPathToPDFLinesArgs(path) {
  12535. // - starting coordinate pair
  12536. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  12537. // - scale array [horizontal, vertical] ratios
  12538. // - style (stroke, fill, both)
  12539. var x = parseFloat(path[1]),
  12540. y = parseFloat(path[2]),
  12541. vectors = [],
  12542. position = 3,
  12543. len = path.length;
  12544. while (position < len) {
  12545. if (path[position] === 'c') {
  12546. 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])]);
  12547. position += 7;
  12548. } else if (path[position] === 'l') {
  12549. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  12550. position += 3;
  12551. } else {
  12552. position += 1;
  12553. }
  12554. }
  12555. return [x, y, vectors];
  12556. }
  12557. var workernode = createWorkerNode(document),
  12558. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  12559. scale = [1, 1],
  12560. svgw = parseFloat(svgnode.getAttribute('width')),
  12561. svgh = parseFloat(svgnode.getAttribute('height'));
  12562. if (svgw && svgh) {
  12563. // setting both w and h makes image stretch to size.
  12564. // this may distort the image, but fits your demanded size
  12565. if (w && h) {
  12566. scale = [w / svgw, h / svgh];
  12567. } // if only one is set, that value is set as max and SVG
  12568. // is scaled proportionately.
  12569. else if (w) {
  12570. scale = [w / svgw, w / svgw];
  12571. } else if (h) {
  12572. scale = [h / svgh, h / svgh];
  12573. }
  12574. }
  12575. var i,
  12576. l,
  12577. tmp,
  12578. linesargs,
  12579. items = svgnode.childNodes;
  12580. for (i = 0, l = items.length; i < l; i++) {
  12581. tmp = items[i];
  12582. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  12583. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' ')); // path start x coordinate
  12584. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  12585. // path start y coordinate
  12586. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  12587. // the rest of lines are vectors. these will adjust with scale value auto.
  12588. this.lines.call(this, linesargs[2] // lines
  12589. , linesargs[0] // starting x
  12590. , linesargs[1] // starting y
  12591. , scale);
  12592. }
  12593. } // clean up
  12594. // workernode.parentNode.removeChild(workernode)
  12595. return this;
  12596. }; //fallback
  12597. jsPDFAPI.addSVG = jsPDFAPI.addSvg;
  12598. /**
  12599. * Parses SVG XML and saves it as image into the PDF.
  12600. *
  12601. * Depends on canvas-element and canvg
  12602. *
  12603. * @name addSvgAsImage
  12604. * @public
  12605. * @function
  12606. * @param {string} SVG-Data as Text
  12607. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  12608. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  12609. * @param {number} width of SVG-Image (in units declared at inception of PDF document)
  12610. * @param {number} height of SVG-Image (in units declared at inception of PDF document)
  12611. * @param {string} alias of SVG-Image (if used multiple times)
  12612. * @param {string} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  12613. * @param {number} rotation of the image in degrees (0-359)
  12614. *
  12615. * @returns jsPDF jsPDF-instance
  12616. */
  12617. jsPDFAPI.addSvgAsImage = function (svg, x, y, w, h, alias, compression, rotation) {
  12618. if (isNaN(x) || isNaN(y)) {
  12619. console.error('jsPDF.addSvgAsImage: Invalid coordinates', arguments);
  12620. throw new Error('Invalid coordinates passed to jsPDF.addSvgAsImage');
  12621. }
  12622. if (isNaN(w) || isNaN(h)) {
  12623. console.error('jsPDF.addSvgAsImage: Invalid measurements', arguments);
  12624. throw new Error('Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage');
  12625. }
  12626. var canvas = document.createElement('canvas');
  12627. canvas.width = w;
  12628. canvas.height = h;
  12629. var ctx = canvas.getContext('2d');
  12630. ctx.fillStyle = '#fff'; /// set white fill style
  12631. ctx.fillRect(0, 0, canvas.width, canvas.height); //load a svg snippet in the canvas with id = 'drawingArea'
  12632. canvg(canvas, svg, {
  12633. ignoreMouse: true,
  12634. ignoreAnimation: true,
  12635. ignoreDimensions: true,
  12636. ignoreClear: true
  12637. });
  12638. this.addImage(canvas.toDataURL("image/jpeg", 1.0), x, y, w, h, compression, rotation);
  12639. return this;
  12640. };
  12641. })(jsPDF.API);
  12642. /**
  12643. * @license
  12644. * ====================================================================
  12645. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  12646. *
  12647. *
  12648. * ====================================================================
  12649. */
  12650. /**
  12651. * jsPDF total_pages plugin
  12652. * @name total_pages
  12653. * @module
  12654. */
  12655. (function (jsPDFAPI) {
  12656. /**
  12657. * @name putTotalPages
  12658. * @function
  12659. * @param {string} pageExpression Regular Expression
  12660. * @returns {jsPDF} jsPDF-instance
  12661. */
  12662. jsPDFAPI.putTotalPages = function (pageExpression) {
  12663. var replaceExpression;
  12664. var totalNumberOfPages = 0;
  12665. if (parseInt(this.internal.getFont().id.substr(1), 10) < 15) {
  12666. replaceExpression = new RegExp(pageExpression, 'g');
  12667. totalNumberOfPages = this.internal.getNumberOfPages();
  12668. } else {
  12669. replaceExpression = new RegExp(this.pdfEscape16(pageExpression, this.internal.getFont()), 'g');
  12670. totalNumberOfPages = this.pdfEscape16(this.internal.getNumberOfPages() + '', this.internal.getFont());
  12671. }
  12672. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  12673. for (var i = 0; i < this.internal.pages[n].length; i++) {
  12674. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, totalNumberOfPages);
  12675. }
  12676. }
  12677. return this;
  12678. };
  12679. })(jsPDF.API);
  12680. /**
  12681. * jsPDF viewerPreferences Plugin
  12682. * @author Aras Abbasi (github.com/arasabbasi)
  12683. * Licensed under the MIT License.
  12684. * http://opensource.org/licenses/mit-license
  12685. */
  12686. /**
  12687. * Adds the ability to set ViewerPreferences and by thus
  12688. * controlling the way the document is to be presented on the
  12689. * screen or in print.
  12690. * @name viewerpreferences
  12691. * @module
  12692. */
  12693. (function (jsPDFAPI) {
  12694. /**
  12695. * Set the ViewerPreferences of the generated PDF
  12696. *
  12697. * @name viewerPreferences
  12698. * @function
  12699. * @public
  12700. * @param {Object} options Array with the ViewerPreferences<br />
  12701. * Example: doc.viewerPreferences({"FitWindow":true});<br />
  12702. * <br />
  12703. * You can set following preferences:<br />
  12704. * <br/>
  12705. * <b>HideToolbar</b> <i>(boolean)</i><br />
  12706. * Default value: false<br />
  12707. * <br />
  12708. * <b>HideMenubar</b> <i>(boolean)</i><br />
  12709. * Default value: false.<br />
  12710. * <br />
  12711. * <b>HideWindowUI</b> <i>(boolean)</i><br />
  12712. * Default value: false.<br />
  12713. * <br />
  12714. * <b>FitWindow</b> <i>(boolean)</i><br />
  12715. * Default value: false.<br />
  12716. * <br />
  12717. * <b>CenterWindow</b> <i>(boolean)</i><br />
  12718. * Default value: false<br />
  12719. * <br />
  12720. * <b>DisplayDocTitle</b> <i>(boolean)</i><br />
  12721. * Default value: false.<br />
  12722. * <br />
  12723. * <b>NonFullScreenPageMode</b> <i>(string)</i><br />
  12724. * Possible values: UseNone, UseOutlines, UseThumbs, UseOC<br />
  12725. * Default value: UseNone<br/>
  12726. * <br />
  12727. * <b>Direction</b> <i>(string)</i><br />
  12728. * Possible values: L2R, R2L<br />
  12729. * Default value: L2R.<br />
  12730. * <br />
  12731. * <b>ViewArea</b> <i>(string)</i><br />
  12732. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12733. * Default value: CropBox.<br />
  12734. * <br />
  12735. * <b>ViewClip</b> <i>(string)</i><br />
  12736. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12737. * Default value: CropBox<br />
  12738. * <br />
  12739. * <b>PrintArea</b> <i>(string)</i><br />
  12740. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12741. * Default value: CropBox<br />
  12742. * <br />
  12743. * <b>PrintClip</b> <i>(string)</i><br />
  12744. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12745. * Default value: CropBox.<br />
  12746. * <br />
  12747. * <b>PrintScaling</b> <i>(string)</i><br />
  12748. * Possible values: AppDefault, None<br />
  12749. * Default value: AppDefault.<br />
  12750. * <br />
  12751. * <b>Duplex</b> <i>(string)</i><br />
  12752. * Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge
  12753. * Default value: none<br />
  12754. * <br />
  12755. * <b>PickTrayByPDFSize</b> <i>(boolean)</i><br />
  12756. * Default value: false<br />
  12757. * <br />
  12758. * <b>PrintPageRange</b> <i>(Array)</i><br />
  12759. * Example: [[1,5], [7,9]]<br />
  12760. * Default value: as defined by PDF viewer application<br />
  12761. * <br />
  12762. * <b>NumCopies</b> <i>(Number)</i><br />
  12763. * Possible values: 1, 2, 3, 4, 5<br />
  12764. * Default value: 1<br />
  12765. * <br />
  12766. * For more information see the PDF Reference, sixth edition on Page 577
  12767. * @param {boolean} doReset True to reset the settings
  12768. * @function
  12769. * @returns jsPDF jsPDF-instance
  12770. * @example
  12771. * var doc = new jsPDF()
  12772. * doc.text('This is a test', 10, 10)
  12773. * doc.viewerPreferences({'FitWindow': true}, true)
  12774. * doc.save("viewerPreferences.pdf")
  12775. *
  12776. * // Example printing 10 copies, using cropbox, and hiding UI.
  12777. * doc.viewerPreferences({
  12778. * 'HideWindowUI': true,
  12779. * 'PrintArea': 'CropBox',
  12780. * 'NumCopies': 10
  12781. * })
  12782. */
  12783. jsPDFAPI.viewerPreferences = function (options, doReset) {
  12784. options = options || {};
  12785. doReset = doReset || false;
  12786. var configuration;
  12787. var configurationTemplate = {
  12788. "HideToolbar": {
  12789. defaultValue: false,
  12790. value: false,
  12791. type: "boolean",
  12792. explicitSet: false,
  12793. valueSet: [true, false],
  12794. pdfVersion: 1.3
  12795. },
  12796. "HideMenubar": {
  12797. defaultValue: false,
  12798. value: false,
  12799. type: "boolean",
  12800. explicitSet: false,
  12801. valueSet: [true, false],
  12802. pdfVersion: 1.3
  12803. },
  12804. "HideWindowUI": {
  12805. defaultValue: false,
  12806. value: false,
  12807. type: "boolean",
  12808. explicitSet: false,
  12809. valueSet: [true, false],
  12810. pdfVersion: 1.3
  12811. },
  12812. "FitWindow": {
  12813. defaultValue: false,
  12814. value: false,
  12815. type: "boolean",
  12816. explicitSet: false,
  12817. valueSet: [true, false],
  12818. pdfVersion: 1.3
  12819. },
  12820. "CenterWindow": {
  12821. defaultValue: false,
  12822. value: false,
  12823. type: "boolean",
  12824. explicitSet: false,
  12825. valueSet: [true, false],
  12826. pdfVersion: 1.3
  12827. },
  12828. "DisplayDocTitle": {
  12829. defaultValue: false,
  12830. value: false,
  12831. type: "boolean",
  12832. explicitSet: false,
  12833. valueSet: [true, false],
  12834. pdfVersion: 1.4
  12835. },
  12836. "NonFullScreenPageMode": {
  12837. defaultValue: "UseNone",
  12838. value: "UseNone",
  12839. type: "name",
  12840. explicitSet: false,
  12841. valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"],
  12842. pdfVersion: 1.3
  12843. },
  12844. "Direction": {
  12845. defaultValue: "L2R",
  12846. value: "L2R",
  12847. type: "name",
  12848. explicitSet: false,
  12849. valueSet: ["L2R", "R2L"],
  12850. pdfVersion: 1.3
  12851. },
  12852. "ViewArea": {
  12853. defaultValue: "CropBox",
  12854. value: "CropBox",
  12855. type: "name",
  12856. explicitSet: false,
  12857. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12858. pdfVersion: 1.4
  12859. },
  12860. "ViewClip": {
  12861. defaultValue: "CropBox",
  12862. value: "CropBox",
  12863. type: "name",
  12864. explicitSet: false,
  12865. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12866. pdfVersion: 1.4
  12867. },
  12868. "PrintArea": {
  12869. defaultValue: "CropBox",
  12870. value: "CropBox",
  12871. type: "name",
  12872. explicitSet: false,
  12873. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12874. pdfVersion: 1.4
  12875. },
  12876. "PrintClip": {
  12877. defaultValue: "CropBox",
  12878. value: "CropBox",
  12879. type: "name",
  12880. explicitSet: false,
  12881. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12882. pdfVersion: 1.4
  12883. },
  12884. "PrintScaling": {
  12885. defaultValue: "AppDefault",
  12886. value: "AppDefault",
  12887. type: "name",
  12888. explicitSet: false,
  12889. valueSet: ["AppDefault", "None"],
  12890. pdfVersion: 1.6
  12891. },
  12892. "Duplex": {
  12893. defaultValue: "",
  12894. value: "none",
  12895. type: "name",
  12896. explicitSet: false,
  12897. valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"],
  12898. pdfVersion: 1.7
  12899. },
  12900. "PickTrayByPDFSize": {
  12901. defaultValue: false,
  12902. value: false,
  12903. type: "boolean",
  12904. explicitSet: false,
  12905. valueSet: [true, false],
  12906. pdfVersion: 1.7
  12907. },
  12908. "PrintPageRange": {
  12909. defaultValue: "",
  12910. value: "",
  12911. type: "array",
  12912. explicitSet: false,
  12913. valueSet: null,
  12914. pdfVersion: 1.7
  12915. },
  12916. "NumCopies": {
  12917. defaultValue: 1,
  12918. value: 1,
  12919. type: "integer",
  12920. explicitSet: false,
  12921. valueSet: null,
  12922. pdfVersion: 1.7
  12923. }
  12924. };
  12925. var configurationKeys = Object.keys(configurationTemplate);
  12926. var rangeArray = [];
  12927. var i = 0;
  12928. var j = 0;
  12929. var k = 0;
  12930. var isValid = true;
  12931. var method;
  12932. var value;
  12933. function arrayContainsElement(array, element) {
  12934. var iterator;
  12935. var result = false;
  12936. for (iterator = 0; iterator < array.length; iterator += 1) {
  12937. if (array[iterator] === element) {
  12938. result = true;
  12939. }
  12940. }
  12941. return result;
  12942. }
  12943. if (this.internal.viewerpreferences === undefined) {
  12944. this.internal.viewerpreferences = {};
  12945. this.internal.viewerpreferences.configuration = JSON.parse(JSON.stringify(configurationTemplate));
  12946. this.internal.viewerpreferences.isSubscribed = false;
  12947. }
  12948. configuration = this.internal.viewerpreferences.configuration;
  12949. if (options === "reset" || doReset === true) {
  12950. var len = configurationKeys.length;
  12951. for (k = 0; k < len; k += 1) {
  12952. configuration[configurationKeys[k]].value = configuration[configurationKeys[k]].defaultValue;
  12953. configuration[configurationKeys[k]].explicitSet = false;
  12954. }
  12955. }
  12956. if (_typeof(options) === "object") {
  12957. for (method in options) {
  12958. value = options[method];
  12959. if (arrayContainsElement(configurationKeys, method) && value !== undefined) {
  12960. if (configuration[method].type === "boolean" && typeof value === "boolean") {
  12961. configuration[method].value = value;
  12962. } else if (configuration[method].type === "name" && arrayContainsElement(configuration[method].valueSet, value)) {
  12963. configuration[method].value = value;
  12964. } else if (configuration[method].type === "integer" && Number.isInteger(value)) {
  12965. configuration[method].value = value;
  12966. } else if (configuration[method].type === "array") {
  12967. for (i = 0; i < value.length; i += 1) {
  12968. isValid = true;
  12969. if (value[i].length === 1 && typeof value[i][0] === "number") {
  12970. rangeArray.push(String(value[i] - 1));
  12971. } else if (value[i].length > 1) {
  12972. for (j = 0; j < value[i].length; j += 1) {
  12973. if (typeof value[i][j] !== "number") {
  12974. isValid = false;
  12975. }
  12976. }
  12977. if (isValid === true) {
  12978. rangeArray.push([value[i][0] - 1, value[i][1] - 1].join(" "));
  12979. }
  12980. }
  12981. }
  12982. configuration[method].value = "[" + rangeArray.join(" ") + "]";
  12983. } else {
  12984. configuration[method].value = configuration[method].defaultValue;
  12985. }
  12986. configuration[method].explicitSet = true;
  12987. }
  12988. }
  12989. }
  12990. if (this.internal.viewerpreferences.isSubscribed === false) {
  12991. this.internal.events.subscribe("putCatalog", function () {
  12992. var pdfDict = [];
  12993. var vPref;
  12994. for (vPref in configuration) {
  12995. if (configuration[vPref].explicitSet === true) {
  12996. if (configuration[vPref].type === "name") {
  12997. pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
  12998. } else {
  12999. pdfDict.push("/" + vPref + " " + configuration[vPref].value);
  13000. }
  13001. }
  13002. }
  13003. if (pdfDict.length !== 0) {
  13004. this.internal.write("/ViewerPreferences\n<<\n" + pdfDict.join("\n") + "\n>>");
  13005. }
  13006. });
  13007. this.internal.viewerpreferences.isSubscribed = true;
  13008. }
  13009. this.internal.viewerpreferences.configuration = configuration;
  13010. return this;
  13011. };
  13012. })(jsPDF.API);
  13013. /** ====================================================================
  13014. * jsPDF XMP metadata plugin
  13015. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  13016. *
  13017. *
  13018. * ====================================================================
  13019. */
  13020. /*global jsPDF */
  13021. /**
  13022. * @name xmp_metadata
  13023. * @module
  13024. */
  13025. (function (jsPDFAPI) {
  13026. var xmpmetadata = "";
  13027. var xmpnamespaceuri = "";
  13028. var metadata_object_number = "";
  13029. /**
  13030. * Adds XMP formatted metadata to PDF
  13031. *
  13032. * @name addMetadata
  13033. * @function
  13034. * @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.
  13035. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  13036. * @returns {jsPDF} jsPDF-instance
  13037. */
  13038. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  13039. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  13040. xmpmetadata = metadata;
  13041. this.internal.events.subscribe('postPutResources', function () {
  13042. if (!xmpmetadata) {
  13043. metadata_object_number = "";
  13044. } else {
  13045. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  13046. 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>';
  13047. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  13048. var xmpmeta_ending = '</x:xmpmeta>';
  13049. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  13050. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  13051. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  13052. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  13053. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  13054. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  13055. metadata_object_number = this.internal.newObject();
  13056. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  13057. this.internal.write('stream');
  13058. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  13059. this.internal.write('endstream');
  13060. this.internal.write('endobj');
  13061. }
  13062. });
  13063. this.internal.events.subscribe('putCatalog', function () {
  13064. if (metadata_object_number) {
  13065. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  13066. }
  13067. });
  13068. return this;
  13069. };
  13070. })(jsPDF.API);
  13071. /**
  13072. * @name utf8
  13073. * @module
  13074. */
  13075. (function (jsPDF, global) {
  13076. var jsPDFAPI = jsPDF.API;
  13077. /**************************************************/
  13078. /* function : toHex */
  13079. /* comment : Replace str with a hex string. */
  13080. /**************************************************/
  13081. function toHex(str) {
  13082. var hex = '';
  13083. for (var i = 0; i < str.length; i++) {
  13084. hex += '' + str.charCodeAt(i).toString(16);
  13085. }
  13086. return hex;
  13087. }
  13088. /***************************************************************************************************/
  13089. /* function : pdfEscape16 */
  13090. /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
  13091. /* the corresponding glyph id and width, and then adding padding to the string. */
  13092. /***************************************************************************************************/
  13093. var pdfEscape16 = jsPDFAPI.pdfEscape16 = function (text, font) {
  13094. var widths = font.metadata.Unicode.widths;
  13095. var padz = ["", "0", "00", "000", "0000"];
  13096. var ar = [""];
  13097. for (var i = 0, l = text.length, t; i < l; ++i) {
  13098. t = font.metadata.characterToGlyph(text.charCodeAt(i));
  13099. font.metadata.glyIdsUsed.push(t);
  13100. font.metadata.toUnicode[t] = text.charCodeAt(i);
  13101. if (widths.indexOf(t) == -1) {
  13102. widths.push(t);
  13103. widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
  13104. }
  13105. if (t == '0') {
  13106. //Spaces are not allowed in cmap.
  13107. return ar.join("");
  13108. } else {
  13109. t = t.toString(16);
  13110. ar.push(padz[4 - t.length], t);
  13111. }
  13112. }
  13113. return ar.join("");
  13114. };
  13115. var toUnicodeCmap = function toUnicodeCmap(map) {
  13116. var code, codes, range, unicode, unicodeMap, _i, _len;
  13117. unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange';
  13118. codes = Object.keys(map).sort(function (a, b) {
  13119. return a - b;
  13120. });
  13121. range = [];
  13122. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  13123. code = codes[_i];
  13124. if (range.length >= 100) {
  13125. unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar";
  13126. range = [];
  13127. }
  13128. unicode = ('0000' + map[code].toString(16)).slice(-4);
  13129. code = ('0000' + (+code).toString(16)).slice(-4);
  13130. range.push("<" + code + "><" + unicode + ">");
  13131. }
  13132. if (range.length) {
  13133. unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar\n";
  13134. }
  13135. unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
  13136. return unicodeMap;
  13137. };
  13138. var identityHFunction = function identityHFunction(font, out, newObject, putStream) {
  13139. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'Identity-H') {
  13140. //Tag with Identity-H
  13141. var widths = font.metadata.Unicode.widths;
  13142. var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
  13143. var pdfOutput = data;
  13144. var pdfOutput2 = "";
  13145. for (var i = 0; i < pdfOutput.length; i++) {
  13146. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  13147. }
  13148. var fontTable = newObject();
  13149. putStream({
  13150. data: pdfOutput2,
  13151. addLength1: true
  13152. });
  13153. out('endobj');
  13154. var cmap = newObject();
  13155. var cmapData = toUnicodeCmap(font.metadata.toUnicode);
  13156. putStream({
  13157. data: cmapData,
  13158. addLength1: true
  13159. });
  13160. out('endobj');
  13161. var fontDescriptor = newObject();
  13162. out('<<');
  13163. out('/Type /FontDescriptor');
  13164. out('/FontName /' + font.fontName);
  13165. out('/FontFile2 ' + fontTable + ' 0 R');
  13166. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  13167. out('/Flags ' + font.metadata.flags);
  13168. out('/StemV ' + font.metadata.stemV);
  13169. out('/ItalicAngle ' + font.metadata.italicAngle);
  13170. out('/Ascent ' + font.metadata.ascender);
  13171. out('/Descent ' + font.metadata.decender);
  13172. out('/CapHeight ' + font.metadata.capHeight);
  13173. out('>>');
  13174. out('endobj');
  13175. var DescendantFont = newObject();
  13176. out('<<');
  13177. out('/Type /Font');
  13178. out('/BaseFont /' + font.fontName);
  13179. out('/FontDescriptor ' + fontDescriptor + ' 0 R');
  13180. out('/W ' + jsPDF.API.PDFObject.convert(widths));
  13181. out('/CIDToGIDMap /Identity');
  13182. out('/DW 1000');
  13183. out('/Subtype /CIDFontType2');
  13184. out('/CIDSystemInfo');
  13185. out('<<');
  13186. out('/Supplement 0');
  13187. out('/Registry (Adobe)');
  13188. out('/Ordering (' + font.encoding + ')');
  13189. out('>>');
  13190. out('>>');
  13191. out('endobj');
  13192. font.objectNumber = newObject();
  13193. out('<<');
  13194. out('/Type /Font');
  13195. out('/Subtype /Type0');
  13196. out('/ToUnicode ' + cmap + ' 0 R');
  13197. out('/BaseFont /' + font.fontName);
  13198. out('/Encoding /' + font.encoding);
  13199. out('/DescendantFonts [' + DescendantFont + ' 0 R]');
  13200. out('>>');
  13201. out('endobj');
  13202. font.isAlreadyPutted = true;
  13203. }
  13204. };
  13205. jsPDFAPI.events.push(['putFont', function (args) {
  13206. identityHFunction(args.font, args.out, args.newObject, args.putStream);
  13207. }]);
  13208. var winAnsiEncodingFunction = function winAnsiEncodingFunction(font, out, newObject, putStream) {
  13209. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'WinAnsiEncoding') {
  13210. //Tag with WinAnsi encoding
  13211. var widths = font.metadata.Unicode.widths;
  13212. var data = font.metadata.rawData;
  13213. var pdfOutput = data;
  13214. var pdfOutput2 = "";
  13215. for (var i = 0; i < pdfOutput.length; i++) {
  13216. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  13217. }
  13218. var fontTable = newObject();
  13219. putStream({
  13220. data: pdfOutput2,
  13221. addLength1: true
  13222. });
  13223. out('endobj');
  13224. var cmap = newObject();
  13225. var cmapData = toUnicodeCmap(font.metadata.toUnicode);
  13226. putStream({
  13227. data: cmapData,
  13228. addLength1: true
  13229. });
  13230. out('endobj');
  13231. var fontDescriptor = newObject();
  13232. out('<<');
  13233. out('/Descent ' + font.metadata.decender);
  13234. out('/CapHeight ' + font.metadata.capHeight);
  13235. out('/StemV ' + font.metadata.stemV);
  13236. out('/Type /FontDescriptor');
  13237. out('/FontFile2 ' + fontTable + ' 0 R');
  13238. out('/Flags 96');
  13239. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  13240. out('/FontName /' + font.fontName);
  13241. out('/ItalicAngle ' + font.metadata.italicAngle);
  13242. out('/Ascent ' + font.metadata.ascender);
  13243. out('>>');
  13244. out('endobj');
  13245. font.objectNumber = newObject();
  13246. for (var i = 0; i < font.metadata.hmtx.widths.length; i++) {
  13247. 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.
  13248. }
  13249. out('<</Subtype/TrueType/Type/Font/ToUnicode ' + cmap + ' 0 R/BaseFont/' + font.fontName + '/FontDescriptor ' + fontDescriptor + ' 0 R' + '/Encoding/' + font.encoding + ' /FirstChar 29 /LastChar 255 /Widths ' + jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) + '>>');
  13250. out('endobj');
  13251. font.isAlreadyPutted = true;
  13252. }
  13253. };
  13254. jsPDFAPI.events.push(['putFont', function (args) {
  13255. winAnsiEncodingFunction(args.font, args.out, args.newObject, args.putStream);
  13256. }]);
  13257. var utf8TextFunction = function utf8TextFunction(args) {
  13258. var text = args.text || '';
  13259. var x = args.x;
  13260. var y = args.y;
  13261. var options = args.options || {};
  13262. var mutex = args.mutex || {};
  13263. var pdfEscape = mutex.pdfEscape;
  13264. var activeFontKey = mutex.activeFontKey;
  13265. var fonts = mutex.fonts;
  13266. var key,
  13267. fontSize = mutex.activeFontSize;
  13268. var str = '',
  13269. s = 0,
  13270. cmapConfirm;
  13271. var strText = '';
  13272. var key = activeFontKey;
  13273. var encoding = fonts[key].encoding;
  13274. if (fonts[key].encoding !== 'Identity-H') {
  13275. return {
  13276. text: text,
  13277. x: x,
  13278. y: y,
  13279. options: options,
  13280. mutex: mutex
  13281. };
  13282. }
  13283. strText = text;
  13284. key = activeFontKey;
  13285. if (Object.prototype.toString.call(text) === '[object Array]') {
  13286. strText = text[0];
  13287. }
  13288. for (s = 0; s < strText.length; s += 1) {
  13289. if (fonts[key].metadata.hasOwnProperty('cmap')) {
  13290. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
  13291. /*
  13292. if (Object.prototype.toString.call(text) === '[object Array]') {
  13293. var i = 0;
  13294. // for (i = 0; i < text.length; i += 1) {
  13295. if (Object.prototype.toString.call(text[s]) === '[object Array]') {
  13296. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  13297. } else {
  13298. }
  13299. //}
  13300. } else {
  13301. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  13302. }*/
  13303. }
  13304. if (!cmapConfirm) {
  13305. if (strText[s].charCodeAt(0) < 256 && fonts[key].metadata.hasOwnProperty('Unicode')) {
  13306. str += strText[s];
  13307. } else {
  13308. str += '';
  13309. }
  13310. } else {
  13311. str += strText[s];
  13312. }
  13313. }
  13314. var result = '';
  13315. if (parseInt(key.slice(1)) < 14 || encoding === 'WinAnsiEncoding') {
  13316. //For the default 13 font
  13317. result = toHex(pdfEscape(str, key));
  13318. } else if (encoding === 'Identity-H') {
  13319. result = pdfEscape16(str, fonts[key]);
  13320. }
  13321. mutex.isHex = true;
  13322. return {
  13323. text: result,
  13324. x: x,
  13325. y: y,
  13326. options: options,
  13327. mutex: mutex
  13328. };
  13329. };
  13330. var utf8EscapeFunction = function utf8EscapeFunction(parms) {
  13331. var text = parms.text || '',
  13332. x = parms.x,
  13333. y = parms.y,
  13334. options = parms.options,
  13335. mutex = parms.mutex;
  13336. var lang = options.lang;
  13337. var tmpText = [];
  13338. var args = {
  13339. text: text,
  13340. x: x,
  13341. y: y,
  13342. options: options,
  13343. mutex: mutex
  13344. };
  13345. if (Object.prototype.toString.call(text) === '[object Array]') {
  13346. var i = 0;
  13347. for (i = 0; i < text.length; i += 1) {
  13348. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  13349. if (text[i].length === 3) {
  13350. tmpText.push([utf8TextFunction(Object.assign({}, args, {
  13351. text: text[i][0]
  13352. })).text, text[i][1], text[i][2]]);
  13353. } else {
  13354. tmpText.push(utf8TextFunction(Object.assign({}, args, {
  13355. text: text[i]
  13356. })).text);
  13357. }
  13358. } else {
  13359. tmpText.push(utf8TextFunction(Object.assign({}, args, {
  13360. text: text[i]
  13361. })).text);
  13362. }
  13363. }
  13364. parms.text = tmpText;
  13365. } else {
  13366. parms.text = utf8TextFunction(Object.assign({}, args, {
  13367. text: text
  13368. })).text;
  13369. }
  13370. };
  13371. jsPDFAPI.events.push(['postProcessText', utf8EscapeFunction]);
  13372. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  13373. /**
  13374. * jsPDF virtual FileSystem functionality
  13375. *
  13376. * Licensed under the MIT License.
  13377. * http://opensource.org/licenses/mit-license
  13378. */
  13379. /**
  13380. * Use the vFS to handle files
  13381. *
  13382. * @name vFS
  13383. * @module
  13384. */
  13385. (function (jsPDFAPI) {
  13386. var _initializeVFS = function _initializeVFS(instance) {
  13387. if (typeof instance === "undefined") {
  13388. return false;
  13389. }
  13390. if (typeof instance.vFS === "undefined") {
  13391. instance.vFS = {};
  13392. }
  13393. return true;
  13394. };
  13395. /**
  13396. * Check if the file exists in the vFS
  13397. *
  13398. * @name existsFileInVFS
  13399. * @function
  13400. * @param {string} Possible filename in the vFS.
  13401. * @returns {boolean}
  13402. * @example
  13403. * doc.existsFileInVFS("someFile.txt");
  13404. */
  13405. jsPDFAPI.existsFileInVFS = function (filename) {
  13406. if (_initializeVFS(this.internal)) {
  13407. return typeof this.internal.vFS[filename] !== "undefined";
  13408. }
  13409. return false;
  13410. };
  13411. /**
  13412. * Add a file to the vFS
  13413. *
  13414. * @name addFileToVFS
  13415. * @function
  13416. * @param {string} filename The name of the file which should be added.
  13417. * @param {string} filecontent The content of the file.
  13418. * @returns {jsPDF}
  13419. * @example
  13420. * doc.addFileToVFS("someFile.txt", "BADFACE1");
  13421. */
  13422. jsPDFAPI.addFileToVFS = function (filename, filecontent) {
  13423. _initializeVFS(this.internal);
  13424. this.internal.vFS[filename] = filecontent;
  13425. return this;
  13426. };
  13427. /**
  13428. * Get the file from the vFS
  13429. *
  13430. * @name getFileFromVFS
  13431. * @function
  13432. * @param {string} The name of the file which gets requested.
  13433. * @returns {string}
  13434. * @example
  13435. * doc.getFileFromVFS("someFile.txt");
  13436. */
  13437. jsPDFAPI.getFileFromVFS = function (filename) {
  13438. _initializeVFS(this.internal);
  13439. if (typeof this.internal.vFS[filename] !== "undefined") {
  13440. return this.internal.vFS[filename];
  13441. }
  13442. return null;
  13443. };
  13444. })(jsPDF.API);
  13445. /**
  13446. * jsPDF addHTML PlugIn
  13447. * Copyright (c) 2014 Diego Casorran
  13448. *
  13449. * Licensed under the MIT License.
  13450. * http://opensource.org/licenses/mit-license
  13451. */
  13452. (function (jsPDFAPI) {
  13453. /**
  13454. * Renders an HTML element to canvas object which added to the PDF
  13455. *
  13456. * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
  13457. * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
  13458. *
  13459. * @returns {jsPDF}
  13460. * @name addHTML
  13461. * @param element {Mixed} HTML Element, or anything supported by html2canvas.
  13462. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  13463. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  13464. * @param options {Object} Additional options, check the code below.
  13465. * @param callback {Function} to call when the rendering has finished.
  13466. * NOTE: Every parameter is optional except 'element' and 'callback', in such
  13467. * case the image is positioned at 0x0 covering the whole PDF document
  13468. * size. Ie, to easily take screenshots of webpages saving them to PDF.
  13469. * @deprecated This is being replace with a vector-supporting API. See
  13470. * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
  13471. */
  13472. jsPDFAPI.addHTML = function (element, x, y, options, callback) {
  13473. 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');
  13474. if (typeof x !== 'number') {
  13475. options = x;
  13476. callback = y;
  13477. }
  13478. if (typeof options === 'function') {
  13479. callback = options;
  13480. options = null;
  13481. }
  13482. if (typeof callback !== 'function') {
  13483. callback = function callback() {};
  13484. }
  13485. var I = this.internal,
  13486. K = I.scaleFactor,
  13487. W = I.pageSize.getWidth(),
  13488. H = I.pageSize.getHeight();
  13489. options = options || {};
  13490. options.onrendered = function (obj) {
  13491. x = parseInt(x) || 0;
  13492. y = parseInt(y) || 0;
  13493. var dim = options.dim || {};
  13494. var margin = Object.assign({
  13495. top: 0,
  13496. right: 0,
  13497. bottom: 0,
  13498. left: 0,
  13499. useFor: 'content'
  13500. }, options.margin);
  13501. var h = dim.h || Math.min(H, obj.height / K);
  13502. var w = dim.w || Math.min(W, obj.width / K) - x;
  13503. var format = options.format || 'JPEG';
  13504. var imageCompression = options.imageCompression || 'SLOW';
  13505. var notFittingHeight = obj.height > H - margin.top - margin.bottom;
  13506. if (notFittingHeight && options.pagesplit) {
  13507. var cropArea = function cropArea(parmObj, parmX, parmY, parmWidth, parmHeight) {
  13508. var canvas = document.createElement('canvas');
  13509. canvas.height = parmHeight;
  13510. canvas.width = parmWidth;
  13511. var ctx = canvas.getContext('2d');
  13512. ctx.mozImageSmoothingEnabled = false;
  13513. ctx.webkitImageSmoothingEnabled = false;
  13514. ctx.msImageSmoothingEnabled = false;
  13515. ctx.imageSmoothingEnabled = false;
  13516. ctx.fillStyle = options.backgroundColor || '#ffffff';
  13517. ctx.fillRect(0, 0, parmWidth, parmHeight);
  13518. ctx.drawImage(parmObj, parmX, parmY, parmWidth, parmHeight, 0, 0, parmWidth, parmHeight);
  13519. return canvas;
  13520. };
  13521. var crop = function () {
  13522. var cy = 0;
  13523. var cx = 0;
  13524. var position = {};
  13525. var isOverWide = false;
  13526. var width;
  13527. var height;
  13528. while (1) {
  13529. cx = 0;
  13530. position.top = cy !== 0 ? margin.top : y;
  13531. position.left = cy !== 0 ? margin.left : x;
  13532. isOverWide = (W - margin.left - margin.right) * K < obj.width;
  13533. if (margin.useFor === "content") {
  13534. if (cy === 0) {
  13535. width = Math.min((W - margin.left) * K, obj.width);
  13536. height = Math.min((H - margin.top) * K, obj.height - cy);
  13537. } else {
  13538. width = Math.min(W * K, obj.width);
  13539. height = Math.min(H * K, obj.height - cy);
  13540. position.top = 0;
  13541. }
  13542. } else {
  13543. width = Math.min((W - margin.left - margin.right) * K, obj.width);
  13544. height = Math.min((H - margin.bottom - margin.top) * K, obj.height - cy);
  13545. }
  13546. if (isOverWide) {
  13547. while (1) {
  13548. if (margin.useFor === "content") {
  13549. if (cx === 0) {
  13550. width = Math.min((W - margin.left) * K, obj.width);
  13551. } else {
  13552. width = Math.min(W * K, obj.width - cx);
  13553. position.left = 0;
  13554. }
  13555. }
  13556. var canvas = cropArea(obj, cx, cy, width, height);
  13557. var args = [canvas, position.left, position.top, canvas.width / K, canvas.height / K, format, null, imageCompression];
  13558. this.addImage.apply(this, args);
  13559. cx += width;
  13560. if (cx >= obj.width) {
  13561. break;
  13562. }
  13563. this.addPage();
  13564. }
  13565. } else {
  13566. var canvas = cropArea(obj, 0, cy, width, height);
  13567. var args = [canvas, position.left, position.top, canvas.width / K, canvas.height / K, format, null, imageCompression];
  13568. this.addImage.apply(this, args);
  13569. }
  13570. cy += height;
  13571. if (cy >= obj.height) {
  13572. break;
  13573. }
  13574. this.addPage();
  13575. }
  13576. callback(w, cy, null, args);
  13577. }.bind(this);
  13578. if (obj.nodeName === 'CANVAS') {
  13579. var img = new Image();
  13580. img.onload = crop;
  13581. img.src = obj.toDataURL("image/png");
  13582. obj = img;
  13583. } else {
  13584. crop();
  13585. }
  13586. } else {
  13587. var alias = Math.random().toString(35);
  13588. var args = [obj, x, y, w, h, format, alias, imageCompression];
  13589. this.addImage.apply(this, args);
  13590. callback(w, h, alias, args);
  13591. }
  13592. }.bind(this);
  13593. if (typeof html2canvas !== 'undefined' && !options.rstz) {
  13594. return html2canvas(element, options);
  13595. }
  13596. if (typeof rasterizeHTML !== 'undefined') {
  13597. var meth = 'drawDocument';
  13598. if (typeof element === 'string') {
  13599. meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
  13600. }
  13601. options.width = options.width || W * K;
  13602. return rasterizeHTML[meth](element, void 0, options).then(function (r) {
  13603. options.onrendered(r.image);
  13604. }, function (e) {
  13605. callback(null, e);
  13606. });
  13607. }
  13608. return null;
  13609. };
  13610. })(jsPDF.API);
  13611. /**
  13612. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  13613. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  13614. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  13615. * 2014 Diego Casorran, https://github.com/diegocr
  13616. * 2014 Daniel Husar, https://github.com/danielhusar
  13617. * 2014 Wolfgang Gassler, https://github.com/woolfg
  13618. * 2014 Steven Spungin, https://github.com/flamenco
  13619. *
  13620. * @license
  13621. *
  13622. * ====================================================================
  13623. */
  13624. (function (jsPDFAPI) {
  13625. var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
  13626. clone = function () {
  13627. return function (obj) {
  13628. Clone.prototype = obj;
  13629. return new Clone();
  13630. };
  13631. function Clone() {}
  13632. }();
  13633. PurgeWhiteSpace = function PurgeWhiteSpace(array) {
  13634. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  13635. i = 0;
  13636. l = array.length;
  13637. fragment = void 0;
  13638. lTrimmed = false;
  13639. rTrimmed = false;
  13640. while (!lTrimmed && i !== l) {
  13641. fragment = array[i] = array[i].trimLeft();
  13642. if (fragment) {
  13643. lTrimmed = true;
  13644. }
  13645. i++;
  13646. }
  13647. i = l - 1;
  13648. while (l && !rTrimmed && i !== -1) {
  13649. fragment = array[i] = array[i].trimRight();
  13650. if (fragment) {
  13651. rTrimmed = true;
  13652. }
  13653. i--;
  13654. }
  13655. r = /\s+$/g;
  13656. trailingSpace = true;
  13657. i = 0;
  13658. while (i !== l) {
  13659. // Leave the line breaks intact
  13660. if (array[i] != "\u2028") {
  13661. fragment = array[i].replace(/\s+/g, " ");
  13662. if (trailingSpace) {
  13663. fragment = fragment.trimLeft();
  13664. }
  13665. if (fragment) {
  13666. trailingSpace = r.test(fragment);
  13667. }
  13668. array[i] = fragment;
  13669. }
  13670. i++;
  13671. }
  13672. return array;
  13673. };
  13674. Renderer = function Renderer(pdf, x, y, settings) {
  13675. this.pdf = pdf;
  13676. this.x = x;
  13677. this.y = y;
  13678. this.settings = settings; //list of functions which are called after each element-rendering process
  13679. this.watchFunctions = [];
  13680. this.init();
  13681. return this;
  13682. };
  13683. ResolveFont = function ResolveFont(css_font_family_string) {
  13684. var name, part, parts;
  13685. name = void 0;
  13686. parts = css_font_family_string.split(",");
  13687. part = parts.shift();
  13688. while (!name && part) {
  13689. name = FontNameDB[part.trim().toLowerCase()];
  13690. part = parts.shift();
  13691. }
  13692. return name;
  13693. };
  13694. ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
  13695. //IE8 issues
  13696. css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
  13697. if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
  13698. css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
  13699. }
  13700. if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
  13701. css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
  13702. }
  13703. var normal, undef, value;
  13704. undef = void 0;
  13705. normal = 16.00;
  13706. value = UnitedNumberMap[css_line_height_string];
  13707. if (value) {
  13708. return value;
  13709. }
  13710. value = {
  13711. "xx-small": 9,
  13712. "x-small": 11,
  13713. small: 13,
  13714. medium: 16,
  13715. large: 19,
  13716. "x-large": 23,
  13717. "xx-large": 28,
  13718. auto: 0
  13719. }[css_line_height_string];
  13720. if (value !== undef) {
  13721. return UnitedNumberMap[css_line_height_string] = value / normal;
  13722. }
  13723. if (value = parseFloat(css_line_height_string)) {
  13724. return UnitedNumberMap[css_line_height_string] = value / normal;
  13725. }
  13726. value = css_line_height_string.match(/([\d\.]+)(px)/);
  13727. if (Array.isArray(value) && value.length === 3) {
  13728. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  13729. }
  13730. return UnitedNumberMap[css_line_height_string] = 1;
  13731. };
  13732. GetCSS = function GetCSS(element) {
  13733. var css, tmp, computedCSSElement;
  13734. computedCSSElement = function (el) {
  13735. var compCSS;
  13736. compCSS = function (el) {
  13737. if (document.defaultView && document.defaultView.getComputedStyle) {
  13738. return document.defaultView.getComputedStyle(el, null);
  13739. } else if (el.currentStyle) {
  13740. return el.currentStyle;
  13741. } else {
  13742. return el.style;
  13743. }
  13744. }(el);
  13745. return function (prop) {
  13746. prop = prop.replace(/-\D/g, function (match) {
  13747. return match.charAt(1).toUpperCase();
  13748. });
  13749. return compCSS[prop];
  13750. };
  13751. }(element);
  13752. css = {};
  13753. tmp = void 0;
  13754. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  13755. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  13756. css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
  13757. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  13758. if (tmp === "bold") {
  13759. if (css["font-style"] === "normal") {
  13760. css["font-style"] = tmp;
  13761. } else {
  13762. css["font-style"] = tmp + css["font-style"];
  13763. }
  13764. }
  13765. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  13766. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  13767. css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
  13768. tmp = css["display"] === "block";
  13769. css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  13770. css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  13771. css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  13772. css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  13773. css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  13774. css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  13775. css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  13776. css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  13777. css["page-break-before"] = computedCSSElement("page-break-before") || "auto"; //float and clearing of floats
  13778. css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
  13779. css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
  13780. css["color"] = computedCSSElement("color");
  13781. return css;
  13782. };
  13783. elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
  13784. var handlers, i, isHandledElsewhere, l, classNames;
  13785. isHandledElsewhere = false;
  13786. i = void 0;
  13787. l = void 0;
  13788. handlers = elementHandlers["#" + element.id];
  13789. if (handlers) {
  13790. if (typeof handlers === "function") {
  13791. isHandledElsewhere = handlers(element, renderer);
  13792. } else {
  13793. i = 0;
  13794. l = handlers.length;
  13795. while (!isHandledElsewhere && i !== l) {
  13796. isHandledElsewhere = handlers[i](element, renderer);
  13797. i++;
  13798. }
  13799. }
  13800. }
  13801. handlers = elementHandlers[element.nodeName];
  13802. if (!isHandledElsewhere && handlers) {
  13803. if (typeof handlers === "function") {
  13804. isHandledElsewhere = handlers(element, renderer);
  13805. } else {
  13806. i = 0;
  13807. l = handlers.length;
  13808. while (!isHandledElsewhere && i !== l) {
  13809. isHandledElsewhere = handlers[i](element, renderer);
  13810. i++;
  13811. }
  13812. }
  13813. } // Try class names
  13814. classNames = typeof element.className === 'string' ? element.className.split(' ') : [];
  13815. for (i = 0; i < classNames.length; i++) {
  13816. handlers = elementHandlers['.' + classNames[i]];
  13817. if (!isHandledElsewhere && handlers) {
  13818. if (typeof handlers === "function") {
  13819. isHandledElsewhere = handlers(element, renderer);
  13820. } else {
  13821. i = 0;
  13822. l = handlers.length;
  13823. while (!isHandledElsewhere && i !== l) {
  13824. isHandledElsewhere = handlers[i](element, renderer);
  13825. i++;
  13826. }
  13827. }
  13828. }
  13829. }
  13830. return isHandledElsewhere;
  13831. };
  13832. tableToJson = function tableToJson(table, renderer) {
  13833. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  13834. data = [];
  13835. headers = [];
  13836. i = 0;
  13837. l = table.rows[0].cells.length;
  13838. table_with = table.clientWidth;
  13839. while (i < l) {
  13840. cell = table.rows[0].cells[i];
  13841. headers[i] = {
  13842. name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
  13843. prompt: cell.textContent.replace(/\r?\n/g, ''),
  13844. width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.getWidth()
  13845. };
  13846. i++;
  13847. }
  13848. i = 1;
  13849. while (i < table.rows.length) {
  13850. tableRow = table.rows[i];
  13851. rowData = {};
  13852. j = 0;
  13853. while (j < tableRow.cells.length) {
  13854. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
  13855. j++;
  13856. }
  13857. data.push(rowData);
  13858. i++;
  13859. }
  13860. return table_obj = {
  13861. rows: data,
  13862. headers: headers
  13863. };
  13864. };
  13865. var SkipNode = {
  13866. SCRIPT: 1,
  13867. STYLE: 1,
  13868. NOSCRIPT: 1,
  13869. OBJECT: 1,
  13870. EMBED: 1,
  13871. SELECT: 1
  13872. };
  13873. var listCount = 1;
  13874. _DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
  13875. var cn, cns, fragmentCSS, i, isBlock, l, table2json, cb;
  13876. cns = element.childNodes;
  13877. cn = void 0;
  13878. fragmentCSS = GetCSS(element);
  13879. isBlock = fragmentCSS.display === "block";
  13880. if (isBlock) {
  13881. renderer.setBlockBoundary();
  13882. renderer.setBlockStyle(fragmentCSS);
  13883. }
  13884. i = 0;
  13885. l = cns.length;
  13886. while (i < l) {
  13887. cn = cns[i];
  13888. if (_typeof(cn) === "object") {
  13889. //execute all watcher functions to e.g. reset floating
  13890. renderer.executeWatchFunctions(cn);
  13891. /*** HEADER rendering **/
  13892. if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
  13893. var header = cn; //store old top margin
  13894. var oldMarginTop = renderer.pdf.margins_doc.top; //subscribe for new page event and render header first on every page
  13895. renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
  13896. //set current y position to old margin
  13897. renderer.y = oldMarginTop; //render all child nodes of the header element
  13898. _DrillForContent(header, renderer, elementHandlers); //set margin to old margin + rendered header + 10 space to prevent overlapping
  13899. //important for other plugins (e.g. table) to start rendering at correct position after header
  13900. renderer.pdf.margins_doc.top = renderer.y + 10;
  13901. renderer.y += 10;
  13902. }, false);
  13903. }
  13904. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  13905. if (~cn.textContent.indexOf("ADD_PAGE")) {
  13906. renderer.pdf.addPage();
  13907. renderer.y = renderer.pdf.margins_doc.top;
  13908. }
  13909. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  13910. /*** IMAGE RENDERING ***/
  13911. var cached_image;
  13912. if (cn.nodeName === "IMG") {
  13913. var url = cn.getAttribute("src");
  13914. cached_image = images[renderer.pdf.sHashCode(url) || url];
  13915. }
  13916. if (cached_image) {
  13917. if (renderer.pdf.internal.pageSize.getHeight() - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
  13918. renderer.pdf.addPage();
  13919. renderer.y = renderer.pdf.margins_doc.top; //check if we have to set back some values due to e.g. header rendering for new page
  13920. renderer.executeWatchFunctions(cn);
  13921. }
  13922. var imagesCSS = GetCSS(cn);
  13923. var imageX = renderer.x;
  13924. var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor; //define additional paddings, margins which have to be taken into account for margin calculations
  13925. var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
  13926. var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
  13927. var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
  13928. var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio; //if float is set to right, move the image to the right border
  13929. //add space if margin is set
  13930. if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
  13931. imageX += renderer.settings.width - cn.width - additionalSpaceRight;
  13932. } else {
  13933. imageX += additionalSpaceLeft;
  13934. }
  13935. renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
  13936. cached_image = undefined; //if the float prop is specified we have to float the text around the image
  13937. if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
  13938. //add functiont to set back coordinates after image rendering
  13939. renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
  13940. //undo drawing box adaptions which were set by floating
  13941. if (renderer.y >= thresholdY) {
  13942. renderer.x += diffX;
  13943. renderer.settings.width += diffWidth;
  13944. return true;
  13945. } else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
  13946. renderer.x += diffX;
  13947. renderer.y = thresholdY;
  13948. renderer.settings.width += diffWidth;
  13949. return true;
  13950. } else {
  13951. return false;
  13952. }
  13953. }.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width)); //reset floating by clear:both divs
  13954. //just set cursorY after the floating element
  13955. renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
  13956. if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
  13957. if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
  13958. renderer.y = yPositionAfterFloating;
  13959. return true;
  13960. } else {
  13961. return false;
  13962. }
  13963. } else {
  13964. return true;
  13965. }
  13966. }.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages())); //if floating is set we decrease the available width by the image width
  13967. renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight; //if left just add the image width to the X coordinate
  13968. if (imagesCSS['float'] === 'left') {
  13969. renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
  13970. }
  13971. } else {
  13972. //if no floating is set, move the rendering cursor after the image height
  13973. renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
  13974. }
  13975. /*** TABLE RENDERING ***/
  13976. } else if (cn.nodeName === "TABLE") {
  13977. table2json = tableToJson(cn, renderer);
  13978. renderer.y += 10;
  13979. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  13980. autoSize: false,
  13981. printHeaders: elementHandlers.printHeaders,
  13982. margins: renderer.pdf.margins_doc,
  13983. css: GetCSS(cn)
  13984. });
  13985. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  13986. } else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
  13987. listCount = 1;
  13988. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  13989. _DrillForContent(cn, renderer, elementHandlers);
  13990. }
  13991. renderer.y += 10;
  13992. } else if (cn.nodeName === "LI") {
  13993. var temp = renderer.x;
  13994. renderer.x += 20 / renderer.pdf.internal.scaleFactor;
  13995. renderer.y += 3;
  13996. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  13997. _DrillForContent(cn, renderer, elementHandlers);
  13998. }
  13999. renderer.x = temp;
  14000. } else if (cn.nodeName === "BR") {
  14001. renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
  14002. renderer.addText("\u2028", clone(fragmentCSS));
  14003. } else {
  14004. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  14005. _DrillForContent(cn, renderer, elementHandlers);
  14006. }
  14007. }
  14008. } else if (cn.nodeType === 3) {
  14009. var value = cn.nodeValue;
  14010. if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
  14011. if (cn.parentNode.parentNode.nodeName === "OL") {
  14012. value = listCount++ + '. ' + value;
  14013. } else {
  14014. var fontSize = fragmentCSS["font-size"];
  14015. var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
  14016. var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
  14017. var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
  14018. cb = function cb(x, y) {
  14019. this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
  14020. };
  14021. }
  14022. } // Only add the text if the text node is in the body element
  14023. // Add compatibility with IE11
  14024. if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
  14025. renderer.addText(value, fragmentCSS);
  14026. }
  14027. } else if (typeof cn === "string") {
  14028. renderer.addText(cn, fragmentCSS);
  14029. }
  14030. }
  14031. i++;
  14032. }
  14033. elementHandlers.outY = renderer.y;
  14034. if (isBlock) {
  14035. return renderer.setBlockBoundary(cb);
  14036. }
  14037. };
  14038. images = {};
  14039. loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
  14040. var imgs = element.getElementsByTagName('img'),
  14041. l = imgs.length,
  14042. found_images,
  14043. x = 0;
  14044. function done() {
  14045. renderer.pdf.internal.events.publish('imagesLoaded');
  14046. cb(found_images);
  14047. }
  14048. function loadImage(url, width, height) {
  14049. if (!url) return;
  14050. var img = new Image();
  14051. found_images = ++x;
  14052. img.crossOrigin = '';
  14053. img.onerror = img.onload = function () {
  14054. if (img.complete) {
  14055. //to support data urls in images, set width and height
  14056. //as those values are not recognized automatically
  14057. if (img.src.indexOf('data:image/') === 0) {
  14058. img.width = width || img.width || 0;
  14059. img.height = height || img.height || 0;
  14060. } //if valid image add to known images array
  14061. if (img.width + img.height) {
  14062. var hash = renderer.pdf.sHashCode(url) || url;
  14063. images[hash] = images[hash] || img;
  14064. }
  14065. }
  14066. if (! --x) {
  14067. done();
  14068. }
  14069. };
  14070. img.src = url;
  14071. }
  14072. while (l--) {
  14073. loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
  14074. }
  14075. return x || done();
  14076. };
  14077. checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
  14078. //check if we can found a <footer> element
  14079. var footer = elem.getElementsByTagName("footer");
  14080. if (footer.length > 0) {
  14081. footer = footer[0]; //bad hack to get height of footer
  14082. //creat dummy out and check new y after fake rendering
  14083. var oldOut = renderer.pdf.internal.write;
  14084. var oldY = renderer.y;
  14085. renderer.pdf.internal.write = function () {};
  14086. _DrillForContent(footer, renderer, elementHandlers);
  14087. var footerHeight = Math.ceil(renderer.y - oldY) + 5;
  14088. renderer.y = oldY;
  14089. renderer.pdf.internal.write = oldOut; //add 20% to prevent overlapping
  14090. renderer.pdf.margins_doc.bottom += footerHeight; //Create function render header on every page
  14091. var renderFooter = function renderFooter(pageInfo) {
  14092. var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1; //set current y position to old margin
  14093. var oldPosition = renderer.y; //render all child nodes of the header element
  14094. renderer.y = renderer.pdf.internal.pageSize.getHeight() - renderer.pdf.margins_doc.bottom;
  14095. renderer.pdf.margins_doc.bottom -= footerHeight; //check if we have to add page numbers
  14096. var spans = footer.getElementsByTagName('span');
  14097. for (var i = 0; i < spans.length; ++i) {
  14098. //if we find some span element with class pageCounter, set the page
  14099. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
  14100. spans[i].innerHTML = pageNumber;
  14101. } //if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
  14102. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  14103. spans[i].innerHTML = '###jsPDFVarTotalPages###';
  14104. }
  14105. } //render footer content
  14106. _DrillForContent(footer, renderer, elementHandlers); //set bottom margin to previous height including the footer height
  14107. renderer.pdf.margins_doc.bottom += footerHeight; //important for other plugins (e.g. table) to start rendering at correct position after header
  14108. renderer.y = oldPosition;
  14109. }; //check if footer contains totalPages which should be replace at the disoposal of the document
  14110. var spans = footer.getElementsByTagName('span');
  14111. for (var i = 0; i < spans.length; ++i) {
  14112. if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
  14113. renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
  14114. }
  14115. } //register event to render footer on every new page
  14116. renderer.pdf.internal.events.subscribe('addPage', renderFooter, false); //render footer on first page
  14117. renderFooter(); //prevent footer rendering
  14118. SkipNode['FOOTER'] = 1;
  14119. }
  14120. };
  14121. process = function process(pdf, element, x, y, settings, callback) {
  14122. if (!element) return false;
  14123. if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
  14124. if (typeof element === "string") {
  14125. element = function (element) {
  14126. var $frame, $hiddendiv, framename, visuallyhidden;
  14127. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  14128. 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;";
  14129. $hiddendiv = document.createElement('div');
  14130. $hiddendiv.style.cssText = visuallyhidden;
  14131. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  14132. document.body.appendChild($hiddendiv);
  14133. $frame = window.frames[framename];
  14134. $frame.document.open();
  14135. $frame.document.writeln(element);
  14136. $frame.document.close();
  14137. return $frame.document.body;
  14138. }(element.replace(/<\/?script[^>]*?>/gi, ''));
  14139. }
  14140. var r = new Renderer(pdf, x, y, settings),
  14141. out; // 1. load images
  14142. // 2. prepare optional footer elements
  14143. // 3. render content
  14144. loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
  14145. checkForFooter(element, r, settings.elementHandlers);
  14146. _DrillForContent(element, r, settings.elementHandlers); //send event dispose for final taks (e.g. footer totalpage replacement)
  14147. r.pdf.internal.events.publish('htmlRenderingFinished');
  14148. out = r.dispose();
  14149. if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
  14150. });
  14151. return out || {
  14152. x: r.x,
  14153. y: r.y
  14154. };
  14155. };
  14156. Renderer.prototype.init = function () {
  14157. this.paragraph = {
  14158. text: [],
  14159. style: []
  14160. };
  14161. return this.pdf.internal.write("q");
  14162. };
  14163. Renderer.prototype.dispose = function () {
  14164. this.pdf.internal.write("Q");
  14165. return {
  14166. x: this.x,
  14167. y: this.y,
  14168. ready: true
  14169. };
  14170. }; //Checks if we have to execute some watcher functions
  14171. //e.g. to end text floating around an image
  14172. Renderer.prototype.executeWatchFunctions = function (el) {
  14173. var ret = false;
  14174. var narray = [];
  14175. if (this.watchFunctions.length > 0) {
  14176. for (var i = 0; i < this.watchFunctions.length; ++i) {
  14177. if (this.watchFunctions[i](el) === true) {
  14178. ret = true;
  14179. } else {
  14180. narray.push(this.watchFunctions[i]);
  14181. }
  14182. }
  14183. this.watchFunctions = narray;
  14184. }
  14185. return ret;
  14186. };
  14187. Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
  14188. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  14189. defaultFontSize = 12;
  14190. k = this.pdf.internal.scaleFactor;
  14191. fontMetricsCache = {};
  14192. ff = void 0;
  14193. fs = void 0;
  14194. fontMetrics = void 0;
  14195. fragment = void 0;
  14196. style = void 0;
  14197. fragmentSpecificMetrics = void 0;
  14198. fragmentLength = void 0;
  14199. fragmentChopped = void 0;
  14200. line = [];
  14201. lines = [line];
  14202. currentLineLength = 0;
  14203. maxLineLength = this.settings.width;
  14204. while (fragments.length) {
  14205. fragment = fragments.shift();
  14206. style = styles.shift();
  14207. if (fragment) {
  14208. ff = style["font-family"];
  14209. fs = style["font-style"];
  14210. fontMetrics = fontMetricsCache[ff + fs];
  14211. if (!fontMetrics) {
  14212. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  14213. fontMetricsCache[ff + fs] = fontMetrics;
  14214. }
  14215. fragmentSpecificMetrics = {
  14216. widths: fontMetrics.widths,
  14217. kerning: fontMetrics.kerning,
  14218. fontSize: style["font-size"] * defaultFontSize,
  14219. textIndent: currentLineLength
  14220. };
  14221. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  14222. if (fragment == "\u2028") {
  14223. line = [];
  14224. lines.push(line);
  14225. } else if (currentLineLength + fragmentLength > maxLineLength) {
  14226. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  14227. line.push([fragmentChopped.shift(), style]);
  14228. while (fragmentChopped.length) {
  14229. line = [[fragmentChopped.shift(), style]];
  14230. lines.push(line);
  14231. }
  14232. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  14233. } else {
  14234. line.push([fragment, style]);
  14235. currentLineLength += fragmentLength;
  14236. }
  14237. }
  14238. } //if text alignment was set, set margin/indent of each line
  14239. if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
  14240. for (var i = 0; i < lines.length; ++i) {
  14241. var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k; //if there is more than on line we have to clone the style object as all lines hold a reference on this object
  14242. if (i > 0) {
  14243. lines[i][0][1] = clone(lines[i][0][1]);
  14244. }
  14245. var space = maxLineLength - length;
  14246. if (style['text-align'] === 'right') {
  14247. lines[i][0][1]['margin-left'] = space; //if alignment is not right, it has to be center so split the space to the left and the right
  14248. } else if (style['text-align'] === 'center') {
  14249. lines[i][0][1]['margin-left'] = space / 2; //if justify was set, calculate the word spacing and define in by using the css property
  14250. } else if (style['text-align'] === 'justify') {
  14251. var countSpaces = lines[i][0][0].split(' ').length - 1;
  14252. lines[i][0][1]['word-spacing'] = space / countSpaces; //ignore the last line in justify mode
  14253. if (i === lines.length - 1) {
  14254. lines[i][0][1]['word-spacing'] = 0;
  14255. }
  14256. }
  14257. }
  14258. }
  14259. return lines;
  14260. };
  14261. Renderer.prototype.RenderTextFragment = function (text, style) {
  14262. var defaultFontSize, font, maxLineHeight;
  14263. maxLineHeight = 0;
  14264. defaultFontSize = 12;
  14265. if (this.pdf.internal.pageSize.getHeight() - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  14266. this.pdf.internal.write("ET", "Q");
  14267. this.pdf.addPage();
  14268. this.y = this.pdf.margins_doc.top;
  14269. this.pdf.internal.write("q", "BT", this.getPdfColor(style.color), this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); //move cursor by one line on new page
  14270. maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
  14271. this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  14272. }
  14273. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]); // text color
  14274. var pdfTextColor = this.getPdfColor(style["color"]);
  14275. if (pdfTextColor !== this.lastTextColor) {
  14276. this.pdf.internal.write(pdfTextColor);
  14277. this.lastTextColor = pdfTextColor;
  14278. } //set the word spacing for e.g. justify style
  14279. if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
  14280. this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
  14281. }
  14282. this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj"); //set the word spacing back to neutral => 0
  14283. if (style['word-spacing'] !== undefined) {
  14284. this.pdf.internal.write(0, "Tw");
  14285. }
  14286. }; // Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
  14287. Renderer.prototype.getPdfColor = function (style) {
  14288. var textColor;
  14289. var r, g, b;
  14290. var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
  14291. var m = rx.exec(style);
  14292. if (m != null) {
  14293. r = parseInt(m[1]);
  14294. g = parseInt(m[2]);
  14295. b = parseInt(m[3]);
  14296. } else {
  14297. if (typeof style === "string" && style.charAt(0) != '#') {
  14298. var rgbColor = new RGBColor(style);
  14299. if (rgbColor.ok) {
  14300. style = rgbColor.toHex();
  14301. } else {
  14302. style = '#000000';
  14303. }
  14304. }
  14305. r = style.substring(1, 3);
  14306. r = parseInt(r, 16);
  14307. g = style.substring(3, 5);
  14308. g = parseInt(g, 16);
  14309. b = style.substring(5, 7);
  14310. b = parseInt(b, 16);
  14311. }
  14312. if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
  14313. var hex = parseInt(r.substr(1), 16);
  14314. r = hex >> 16 & 255;
  14315. g = hex >> 8 & 255;
  14316. b = hex & 255;
  14317. }
  14318. var f3 = this.f3;
  14319. if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
  14320. textColor = f3(r / 255) + ' g';
  14321. } else {
  14322. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  14323. }
  14324. return textColor;
  14325. };
  14326. Renderer.prototype.f3 = function (number) {
  14327. return number.toFixed(3); // Ie, %.3f
  14328. }, Renderer.prototype.renderParagraph = function (cb) {
  14329. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
  14330. fragments = PurgeWhiteSpace(this.paragraph.text);
  14331. styles = this.paragraph.style;
  14332. blockstyle = this.paragraph.blockstyle;
  14333. priorblockstyle = this.paragraph.priorblockstyle || {};
  14334. this.paragraph = {
  14335. text: [],
  14336. style: [],
  14337. blockstyle: {},
  14338. priorblockstyle: blockstyle
  14339. };
  14340. if (!fragments.join("").trim()) {
  14341. return;
  14342. }
  14343. lines = this.splitFragmentsIntoLines(fragments, styles);
  14344. line = void 0;
  14345. maxLineHeight = void 0;
  14346. defaultFontSize = 12;
  14347. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  14348. this.priorMarginBottom = this.priorMarginBottom || 0;
  14349. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  14350. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  14351. this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
  14352. if (blockstyle['page-break-before'] === 'always') {
  14353. this.pdf.addPage();
  14354. this.y = 0;
  14355. paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  14356. }
  14357. out = this.pdf.internal.write;
  14358. i = void 0;
  14359. l = void 0;
  14360. this.y += paragraphspacing_before;
  14361. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td"); //stores the current indent of cursor position
  14362. var currentIndent = 0;
  14363. while (lines.length) {
  14364. line = lines.shift();
  14365. maxLineHeight = 0;
  14366. i = 0;
  14367. l = line.length;
  14368. while (i !== l) {
  14369. if (line[i][0].trim()) {
  14370. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  14371. fontSize = line[i][1]["font-size"] * 7;
  14372. }
  14373. i++;
  14374. } //if we have to move the cursor to adapt the indent
  14375. var indentMove = 0;
  14376. var wantedIndent = 0; //if a margin was added (by e.g. a text-alignment), move the cursor
  14377. if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
  14378. wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
  14379. indentMove = wantedIndent - currentIndent;
  14380. currentIndent = wantedIndent;
  14381. }
  14382. var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio; //move the cursor
  14383. out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  14384. i = 0;
  14385. l = line.length;
  14386. while (i !== l) {
  14387. if (line[i][0]) {
  14388. this.RenderTextFragment(line[i][0], line[i][1]);
  14389. }
  14390. i++;
  14391. }
  14392. this.y += maxLineHeight * fontToUnitRatio; //if some watcher function was executed successful, so e.g. margin and widths were changed,
  14393. //reset line drawing and calculate position and lines again
  14394. //e.g. to stop text floating around an image
  14395. if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
  14396. var localFragments = [];
  14397. var localStyles = []; //create fragment array of
  14398. lines.forEach(function (localLine) {
  14399. var i = 0;
  14400. var l = localLine.length;
  14401. while (i !== l) {
  14402. if (localLine[i][0]) {
  14403. localFragments.push(localLine[i][0] + ' ');
  14404. localStyles.push(localLine[i][1]);
  14405. }
  14406. ++i;
  14407. }
  14408. }); //split lines again due to possible coordinate changes
  14409. lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles); //reposition the current cursor
  14410. out("ET", "Q");
  14411. out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  14412. }
  14413. }
  14414. if (cb && typeof cb === "function") {
  14415. cb.call(this, this.x - 9, this.y - fontSize / 2);
  14416. }
  14417. out("ET", "Q");
  14418. return this.y += paragraphspacing_after;
  14419. };
  14420. Renderer.prototype.setBlockBoundary = function (cb) {
  14421. return this.renderParagraph(cb);
  14422. };
  14423. Renderer.prototype.setBlockStyle = function (css) {
  14424. return this.paragraph.blockstyle = css;
  14425. };
  14426. Renderer.prototype.addText = function (text, css) {
  14427. this.paragraph.text.push(text);
  14428. return this.paragraph.style.push(css);
  14429. };
  14430. FontNameDB = {
  14431. helvetica: "helvetica",
  14432. "sans-serif": "helvetica",
  14433. "times new roman": "times",
  14434. serif: "times",
  14435. times: "times",
  14436. monospace: "courier",
  14437. courier: "courier"
  14438. };
  14439. FontWeightMap = {
  14440. 100: "normal",
  14441. 200: "normal",
  14442. 300: "normal",
  14443. 400: "normal",
  14444. 500: "bold",
  14445. 600: "bold",
  14446. 700: "bold",
  14447. 800: "bold",
  14448. 900: "bold",
  14449. normal: "normal",
  14450. bold: "bold",
  14451. bolder: "bold",
  14452. lighter: "normal"
  14453. };
  14454. FontStyleMap = {
  14455. normal: "normal",
  14456. italic: "italic",
  14457. oblique: "italic"
  14458. };
  14459. TextAlignMap = {
  14460. left: "left",
  14461. right: "right",
  14462. center: "center",
  14463. justify: "justify"
  14464. };
  14465. FloatMap = {
  14466. none: 'none',
  14467. right: 'right',
  14468. left: 'left'
  14469. };
  14470. ClearMap = {
  14471. none: 'none',
  14472. both: 'both'
  14473. };
  14474. UnitedNumberMap = {
  14475. normal: 1
  14476. };
  14477. /**
  14478. * Converts HTML-formatted text into formatted PDF text.
  14479. *
  14480. * Notes:
  14481. * 2012-07-18
  14482. * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  14483. * Plugin relies on jQuery for CSS extraction.
  14484. * Targeting HTML output from Markdown templating, which is a very simple
  14485. * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  14486. * Images, tables are NOT supported.
  14487. *
  14488. * @public
  14489. * @function
  14490. * @param HTML {String|Object} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  14491. * @param x {Number} starting X coordinate in jsPDF instance's declared units.
  14492. * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  14493. * @param settings {Object} Additional / optional variables controlling parsing, rendering.
  14494. * @returns {Object} jsPDF instance
  14495. */
  14496. jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
  14497. this.margins_doc = margins || {
  14498. top: 0,
  14499. bottom: 0
  14500. };
  14501. if (!settings) settings = {};
  14502. if (!settings.elementHandlers) settings.elementHandlers = {};
  14503. return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
  14504. };
  14505. })(jsPDF.API);
  14506. /**
  14507. * html2pdf.js
  14508. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  14509. *
  14510. * Licensed under the MIT License.
  14511. * http://opensource.org/licenses/mit-license
  14512. */
  14513. (function (jsPDFAPI, globalObj) {
  14514. globalObj.html2pdf = function (html, pdf, callback) {
  14515. var canvas = pdf.canvas;
  14516. if (!canvas) {
  14517. alert('jsPDF canvas plugin not installed');
  14518. return;
  14519. }
  14520. canvas.pdf = pdf;
  14521. pdf.annotations = {
  14522. _nameMap: [],
  14523. createAnnotation: function createAnnotation(href, bounds) {
  14524. var x = pdf.context2d._wrapX(bounds.left);
  14525. var y = pdf.context2d._wrapY(bounds.top);
  14526. var page = pdf.context2d._page(bounds.top);
  14527. var options;
  14528. var index = href.indexOf('#');
  14529. if (index >= 0) {
  14530. options = {
  14531. name: href.substring(index + 1)
  14532. };
  14533. } else {
  14534. options = {
  14535. url: href
  14536. };
  14537. }
  14538. pdf.link(x, y, bounds.right - bounds.left, bounds.bottom - bounds.top, options);
  14539. },
  14540. setName: function setName(name, bounds) {
  14541. var x = pdf.context2d._wrapX(bounds.left);
  14542. var y = pdf.context2d._wrapY(bounds.top);
  14543. var page = pdf.context2d._page(bounds.top);
  14544. this._nameMap[name] = {
  14545. page: page,
  14546. x: x,
  14547. y: y
  14548. };
  14549. }
  14550. };
  14551. canvas.annotations = pdf.annotations;
  14552. pdf.context2d._pageBreakAt = function (y) {
  14553. this.pageBreaks.push(y);
  14554. };
  14555. pdf.context2d._gotoPage = function (pageOneBased) {
  14556. while (pdf.internal.getNumberOfPages() < pageOneBased) {
  14557. pdf.addPage();
  14558. }
  14559. pdf.setPage(pageOneBased);
  14560. };
  14561. var htmlElement;
  14562. var height;
  14563. if (typeof html === 'string') {
  14564. // remove all scripts
  14565. html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
  14566. var iframe = document.createElement('iframe'); //iframe.style.width = canvas.width;
  14567. //iframe.src = "";
  14568. //iframe.document.domain =
  14569. document.body.appendChild(iframe);
  14570. var doc;
  14571. var body;
  14572. doc = iframe.contentDocument;
  14573. if (doc == undefined || doc == null) {
  14574. doc = iframe.contentWindow.document;
  14575. } //iframe.setAttribute('style', 'position:absolute;right:0; top:0; bottom:0; height:100%; width:500px');
  14576. doc.open();
  14577. doc.write(html);
  14578. doc.close();
  14579. htmlElement = doc.body;
  14580. body = doc.body || {}, html = doc.documentElement || {};
  14581. height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  14582. } else {
  14583. htmlElement = html;
  14584. body = html.body || {}, height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  14585. }
  14586. height = pdf.internal.pageSize.getHeight();
  14587. var options = {
  14588. async: true,
  14589. allowTaint: true,
  14590. backgroundColor: '#ffffff',
  14591. canvas: canvas,
  14592. imageTimeout: 15000,
  14593. logging: true,
  14594. proxy: null,
  14595. removeContainer: true,
  14596. foreignObjectRendering: false,
  14597. useCORS: false,
  14598. windowHeight: height,
  14599. scrollY: height
  14600. };
  14601. pdf.context2d.pageWrapYEnabled = true;
  14602. pdf.context2d.pageWrapY = pdf.internal.pageSize.getHeight();
  14603. var promise = html2canvas(htmlElement, options).then(function (canvas) {
  14604. if (callback) {
  14605. if (iframe) {
  14606. iframe.parentElement.removeChild(iframe);
  14607. }
  14608. callback(pdf);
  14609. }
  14610. });
  14611. };
  14612. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  14613. /*rollup-keeper-start*/
  14614. window.tmp = html2pdf;
  14615. /*rollup-keeper-end*/
  14616. /* Blob.js
  14617. * A Blob, File, FileReader & URL implementation.
  14618. * 2018-08-09
  14619. *
  14620. * By Eli Grey, http://eligrey.com
  14621. * By Jimmy Wärting, https://github.com/jimmywarting
  14622. * License: MIT
  14623. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  14624. */
  14625. (function (global) {
  14626. var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder;
  14627. global.URL = global.URL || global.webkitURL || function (href, a) {
  14628. a = document.createElement('a');
  14629. a.href = href;
  14630. return a;
  14631. };
  14632. var origBlob = global.Blob;
  14633. var createObjectURL = URL.createObjectURL;
  14634. var revokeObjectURL = URL.revokeObjectURL;
  14635. var strTag = global.Symbol && global.Symbol.toStringTag;
  14636. var blobSupported = false;
  14637. var blobSupportsArrayBufferView = false;
  14638. var arrayBufferSupported = !!global.ArrayBuffer;
  14639. var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob;
  14640. try {
  14641. // Check if Blob constructor is supported
  14642. blobSupported = new Blob(['ä']).size === 2; // Check if Blob constructor supports ArrayBufferViews
  14643. // Fails in Safari 6, so we need to map to ArrayBuffers there.
  14644. blobSupportsArrayBufferView = new Blob([new Uint8Array([1, 2])]).size === 2;
  14645. } catch (e) {}
  14646. /**
  14647. * Helper function that maps ArrayBufferViews to ArrayBuffers
  14648. * Used by BlobBuilder constructor and old browsers that didn't
  14649. * support it in the Blob constructor.
  14650. */
  14651. function mapArrayBufferViews(ary) {
  14652. return ary.map(function (chunk) {
  14653. if (chunk.buffer instanceof ArrayBuffer) {
  14654. var buf = chunk.buffer; // if this is a subarray, make a copy so we only
  14655. // include the subarray region from the underlying buffer
  14656. if (chunk.byteLength !== buf.byteLength) {
  14657. var copy = new Uint8Array(chunk.byteLength);
  14658. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  14659. buf = copy.buffer;
  14660. }
  14661. return buf;
  14662. }
  14663. return chunk;
  14664. });
  14665. }
  14666. function BlobBuilderConstructor(ary, options) {
  14667. options = options || {};
  14668. var bb = new BlobBuilder();
  14669. mapArrayBufferViews(ary).forEach(function (part) {
  14670. bb.append(part);
  14671. });
  14672. return options.type ? bb.getBlob(options.type) : bb.getBlob();
  14673. }
  14674. function BlobConstructor(ary, options) {
  14675. return new origBlob(mapArrayBufferViews(ary), options || {});
  14676. }
  14677. if (global.Blob) {
  14678. BlobBuilderConstructor.prototype = Blob.prototype;
  14679. BlobConstructor.prototype = Blob.prototype;
  14680. }
  14681. function FakeBlobBuilder() {
  14682. function toUTF8Array(str) {
  14683. var utf8 = [];
  14684. for (var i = 0; i < str.length; i++) {
  14685. var charcode = str.charCodeAt(i);
  14686. if (charcode < 0x80) utf8.push(charcode);else if (charcode < 0x800) {
  14687. utf8.push(0xc0 | charcode >> 6, 0x80 | charcode & 0x3f);
  14688. } else if (charcode < 0xd800 || charcode >= 0xe000) {
  14689. utf8.push(0xe0 | charcode >> 12, 0x80 | charcode >> 6 & 0x3f, 0x80 | charcode & 0x3f);
  14690. } // surrogate pair
  14691. else {
  14692. i++; // UTF-16 encodes 0x10000-0x10FFFF by
  14693. // subtracting 0x10000 and splitting the
  14694. // 20 bits of 0x0-0xFFFFF into two halves
  14695. charcode = 0x10000 + ((charcode & 0x3ff) << 10 | str.charCodeAt(i) & 0x3ff);
  14696. utf8.push(0xf0 | charcode >> 18, 0x80 | charcode >> 12 & 0x3f, 0x80 | charcode >> 6 & 0x3f, 0x80 | charcode & 0x3f);
  14697. }
  14698. }
  14699. return utf8;
  14700. }
  14701. function fromUtf8Array(array) {
  14702. var out, i, len, c;
  14703. var char2, char3;
  14704. out = "";
  14705. len = array.length;
  14706. i = 0;
  14707. while (i < len) {
  14708. c = array[i++];
  14709. switch (c >> 4) {
  14710. case 0:
  14711. case 1:
  14712. case 2:
  14713. case 3:
  14714. case 4:
  14715. case 5:
  14716. case 6:
  14717. case 7:
  14718. // 0xxxxxxx
  14719. out += String.fromCharCode(c);
  14720. break;
  14721. case 12:
  14722. case 13:
  14723. // 110x xxxx 10xx xxxx
  14724. char2 = array[i++];
  14725. out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
  14726. break;
  14727. case 14:
  14728. // 1110 xxxx 10xx xxxx 10xx xxxx
  14729. char2 = array[i++];
  14730. char3 = array[i++];
  14731. out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
  14732. break;
  14733. }
  14734. }
  14735. return out;
  14736. }
  14737. function isDataView(obj) {
  14738. return obj && DataView.prototype.isPrototypeOf(obj);
  14739. }
  14740. function bufferClone(buf) {
  14741. var view = new Array(buf.byteLength);
  14742. var array = new Uint8Array(buf);
  14743. var i = view.length;
  14744. while (i--) {
  14745. view[i] = array[i];
  14746. }
  14747. return view;
  14748. }
  14749. function encodeByteArray(input) {
  14750. var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  14751. var output = [];
  14752. for (var i = 0; i < input.length; i += 3) {
  14753. var byte1 = input[i];
  14754. var haveByte2 = i + 1 < input.length;
  14755. var byte2 = haveByte2 ? input[i + 1] : 0;
  14756. var haveByte3 = i + 2 < input.length;
  14757. var byte3 = haveByte3 ? input[i + 2] : 0;
  14758. var outByte1 = byte1 >> 2;
  14759. var outByte2 = (byte1 & 0x03) << 4 | byte2 >> 4;
  14760. var outByte3 = (byte2 & 0x0F) << 2 | byte3 >> 6;
  14761. var outByte4 = byte3 & 0x3F;
  14762. if (!haveByte3) {
  14763. outByte4 = 64;
  14764. if (!haveByte2) {
  14765. outByte3 = 64;
  14766. }
  14767. }
  14768. output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
  14769. }
  14770. return output.join('');
  14771. }
  14772. var create = Object.create || function (a) {
  14773. function c() {}
  14774. c.prototype = a;
  14775. return new c();
  14776. };
  14777. if (arrayBufferSupported) {
  14778. var viewClasses = ['[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]'];
  14779. var isArrayBufferView = ArrayBuffer.isView || function (obj) {
  14780. return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
  14781. };
  14782. }
  14783. /********************************************************/
  14784. /* Blob constructor */
  14785. /********************************************************/
  14786. function Blob(chunks, opts) {
  14787. chunks = chunks || [];
  14788. for (var i = 0, len = chunks.length; i < len; i++) {
  14789. var chunk = chunks[i];
  14790. if (chunk instanceof Blob) {
  14791. chunks[i] = chunk._buffer;
  14792. } else if (typeof chunk === 'string') {
  14793. chunks[i] = toUTF8Array(chunk);
  14794. } else if (arrayBufferSupported && (ArrayBuffer.prototype.isPrototypeOf(chunk) || isArrayBufferView(chunk))) {
  14795. chunks[i] = bufferClone(chunk);
  14796. } else if (arrayBufferSupported && isDataView(chunk)) {
  14797. chunks[i] = bufferClone(chunk.buffer);
  14798. } else {
  14799. chunks[i] = toUTF8Array(String(chunk));
  14800. }
  14801. }
  14802. this._buffer = [].concat.apply([], chunks);
  14803. this.size = this._buffer.length;
  14804. this.type = opts ? opts.type || '' : '';
  14805. }
  14806. Blob.prototype.slice = function (start, end, type) {
  14807. var slice = this._buffer.slice(start || 0, end || this._buffer.length);
  14808. return new Blob([slice], {
  14809. type: type
  14810. });
  14811. };
  14812. Blob.prototype.toString = function () {
  14813. return '[object Blob]';
  14814. };
  14815. /********************************************************/
  14816. /* File constructor */
  14817. /********************************************************/
  14818. function File(chunks, name, opts) {
  14819. opts = opts || {};
  14820. var a = Blob.call(this, chunks, opts) || this;
  14821. a.name = name;
  14822. a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date();
  14823. a.lastModified = +a.lastModifiedDate;
  14824. return a;
  14825. }
  14826. File.prototype = create(Blob.prototype);
  14827. File.prototype.constructor = File;
  14828. if (Object.setPrototypeOf) Object.setPrototypeOf(File, Blob);else {
  14829. try {
  14830. File.__proto__ = Blob;
  14831. } catch (e) {}
  14832. }
  14833. File.prototype.toString = function () {
  14834. return '[object File]';
  14835. };
  14836. /********************************************************/
  14837. /* FileReader constructor */
  14838. /********************************************************/
  14839. function FileReader() {
  14840. if (!(this instanceof FileReader)) throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
  14841. var delegate = document.createDocumentFragment();
  14842. this.addEventListener = delegate.addEventListener;
  14843. this.dispatchEvent = function (evt) {
  14844. var local = this['on' + evt.type];
  14845. if (typeof local === 'function') local(evt);
  14846. delegate.dispatchEvent(evt);
  14847. };
  14848. this.removeEventListener = delegate.removeEventListener;
  14849. }
  14850. function _read(fr, blob, kind) {
  14851. if (!(blob instanceof Blob)) throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.");
  14852. fr.result = '';
  14853. setTimeout(function () {
  14854. this.readyState = FileReader.LOADING;
  14855. fr.dispatchEvent(new Event('load'));
  14856. fr.dispatchEvent(new Event('loadend'));
  14857. });
  14858. }
  14859. FileReader.EMPTY = 0;
  14860. FileReader.LOADING = 1;
  14861. FileReader.DONE = 2;
  14862. FileReader.prototype.error = null;
  14863. FileReader.prototype.onabort = null;
  14864. FileReader.prototype.onerror = null;
  14865. FileReader.prototype.onload = null;
  14866. FileReader.prototype.onloadend = null;
  14867. FileReader.prototype.onloadstart = null;
  14868. FileReader.prototype.onprogress = null;
  14869. FileReader.prototype.readAsDataURL = function (blob) {
  14870. _read(this, blob, 'readAsDataURL');
  14871. this.result = 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer);
  14872. };
  14873. FileReader.prototype.readAsText = function (blob) {
  14874. _read(this, blob, 'readAsText');
  14875. this.result = fromUtf8Array(blob._buffer);
  14876. };
  14877. FileReader.prototype.readAsArrayBuffer = function (blob) {
  14878. _read(this, blob, 'readAsText');
  14879. this.result = blob._buffer.slice();
  14880. };
  14881. FileReader.prototype.abort = function () {};
  14882. /********************************************************/
  14883. /* URL */
  14884. /********************************************************/
  14885. URL.createObjectURL = function (blob) {
  14886. return blob instanceof Blob ? 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer) : createObjectURL.call(URL, blob);
  14887. };
  14888. URL.revokeObjectURL = function (url) {
  14889. revokeObjectURL && revokeObjectURL.call(URL, url);
  14890. };
  14891. /********************************************************/
  14892. /* XHR */
  14893. /********************************************************/
  14894. var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send;
  14895. if (_send) {
  14896. XMLHttpRequest.prototype.send = function (data) {
  14897. if (data instanceof Blob) {
  14898. this.setRequestHeader('Content-Type', data.type);
  14899. _send.call(this, fromUtf8Array(data._buffer));
  14900. } else {
  14901. _send.call(this, data);
  14902. }
  14903. };
  14904. }
  14905. global.FileReader = FileReader;
  14906. global.File = File;
  14907. global.Blob = Blob;
  14908. }
  14909. if (strTag) {
  14910. try {
  14911. File.prototype[strTag] = 'File';
  14912. Blob.prototype[strTag] = 'Blob';
  14913. FileReader.prototype[strTag] = 'FileReader';
  14914. } catch (e) {}
  14915. }
  14916. function fixFileAndXHR() {
  14917. var isIE = !!global.ActiveXObject || '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style; // Monkey patched
  14918. // IE don't set Content-Type header on XHR whose body is a typed Blob
  14919. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6047383
  14920. var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send;
  14921. if (isIE && _send) {
  14922. XMLHttpRequest.prototype.send = function (data) {
  14923. if (data instanceof Blob) {
  14924. this.setRequestHeader('Content-Type', data.type);
  14925. _send.call(this, data);
  14926. } else {
  14927. _send.call(this, data);
  14928. }
  14929. };
  14930. }
  14931. try {
  14932. new File([], '');
  14933. } catch (e) {
  14934. try {
  14935. var klass = new Function('class File extends Blob {' + 'constructor(chunks, name, opts) {' + 'opts = opts || {};' + 'super(chunks, opts || {});' + 'this.name = name;' + 'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date;' + 'this.lastModified = +this.lastModifiedDate;' + '}};' + 'return new File([], ""), File')();
  14936. global.File = klass;
  14937. } catch (e) {
  14938. var klass = function klass(b, d, c) {
  14939. var blob = new Blob(b, c);
  14940. var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date();
  14941. blob.name = d;
  14942. blob.lastModifiedDate = t;
  14943. blob.lastModified = +t;
  14944. blob.toString = function () {
  14945. return '[object File]';
  14946. };
  14947. if (strTag) blob[strTag] = 'File';
  14948. return blob;
  14949. };
  14950. global.File = klass;
  14951. }
  14952. }
  14953. }
  14954. if (blobSupported) {
  14955. fixFileAndXHR();
  14956. global.Blob = blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  14957. } else if (blobBuilderSupported) {
  14958. fixFileAndXHR();
  14959. global.Blob = BlobBuilderConstructor;
  14960. } else {
  14961. FakeBlobBuilder();
  14962. }
  14963. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')());
  14964. /* FileSaver.js
  14965. * A saveAs() FileSaver implementation.
  14966. * 1.3.8
  14967. * 2018-03-22 14:03:47
  14968. *
  14969. * By Eli Grey, https://eligrey.com
  14970. * License: MIT
  14971. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  14972. */
  14973. /*global self */
  14974. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  14975. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/src/FileSaver.js */
  14976. var saveAs = saveAs || function (view) {
  14977. if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  14978. return;
  14979. }
  14980. var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet
  14981. ,
  14982. get_URL = function () {
  14983. return view.URL || view.webkitURL || view;
  14984. },
  14985. save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
  14986. can_use_save_link = "download" in save_link,
  14987. click = function (node) {
  14988. var event = new MouseEvent("click");
  14989. node.dispatchEvent(event);
  14990. },
  14991. is_safari = /constructor/i.test(view.HTMLElement) || view.safari,
  14992. is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent),
  14993. setImmediate = view.setImmediate || view.setTimeout,
  14994. throw_outside = function (ex) {
  14995. setImmediate(function () {
  14996. throw ex;
  14997. }, 0);
  14998. },
  14999. force_saveable_type = "application/octet-stream" // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  15000. ,
  15001. arbitrary_revoke_timeout = 1000 * 40 // in ms
  15002. ,
  15003. revoke = function (file) {
  15004. var revoker = function () {
  15005. if (typeof file === "string") {
  15006. // file is an object URL
  15007. get_URL().revokeObjectURL(file);
  15008. } else {
  15009. // file is a File
  15010. file.remove();
  15011. }
  15012. };
  15013. setTimeout(revoker, arbitrary_revoke_timeout);
  15014. },
  15015. dispatch = function (filesaver, event_types, event) {
  15016. event_types = [].concat(event_types);
  15017. var i = event_types.length;
  15018. while (i--) {
  15019. var listener = filesaver["on" + event_types[i]];
  15020. if (typeof listener === "function") {
  15021. try {
  15022. listener.call(filesaver, event || filesaver);
  15023. } catch (ex) {
  15024. throw_outside(ex);
  15025. }
  15026. }
  15027. }
  15028. },
  15029. auto_bom = function (blob) {
  15030. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  15031. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  15032. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  15033. return new Blob([String.fromCharCode(0xFEFF), blob], {
  15034. type: blob.type
  15035. });
  15036. }
  15037. return blob;
  15038. },
  15039. FileSaver = function (blob, name, no_auto_bom) {
  15040. if (!no_auto_bom) {
  15041. blob = auto_bom(blob);
  15042. } // First try a.download, then web filesystem, then object URLs
  15043. var filesaver = this,
  15044. type = blob.type,
  15045. force = type === force_saveable_type,
  15046. object_url,
  15047. dispatch_all = function () {
  15048. dispatch(filesaver, "writestart progress write writeend".split(" "));
  15049. } // on any filesys errors revert to saving with object URLs
  15050. ,
  15051. fs_error = function () {
  15052. if ((is_chrome_ios || force && is_safari) && view.FileReader) {
  15053. // Safari doesn't allow downloading of blob urls
  15054. var reader = new FileReader();
  15055. reader.onloadend = function () {
  15056. var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
  15057. var popup = view.open(url, '_blank');
  15058. if (!popup) view.location.href = url;
  15059. url = undefined; // release reference before dispatching
  15060. filesaver.readyState = filesaver.DONE;
  15061. dispatch_all();
  15062. };
  15063. reader.readAsDataURL(blob);
  15064. filesaver.readyState = filesaver.INIT;
  15065. return;
  15066. } // don't create more object URLs than needed
  15067. if (!object_url) {
  15068. object_url = get_URL().createObjectURL(blob);
  15069. }
  15070. if (force) {
  15071. view.location.href = object_url;
  15072. } else {
  15073. var opened = view.open(object_url, "_blank");
  15074. if (!opened) {
  15075. // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
  15076. view.location.href = object_url;
  15077. }
  15078. }
  15079. filesaver.readyState = filesaver.DONE;
  15080. dispatch_all();
  15081. revoke(object_url);
  15082. };
  15083. filesaver.readyState = filesaver.INIT;
  15084. if (can_use_save_link) {
  15085. object_url = get_URL().createObjectURL(blob);
  15086. setImmediate(function () {
  15087. save_link.href = object_url;
  15088. save_link.download = name;
  15089. click(save_link);
  15090. dispatch_all();
  15091. revoke(object_url);
  15092. filesaver.readyState = filesaver.DONE;
  15093. }, 0);
  15094. return;
  15095. }
  15096. fs_error();
  15097. },
  15098. FS_proto = FileSaver.prototype,
  15099. saveAs = function (blob, name, no_auto_bom) {
  15100. return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
  15101. }; // IE 10+ (native saveAs)
  15102. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  15103. return function (blob, name, no_auto_bom) {
  15104. name = name || blob.name || "download";
  15105. if (!no_auto_bom) {
  15106. blob = auto_bom(blob);
  15107. }
  15108. return navigator.msSaveOrOpenBlob(blob, name);
  15109. };
  15110. } // todo: detect chrome extensions & packaged apps
  15111. //save_link.target = "_blank";
  15112. FS_proto.abort = function () {};
  15113. FS_proto.readyState = FS_proto.INIT = 0;
  15114. FS_proto.WRITING = 1;
  15115. FS_proto.DONE = 2;
  15116. FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
  15117. return saveAs;
  15118. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
  15119. // (c) Dean McNamee <dean@gmail.com>, 2013.
  15120. //
  15121. // https://github.com/deanm/omggif
  15122. //
  15123. //
  15124. //
  15125. // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
  15126. // including animation and compression. It does not rely on any specific
  15127. // underlying system, so should run in the browser, Node, or Plask.
  15128. function GifWriter(buf, width, height, gopts) {
  15129. var p = 0;
  15130. var gopts = gopts === undefined ? {} : gopts;
  15131. var loop_count = gopts.loop === undefined ? null : gopts.loop;
  15132. var global_palette = gopts.palette === undefined ? null : gopts.palette;
  15133. if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw "Width/Height invalid.";
  15134. function check_palette_and_num_colors(palette) {
  15135. var num_colors = palette.length;
  15136. if (num_colors < 2 || num_colors > 256 || num_colors & num_colors - 1) throw "Invalid code/color length, must be power of 2 and 2 .. 256.";
  15137. return num_colors;
  15138. } // - Header.
  15139. buf[p++] = 0x47;
  15140. buf[p++] = 0x49;
  15141. buf[p++] = 0x46; // GIF
  15142. buf[p++] = 0x38;
  15143. buf[p++] = 0x39;
  15144. buf[p++] = 0x61; // 89a
  15145. // Handling of Global Color Table (palette) and background index.
  15146. var gp_num_colors_pow2 = 0;
  15147. var background = 0;
  15148. if (global_palette !== null) {
  15149. var gp_num_colors = check_palette_and_num_colors(global_palette);
  15150. while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
  15151. gp_num_colors = 1 << gp_num_colors_pow2;
  15152. --gp_num_colors_pow2;
  15153. if (gopts.background !== undefined) {
  15154. background = gopts.background;
  15155. if (background >= gp_num_colors) throw "Background index out of range."; // The GIF spec states that a background index of 0 should be ignored, so
  15156. // this is probably a mistake and you really want to set it to another
  15157. // slot in the palette. But actually in the end most browsers, etc end
  15158. // up ignoring this almost completely (including for dispose background).
  15159. if (background === 0) throw "Background index explicitly passed as 0.";
  15160. }
  15161. } // - Logical Screen Descriptor.
  15162. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
  15163. buf[p++] = width & 0xff;
  15164. buf[p++] = width >> 8 & 0xff;
  15165. buf[p++] = height & 0xff;
  15166. buf[p++] = height >> 8 & 0xff; // NOTE: Indicates 0-bpp original color resolution (unused?).
  15167. buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
  15168. gp_num_colors_pow2; // NOTE: No sort flag (unused?).
  15169. buf[p++] = background; // Background Color Index.
  15170. buf[p++] = 0; // Pixel aspect ratio (unused?).
  15171. // - Global Color Table
  15172. if (global_palette !== null) {
  15173. for (var i = 0, il = global_palette.length; i < il; ++i) {
  15174. var rgb = global_palette[i];
  15175. buf[p++] = rgb >> 16 & 0xff;
  15176. buf[p++] = rgb >> 8 & 0xff;
  15177. buf[p++] = rgb & 0xff;
  15178. }
  15179. }
  15180. if (loop_count !== null) {
  15181. // Netscape block for looping.
  15182. if (loop_count < 0 || loop_count > 65535) throw "Loop count invalid."; // Extension code, label, and length.
  15183. buf[p++] = 0x21;
  15184. buf[p++] = 0xff;
  15185. buf[p++] = 0x0b; // NETSCAPE2.0
  15186. buf[p++] = 0x4e;
  15187. buf[p++] = 0x45;
  15188. buf[p++] = 0x54;
  15189. buf[p++] = 0x53;
  15190. buf[p++] = 0x43;
  15191. buf[p++] = 0x41;
  15192. buf[p++] = 0x50;
  15193. buf[p++] = 0x45;
  15194. buf[p++] = 0x32;
  15195. buf[p++] = 0x2e;
  15196. buf[p++] = 0x30; // Sub-block
  15197. buf[p++] = 0x03;
  15198. buf[p++] = 0x01;
  15199. buf[p++] = loop_count & 0xff;
  15200. buf[p++] = loop_count >> 8 & 0xff;
  15201. buf[p++] = 0x00; // Terminator.
  15202. }
  15203. var ended = false;
  15204. this.addFrame = function (x, y, w, h, indexed_pixels, opts) {
  15205. if (ended === true) {
  15206. --p;
  15207. ended = false;
  15208. } // Un-end.
  15209. opts = opts === undefined ? {} : opts; // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
  15210. // canvas width/height, I imagine?
  15211. if (x < 0 || y < 0 || x > 65535 || y > 65535) throw "x/y invalid.";
  15212. if (w <= 0 || h <= 0 || w > 65535 || h > 65535) throw "Width/Height invalid.";
  15213. if (indexed_pixels.length < w * h) throw "Not enough pixels for the frame size.";
  15214. var using_local_palette = true;
  15215. var palette = opts.palette;
  15216. if (palette === undefined || palette === null) {
  15217. using_local_palette = false;
  15218. palette = global_palette;
  15219. }
  15220. if (palette === undefined || palette === null) throw "Must supply either a local or global palette.";
  15221. var num_colors = check_palette_and_num_colors(palette); // Compute the min_code_size (power of 2), destroying num_colors.
  15222. var min_code_size = 0;
  15223. while (num_colors >>= 1) ++min_code_size;
  15224. num_colors = 1 << min_code_size; // Now we can easily get it back.
  15225. var delay = opts.delay === undefined ? 0 : opts.delay; // From the spec:
  15226. // 0 - No disposal specified. The decoder is
  15227. // not required to take any action.
  15228. // 1 - Do not dispose. The graphic is to be left
  15229. // in place.
  15230. // 2 - Restore to background color. The area used by the
  15231. // graphic must be restored to the background color.
  15232. // 3 - Restore to previous. The decoder is required to
  15233. // restore the area overwritten by the graphic with
  15234. // what was there prior to rendering the graphic.
  15235. // 4-7 - To be defined.
  15236. // NOTE(deanm): Dispose background doesn't really work, apparently most
  15237. // browsers ignore the background palette index and clear to transparency.
  15238. var disposal = opts.disposal === undefined ? 0 : opts.disposal;
  15239. if (disposal < 0 || disposal > 3) // 4-7 is reserved.
  15240. throw "Disposal out of range.";
  15241. var use_transparency = false;
  15242. var transparent_index = 0;
  15243. if (opts.transparent !== undefined && opts.transparent !== null) {
  15244. use_transparency = true;
  15245. transparent_index = opts.transparent;
  15246. if (transparent_index < 0 || transparent_index >= num_colors) throw "Transparent color index.";
  15247. }
  15248. if (disposal !== 0 || use_transparency || delay !== 0) {
  15249. // - Graphics Control Extension
  15250. buf[p++] = 0x21;
  15251. buf[p++] = 0xf9; // Extension / Label.
  15252. buf[p++] = 4; // Byte size.
  15253. buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
  15254. buf[p++] = delay & 0xff;
  15255. buf[p++] = delay >> 8 & 0xff;
  15256. buf[p++] = transparent_index; // Transparent color index.
  15257. buf[p++] = 0; // Block Terminator.
  15258. } // - Image Descriptor
  15259. buf[p++] = 0x2c; // Image Seperator.
  15260. buf[p++] = x & 0xff;
  15261. buf[p++] = x >> 8 & 0xff; // Left.
  15262. buf[p++] = y & 0xff;
  15263. buf[p++] = y >> 8 & 0xff; // Top.
  15264. buf[p++] = w & 0xff;
  15265. buf[p++] = w >> 8 & 0xff;
  15266. buf[p++] = h & 0xff;
  15267. buf[p++] = h >> 8 & 0xff; // NOTE: No sort flag (unused?).
  15268. // TODO(deanm): Support interlace.
  15269. buf[p++] = using_local_palette === true ? 0x80 | min_code_size - 1 : 0; // - Local Color Table
  15270. if (using_local_palette === true) {
  15271. for (var i = 0, il = palette.length; i < il; ++i) {
  15272. var rgb = palette[i];
  15273. buf[p++] = rgb >> 16 & 0xff;
  15274. buf[p++] = rgb >> 8 & 0xff;
  15275. buf[p++] = rgb & 0xff;
  15276. }
  15277. }
  15278. p = GifWriterOutputLZWCodeStream(buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
  15279. };
  15280. this.end = function () {
  15281. if (ended === false) {
  15282. buf[p++] = 0x3b; // Trailer.
  15283. ended = true;
  15284. }
  15285. return p;
  15286. };
  15287. } // Main compression routine, palette indexes -> LZW code stream.
  15288. // |index_stream| must have at least one entry.
  15289. function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
  15290. buf[p++] = min_code_size;
  15291. var cur_subblock = p++; // Pointing at the length field.
  15292. var clear_code = 1 << min_code_size;
  15293. var code_mask = clear_code - 1;
  15294. var eoi_code = clear_code + 1;
  15295. var next_code = eoi_code + 1;
  15296. var cur_code_size = min_code_size + 1; // Number of bits per code.
  15297. var cur_shift = 0; // We have at most 12-bit codes, so we should have to hold a max of 19
  15298. // bits here (and then we would write out).
  15299. var cur = 0;
  15300. function emit_bytes_to_buffer(bit_block_size) {
  15301. while (cur_shift >= bit_block_size) {
  15302. buf[p++] = cur & 0xff;
  15303. cur >>= 8;
  15304. cur_shift -= 8;
  15305. if (p === cur_subblock + 256) {
  15306. // Finished a subblock.
  15307. buf[cur_subblock] = 255;
  15308. cur_subblock = p++;
  15309. }
  15310. }
  15311. }
  15312. function emit_code(c) {
  15313. cur |= c << cur_shift;
  15314. cur_shift += cur_code_size;
  15315. emit_bytes_to_buffer(8);
  15316. } // I am not an expert on the topic, and I don't want to write a thesis.
  15317. // However, it is good to outline here the basic algorithm and the few data
  15318. // structures and optimizations here that make this implementation fast.
  15319. // The basic idea behind LZW is to build a table of previously seen runs
  15320. // addressed by a short id (herein called output code). All data is
  15321. // referenced by a code, which represents one or more values from the
  15322. // original input stream. All input bytes can be referenced as the same
  15323. // value as an output code. So if you didn't want any compression, you
  15324. // could more or less just output the original bytes as codes (there are
  15325. // some details to this, but it is the idea). In order to achieve
  15326. // compression, values greater then the input range (codes can be up to
  15327. // 12-bit while input only 8-bit) represent a sequence of previously seen
  15328. // inputs. The decompressor is able to build the same mapping while
  15329. // decoding, so there is always a shared common knowledge between the
  15330. // encoding and decoder, which is also important for "timing" aspects like
  15331. // how to handle variable bit width code encoding.
  15332. //
  15333. // One obvious but very important consequence of the table system is there
  15334. // is always a unique id (at most 12-bits) to map the runs. 'A' might be
  15335. // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
  15336. // can be used for an effecient lookup strategy for the code mapping. We
  15337. // need to know if a run has been seen before, and be able to map that run
  15338. // to the output code. Since we start with known unique ids (input bytes),
  15339. // and then from those build more unique ids (table entries), we can
  15340. // continue this chain (almost like a linked list) to always have small
  15341. // integer values that represent the current byte chains in the encoder.
  15342. // This means instead of tracking the input bytes (AAAABCD) to know our
  15343. // current state, we can track the table entry for AAAABC (it is guaranteed
  15344. // to exist by the nature of the algorithm) and the next character D.
  15345. // Therefor the tuple of (table_entry, byte) is guaranteed to also be
  15346. // unique. This allows us to create a simple lookup key for mapping input
  15347. // sequences to codes (table indices) without having to store or search
  15348. // any of the code sequences. So if 'AAAA' has a table entry of 12, the
  15349. // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
  15350. // key. This leads to a integer value at most 20-bits, which can always
  15351. // fit in an SMI value and be used as a fast sparse array / object key.
  15352. // Output code for the current contents of the index buffer.
  15353. var ib_code = index_stream[0] & code_mask; // Load first input index.
  15354. var code_table = {}; // Key'd on our 20-bit "tuple".
  15355. emit_code(clear_code); // Spec says first code should be a clear code.
  15356. // First index already loaded, process the rest of the stream.
  15357. for (var i = 1, il = index_stream.length; i < il; ++i) {
  15358. var k = index_stream[i] & code_mask;
  15359. var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.
  15360. var cur_code = code_table[cur_key]; // buffer + k.
  15361. // Check if we have to create a new code table entry.
  15362. if (cur_code === undefined) {
  15363. // We don't have buffer + k.
  15364. // Emit index buffer (without k).
  15365. // This is an inline version of emit_code, because this is the core
  15366. // writing routine of the compressor (and V8 cannot inline emit_code
  15367. // because it is a closure here in a different context). Additionally
  15368. // we can call emit_byte_to_buffer less often, because we can have
  15369. // 30-bits (from our 31-bit signed SMI), and we know our codes will only
  15370. // be 12-bits, so can safely have 18-bits there without overflow.
  15371. // emit_code(ib_code);
  15372. cur |= ib_code << cur_shift;
  15373. cur_shift += cur_code_size;
  15374. while (cur_shift >= 8) {
  15375. buf[p++] = cur & 0xff;
  15376. cur >>= 8;
  15377. cur_shift -= 8;
  15378. if (p === cur_subblock + 256) {
  15379. // Finished a subblock.
  15380. buf[cur_subblock] = 255;
  15381. cur_subblock = p++;
  15382. }
  15383. }
  15384. if (next_code === 4096) {
  15385. // Table full, need a clear.
  15386. emit_code(clear_code);
  15387. next_code = eoi_code + 1;
  15388. cur_code_size = min_code_size + 1;
  15389. code_table = {};
  15390. } else {
  15391. // Table not full, insert a new entry.
  15392. // Increase our variable bit code sizes if necessary. This is a bit
  15393. // tricky as it is based on "timing" between the encoding and
  15394. // decoder. From the encoders perspective this should happen after
  15395. // we've already emitted the index buffer and are about to create the
  15396. // first table entry that would overflow our current code bit size.
  15397. if (next_code >= 1 << cur_code_size) ++cur_code_size;
  15398. code_table[cur_key] = next_code++; // Insert into code table.
  15399. }
  15400. ib_code = k; // Index buffer to single input k.
  15401. } else {
  15402. ib_code = cur_code; // Index buffer to sequence in code table.
  15403. }
  15404. }
  15405. emit_code(ib_code); // There will still be something in the index buffer.
  15406. emit_code(eoi_code); // End Of Information.
  15407. // Flush / finalize the sub-blocks stream to the buffer.
  15408. emit_bytes_to_buffer(1); // Finish the sub-blocks, writing out any unfinished lengths and
  15409. // terminating with a sub-block of length 0. If we have already started
  15410. // but not yet used a sub-block it can just become the terminator.
  15411. if (cur_subblock + 1 === p) {
  15412. // Started but unused.
  15413. buf[cur_subblock] = 0;
  15414. } else {
  15415. // Started and used, write length and additional terminator block.
  15416. buf[cur_subblock] = p - cur_subblock - 1;
  15417. buf[p++] = 0;
  15418. }
  15419. return p;
  15420. }
  15421. function GifReader(buf) {
  15422. var p = 0; // - Header (GIF87a or GIF89a).
  15423. if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 || buf[p++] !== 0x38 || (buf[p++] + 1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {
  15424. throw "Invalid GIF 87a/89a header.";
  15425. } // - Logical Screen Descriptor.
  15426. var width = buf[p++] | buf[p++] << 8;
  15427. var height = buf[p++] | buf[p++] << 8;
  15428. var pf0 = buf[p++]; // <Packed Fields>.
  15429. var global_palette_flag = pf0 >> 7;
  15430. var num_global_colors_pow2 = pf0 & 0x7;
  15431. var num_global_colors = 1 << num_global_colors_pow2 + 1;
  15432. var background = buf[p++];
  15433. buf[p++]; // Pixel aspect ratio (unused?).
  15434. var global_palette_offset = null;
  15435. if (global_palette_flag) {
  15436. global_palette_offset = p;
  15437. p += num_global_colors * 3; // Seek past palette.
  15438. }
  15439. var no_eof = true;
  15440. var frames = [];
  15441. var delay = 0;
  15442. var transparent_index = null;
  15443. var disposal = 0; // 0 - No disposal specified.
  15444. var loop_count = null;
  15445. this.width = width;
  15446. this.height = height;
  15447. while (no_eof && p < buf.length) {
  15448. switch (buf[p++]) {
  15449. case 0x21:
  15450. // Graphics Control Extension Block
  15451. switch (buf[p++]) {
  15452. case 0xff:
  15453. // Application specific block
  15454. // Try if it's a Netscape block (with animation loop counter).
  15455. if (buf[p] !== 0x0b || // 21 FF already read, check block size.
  15456. // NETSCAPE2.0
  15457. buf[p + 1] == 0x4e && buf[p + 2] == 0x45 && buf[p + 3] == 0x54 && buf[p + 4] == 0x53 && buf[p + 5] == 0x43 && buf[p + 6] == 0x41 && buf[p + 7] == 0x50 && buf[p + 8] == 0x45 && buf[p + 9] == 0x32 && buf[p + 10] == 0x2e && buf[p + 11] == 0x30 && // Sub-block
  15458. buf[p + 12] == 0x03 && buf[p + 13] == 0x01 && buf[p + 16] == 0) {
  15459. p += 14;
  15460. loop_count = buf[p++] | buf[p++] << 8;
  15461. p++; // Skip terminator.
  15462. } else {
  15463. // We don't know what it is, just try to get past it.
  15464. p += 12;
  15465. while (true) {
  15466. // Seek through subblocks.
  15467. var block_size = buf[p++];
  15468. if (block_size === 0) break;
  15469. p += block_size;
  15470. }
  15471. }
  15472. break;
  15473. case 0xf9:
  15474. // Graphics Control Extension
  15475. if (buf[p++] !== 0x4 || buf[p + 4] !== 0) throw "Invalid graphics extension block.";
  15476. var pf1 = buf[p++];
  15477. delay = buf[p++] | buf[p++] << 8;
  15478. transparent_index = buf[p++];
  15479. if ((pf1 & 1) === 0) transparent_index = null;
  15480. disposal = pf1 >> 2 & 0x7;
  15481. p++; // Skip terminator.
  15482. break;
  15483. case 0xfe:
  15484. // Comment Extension.
  15485. while (true) {
  15486. // Seek through subblocks.
  15487. var block_size = buf[p++];
  15488. if (block_size === 0) break; // console.log(buf.slice(p, p+block_size).toString('ascii'));
  15489. p += block_size;
  15490. }
  15491. break;
  15492. default:
  15493. throw "Unknown graphic control label: 0x" + buf[p - 1].toString(16);
  15494. }
  15495. break;
  15496. case 0x2c:
  15497. // Image Descriptor.
  15498. var x = buf[p++] | buf[p++] << 8;
  15499. var y = buf[p++] | buf[p++] << 8;
  15500. var w = buf[p++] | buf[p++] << 8;
  15501. var h = buf[p++] | buf[p++] << 8;
  15502. var pf2 = buf[p++];
  15503. var local_palette_flag = pf2 >> 7;
  15504. var interlace_flag = pf2 >> 6 & 1;
  15505. var num_local_colors_pow2 = pf2 & 0x7;
  15506. var num_local_colors = 1 << num_local_colors_pow2 + 1;
  15507. var palette_offset = global_palette_offset;
  15508. var has_local_palette = false;
  15509. if (local_palette_flag) {
  15510. var has_local_palette = true;
  15511. palette_offset = p; // Override with local palette.
  15512. p += num_local_colors * 3; // Seek past palette.
  15513. }
  15514. var data_offset = p;
  15515. p++; // codesize
  15516. while (true) {
  15517. var block_size = buf[p++];
  15518. if (block_size === 0) break;
  15519. p += block_size;
  15520. }
  15521. frames.push({
  15522. x: x,
  15523. y: y,
  15524. width: w,
  15525. height: h,
  15526. has_local_palette: has_local_palette,
  15527. palette_offset: palette_offset,
  15528. data_offset: data_offset,
  15529. data_length: p - data_offset,
  15530. transparent_index: transparent_index,
  15531. interlaced: !!interlace_flag,
  15532. delay: delay,
  15533. disposal: disposal
  15534. });
  15535. break;
  15536. case 0x3b:
  15537. // Trailer Marker (end of file).
  15538. no_eof = false;
  15539. break;
  15540. default:
  15541. throw "Unknown gif block: 0x" + buf[p - 1].toString(16);
  15542. break;
  15543. }
  15544. }
  15545. this.numFrames = function () {
  15546. return frames.length;
  15547. };
  15548. this.loopCount = function () {
  15549. return loop_count;
  15550. };
  15551. this.frameInfo = function (frame_num) {
  15552. if (frame_num < 0 || frame_num >= frames.length) throw "Frame index out of range.";
  15553. return frames[frame_num];
  15554. };
  15555. this.decodeAndBlitFrameBGRA = function (frame_num, pixels) {
  15556. var frame = this.frameInfo(frame_num);
  15557. var num_pixels = frame.width * frame.height;
  15558. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  15559. GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels);
  15560. var palette_offset = frame.palette_offset; // NOTE(deanm): It seems to be much faster to compare index to 256 than
  15561. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  15562. // the profile, not sure if it's related to using a Uint8Array.
  15563. var trans = frame.transparent_index;
  15564. if (trans === null) trans = 256; // We are possibly just blitting to a portion of the entire frame.
  15565. // That is a subrect within the framerect, so the additional pixels
  15566. // must be skipped over after we finished a scanline.
  15567. var framewidth = frame.width;
  15568. var framestride = width - framewidth;
  15569. var xleft = framewidth; // Number of subrect pixels left in scanline.
  15570. // Output indicies of the top left and bottom right corners of the subrect.
  15571. var opbeg = (frame.y * width + frame.x) * 4;
  15572. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  15573. var op = opbeg;
  15574. var scanstride = framestride * 4; // Use scanstride to skip past the rows when interlacing. This is skipping
  15575. // 7 rows for the first two passes, then 3 then 1.
  15576. if (frame.interlaced === true) {
  15577. scanstride += (framewidth + framestride) * 4 * 7; // Pass 1.
  15578. }
  15579. var interlaceskip = 8; // Tracking the row interval in the current pass.
  15580. for (var i = 0, il = index_stream.length; i < il; ++i) {
  15581. var index = index_stream[i];
  15582. if (xleft === 0) {
  15583. // Beginning of new scan line
  15584. op += scanstride;
  15585. xleft = framewidth;
  15586. if (op >= opend) {
  15587. // Catch the wrap to switch passes when interlacing.
  15588. scanstride = framestride + (framewidth + framestride) * 4 * (interlaceskip - 1); // interlaceskip / 2 * 4 is interlaceskip << 1.
  15589. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  15590. interlaceskip >>= 1;
  15591. }
  15592. }
  15593. if (index === trans) {
  15594. op += 4;
  15595. } else {
  15596. var r = buf[palette_offset + index * 3];
  15597. var g = buf[palette_offset + index * 3 + 1];
  15598. var b = buf[palette_offset + index * 3 + 2];
  15599. pixels[op++] = b;
  15600. pixels[op++] = g;
  15601. pixels[op++] = r;
  15602. pixels[op++] = 255;
  15603. }
  15604. --xleft;
  15605. }
  15606. }; // I will go to copy and paste hell one day...
  15607. this.decodeAndBlitFrameRGBA = function (frame_num, pixels) {
  15608. var frame = this.frameInfo(frame_num);
  15609. var num_pixels = frame.width * frame.height;
  15610. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  15611. GifReaderLZWOutputIndexStream(buf, frame.data_offset, index_stream, num_pixels);
  15612. var palette_offset = frame.palette_offset; // NOTE(deanm): It seems to be much faster to compare index to 256 than
  15613. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  15614. // the profile, not sure if it's related to using a Uint8Array.
  15615. var trans = frame.transparent_index;
  15616. if (trans === null) trans = 256; // We are possibly just blitting to a portion of the entire frame.
  15617. // That is a subrect within the framerect, so the additional pixels
  15618. // must be skipped over after we finished a scanline.
  15619. var framewidth = frame.width;
  15620. var framestride = width - framewidth;
  15621. var xleft = framewidth; // Number of subrect pixels left in scanline.
  15622. // Output indicies of the top left and bottom right corners of the subrect.
  15623. var opbeg = (frame.y * width + frame.x) * 4;
  15624. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  15625. var op = opbeg;
  15626. var scanstride = framestride * 4; // Use scanstride to skip past the rows when interlacing. This is skipping
  15627. // 7 rows for the first two passes, then 3 then 1.
  15628. if (frame.interlaced === true) {
  15629. scanstride += (framewidth + framestride) * 4 * 7; // Pass 1.
  15630. }
  15631. var interlaceskip = 8; // Tracking the row interval in the current pass.
  15632. for (var i = 0, il = index_stream.length; i < il; ++i) {
  15633. var index = index_stream[i];
  15634. if (xleft === 0) {
  15635. // Beginning of new scan line
  15636. op += scanstride;
  15637. xleft = framewidth;
  15638. if (op >= opend) {
  15639. // Catch the wrap to switch passes when interlacing.
  15640. scanstride = framestride + (framewidth + framestride) * 4 * (interlaceskip - 1); // interlaceskip / 2 * 4 is interlaceskip << 1.
  15641. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  15642. interlaceskip >>= 1;
  15643. }
  15644. }
  15645. if (index === trans) {
  15646. op += 4;
  15647. } else {
  15648. var r = buf[palette_offset + index * 3];
  15649. var g = buf[palette_offset + index * 3 + 1];
  15650. var b = buf[palette_offset + index * 3 + 2];
  15651. pixels[op++] = r;
  15652. pixels[op++] = g;
  15653. pixels[op++] = b;
  15654. pixels[op++] = 255;
  15655. }
  15656. --xleft;
  15657. }
  15658. };
  15659. }
  15660. function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
  15661. var min_code_size = code_stream[p++];
  15662. var clear_code = 1 << min_code_size;
  15663. var eoi_code = clear_code + 1;
  15664. var next_code = eoi_code + 1;
  15665. var cur_code_size = min_code_size + 1; // Number of bits per code.
  15666. // NOTE: This shares the same name as the encoder, but has a different
  15667. // meaning here. Here this masks each code coming from the code stream.
  15668. var code_mask = (1 << cur_code_size) - 1;
  15669. var cur_shift = 0;
  15670. var cur = 0;
  15671. var op = 0; // Output pointer.
  15672. var subblock_size = code_stream[p++]; // TODO(deanm): Would using a TypedArray be any faster? At least it would
  15673. // solve the fast mode / backing store uncertainty.
  15674. // var code_table = Array(4096);
  15675. var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
  15676. var prev_code = null; // Track code-1.
  15677. while (true) {
  15678. // Read up to two bytes, making sure we always 12-bits for max sized code.
  15679. while (cur_shift < 16) {
  15680. if (subblock_size === 0) break; // No more data to be read.
  15681. cur |= code_stream[p++] << cur_shift;
  15682. cur_shift += 8;
  15683. if (subblock_size === 1) {
  15684. // Never let it get to 0 to hold logic above.
  15685. subblock_size = code_stream[p++]; // Next subblock.
  15686. } else {
  15687. --subblock_size;
  15688. }
  15689. } // TODO(deanm): We should never really get here, we should have received
  15690. // and EOI.
  15691. if (cur_shift < cur_code_size) break;
  15692. var code = cur & code_mask;
  15693. cur >>= cur_code_size;
  15694. cur_shift -= cur_code_size; // TODO(deanm): Maybe should check that the first code was a clear code,
  15695. // at least this is what you're supposed to do. But actually our encoder
  15696. // now doesn't emit a clear code first anyway.
  15697. if (code === clear_code) {
  15698. // We don't actually have to clear the table. This could be a good idea
  15699. // for greater error checking, but we don't really do any anyway. We
  15700. // will just track it with next_code and overwrite old entries.
  15701. next_code = eoi_code + 1;
  15702. cur_code_size = min_code_size + 1;
  15703. code_mask = (1 << cur_code_size) - 1; // Don't update prev_code ?
  15704. prev_code = null;
  15705. continue;
  15706. } else if (code === eoi_code) {
  15707. break;
  15708. } // We have a similar situation as the decoder, where we want to store
  15709. // variable length entries (code table entries), but we want to do in a
  15710. // faster manner than an array of arrays. The code below stores sort of a
  15711. // linked list within the code table, and then "chases" through it to
  15712. // construct the dictionary entries. When a new entry is created, just the
  15713. // last byte is stored, and the rest (prefix) of the entry is only
  15714. // referenced by its table entry. Then the code chases through the
  15715. // prefixes until it reaches a single byte code. We have to chase twice,
  15716. // first to compute the length, and then to actually copy the data to the
  15717. // output (backwards, since we know the length). The alternative would be
  15718. // storing something in an intermediate stack, but that doesn't make any
  15719. // more sense. I implemented an approach where it also stored the length
  15720. // in the code table, although it's a bit tricky because you run out of
  15721. // bits (12 + 12 + 8), but I didn't measure much improvements (the table
  15722. // entries are generally not the long). Even when I created benchmarks for
  15723. // very long table entries the complexity did not seem worth it.
  15724. // The code table stores the prefix entry in 12 bits and then the suffix
  15725. // byte in 8 bits, so each entry is 20 bits.
  15726. var chase_code = code < next_code ? code : prev_code; // Chase what we will output, either {CODE} or {CODE-1}.
  15727. var chase_length = 0;
  15728. var chase = chase_code;
  15729. while (chase > clear_code) {
  15730. chase = code_table[chase] >> 8;
  15731. ++chase_length;
  15732. }
  15733. var k = chase;
  15734. var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
  15735. if (op_end > output_length) {
  15736. console.log("Warning, gif stream longer than expected.");
  15737. return;
  15738. } // Already have the first byte from the chase, might as well write it fast.
  15739. output[op++] = k;
  15740. op += chase_length;
  15741. var b = op; // Track pointer, writing backwards.
  15742. if (chase_code !== code) // The case of emitting {CODE-1} + k.
  15743. output[op++] = k;
  15744. chase = chase_code;
  15745. while (chase_length--) {
  15746. chase = code_table[chase];
  15747. output[--b] = chase & 0xff; // Write backwards.
  15748. chase >>= 8; // Pull down to the prefix code.
  15749. }
  15750. if (prev_code !== null && next_code < 4096) {
  15751. code_table[next_code++] = prev_code << 8 | k; // TODO(deanm): Figure out this clearing vs code growth logic better. I
  15752. // have an feeling that it should just happen somewhere else, for now it
  15753. // is awkward between when we grow past the max and then hit a clear code.
  15754. // For now just check if we hit the max 12-bits (then a clear code should
  15755. // follow, also of course encoded in 12-bits).
  15756. if (next_code >= code_mask + 1 && cur_code_size < 12) {
  15757. ++cur_code_size;
  15758. code_mask = code_mask << 1 | 1;
  15759. }
  15760. }
  15761. prev_code = code;
  15762. }
  15763. if (op !== output_length) {
  15764. console.log("Warning, gif stream shorter than expected.");
  15765. }
  15766. return output;
  15767. }
  15768. try {
  15769. exports.GifWriter = GifWriter;
  15770. exports.GifReader = GifReader;
  15771. } catch (e) {} // CommonJS.
  15772. /*rollup-keeper-start*/
  15773. window.tmp = GifReader;
  15774. /*rollup-keeper-end*/
  15775. /*
  15776. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  15777. *
  15778. * Licensed under the MIT License.
  15779. * http://opensource.org/licenses/mit-license
  15780. */
  15781. (function (jsPDF, callback) {
  15782. jsPDF.API.adler32cs = callback();
  15783. })(jsPDF, function () {
  15784. var _hasArrayBuffer = typeof ArrayBuffer === 'function' && typeof Uint8Array === 'function';
  15785. var _Buffer = null,
  15786. _isBuffer = function () {
  15787. if (!_hasArrayBuffer) return function _isBuffer() {
  15788. return false;
  15789. };
  15790. try {
  15791. var buffer = {};
  15792. if (typeof buffer.Buffer === 'function') _Buffer = buffer.Buffer;
  15793. } catch (error) {}
  15794. return function _isBuffer(value) {
  15795. return value instanceof ArrayBuffer || _Buffer !== null && value instanceof _Buffer;
  15796. };
  15797. }();
  15798. var _utf8ToBinary = function () {
  15799. if (_Buffer !== null) {
  15800. return function _utf8ToBinary(utf8String) {
  15801. return new _Buffer(utf8String, 'utf8').toString('binary');
  15802. };
  15803. } else {
  15804. return function _utf8ToBinary(utf8String) {
  15805. return unescape(encodeURIComponent(utf8String));
  15806. };
  15807. }
  15808. }();
  15809. var MOD = 65521;
  15810. var _update = function _update(checksum, binaryString) {
  15811. var a = checksum & 0xFFFF,
  15812. b = checksum >>> 16;
  15813. for (var i = 0, length = binaryString.length; i < length; i++) {
  15814. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  15815. b = (b + a) % MOD;
  15816. }
  15817. return (b << 16 | a) >>> 0;
  15818. };
  15819. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  15820. var a = checksum & 0xFFFF,
  15821. b = checksum >>> 16;
  15822. for (var i = 0, length = uint8Array.length; i < length; i++) {
  15823. a = (a + uint8Array[i]) % MOD;
  15824. b = (b + a) % MOD;
  15825. }
  15826. return (b << 16 | a) >>> 0;
  15827. };
  15828. var exports = {};
  15829. var Adler32 = exports.Adler32 = function () {
  15830. var ctor = function Adler32(checksum) {
  15831. if (!(this instanceof ctor)) {
  15832. throw new TypeError('Constructor cannot called be as a function.');
  15833. }
  15834. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  15835. throw new Error('First arguments needs to be a finite number.');
  15836. }
  15837. this.checksum = checksum >>> 0;
  15838. };
  15839. var proto = ctor.prototype = {};
  15840. proto.constructor = ctor;
  15841. ctor.from = function (from) {
  15842. from.prototype = proto;
  15843. return from;
  15844. }(function from(binaryString) {
  15845. if (!(this instanceof ctor)) {
  15846. throw new TypeError('Constructor cannot called be as a function.');
  15847. }
  15848. if (binaryString == null) throw new Error('First argument needs to be a string.');
  15849. this.checksum = _update(1, binaryString.toString());
  15850. });
  15851. ctor.fromUtf8 = function (fromUtf8) {
  15852. fromUtf8.prototype = proto;
  15853. return fromUtf8;
  15854. }(function fromUtf8(utf8String) {
  15855. if (!(this instanceof ctor)) {
  15856. throw new TypeError('Constructor cannot called be as a function.');
  15857. }
  15858. if (utf8String == null) throw new Error('First argument needs to be a string.');
  15859. var binaryString = _utf8ToBinary(utf8String.toString());
  15860. this.checksum = _update(1, binaryString);
  15861. });
  15862. if (_hasArrayBuffer) {
  15863. ctor.fromBuffer = function (fromBuffer) {
  15864. fromBuffer.prototype = proto;
  15865. return fromBuffer;
  15866. }(function fromBuffer(buffer) {
  15867. if (!(this instanceof ctor)) {
  15868. throw new TypeError('Constructor cannot called be as a function.');
  15869. }
  15870. if (!_isBuffer(buffer)) throw new Error('First argument needs to be ArrayBuffer.');
  15871. var array = new Uint8Array(buffer);
  15872. return this.checksum = _updateUint8Array(1, array);
  15873. });
  15874. }
  15875. proto.update = function update(binaryString) {
  15876. if (binaryString == null) throw new Error('First argument needs to be a string.');
  15877. binaryString = binaryString.toString();
  15878. return this.checksum = _update(this.checksum, binaryString);
  15879. };
  15880. proto.updateUtf8 = function updateUtf8(utf8String) {
  15881. if (utf8String == null) throw new Error('First argument needs to be a string.');
  15882. var binaryString = _utf8ToBinary(utf8String.toString());
  15883. return this.checksum = _update(this.checksum, binaryString);
  15884. };
  15885. if (_hasArrayBuffer) {
  15886. proto.updateBuffer = function updateBuffer(buffer) {
  15887. if (!_isBuffer(buffer)) throw new Error('First argument needs to be ArrayBuffer.');
  15888. var array = new Uint8Array(buffer);
  15889. return this.checksum = _updateUint8Array(this.checksum, array);
  15890. };
  15891. }
  15892. proto.clone = function clone() {
  15893. return new Adler32(this.checksum);
  15894. };
  15895. return ctor;
  15896. }();
  15897. exports.from = function from(binaryString) {
  15898. if (binaryString == null) throw new Error('First argument needs to be a string.');
  15899. return _update(1, binaryString.toString());
  15900. };
  15901. exports.fromUtf8 = function fromUtf8(utf8String) {
  15902. if (utf8String == null) throw new Error('First argument needs to be a string.');
  15903. var binaryString = _utf8ToBinary(utf8String.toString());
  15904. return _update(1, binaryString);
  15905. };
  15906. if (_hasArrayBuffer) {
  15907. exports.fromBuffer = function fromBuffer(buffer) {
  15908. if (!_isBuffer(buffer)) throw new Error('First argument need to be ArrayBuffer.');
  15909. var array = new Uint8Array(buffer);
  15910. return _updateUint8Array(1, array);
  15911. };
  15912. }
  15913. return exports;
  15914. });
  15915. /**
  15916. * Unicode Bidi Engine based on the work of Alex Shensis (@asthensis)
  15917. * MIT License
  15918. */
  15919. (function (jsPDF) {
  15920. /**
  15921. * Table of Unicode types.
  15922. *
  15923. * Generated by:
  15924. *
  15925. * var bidi = require("./bidi/index");
  15926. * var bidi_accumulate = bidi.slice(0, 256).concat(bidi.slice(0x0500, 0x0500 + 256 * 3)).
  15927. * concat(bidi.slice(0x2000, 0x2000 + 256)).concat(bidi.slice(0xFB00, 0xFB00 + 256)).
  15928. * concat(bidi.slice(0xFE00, 0xFE00 + 2 * 256));
  15929. *
  15930. * for( var i = 0; i < bidi_accumulate.length; i++) {
  15931. * if(bidi_accumulate[i] === undefined || bidi_accumulate[i] === 'ON')
  15932. * bidi_accumulate[i] = 'N'; //mark as neutral to conserve space and substitute undefined
  15933. * }
  15934. * var bidiAccumulateStr = 'return [ "' + bidi_accumulate.toString().replace(/,/g, '", "') + '" ];';
  15935. * require("fs").writeFile('unicode-types.js', bidiAccumulateStr);
  15936. *
  15937. * Based on:
  15938. * https://github.com/mathiasbynens/unicode-8.0.0
  15939. */
  15940. var bidiUnicodeTypes = ["BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "S", "B", "S", "WS", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "B", "B", "B", "S", "WS", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "BN", "BN", "BN", "BN", "BN", "BN", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "CS", "N", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "L", "N", "N", "BN", "N", "N", "ET", "ET", "EN", "EN", "N", "L", "N", "N", "N", "EN", "L", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "N", "N", "N", "N", "N", "ET", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "NSM", "R", "NSM", "NSM", "R", "NSM", "NSM", "R", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AN", "AN", "AN", "AN", "AN", "AN", "N", "N", "AL", "ET", "ET", "AL", "CS", "AL", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "ET", "AN", "AN", "AL", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "NSM", "NSM", "N", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "R", "N", "N", "N", "N", "R", "N", "N", "N", "N", "N", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "BN", "BN", "BN", "L", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "B", "LRE", "RLE", "PDF", "LRO", "RLO", "CS", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "BN", "BN", "BN", "BN", "BN", "N", "LRI", "RLI", "FSI", "PDI", "BN", "BN", "BN", "BN", "BN", "BN", "EN", "L", "N", "N", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "L", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "R", "NSM", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "ES", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "R", "R", "R", "R", "R", "N", "R", "N", "R", "R", "N", "R", "R", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "CS", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "ET", "N", "N", "ES", "ES", "N", "N", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "BN", "N", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "N", "N", "N", "ET", "ET", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N"];
  15941. /**
  15942. * Unicode Bidi algorithm compliant Bidi engine.
  15943. * For reference see http://unicode.org/reports/tr9/
  15944. */
  15945. /**
  15946. * constructor ( options )
  15947. *
  15948. * Initializes Bidi engine
  15949. *
  15950. * @param {Object} See 'setOptions' below for detailed description.
  15951. * options are cashed between invocation of 'doBidiReorder' method
  15952. *
  15953. * sample usage pattern of BidiEngine:
  15954. * var opt = {
  15955. * isInputVisual: true,
  15956. * isInputRtl: false,
  15957. * isOutputVisual: false,
  15958. * isOutputRtl: false,
  15959. * isSymmetricSwapping: true
  15960. * }
  15961. * var sourceToTarget = [], levels = [];
  15962. * var bidiEng = Globalize.bidiEngine(opt);
  15963. * var src = "text string to be reordered";
  15964. * var ret = bidiEng.doBidiReorder(src, sourceToTarget, levels);
  15965. */
  15966. jsPDF.__bidiEngine__ = jsPDF.prototype.__bidiEngine__ = function (options) {
  15967. var _UNICODE_TYPES = _bidiUnicodeTypes;
  15968. var _STATE_TABLE_LTR = [[0, 3, 0, 1, 0, 0, 0], [0, 3, 0, 1, 2, 2, 0], [0, 3, 0, 0x11, 2, 0, 1], [0, 3, 5, 5, 4, 1, 0], [0, 3, 0x15, 0x15, 4, 0, 1], [0, 3, 5, 5, 4, 2, 0]];
  15969. var _STATE_TABLE_RTL = [[2, 0, 1, 1, 0, 1, 0], [2, 0, 1, 1, 0, 2, 0], [2, 0, 2, 1, 3, 2, 0], [2, 0, 2, 0x21, 3, 1, 1]];
  15970. var _TYPE_NAMES_MAP = {
  15971. "L": 0,
  15972. "R": 1,
  15973. "EN": 2,
  15974. "AN": 3,
  15975. "N": 4,
  15976. "B": 5,
  15977. "S": 6
  15978. };
  15979. var _UNICODE_RANGES_MAP = {
  15980. 0: 0,
  15981. 5: 1,
  15982. 6: 2,
  15983. 7: 3,
  15984. 0x20: 4,
  15985. 0xFB: 5,
  15986. 0xFE: 6,
  15987. 0xFF: 7
  15988. };
  15989. var _SWAP_TABLE = ["(", ")", "(", "<", ">", "<", "[", "]", "[", "{", "}", "{", "\xAB", "\xBB", "\xAB", "\u2039", "\u203A", "\u2039", "\u2045", "\u2046", "\u2045", "\u207D", "\u207E", "\u207D", "\u208D", "\u208E", "\u208D", "\u2264", "\u2265", "\u2264", "\u2329", "\u232A", "\u2329", "\uFE59", "\uFE5A", "\uFE59", "\uFE5B", "\uFE5C", "\uFE5B", "\uFE5D", "\uFE5E", "\uFE5D", "\uFE64", "\uFE65", "\uFE64"];
  15990. var _LTR_RANGES_REG_EXPR = new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/);
  15991. var _lastArabic = false,
  15992. _hasUbatB,
  15993. _hasUbatS,
  15994. DIR_LTR = 0,
  15995. DIR_RTL = 1,
  15996. _isInVisual,
  15997. _isInRtl,
  15998. _isOutVisual,
  15999. _isOutRtl,
  16000. _isSymmetricSwapping,
  16001. _dir = DIR_LTR;
  16002. this.__bidiEngine__ = {};
  16003. var _init = function _init(text, sourceToTargetMap) {
  16004. if (sourceToTargetMap) {
  16005. for (var i = 0; i < text.length; i++) {
  16006. sourceToTargetMap[i] = i;
  16007. }
  16008. }
  16009. if (_isInRtl === undefined) {
  16010. _isInRtl = _isContextualDirRtl(text);
  16011. }
  16012. if (_isOutRtl === undefined) {
  16013. _isOutRtl = _isContextualDirRtl(text);
  16014. }
  16015. }; // for reference see 3.2 in http://unicode.org/reports/tr9/
  16016. //
  16017. var _getCharType = function _getCharType(ch) {
  16018. var charCode = ch.charCodeAt(),
  16019. range = charCode >> 8,
  16020. rangeIdx = _UNICODE_RANGES_MAP[range];
  16021. if (rangeIdx !== undefined) {
  16022. return _UNICODE_TYPES[rangeIdx * 256 + (charCode & 0xFF)];
  16023. } else if (range === 0xFC || range === 0xFD) {
  16024. return "AL";
  16025. } else if (_LTR_RANGES_REG_EXPR.test(range)) {
  16026. //unlikely case
  16027. return "L";
  16028. } else if (range === 8) {
  16029. // even less likely
  16030. return "R";
  16031. }
  16032. return "N"; //undefined type, mark as neutral
  16033. };
  16034. var _isContextualDirRtl = function _isContextualDirRtl(text) {
  16035. for (var i = 0, charType; i < text.length; i++) {
  16036. charType = _getCharType(text.charAt(i));
  16037. if (charType === "L") {
  16038. return false;
  16039. } else if (charType === "R") {
  16040. return true;
  16041. }
  16042. }
  16043. return false;
  16044. }; // for reference see 3.3.4 & 3.3.5 in http://unicode.org/reports/tr9/
  16045. //
  16046. var _resolveCharType = function _resolveCharType(chars, types, resolvedTypes, index) {
  16047. var cType = types[index],
  16048. wType,
  16049. nType,
  16050. i,
  16051. len;
  16052. switch (cType) {
  16053. case "L":
  16054. case "R":
  16055. _lastArabic = false;
  16056. break;
  16057. case "N":
  16058. case "AN":
  16059. break;
  16060. case "EN":
  16061. if (_lastArabic) {
  16062. cType = "AN";
  16063. }
  16064. break;
  16065. case "AL":
  16066. _lastArabic = true;
  16067. cType = "R";
  16068. break;
  16069. case "WS":
  16070. cType = "N";
  16071. break;
  16072. case "CS":
  16073. if (index < 1 || index + 1 >= types.length || (wType = resolvedTypes[index - 1]) !== "EN" && wType !== "AN" || (nType = types[index + 1]) !== "EN" && nType !== "AN") {
  16074. cType = "N";
  16075. } else if (_lastArabic) {
  16076. nType = "AN";
  16077. }
  16078. cType = nType === wType ? nType : "N";
  16079. break;
  16080. case "ES":
  16081. wType = index > 0 ? resolvedTypes[index - 1] : "B";
  16082. cType = wType === "EN" && index + 1 < types.length && types[index + 1] === "EN" ? "EN" : "N";
  16083. break;
  16084. case "ET":
  16085. if (index > 0 && resolvedTypes[index - 1] === "EN") {
  16086. cType = "EN";
  16087. break;
  16088. } else if (_lastArabic) {
  16089. cType = "N";
  16090. break;
  16091. }
  16092. i = index + 1;
  16093. len = types.length;
  16094. while (i < len && types[i] === "ET") {
  16095. i++;
  16096. }
  16097. if (i < len && types[i] === "EN") {
  16098. cType = "EN";
  16099. } else {
  16100. cType = "N";
  16101. }
  16102. break;
  16103. case "NSM":
  16104. if (_isInVisual && !_isInRtl) {
  16105. //V->L
  16106. len = types.length;
  16107. i = index + 1;
  16108. while (i < len && types[i] === "NSM") {
  16109. i++;
  16110. }
  16111. if (i < len) {
  16112. var c = chars[index];
  16113. var rtlCandidate = c >= 0x0591 && c <= 0x08FF || c === 0xFB1E;
  16114. wType = types[i];
  16115. if (rtlCandidate && (wType === "R" || wType === "AL")) {
  16116. cType = "R";
  16117. break;
  16118. }
  16119. }
  16120. }
  16121. if (index < 1 || (wType = types[index - 1]) === "B") {
  16122. cType = "N";
  16123. } else {
  16124. cType = resolvedTypes[index - 1];
  16125. }
  16126. break;
  16127. case "B":
  16128. _lastArabic = false;
  16129. _hasUbatB = true;
  16130. cType = _dir;
  16131. break;
  16132. case "S":
  16133. _hasUbatS = true;
  16134. cType = "N";
  16135. break;
  16136. case "LRE":
  16137. case "RLE":
  16138. case "LRO":
  16139. case "RLO":
  16140. case "PDF":
  16141. _lastArabic = false;
  16142. break;
  16143. case "BN":
  16144. cType = "N";
  16145. break;
  16146. }
  16147. return cType;
  16148. };
  16149. var _handleUbatS = function _handleUbatS(types, levels, length) {
  16150. for (var i = 0; i < length; i++) {
  16151. if (types[i] === "S") {
  16152. levels[i] = _dir;
  16153. for (var j = i - 1; j >= 0; j--) {
  16154. if (types[j] === "WS") {
  16155. levels[j] = _dir;
  16156. } else {
  16157. break;
  16158. }
  16159. }
  16160. }
  16161. }
  16162. };
  16163. var _invertString = function _invertString(text, sourceToTargetMap, levels) {
  16164. var charArray = text.split("");
  16165. if (levels) {
  16166. _computeLevels(charArray, levels, {
  16167. hiLevel: _dir
  16168. });
  16169. }
  16170. charArray.reverse();
  16171. sourceToTargetMap && sourceToTargetMap.reverse();
  16172. return charArray.join("");
  16173. }; // For reference see 3.3 in http://unicode.org/reports/tr9/
  16174. //
  16175. var _computeLevels = function _computeLevels(chars, levels, params) {
  16176. var action,
  16177. condition,
  16178. i,
  16179. index,
  16180. newLevel,
  16181. prevState,
  16182. condPos = -1,
  16183. len = chars.length,
  16184. newState = 0,
  16185. resolvedTypes = [],
  16186. stateTable = _dir ? _STATE_TABLE_RTL : _STATE_TABLE_LTR,
  16187. types = [];
  16188. _lastArabic = false;
  16189. _hasUbatB = false;
  16190. _hasUbatS = false;
  16191. for (i = 0; i < len; i++) {
  16192. types[i] = _getCharType(chars[i]);
  16193. }
  16194. for (index = 0; index < len; index++) {
  16195. prevState = newState;
  16196. resolvedTypes[index] = _resolveCharType(chars, types, resolvedTypes, index);
  16197. newState = stateTable[prevState][_TYPE_NAMES_MAP[resolvedTypes[index]]];
  16198. action = newState & 0xF0;
  16199. newState &= 0x0F;
  16200. levels[index] = newLevel = stateTable[newState][5];
  16201. if (action > 0) {
  16202. if (action === 0x10) {
  16203. for (i = condPos; i < index; i++) {
  16204. levels[i] = 1;
  16205. }
  16206. condPos = -1;
  16207. } else {
  16208. condPos = -1;
  16209. }
  16210. }
  16211. condition = stateTable[newState][6];
  16212. if (condition) {
  16213. if (condPos === -1) {
  16214. condPos = index;
  16215. }
  16216. } else {
  16217. if (condPos > -1) {
  16218. for (i = condPos; i < index; i++) {
  16219. levels[i] = newLevel;
  16220. }
  16221. condPos = -1;
  16222. }
  16223. }
  16224. if (types[index] === "B") {
  16225. levels[index] = 0;
  16226. }
  16227. params.hiLevel |= newLevel;
  16228. }
  16229. if (_hasUbatS) {
  16230. _handleUbatS(types, levels, len);
  16231. }
  16232. }; // for reference see 3.4 in http://unicode.org/reports/tr9/
  16233. //
  16234. var _invertByLevel = function _invertByLevel(level, charArray, sourceToTargetMap, levels, params) {
  16235. if (params.hiLevel < level) {
  16236. return;
  16237. }
  16238. if (level === 1 && _dir === DIR_RTL && !_hasUbatB) {
  16239. charArray.reverse();
  16240. sourceToTargetMap && sourceToTargetMap.reverse();
  16241. return;
  16242. }
  16243. var ch,
  16244. high,
  16245. end,
  16246. low,
  16247. len = charArray.length,
  16248. start = 0;
  16249. while (start < len) {
  16250. if (levels[start] >= level) {
  16251. end = start + 1;
  16252. while (end < len && levels[end] >= level) {
  16253. end++;
  16254. }
  16255. for (low = start, high = end - 1; low < high; low++, high--) {
  16256. ch = charArray[low];
  16257. charArray[low] = charArray[high];
  16258. charArray[high] = ch;
  16259. if (sourceToTargetMap) {
  16260. ch = sourceToTargetMap[low];
  16261. sourceToTargetMap[low] = sourceToTargetMap[high];
  16262. sourceToTargetMap[high] = ch;
  16263. }
  16264. }
  16265. start = end;
  16266. }
  16267. start++;
  16268. }
  16269. }; // for reference see 7 & BD16 in http://unicode.org/reports/tr9/
  16270. //
  16271. var _symmetricSwap = function _symmetricSwap(charArray, levels, params) {
  16272. if (params.hiLevel !== 0 && _isSymmetricSwapping) {
  16273. for (var i = 0, index; i < charArray.length; i++) {
  16274. if (levels[i] === 1) {
  16275. index = _SWAP_TABLE.indexOf(charArray[i]);
  16276. if (index >= 0) {
  16277. charArray[i] = _SWAP_TABLE[index + 1];
  16278. }
  16279. }
  16280. }
  16281. }
  16282. };
  16283. var _reorder = function _reorder(text, sourceToTargetMap, levels) {
  16284. var charArray = text.split(""),
  16285. params = {
  16286. hiLevel: _dir
  16287. };
  16288. if (!levels) {
  16289. levels = [];
  16290. }
  16291. _computeLevels(charArray, levels, params);
  16292. _symmetricSwap(charArray, levels, params);
  16293. _invertByLevel(DIR_RTL + 1, charArray, sourceToTargetMap, levels, params);
  16294. _invertByLevel(DIR_RTL, charArray, sourceToTargetMap, levels, params);
  16295. return charArray.join("");
  16296. }; // doBidiReorder( text, sourceToTargetMap, levels )
  16297. // Performs Bidi reordering by implementing Unicode Bidi algorithm.
  16298. // Returns reordered string
  16299. // @text [String]:
  16300. // - input string to be reordered, this is input parameter
  16301. // $sourceToTargetMap [Array] (optional)
  16302. // - resultant mapping between input and output strings, this is output parameter
  16303. // $levels [Array] (optional)
  16304. // - array of calculated Bidi levels, , this is output parameter
  16305. this.__bidiEngine__.doBidiReorder = function (text, sourceToTargetMap, levels) {
  16306. _init(text, sourceToTargetMap);
  16307. if (!_isInVisual && _isOutVisual && !_isOutRtl) {
  16308. // LLTR->VLTR, LRTL->VLTR
  16309. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  16310. text = _reorder(text, sourceToTargetMap, levels);
  16311. } else if (_isInVisual && _isOutVisual && _isInRtl ^ _isOutRtl) {
  16312. // VRTL->VLTR, VLTR->VRTL
  16313. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  16314. text = _invertString(text, sourceToTargetMap, levels);
  16315. } else if (!_isInVisual && _isOutVisual && _isOutRtl) {
  16316. // LLTR->VRTL, LRTL->VRTL
  16317. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  16318. text = _reorder(text, sourceToTargetMap, levels);
  16319. text = _invertString(text, sourceToTargetMap);
  16320. } else if (_isInVisual && !_isInRtl && !_isOutVisual && !_isOutRtl) {
  16321. // VLTR->LLTR
  16322. _dir = DIR_LTR;
  16323. text = _reorder(text, sourceToTargetMap, levels);
  16324. } else if (_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
  16325. // VLTR->LRTL, VRTL->LLTR
  16326. text = _invertString(text, sourceToTargetMap);
  16327. if (_isInRtl) {
  16328. //LLTR -> VLTR
  16329. _dir = DIR_LTR;
  16330. text = _reorder(text, sourceToTargetMap, levels);
  16331. } else {
  16332. //LRTL -> VRTL
  16333. _dir = DIR_RTL;
  16334. text = _reorder(text, sourceToTargetMap, levels);
  16335. text = _invertString(text, sourceToTargetMap);
  16336. }
  16337. } else if (_isInVisual && _isInRtl && !_isOutVisual && _isOutRtl) {
  16338. // VRTL->LRTL
  16339. _dir = DIR_RTL;
  16340. text = _reorder(text, sourceToTargetMap, levels);
  16341. text = _invertString(text, sourceToTargetMap);
  16342. } else if (!_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
  16343. // LRTL->LLTR, LLTR->LRTL
  16344. var isSymmetricSwappingOrig = _isSymmetricSwapping;
  16345. if (_isInRtl) {
  16346. //LRTL->LLTR
  16347. _dir = DIR_RTL;
  16348. text = _reorder(text, sourceToTargetMap, levels);
  16349. _dir = DIR_LTR;
  16350. _isSymmetricSwapping = false;
  16351. text = _reorder(text, sourceToTargetMap, levels);
  16352. _isSymmetricSwapping = isSymmetricSwappingOrig;
  16353. } else {
  16354. //LLTR->LRTL
  16355. _dir = DIR_LTR;
  16356. text = _reorder(text, sourceToTargetMap, levels);
  16357. text = _invertString(text, sourceToTargetMap);
  16358. _dir = DIR_RTL;
  16359. _isSymmetricSwapping = false;
  16360. text = _reorder(text, sourceToTargetMap, levels);
  16361. _isSymmetricSwapping = isSymmetricSwappingOrig;
  16362. text = _invertString(text, sourceToTargetMap);
  16363. }
  16364. }
  16365. return text;
  16366. };
  16367. /**
  16368. * @name setOptions( options )
  16369. * @function
  16370. * Sets options for Bidi conversion
  16371. * @param {Object}:
  16372. * - isInputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
  16373. * - isInputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong character of input string)
  16374. * - isOutputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
  16375. * - isOutputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong characterof input string)
  16376. * - isSymmetricSwapping {boolean} (defaults to false): allowed values true(needs symmetric swapping), false (no need in symmetric swapping),
  16377. */
  16378. this.__bidiEngine__.setOptions = function (options) {
  16379. if (options) {
  16380. _isInVisual = options.isInputVisual;
  16381. _isOutVisual = options.isOutputVisual;
  16382. _isInRtl = options.isInputRtl;
  16383. _isOutRtl = options.isOutputRtl;
  16384. _isSymmetricSwapping = options.isSymmetricSwapping;
  16385. }
  16386. };
  16387. this.__bidiEngine__.setOptions(options);
  16388. return this.__bidiEngine__;
  16389. };
  16390. var _bidiUnicodeTypes = bidiUnicodeTypes;
  16391. var bidiEngine = new jsPDF.__bidiEngine__({
  16392. isInputVisual: true
  16393. });
  16394. var bidiEngineFunction = function bidiEngineFunction(args) {
  16395. var text = args.text;
  16396. var x = args.x;
  16397. var y = args.y;
  16398. var options = args.options || {};
  16399. var mutex = args.mutex || {};
  16400. var lang = options.lang;
  16401. var tmpText = [];
  16402. if (Object.prototype.toString.call(text) === '[object Array]') {
  16403. var i = 0;
  16404. tmpText = [];
  16405. for (i = 0; i < text.length; i += 1) {
  16406. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  16407. tmpText.push([bidiEngine.doBidiReorder(text[i][0]), text[i][1], text[i][2]]);
  16408. } else {
  16409. tmpText.push([bidiEngine.doBidiReorder(text[i])]);
  16410. }
  16411. }
  16412. args.text = tmpText;
  16413. } else {
  16414. args.text = bidiEngine.doBidiReorder(text);
  16415. }
  16416. };
  16417. jsPDF.API.events.push(['postProcessText', bidiEngineFunction]);
  16418. })(jsPDF);
  16419. /*
  16420. Copyright (c) 2008, Adobe Systems Incorporated
  16421. All rights reserved.
  16422. Redistribution and use in source and binary forms, with or without
  16423. modification, are permitted provided that the following conditions are
  16424. met:
  16425. * Redistributions of source code must retain the above copyright notice,
  16426. this list of conditions and the following disclaimer.
  16427. * Redistributions in binary form must reproduce the above copyright
  16428. notice, this list of conditions and the following disclaimer in the
  16429. documentation and/or other materials provided with the distribution.
  16430. * Neither the name of Adobe Systems Incorporated nor the names of its
  16431. contributors may be used to endorse or promote products derived from
  16432. this software without specific prior written permission.
  16433. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  16434. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  16435. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16436. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  16437. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  16438. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16439. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16440. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  16441. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  16442. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  16443. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16444. */
  16445. /*
  16446. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  16447. Basic GUI blocking jpeg encoder
  16448. */
  16449. function JPEGEncoder(quality) {
  16450. var ffloor = Math.floor;
  16451. var YTable = new Array(64);
  16452. var UVTable = new Array(64);
  16453. var fdtbl_Y = new Array(64);
  16454. var fdtbl_UV = new Array(64);
  16455. var YDC_HT;
  16456. var UVDC_HT;
  16457. var YAC_HT;
  16458. var UVAC_HT;
  16459. var bitcode = new Array(65535);
  16460. var category = new Array(65535);
  16461. var outputfDCTQuant = new Array(64);
  16462. var DU = new Array(64);
  16463. var byteout = [];
  16464. var bytenew = 0;
  16465. var bytepos = 7;
  16466. var YDU = new Array(64);
  16467. var UDU = new Array(64);
  16468. var VDU = new Array(64);
  16469. var clt = new Array(256);
  16470. var RGB_YUV_TABLE = new Array(2048);
  16471. var currentQuality;
  16472. var ZigZag = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63];
  16473. var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
  16474. var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  16475. var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
  16476. var std_ac_luminance_values = [0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
  16477. var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
  16478. var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  16479. var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
  16480. var std_ac_chrominance_values = [0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
  16481. function initQuantTables(sf) {
  16482. var YQT = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99];
  16483. for (var i = 0; i < 64; i++) {
  16484. var t = ffloor((YQT[i] * sf + 50) / 100);
  16485. if (t < 1) {
  16486. t = 1;
  16487. } else if (t > 255) {
  16488. t = 255;
  16489. }
  16490. YTable[ZigZag[i]] = t;
  16491. }
  16492. var UVQT = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99];
  16493. for (var j = 0; j < 64; j++) {
  16494. var u = ffloor((UVQT[j] * sf + 50) / 100);
  16495. if (u < 1) {
  16496. u = 1;
  16497. } else if (u > 255) {
  16498. u = 255;
  16499. }
  16500. UVTable[ZigZag[j]] = u;
  16501. }
  16502. var aasf = [1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379];
  16503. var k = 0;
  16504. for (var row = 0; row < 8; row++) {
  16505. for (var col = 0; col < 8; col++) {
  16506. fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
  16507. fdtbl_UV[k] = 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
  16508. k++;
  16509. }
  16510. }
  16511. }
  16512. function computeHuffmanTbl(nrcodes, std_table) {
  16513. var codevalue = 0;
  16514. var pos_in_table = 0;
  16515. var HT = new Array();
  16516. for (var k = 1; k <= 16; k++) {
  16517. for (var j = 1; j <= nrcodes[k]; j++) {
  16518. HT[std_table[pos_in_table]] = [];
  16519. HT[std_table[pos_in_table]][0] = codevalue;
  16520. HT[std_table[pos_in_table]][1] = k;
  16521. pos_in_table++;
  16522. codevalue++;
  16523. }
  16524. codevalue *= 2;
  16525. }
  16526. return HT;
  16527. }
  16528. function initHuffmanTbl() {
  16529. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
  16530. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
  16531. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
  16532. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
  16533. }
  16534. function initCategoryNumber() {
  16535. var nrlower = 1;
  16536. var nrupper = 2;
  16537. for (var cat = 1; cat <= 15; cat++) {
  16538. //Positive numbers
  16539. for (var nr = nrlower; nr < nrupper; nr++) {
  16540. category[32767 + nr] = cat;
  16541. bitcode[32767 + nr] = [];
  16542. bitcode[32767 + nr][1] = cat;
  16543. bitcode[32767 + nr][0] = nr;
  16544. } //Negative numbers
  16545. for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
  16546. category[32767 + nrneg] = cat;
  16547. bitcode[32767 + nrneg] = [];
  16548. bitcode[32767 + nrneg][1] = cat;
  16549. bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
  16550. }
  16551. nrlower <<= 1;
  16552. nrupper <<= 1;
  16553. }
  16554. }
  16555. function initRGBYUVTable() {
  16556. for (var i = 0; i < 256; i++) {
  16557. RGB_YUV_TABLE[i] = 19595 * i;
  16558. RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
  16559. RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 0x8000;
  16560. RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
  16561. RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
  16562. RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 0x807FFF;
  16563. RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
  16564. RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
  16565. }
  16566. } // IO functions
  16567. function writeBits(bs) {
  16568. var value = bs[0];
  16569. var posval = bs[1] - 1;
  16570. while (posval >= 0) {
  16571. if (value & 1 << posval) {
  16572. bytenew |= 1 << bytepos;
  16573. }
  16574. posval--;
  16575. bytepos--;
  16576. if (bytepos < 0) {
  16577. if (bytenew == 0xFF) {
  16578. writeByte(0xFF);
  16579. writeByte(0);
  16580. } else {
  16581. writeByte(bytenew);
  16582. }
  16583. bytepos = 7;
  16584. bytenew = 0;
  16585. }
  16586. }
  16587. }
  16588. function writeByte(value) {
  16589. //byteout.push(clt[value]); // write char directly instead of converting later
  16590. byteout.push(value);
  16591. }
  16592. function writeWord(value) {
  16593. writeByte(value >> 8 & 0xFF);
  16594. writeByte(value & 0xFF);
  16595. } // DCT & quantization core
  16596. function fDCTQuant(data, fdtbl) {
  16597. var d0, d1, d2, d3, d4, d5, d6, d7;
  16598. /* Pass 1: process rows. */
  16599. var dataOff = 0;
  16600. var i;
  16601. var I8 = 8;
  16602. var I64 = 64;
  16603. for (i = 0; i < I8; ++i) {
  16604. d0 = data[dataOff];
  16605. d1 = data[dataOff + 1];
  16606. d2 = data[dataOff + 2];
  16607. d3 = data[dataOff + 3];
  16608. d4 = data[dataOff + 4];
  16609. d5 = data[dataOff + 5];
  16610. d6 = data[dataOff + 6];
  16611. d7 = data[dataOff + 7];
  16612. var tmp0 = d0 + d7;
  16613. var tmp7 = d0 - d7;
  16614. var tmp1 = d1 + d6;
  16615. var tmp6 = d1 - d6;
  16616. var tmp2 = d2 + d5;
  16617. var tmp5 = d2 - d5;
  16618. var tmp3 = d3 + d4;
  16619. var tmp4 = d3 - d4;
  16620. /* Even part */
  16621. var tmp10 = tmp0 + tmp3;
  16622. /* phase 2 */
  16623. var tmp13 = tmp0 - tmp3;
  16624. var tmp11 = tmp1 + tmp2;
  16625. var tmp12 = tmp1 - tmp2;
  16626. data[dataOff] = tmp10 + tmp11;
  16627. /* phase 3 */
  16628. data[dataOff + 4] = tmp10 - tmp11;
  16629. var z1 = (tmp12 + tmp13) * 0.707106781;
  16630. /* c4 */
  16631. data[dataOff + 2] = tmp13 + z1;
  16632. /* phase 5 */
  16633. data[dataOff + 6] = tmp13 - z1;
  16634. /* Odd part */
  16635. tmp10 = tmp4 + tmp5;
  16636. /* phase 2 */
  16637. tmp11 = tmp5 + tmp6;
  16638. tmp12 = tmp6 + tmp7;
  16639. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  16640. var z5 = (tmp10 - tmp12) * 0.382683433;
  16641. /* c6 */
  16642. var z2 = 0.541196100 * tmp10 + z5;
  16643. /* c2-c6 */
  16644. var z4 = 1.306562965 * tmp12 + z5;
  16645. /* c2+c6 */
  16646. var z3 = tmp11 * 0.707106781;
  16647. /* c4 */
  16648. var z11 = tmp7 + z3;
  16649. /* phase 5 */
  16650. var z13 = tmp7 - z3;
  16651. data[dataOff + 5] = z13 + z2;
  16652. /* phase 6 */
  16653. data[dataOff + 3] = z13 - z2;
  16654. data[dataOff + 1] = z11 + z4;
  16655. data[dataOff + 7] = z11 - z4;
  16656. dataOff += 8;
  16657. /* advance pointer to next row */
  16658. }
  16659. /* Pass 2: process columns. */
  16660. dataOff = 0;
  16661. for (i = 0; i < I8; ++i) {
  16662. d0 = data[dataOff];
  16663. d1 = data[dataOff + 8];
  16664. d2 = data[dataOff + 16];
  16665. d3 = data[dataOff + 24];
  16666. d4 = data[dataOff + 32];
  16667. d5 = data[dataOff + 40];
  16668. d6 = data[dataOff + 48];
  16669. d7 = data[dataOff + 56];
  16670. var tmp0p2 = d0 + d7;
  16671. var tmp7p2 = d0 - d7;
  16672. var tmp1p2 = d1 + d6;
  16673. var tmp6p2 = d1 - d6;
  16674. var tmp2p2 = d2 + d5;
  16675. var tmp5p2 = d2 - d5;
  16676. var tmp3p2 = d3 + d4;
  16677. var tmp4p2 = d3 - d4;
  16678. /* Even part */
  16679. var tmp10p2 = tmp0p2 + tmp3p2;
  16680. /* phase 2 */
  16681. var tmp13p2 = tmp0p2 - tmp3p2;
  16682. var tmp11p2 = tmp1p2 + tmp2p2;
  16683. var tmp12p2 = tmp1p2 - tmp2p2;
  16684. data[dataOff] = tmp10p2 + tmp11p2;
  16685. /* phase 3 */
  16686. data[dataOff + 32] = tmp10p2 - tmp11p2;
  16687. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781;
  16688. /* c4 */
  16689. data[dataOff + 16] = tmp13p2 + z1p2;
  16690. /* phase 5 */
  16691. data[dataOff + 48] = tmp13p2 - z1p2;
  16692. /* Odd part */
  16693. tmp10p2 = tmp4p2 + tmp5p2;
  16694. /* phase 2 */
  16695. tmp11p2 = tmp5p2 + tmp6p2;
  16696. tmp12p2 = tmp6p2 + tmp7p2;
  16697. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  16698. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433;
  16699. /* c6 */
  16700. var z2p2 = 0.541196100 * tmp10p2 + z5p2;
  16701. /* c2-c6 */
  16702. var z4p2 = 1.306562965 * tmp12p2 + z5p2;
  16703. /* c2+c6 */
  16704. var z3p2 = tmp11p2 * 0.707106781;
  16705. /* c4 */
  16706. var z11p2 = tmp7p2 + z3p2;
  16707. /* phase 5 */
  16708. var z13p2 = tmp7p2 - z3p2;
  16709. data[dataOff + 40] = z13p2 + z2p2;
  16710. /* phase 6 */
  16711. data[dataOff + 24] = z13p2 - z2p2;
  16712. data[dataOff + 8] = z11p2 + z4p2;
  16713. data[dataOff + 56] = z11p2 - z4p2;
  16714. dataOff++;
  16715. /* advance pointer to next column */
  16716. } // Quantize/descale the coefficients
  16717. var fDCTQuant;
  16718. for (i = 0; i < I64; ++i) {
  16719. // Apply the quantization and scaling factor & Round to nearest integer
  16720. fDCTQuant = data[i] * fdtbl[i];
  16721. outputfDCTQuant[i] = fDCTQuant > 0.0 ? fDCTQuant + 0.5 | 0 : fDCTQuant - 0.5 | 0; //outputfDCTQuant[i] = fround(fDCTQuant);
  16722. }
  16723. return outputfDCTQuant;
  16724. }
  16725. function writeAPP0() {
  16726. writeWord(0xFFE0); // marker
  16727. writeWord(16); // length
  16728. writeByte(0x4A); // J
  16729. writeByte(0x46); // F
  16730. writeByte(0x49); // I
  16731. writeByte(0x46); // F
  16732. writeByte(0); // = "JFIF",'\0'
  16733. writeByte(1); // versionhi
  16734. writeByte(1); // versionlo
  16735. writeByte(0); // xyunits
  16736. writeWord(1); // xdensity
  16737. writeWord(1); // ydensity
  16738. writeByte(0); // thumbnwidth
  16739. writeByte(0); // thumbnheight
  16740. }
  16741. function writeSOF0(width, height) {
  16742. writeWord(0xFFC0); // marker
  16743. writeWord(17); // length, truecolor YUV JPG
  16744. writeByte(8); // precision
  16745. writeWord(height);
  16746. writeWord(width);
  16747. writeByte(3); // nrofcomponents
  16748. writeByte(1); // IdY
  16749. writeByte(0x11); // HVY
  16750. writeByte(0); // QTY
  16751. writeByte(2); // IdU
  16752. writeByte(0x11); // HVU
  16753. writeByte(1); // QTU
  16754. writeByte(3); // IdV
  16755. writeByte(0x11); // HVV
  16756. writeByte(1); // QTV
  16757. }
  16758. function writeDQT() {
  16759. writeWord(0xFFDB); // marker
  16760. writeWord(132); // length
  16761. writeByte(0);
  16762. for (var i = 0; i < 64; i++) {
  16763. writeByte(YTable[i]);
  16764. }
  16765. writeByte(1);
  16766. for (var j = 0; j < 64; j++) {
  16767. writeByte(UVTable[j]);
  16768. }
  16769. }
  16770. function writeDHT() {
  16771. writeWord(0xFFC4); // marker
  16772. writeWord(0x01A2); // length
  16773. writeByte(0); // HTYDCinfo
  16774. for (var i = 0; i < 16; i++) {
  16775. writeByte(std_dc_luminance_nrcodes[i + 1]);
  16776. }
  16777. for (var j = 0; j <= 11; j++) {
  16778. writeByte(std_dc_luminance_values[j]);
  16779. }
  16780. writeByte(0x10); // HTYACinfo
  16781. for (var k = 0; k < 16; k++) {
  16782. writeByte(std_ac_luminance_nrcodes[k + 1]);
  16783. }
  16784. for (var l = 0; l <= 161; l++) {
  16785. writeByte(std_ac_luminance_values[l]);
  16786. }
  16787. writeByte(1); // HTUDCinfo
  16788. for (var m = 0; m < 16; m++) {
  16789. writeByte(std_dc_chrominance_nrcodes[m + 1]);
  16790. }
  16791. for (var n = 0; n <= 11; n++) {
  16792. writeByte(std_dc_chrominance_values[n]);
  16793. }
  16794. writeByte(0x11); // HTUACinfo
  16795. for (var o = 0; o < 16; o++) {
  16796. writeByte(std_ac_chrominance_nrcodes[o + 1]);
  16797. }
  16798. for (var p = 0; p <= 161; p++) {
  16799. writeByte(std_ac_chrominance_values[p]);
  16800. }
  16801. }
  16802. function writeSOS() {
  16803. writeWord(0xFFDA); // marker
  16804. writeWord(12); // length
  16805. writeByte(3); // nrofcomponents
  16806. writeByte(1); // IdY
  16807. writeByte(0); // HTY
  16808. writeByte(2); // IdU
  16809. writeByte(0x11); // HTU
  16810. writeByte(3); // IdV
  16811. writeByte(0x11); // HTV
  16812. writeByte(0); // Ss
  16813. writeByte(0x3f); // Se
  16814. writeByte(0); // Bf
  16815. }
  16816. function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
  16817. var EOB = HTAC[0x00];
  16818. var M16zeroes = HTAC[0xF0];
  16819. var pos;
  16820. var I16 = 16;
  16821. var I63 = 63;
  16822. var I64 = 64;
  16823. var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder
  16824. for (var j = 0; j < I64; ++j) {
  16825. DU[ZigZag[j]] = DU_DCT[j];
  16826. }
  16827. var Diff = DU[0] - DC;
  16828. DC = DU[0]; //Encode DC
  16829. if (Diff == 0) {
  16830. writeBits(HTDC[0]); // Diff might be 0
  16831. } else {
  16832. pos = 32767 + Diff;
  16833. writeBits(HTDC[category[pos]]);
  16834. writeBits(bitcode[pos]);
  16835. } //Encode ACs
  16836. var end0pos = 63; // was const... which is crazy
  16837. for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
  16838. if (end0pos == 0) {
  16839. writeBits(EOB);
  16840. return DC;
  16841. }
  16842. var i = 1;
  16843. var lng;
  16844. while (i <= end0pos) {
  16845. var startpos = i;
  16846. for (; DU[i] == 0 && i <= end0pos; ++i) {}
  16847. var nrzeroes = i - startpos;
  16848. if (nrzeroes >= I16) {
  16849. lng = nrzeroes >> 4;
  16850. for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) {
  16851. writeBits(M16zeroes);
  16852. }
  16853. nrzeroes = nrzeroes & 0xF;
  16854. }
  16855. pos = 32767 + DU[i];
  16856. writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
  16857. writeBits(bitcode[pos]);
  16858. i++;
  16859. }
  16860. if (end0pos != I63) {
  16861. writeBits(EOB);
  16862. }
  16863. return DC;
  16864. }
  16865. function initCharLookupTable() {
  16866. var sfcc = String.fromCharCode;
  16867. for (var i = 0; i < 256; i++) {
  16868. ///// ACHTUNG // 255
  16869. clt[i] = sfcc(i);
  16870. }
  16871. }
  16872. this.encode = function (image, quality) // image data object
  16873. {
  16874. var time_start = new Date().getTime();
  16875. if (quality) setQuality(quality); // Initialize bit writer
  16876. byteout = new Array();
  16877. bytenew = 0;
  16878. bytepos = 7; // Add JPEG headers
  16879. writeWord(0xFFD8); // SOI
  16880. writeAPP0();
  16881. writeDQT();
  16882. writeSOF0(image.width, image.height);
  16883. writeDHT();
  16884. writeSOS(); // Encode 8x8 macroblocks
  16885. var DCY = 0;
  16886. var DCU = 0;
  16887. var DCV = 0;
  16888. bytenew = 0;
  16889. bytepos = 7;
  16890. this.encode.displayName = "_encode_";
  16891. var imageData = image.data;
  16892. var width = image.width;
  16893. var height = image.height;
  16894. var quadWidth = width * 4;
  16895. var x,
  16896. y = 0;
  16897. var r, g, b;
  16898. var start, p, col, row, pos;
  16899. while (y < height) {
  16900. x = 0;
  16901. while (x < quadWidth) {
  16902. start = quadWidth * y + x;
  16903. p = start;
  16904. col = -1;
  16905. row = 0;
  16906. for (pos = 0; pos < 64; pos++) {
  16907. row = pos >> 3; // /8
  16908. col = (pos & 7) * 4; // %8
  16909. p = start + row * quadWidth + col;
  16910. if (y + row >= height) {
  16911. // padding bottom
  16912. p -= quadWidth * (y + 1 + row - height);
  16913. }
  16914. if (x + col >= quadWidth) {
  16915. // padding right
  16916. p -= x + col - quadWidth + 4;
  16917. }
  16918. r = imageData[p++];
  16919. g = imageData[p++];
  16920. b = imageData[p++];
  16921. /* // calculate YUV values dynamically
  16922. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  16923. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  16924. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  16925. */
  16926. // use lookup table (slightly faster)
  16927. YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
  16928. UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
  16929. VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
  16930. }
  16931. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  16932. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  16933. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  16934. x += 32;
  16935. }
  16936. y += 8;
  16937. } ////////////////////////////////////////////////////////////////
  16938. // Do the bit alignment of the EOI marker
  16939. if (bytepos >= 0) {
  16940. var fillbits = [];
  16941. fillbits[1] = bytepos + 1;
  16942. fillbits[0] = (1 << bytepos + 1) - 1;
  16943. writeBits(fillbits);
  16944. }
  16945. writeWord(0xFFD9); //EOI
  16946. return new Uint8Array(byteout);
  16947. };
  16948. function setQuality(quality) {
  16949. if (quality <= 0) {
  16950. quality = 1;
  16951. }
  16952. if (quality > 100) {
  16953. quality = 100;
  16954. }
  16955. if (currentQuality == quality) return; // don't recalc if unchanged
  16956. var sf = 0;
  16957. if (quality < 50) {
  16958. sf = Math.floor(5000 / quality);
  16959. } else {
  16960. sf = Math.floor(200 - quality * 2);
  16961. }
  16962. initQuantTables(sf);
  16963. currentQuality = quality; //console.log('Quality set to: '+quality +'%');
  16964. }
  16965. function init() {
  16966. var time_start = new Date().getTime();
  16967. if (!quality) quality = 50; // Create tables
  16968. initCharLookupTable();
  16969. initHuffmanTbl();
  16970. initCategoryNumber();
  16971. initRGBYUVTable();
  16972. setQuality(quality);
  16973. var duration = new Date().getTime() - time_start; //console.log('Initialization '+ duration + 'ms');
  16974. }
  16975. init();
  16976. }
  16977. /*rollup-keeper-start*/
  16978. window.tmp = JPEGEncoder;
  16979. /*rollup-keeper-end*/
  16980. /**
  16981. * @author shaozilee
  16982. *
  16983. * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
  16984. *
  16985. */
  16986. function BmpDecoder(buffer, is_with_alpha) {
  16987. this.pos = 0;
  16988. this.buffer = buffer;
  16989. this.datav = new DataView(buffer.buffer);
  16990. this.is_with_alpha = !!is_with_alpha;
  16991. this.bottom_up = true;
  16992. this.flag = String.fromCharCode(this.buffer[0]) + String.fromCharCode(this.buffer[1]);
  16993. this.pos += 2;
  16994. if (["BM", "BA", "CI", "CP", "IC", "PT"].indexOf(this.flag) === -1) throw new Error("Invalid BMP File");
  16995. this.parseHeader();
  16996. this.parseBGR();
  16997. }
  16998. BmpDecoder.prototype.parseHeader = function () {
  16999. this.fileSize = this.datav.getUint32(this.pos, true);
  17000. this.pos += 4;
  17001. this.reserved = this.datav.getUint32(this.pos, true);
  17002. this.pos += 4;
  17003. this.offset = this.datav.getUint32(this.pos, true);
  17004. this.pos += 4;
  17005. this.headerSize = this.datav.getUint32(this.pos, true);
  17006. this.pos += 4;
  17007. this.width = this.datav.getUint32(this.pos, true);
  17008. this.pos += 4;
  17009. this.height = this.datav.getInt32(this.pos, true);
  17010. this.pos += 4;
  17011. this.planes = this.datav.getUint16(this.pos, true);
  17012. this.pos += 2;
  17013. this.bitPP = this.datav.getUint16(this.pos, true);
  17014. this.pos += 2;
  17015. this.compress = this.datav.getUint32(this.pos, true);
  17016. this.pos += 4;
  17017. this.rawSize = this.datav.getUint32(this.pos, true);
  17018. this.pos += 4;
  17019. this.hr = this.datav.getUint32(this.pos, true);
  17020. this.pos += 4;
  17021. this.vr = this.datav.getUint32(this.pos, true);
  17022. this.pos += 4;
  17023. this.colors = this.datav.getUint32(this.pos, true);
  17024. this.pos += 4;
  17025. this.importantColors = this.datav.getUint32(this.pos, true);
  17026. this.pos += 4;
  17027. if (this.bitPP === 16 && this.is_with_alpha) {
  17028. this.bitPP = 15;
  17029. }
  17030. if (this.bitPP < 15) {
  17031. var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
  17032. this.palette = new Array(len);
  17033. for (var i = 0; i < len; i++) {
  17034. var blue = this.datav.getUint8(this.pos++, true);
  17035. var green = this.datav.getUint8(this.pos++, true);
  17036. var red = this.datav.getUint8(this.pos++, true);
  17037. var quad = this.datav.getUint8(this.pos++, true);
  17038. this.palette[i] = {
  17039. red: red,
  17040. green: green,
  17041. blue: blue,
  17042. quad: quad
  17043. };
  17044. }
  17045. }
  17046. if (this.height < 0) {
  17047. this.height *= -1;
  17048. this.bottom_up = false;
  17049. }
  17050. };
  17051. BmpDecoder.prototype.parseBGR = function () {
  17052. this.pos = this.offset;
  17053. try {
  17054. var bitn = "bit" + this.bitPP;
  17055. var len = this.width * this.height * 4;
  17056. this.data = new Uint8Array(len);
  17057. this[bitn]();
  17058. } catch (e) {
  17059. console.log("bit decode error:" + e);
  17060. }
  17061. };
  17062. BmpDecoder.prototype.bit1 = function () {
  17063. var xlen = Math.ceil(this.width / 8);
  17064. var mode = xlen % 4;
  17065. var y = this.height >= 0 ? this.height - 1 : -this.height;
  17066. for (var y = this.height - 1; y >= 0; y--) {
  17067. var line = this.bottom_up ? y : this.height - 1 - y;
  17068. for (var x = 0; x < xlen; x++) {
  17069. var b = this.datav.getUint8(this.pos++, true);
  17070. var location = line * this.width * 4 + x * 8 * 4;
  17071. for (var i = 0; i < 8; i++) {
  17072. if (x * 8 + i < this.width) {
  17073. var rgb = this.palette[b >> 7 - i & 0x1];
  17074. this.data[location + i * 4] = rgb.blue;
  17075. this.data[location + i * 4 + 1] = rgb.green;
  17076. this.data[location + i * 4 + 2] = rgb.red;
  17077. this.data[location + i * 4 + 3] = 0xFF;
  17078. } else {
  17079. break;
  17080. }
  17081. }
  17082. }
  17083. if (mode != 0) {
  17084. this.pos += 4 - mode;
  17085. }
  17086. }
  17087. };
  17088. BmpDecoder.prototype.bit4 = function () {
  17089. var xlen = Math.ceil(this.width / 2);
  17090. var mode = xlen % 4;
  17091. for (var y = this.height - 1; y >= 0; y--) {
  17092. var line = this.bottom_up ? y : this.height - 1 - y;
  17093. for (var x = 0; x < xlen; x++) {
  17094. var b = this.datav.getUint8(this.pos++, true);
  17095. var location = line * this.width * 4 + x * 2 * 4;
  17096. var before = b >> 4;
  17097. var after = b & 0x0F;
  17098. var rgb = this.palette[before];
  17099. this.data[location] = rgb.blue;
  17100. this.data[location + 1] = rgb.green;
  17101. this.data[location + 2] = rgb.red;
  17102. this.data[location + 3] = 0xFF;
  17103. if (x * 2 + 1 >= this.width) break;
  17104. rgb = this.palette[after];
  17105. this.data[location + 4] = rgb.blue;
  17106. this.data[location + 4 + 1] = rgb.green;
  17107. this.data[location + 4 + 2] = rgb.red;
  17108. this.data[location + 4 + 3] = 0xFF;
  17109. }
  17110. if (mode != 0) {
  17111. this.pos += 4 - mode;
  17112. }
  17113. }
  17114. };
  17115. BmpDecoder.prototype.bit8 = function () {
  17116. var mode = this.width % 4;
  17117. for (var y = this.height - 1; y >= 0; y--) {
  17118. var line = this.bottom_up ? y : this.height - 1 - y;
  17119. for (var x = 0; x < this.width; x++) {
  17120. var b = this.datav.getUint8(this.pos++, true);
  17121. var location = line * this.width * 4 + x * 4;
  17122. if (b < this.palette.length) {
  17123. var rgb = this.palette[b];
  17124. this.data[location] = rgb.red;
  17125. this.data[location + 1] = rgb.green;
  17126. this.data[location + 2] = rgb.blue;
  17127. this.data[location + 3] = 0xFF;
  17128. } else {
  17129. this.data[location] = 0xFF;
  17130. this.data[location + 1] = 0xFF;
  17131. this.data[location + 2] = 0xFF;
  17132. this.data[location + 3] = 0xFF;
  17133. }
  17134. }
  17135. if (mode != 0) {
  17136. this.pos += 4 - mode;
  17137. }
  17138. }
  17139. };
  17140. BmpDecoder.prototype.bit15 = function () {
  17141. var dif_w = this.width % 3;
  17142. var _11111 = parseInt("11111", 2),
  17143. _1_5 = _11111;
  17144. for (var y = this.height - 1; y >= 0; y--) {
  17145. var line = this.bottom_up ? y : this.height - 1 - y;
  17146. for (var x = 0; x < this.width; x++) {
  17147. var B = this.datav.getUint16(this.pos, true);
  17148. this.pos += 2;
  17149. var blue = (B & _1_5) / _1_5 * 255 | 0;
  17150. var green = (B >> 5 & _1_5) / _1_5 * 255 | 0;
  17151. var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
  17152. var alpha = B >> 15 ? 0xFF : 0x00;
  17153. var location = line * this.width * 4 + x * 4;
  17154. this.data[location] = red;
  17155. this.data[location + 1] = green;
  17156. this.data[location + 2] = blue;
  17157. this.data[location + 3] = alpha;
  17158. } //skip extra bytes
  17159. this.pos += dif_w;
  17160. }
  17161. };
  17162. BmpDecoder.prototype.bit16 = function () {
  17163. var dif_w = this.width % 3;
  17164. var _11111 = parseInt("11111", 2),
  17165. _1_5 = _11111;
  17166. var _111111 = parseInt("111111", 2),
  17167. _1_6 = _111111;
  17168. for (var y = this.height - 1; y >= 0; y--) {
  17169. var line = this.bottom_up ? y : this.height - 1 - y;
  17170. for (var x = 0; x < this.width; x++) {
  17171. var B = this.datav.getUint16(this.pos, true);
  17172. this.pos += 2;
  17173. var alpha = 0xFF;
  17174. var blue = (B & _1_5) / _1_5 * 255 | 0;
  17175. var green = (B >> 5 & _1_6) / _1_6 * 255 | 0;
  17176. var red = (B >> 11) / _1_5 * 255 | 0;
  17177. var location = line * this.width * 4 + x * 4;
  17178. this.data[location] = red;
  17179. this.data[location + 1] = green;
  17180. this.data[location + 2] = blue;
  17181. this.data[location + 3] = alpha;
  17182. } //skip extra bytes
  17183. this.pos += dif_w;
  17184. }
  17185. };
  17186. BmpDecoder.prototype.bit24 = function () {
  17187. //when height > 0
  17188. for (var y = this.height - 1; y >= 0; y--) {
  17189. var line = this.bottom_up ? y : this.height - 1 - y;
  17190. for (var x = 0; x < this.width; x++) {
  17191. var blue = this.datav.getUint8(this.pos++, true);
  17192. var green = this.datav.getUint8(this.pos++, true);
  17193. var red = this.datav.getUint8(this.pos++, true);
  17194. var location = line * this.width * 4 + x * 4;
  17195. this.data[location] = red;
  17196. this.data[location + 1] = green;
  17197. this.data[location + 2] = blue;
  17198. this.data[location + 3] = 0xFF;
  17199. } //skip extra bytes
  17200. this.pos += this.width % 4;
  17201. }
  17202. };
  17203. /**
  17204. * add 32bit decode func
  17205. * @author soubok
  17206. */
  17207. BmpDecoder.prototype.bit32 = function () {
  17208. //when height > 0
  17209. for (var y = this.height - 1; y >= 0; y--) {
  17210. var line = this.bottom_up ? y : this.height - 1 - y;
  17211. for (var x = 0; x < this.width; x++) {
  17212. var blue = this.datav.getUint8(this.pos++, true);
  17213. var green = this.datav.getUint8(this.pos++, true);
  17214. var red = this.datav.getUint8(this.pos++, true);
  17215. var alpha = this.datav.getUint8(this.pos++, true);
  17216. var location = line * this.width * 4 + x * 4;
  17217. this.data[location] = red;
  17218. this.data[location + 1] = green;
  17219. this.data[location + 2] = blue;
  17220. this.data[location + 3] = alpha;
  17221. } //skip extra bytes
  17222. //this.pos += (this.width % 4);
  17223. }
  17224. };
  17225. BmpDecoder.prototype.getData = function () {
  17226. return this.data;
  17227. };
  17228. /*rollup-keeper-start*/
  17229. window.tmp = BmpDecoder;
  17230. /*rollup-keeper-end*/
  17231. /*
  17232. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  17233. Redistribution and use in source and binary forms, with or without
  17234. modification, are permitted provided that the following conditions are met:
  17235. 1. Redistributions of source code must retain the above copyright notice,
  17236. this list of conditions and the following disclaimer.
  17237. 2. Redistributions in binary form must reproduce the above copyright
  17238. notice, this list of conditions and the following disclaimer in
  17239. the documentation and/or other materials provided with the distribution.
  17240. 3. The names of the authors may not be used to endorse or promote products
  17241. derived from this software without specific prior written permission.
  17242. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  17243. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17244. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  17245. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  17246. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  17247. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  17248. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  17249. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  17250. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  17251. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  17252. */
  17253. /*
  17254. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  17255. * JZlib is based on zlib-1.1.3, so all credit should go authors
  17256. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  17257. * and contributors of zlib.
  17258. */
  17259. (function (global) {
  17260. var MAX_BITS = 15;
  17261. var D_CODES = 30;
  17262. var BL_CODES = 19;
  17263. var LENGTH_CODES = 29;
  17264. var LITERALS = 256;
  17265. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17266. var HEAP_SIZE = 2 * L_CODES + 1;
  17267. var END_BLOCK = 256; // Bit length codes must not exceed MAX_BL_BITS bits
  17268. var MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count)
  17269. var REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count)
  17270. var REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count)
  17271. var REPZ_11_138 = 18; // The lengths of the bit length codes are sent in order of decreasing
  17272. // probability, to avoid transmitting the lengths for unused bit
  17273. // length codes.
  17274. var Buf_size = 8 * 2; // JZlib version : "1.0.2"
  17275. var Z_DEFAULT_COMPRESSION = -1; // compression strategy
  17276. var Z_FILTERED = 1;
  17277. var Z_HUFFMAN_ONLY = 2;
  17278. var Z_DEFAULT_STRATEGY = 0;
  17279. var Z_NO_FLUSH = 0;
  17280. var Z_PARTIAL_FLUSH = 1;
  17281. var Z_FULL_FLUSH = 3;
  17282. var Z_FINISH = 4;
  17283. var Z_OK = 0;
  17284. var Z_STREAM_END = 1;
  17285. var Z_NEED_DICT = 2;
  17286. var Z_STREAM_ERROR = -2;
  17287. var Z_DATA_ERROR = -3;
  17288. var Z_BUF_ERROR = -5; // Tree
  17289. // see definition of array dist_code below
  17290. 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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];
  17291. function Tree() {
  17292. var that = this; // dyn_tree; // the dynamic tree
  17293. // max_code; // largest code with non zero frequency
  17294. // stat_desc; // the corresponding static tree
  17295. // Compute the optimal bit lengths for a tree and update the total bit
  17296. // length
  17297. // for the current block.
  17298. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  17299. // above are the tree nodes sorted by increasing frequency.
  17300. // OUT assertions: the field len is set to the optimal bit length, the
  17301. // array bl_count contains the frequencies for each bit length.
  17302. // The length opt_len is updated; static_len is also updated if stree is
  17303. // not null.
  17304. function gen_bitlen(s) {
  17305. var tree = that.dyn_tree;
  17306. var stree = that.stat_desc.static_tree;
  17307. var extra = that.stat_desc.extra_bits;
  17308. var base = that.stat_desc.extra_base;
  17309. var max_length = that.stat_desc.max_length;
  17310. var h; // heap index
  17311. var n, m; // iterate over the tree elements
  17312. var bits; // bit length
  17313. var xbits; // extra bits
  17314. var f; // frequency
  17315. var overflow = 0; // number of elements with bit length too large
  17316. for (bits = 0; bits <= MAX_BITS; bits++) {
  17317. s.bl_count[bits] = 0;
  17318. } // In a first pass, compute the optimal bit lengths (which may
  17319. // overflow in the case of the bit length tree).
  17320. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  17321. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  17322. n = s.heap[h];
  17323. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  17324. if (bits > max_length) {
  17325. bits = max_length;
  17326. overflow++;
  17327. }
  17328. tree[n * 2 + 1] = bits; // We overwrite tree[n*2+1] which is no longer needed
  17329. if (n > that.max_code) continue; // not a leaf node
  17330. s.bl_count[bits]++;
  17331. xbits = 0;
  17332. if (n >= base) xbits = extra[n - base];
  17333. f = tree[n * 2];
  17334. s.opt_len += f * (bits + xbits);
  17335. if (stree) s.static_len += f * (stree[n * 2 + 1] + xbits);
  17336. }
  17337. if (overflow === 0) return; // This happens for example on obj2 and pic of the Calgary corpus
  17338. // Find the first bit length which could increase:
  17339. do {
  17340. bits = max_length - 1;
  17341. while (s.bl_count[bits] === 0) {
  17342. bits--;
  17343. }
  17344. s.bl_count[bits]--; // move one leaf down the tree
  17345. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  17346. s.bl_count[max_length]--; // The brother of the overflow item also moves one step up,
  17347. // but this does not affect bl_count[max_length]
  17348. overflow -= 2;
  17349. } while (overflow > 0);
  17350. for (bits = max_length; bits !== 0; bits--) {
  17351. n = s.bl_count[bits];
  17352. while (n !== 0) {
  17353. m = s.heap[--h];
  17354. if (m > that.max_code) continue;
  17355. if (tree[m * 2 + 1] != bits) {
  17356. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  17357. tree[m * 2 + 1] = bits;
  17358. }
  17359. n--;
  17360. }
  17361. }
  17362. } // Reverse the first len bits of a code, using straightforward code (a
  17363. // faster
  17364. // method would use a table)
  17365. // IN assertion: 1 <= len <= 15
  17366. function bi_reverse(code, // the value to invert
  17367. len // its bit length
  17368. ) {
  17369. var res = 0;
  17370. do {
  17371. res |= code & 1;
  17372. code >>>= 1;
  17373. res <<= 1;
  17374. } while (--len > 0);
  17375. return res >>> 1;
  17376. } // Generate the codes for a given tree and bit counts (which need not be
  17377. // optimal).
  17378. // IN assertion: the array bl_count contains the bit length statistics for
  17379. // the given tree and the field len is set for all tree elements.
  17380. // OUT assertion: the field code is set for all tree elements of non
  17381. // zero code length.
  17382. function gen_codes(tree, // the tree to decorate
  17383. max_code, // largest code with non zero frequency
  17384. bl_count // number of codes at each bit length
  17385. ) {
  17386. var next_code = []; // next code value for each
  17387. // bit length
  17388. var code = 0; // running code value
  17389. var bits; // bit index
  17390. var n; // code index
  17391. var len; // The distribution counts are first used to generate the code values
  17392. // without bit reversal.
  17393. for (bits = 1; bits <= MAX_BITS; bits++) {
  17394. next_code[bits] = code = code + bl_count[bits - 1] << 1;
  17395. } // Check that the bit counts in bl_count are consistent. The last code
  17396. // must be all ones.
  17397. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17398. // "inconsistent bit counts");
  17399. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17400. for (n = 0; n <= max_code; n++) {
  17401. len = tree[n * 2 + 1];
  17402. if (len === 0) continue; // Now reverse the bits
  17403. tree[n * 2] = bi_reverse(next_code[len]++, len);
  17404. }
  17405. } // Construct one Huffman tree and assigns the code bit strings and lengths.
  17406. // Update the total bit length for the current block.
  17407. // IN assertion: the field freq is set for all tree elements.
  17408. // OUT assertions: the fields len and code are set to the optimal bit length
  17409. // and corresponding code. The length opt_len is updated; static_len is
  17410. // also updated if stree is not null. The field max_code is set.
  17411. that.build_tree = function (s) {
  17412. var tree = that.dyn_tree;
  17413. var stree = that.stat_desc.static_tree;
  17414. var elems = that.stat_desc.elems;
  17415. var n, m; // iterate over heap elements
  17416. var max_code = -1; // largest code with non zero frequency
  17417. var node; // new node being created
  17418. // Construct the initial heap, with least frequent element in
  17419. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17420. // heap[0] is not used.
  17421. s.heap_len = 0;
  17422. s.heap_max = HEAP_SIZE;
  17423. for (n = 0; n < elems; n++) {
  17424. if (tree[n * 2] !== 0) {
  17425. s.heap[++s.heap_len] = max_code = n;
  17426. s.depth[n] = 0;
  17427. } else {
  17428. tree[n * 2 + 1] = 0;
  17429. }
  17430. } // The pkzip format requires that at least one distance code exists,
  17431. // and that at least one bit should be sent even if there is only one
  17432. // possible code. So to avoid special checks later on we force at least
  17433. // two codes of non zero frequency.
  17434. while (s.heap_len < 2) {
  17435. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  17436. tree[node * 2] = 1;
  17437. s.depth[node] = 0;
  17438. s.opt_len--;
  17439. if (stree) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits
  17440. }
  17441. that.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17442. // establish sub-heaps of increasing lengths:
  17443. for (n = Math.floor(s.heap_len / 2); n >= 1; n--) {
  17444. s.pqdownheap(tree, n);
  17445. } // Construct the Huffman tree by repeatedly combining the least two
  17446. // frequent nodes.
  17447. node = elems; // next internal node of the tree
  17448. do {
  17449. // n = node of least frequency
  17450. n = s.heap[1];
  17451. s.heap[1] = s.heap[s.heap_len--];
  17452. s.pqdownheap(tree, 1);
  17453. m = s.heap[1]; // m = node of next least frequency
  17454. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  17455. s.heap[--s.heap_max] = m; // Create a new node father of n and m
  17456. tree[node * 2] = tree[n * 2] + tree[m * 2];
  17457. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  17458. tree[n * 2 + 1] = tree[m * 2 + 1] = node; // and insert the new node in the heap
  17459. s.heap[1] = node++;
  17460. s.pqdownheap(tree, 1);
  17461. } while (s.heap_len >= 2);
  17462. s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now
  17463. // generate the bit lengths.
  17464. gen_bitlen(s); // The field len is now set, we can generate the bit codes
  17465. gen_codes(tree, that.max_code, s.bl_count);
  17466. };
  17467. }
  17468. 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, 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, 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, 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, 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, 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, 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];
  17469. 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];
  17470. 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, 24576]; // Mapping from a distance to a distance code. dist is the distance - 1 and
  17471. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  17472. // used.
  17473. Tree.d_code = function (dist) {
  17474. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17475. }; // extra bits for each length code
  17476. 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]; // extra bits for each distance code
  17477. 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]; // extra bits for each bit length code
  17478. Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  17479. Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; // StaticTree
  17480. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  17481. var that = this;
  17482. that.static_tree = static_tree;
  17483. that.extra_bits = extra_bits;
  17484. that.extra_base = extra_base;
  17485. that.elems = elems;
  17486. that.max_length = max_length;
  17487. }
  17488. 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 99, 8, 227, 8];
  17489. 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, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5];
  17490. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  17491. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  17492. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); // Deflate
  17493. var MAX_MEM_LEVEL = 9;
  17494. var DEF_MEM_LEVEL = 8;
  17495. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  17496. var that = this;
  17497. that.good_length = good_length;
  17498. that.max_lazy = max_lazy;
  17499. that.nice_length = nice_length;
  17500. that.max_chain = max_chain;
  17501. that.func = func;
  17502. }
  17503. var STORED = 0;
  17504. var FAST = 1;
  17505. var SLOW = 2;
  17506. 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), 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), new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW)];
  17507. var z_errmsg = ["need dictionary", // Z_NEED_DICT
  17508. // 2
  17509. "stream end", // Z_STREAM_END 1
  17510. "", // Z_OK 0
  17511. "", // Z_ERRNO (-1)
  17512. "stream error", // Z_STREAM_ERROR (-2)
  17513. "data error", // Z_DATA_ERROR (-3)
  17514. "", // Z_MEM_ERROR (-4)
  17515. "buffer error", // Z_BUF_ERROR (-5)
  17516. "", // Z_VERSION_ERROR (-6)
  17517. ""]; // block not completed, need more input or more output
  17518. var NeedMore = 0; // block flush performed
  17519. var BlockDone = 1; // finish started, need only more output at next deflate
  17520. var FinishStarted = 2; // finish done, accept no more input or output
  17521. var FinishDone = 3; // preset dictionary flag in zlib header
  17522. var PRESET_DICT = 0x20;
  17523. var INIT_STATE = 42;
  17524. var BUSY_STATE = 113;
  17525. var FINISH_STATE = 666; // The deflate compression method
  17526. var Z_DEFLATED = 8;
  17527. var STORED_BLOCK = 0;
  17528. var STATIC_TREES = 1;
  17529. var DYN_TREES = 2;
  17530. var MIN_MATCH = 3;
  17531. var MAX_MATCH = 258;
  17532. var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
  17533. function smaller(tree, n, m, depth) {
  17534. var tn2 = tree[n * 2];
  17535. var tm2 = tree[m * 2];
  17536. return tn2 < tm2 || tn2 == tm2 && depth[n] <= depth[m];
  17537. }
  17538. function Deflate() {
  17539. var that = this;
  17540. var strm; // pointer back to this zlib stream
  17541. var status; // as the name implies
  17542. // pending_buf; // output still pending
  17543. var pending_buf_size; // size of pending_buf
  17544. var last_flush; // value of flush param for previous deflate call
  17545. var w_size; // LZ77 window size (32K by default)
  17546. var w_bits; // log2(w_size) (8..16)
  17547. var w_mask; // w_size - 1
  17548. var window; // Sliding window. Input bytes are read into the second half of the window,
  17549. // and move to the first half later to keep a dictionary of at least wSize
  17550. // bytes. With this organization, matches are limited to a distance of
  17551. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  17552. // performed with a length multiple of the block size. Also, it limits
  17553. // the window size to 64K, which is quite useful on MSDOS.
  17554. // To do: use the user input buffer as sliding window.
  17555. var window_size; // Actual size of window: 2*wSize, except when the user input buffer
  17556. // is directly used as sliding window.
  17557. var prev; // Link to older string with same hash index. To limit the size of this
  17558. // array to 64K, this link is maintained only for the last 32K strings.
  17559. // An index in this array is thus a window index modulo 32K.
  17560. var head; // Heads of the hash chains or NIL.
  17561. var ins_h; // hash index of string to be inserted
  17562. var hash_size; // number of elements in hash table
  17563. var hash_bits; // log2(hash_size)
  17564. var hash_mask; // hash_size-1
  17565. // Number of bits by which ins_h must be shifted at each input
  17566. // step. It must be such that after MIN_MATCH steps, the oldest
  17567. // byte no longer takes part in the hash key, that is:
  17568. // hash_shift * MIN_MATCH >= hash_bits
  17569. var hash_shift; // Window position at the beginning of the current output block. Gets
  17570. // negative when the window is moved backwards.
  17571. var block_start;
  17572. var match_length; // length of best match
  17573. var prev_match; // previous match
  17574. var match_available; // set if previous match exists
  17575. var strstart; // start of string to insert
  17576. var match_start; // start of matching string
  17577. var lookahead; // number of valid bytes ahead in window
  17578. // Length of the best match at previous step. Matches not greater than this
  17579. // are discarded. This is used in the lazy match evaluation.
  17580. var prev_length; // To speed up deflation, hash chains are never searched beyond this
  17581. // length. A higher limit improves compression ratio but degrades the speed.
  17582. var max_chain_length; // Attempt to find a better match only when the current match is strictly
  17583. // smaller than this value. This mechanism is used only for compression
  17584. // levels >= 4.
  17585. var max_lazy_match; // Insert new strings in the hash table only if the match length is not
  17586. // greater than this length. This saves time but degrades compression.
  17587. // max_insert_length is used only for compression levels <= 3.
  17588. var level; // compression level (1..9)
  17589. var strategy; // favor or force Huffman coding
  17590. // Use a faster search when the previous match is longer than this
  17591. var good_match; // Stop searching when current match exceeds this
  17592. var nice_match;
  17593. var dyn_ltree; // literal and length tree
  17594. var dyn_dtree; // distance tree
  17595. var bl_tree; // Huffman tree for bit lengths
  17596. var l_desc = new Tree(); // desc for literal tree
  17597. var d_desc = new Tree(); // desc for distance tree
  17598. var bl_desc = new Tree(); // desc for bit length tree
  17599. // that.heap_len; // number of elements in the heap
  17600. // that.heap_max; // element of largest frequency
  17601. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  17602. // The same heap array is used to build all trees.
  17603. // Depth of each subtree used as tie breaker for trees of equal frequency
  17604. that.depth = [];
  17605. var l_buf; // index for literals or lengths */
  17606. // Size of match buffer for literals/lengths. There are 4 reasons for
  17607. // limiting lit_bufsize to 64K:
  17608. // - frequencies can be kept in 16 bit counters
  17609. // - if compression is not successful for the first block, all input
  17610. // data is still in the window so we can still emit a stored block even
  17611. // when input comes from standard input. (This can also be done for
  17612. // all blocks if lit_bufsize is not greater than 32K.)
  17613. // - if compression is not successful for a file smaller than 64K, we can
  17614. // even emit a stored file instead of a stored block (saving 5 bytes).
  17615. // This is applicable only for zip (not gzip or zlib).
  17616. // - creating new Huffman trees less frequently may not provide fast
  17617. // adaptation to changes in the input data statistics. (Take for
  17618. // example a binary file with poorly compressible code followed by
  17619. // a highly compressible string table.) Smaller buffer sizes give
  17620. // fast adaptation but have of course the overhead of transmitting
  17621. // trees more frequently.
  17622. // - I can't count above 4
  17623. var lit_bufsize;
  17624. var last_lit; // running index in l_buf
  17625. // Buffer for distances. To simplify the code, d_buf and l_buf have
  17626. // the same number of elements. To use different lengths, an extra flag
  17627. // array would be necessary.
  17628. var d_buf; // index of pendig_buf
  17629. // that.opt_len; // bit length of current block with optimal trees
  17630. // that.static_len; // bit length of current block with static trees
  17631. var matches; // number of string matches in current block
  17632. var last_eob_len; // bit length of EOB code for last block
  17633. // Output buffer. bits are inserted starting at the bottom (least
  17634. // significant bits).
  17635. var bi_buf; // Number of valid bits in bi_buf. All bits above the last valid bit
  17636. // are always zero.
  17637. var bi_valid; // number of codes at each bit length for an optimal tree
  17638. that.bl_count = []; // heap used to build the Huffman trees
  17639. that.heap = [];
  17640. dyn_ltree = [];
  17641. dyn_dtree = [];
  17642. bl_tree = [];
  17643. function lm_init() {
  17644. var i;
  17645. window_size = 2 * w_size;
  17646. head[hash_size - 1] = 0;
  17647. for (i = 0; i < hash_size - 1; i++) {
  17648. head[i] = 0;
  17649. } // Set the default configuration parameters:
  17650. max_lazy_match = config_table[level].max_lazy;
  17651. good_match = config_table[level].good_length;
  17652. nice_match = config_table[level].nice_length;
  17653. max_chain_length = config_table[level].max_chain;
  17654. strstart = 0;
  17655. block_start = 0;
  17656. lookahead = 0;
  17657. match_length = prev_length = MIN_MATCH - 1;
  17658. match_available = 0;
  17659. ins_h = 0;
  17660. }
  17661. function init_block() {
  17662. var i; // Initialize the trees.
  17663. for (i = 0; i < L_CODES; i++) {
  17664. dyn_ltree[i * 2] = 0;
  17665. }
  17666. for (i = 0; i < D_CODES; i++) {
  17667. dyn_dtree[i * 2] = 0;
  17668. }
  17669. for (i = 0; i < BL_CODES; i++) {
  17670. bl_tree[i * 2] = 0;
  17671. }
  17672. dyn_ltree[END_BLOCK * 2] = 1;
  17673. that.opt_len = that.static_len = 0;
  17674. last_lit = matches = 0;
  17675. } // Initialize the tree data structures for a new zlib stream.
  17676. function tr_init() {
  17677. l_desc.dyn_tree = dyn_ltree;
  17678. l_desc.stat_desc = StaticTree.static_l_desc;
  17679. d_desc.dyn_tree = dyn_dtree;
  17680. d_desc.stat_desc = StaticTree.static_d_desc;
  17681. bl_desc.dyn_tree = bl_tree;
  17682. bl_desc.stat_desc = StaticTree.static_bl_desc;
  17683. bi_buf = 0;
  17684. bi_valid = 0;
  17685. last_eob_len = 8; // enough lookahead for inflate
  17686. // Initialize the first block of the first file:
  17687. init_block();
  17688. } // Restore the heap property by moving down the tree starting at node k,
  17689. // exchanging a node with the smallest of its two sons if necessary,
  17690. // stopping
  17691. // when the heap property is re-established (each father smaller than its
  17692. // two sons).
  17693. that.pqdownheap = function (tree, // the tree to restore
  17694. k // node to move down
  17695. ) {
  17696. var heap = that.heap;
  17697. var v = heap[k];
  17698. var j = k << 1; // left son of k
  17699. while (j <= that.heap_len) {
  17700. // Set j to the smallest of the two sons:
  17701. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  17702. j++;
  17703. } // Exit if v is smaller than both sons
  17704. if (smaller(tree, v, heap[j], that.depth)) break; // Exchange v with the smallest son
  17705. heap[k] = heap[j];
  17706. k = j; // And continue down the tree, setting j to the left son of k
  17707. j <<= 1;
  17708. }
  17709. heap[k] = v;
  17710. }; // Scan a literal or distance tree to determine the frequencies of the codes
  17711. // in the bit length tree.
  17712. function scan_tree(tree, // the tree to be scanned
  17713. max_code // and its largest code of non zero frequency
  17714. ) {
  17715. var n; // iterates over all tree elements
  17716. var prevlen = -1; // last emitted length
  17717. var curlen; // length of current code
  17718. var nextlen = tree[0 * 2 + 1]; // length of next code
  17719. var count = 0; // repeat count of the current code
  17720. var max_count = 7; // max repeat count
  17721. var min_count = 4; // min repeat count
  17722. if (nextlen === 0) {
  17723. max_count = 138;
  17724. min_count = 3;
  17725. }
  17726. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  17727. for (n = 0; n <= max_code; n++) {
  17728. curlen = nextlen;
  17729. nextlen = tree[(n + 1) * 2 + 1];
  17730. if (++count < max_count && curlen == nextlen) {
  17731. continue;
  17732. } else if (count < min_count) {
  17733. bl_tree[curlen * 2] += count;
  17734. } else if (curlen !== 0) {
  17735. if (curlen != prevlen) bl_tree[curlen * 2]++;
  17736. bl_tree[REP_3_6 * 2]++;
  17737. } else if (count <= 10) {
  17738. bl_tree[REPZ_3_10 * 2]++;
  17739. } else {
  17740. bl_tree[REPZ_11_138 * 2]++;
  17741. }
  17742. count = 0;
  17743. prevlen = curlen;
  17744. if (nextlen === 0) {
  17745. max_count = 138;
  17746. min_count = 3;
  17747. } else if (curlen == nextlen) {
  17748. max_count = 6;
  17749. min_count = 3;
  17750. } else {
  17751. max_count = 7;
  17752. min_count = 4;
  17753. }
  17754. }
  17755. } // Construct the Huffman tree for the bit lengths and return the index in
  17756. // bl_order of the last bit length code to send.
  17757. function build_bl_tree() {
  17758. var max_blindex; // index of last bit length code of non zero freq
  17759. // Determine the bit length frequencies for literal and distance trees
  17760. scan_tree(dyn_ltree, l_desc.max_code);
  17761. scan_tree(dyn_dtree, d_desc.max_code); // Build the bit length tree:
  17762. bl_desc.build_tree(that); // opt_len now includes the length of the tree representations, except
  17763. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  17764. // counts.
  17765. // Determine the number of bit length codes to send. The pkzip format
  17766. // requires that at least 4 bit length codes be sent. (appnote.txt says
  17767. // 3 but the actual value used is 4.)
  17768. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  17769. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0) break;
  17770. } // Update opt_len to include the bit length tree and counts
  17771. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  17772. return max_blindex;
  17773. } // Output a byte on the stream.
  17774. // IN assertion: there is enough room in pending_buf.
  17775. function put_byte(p) {
  17776. that.pending_buf[that.pending++] = p;
  17777. }
  17778. function put_short(w) {
  17779. put_byte(w & 0xff);
  17780. put_byte(w >>> 8 & 0xff);
  17781. }
  17782. function putShortMSB(b) {
  17783. put_byte(b >> 8 & 0xff);
  17784. put_byte(b & 0xff & 0xff);
  17785. }
  17786. function send_bits(value, length) {
  17787. var val,
  17788. len = length;
  17789. if (bi_valid > Buf_size - len) {
  17790. val = value; // bi_buf |= (val << bi_valid);
  17791. bi_buf |= val << bi_valid & 0xffff;
  17792. put_short(bi_buf);
  17793. bi_buf = val >>> Buf_size - bi_valid;
  17794. bi_valid += len - Buf_size;
  17795. } else {
  17796. // bi_buf |= (value) << bi_valid;
  17797. bi_buf |= value << bi_valid & 0xffff;
  17798. bi_valid += len;
  17799. }
  17800. }
  17801. function send_code(c, tree) {
  17802. var c2 = c * 2;
  17803. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  17804. } // Send a literal or distance tree in compressed form, using the codes in
  17805. // bl_tree.
  17806. function send_tree(tree, // the tree to be sent
  17807. max_code // and its largest code of non zero frequency
  17808. ) {
  17809. var n; // iterates over all tree elements
  17810. var prevlen = -1; // last emitted length
  17811. var curlen; // length of current code
  17812. var nextlen = tree[0 * 2 + 1]; // length of next code
  17813. var count = 0; // repeat count of the current code
  17814. var max_count = 7; // max repeat count
  17815. var min_count = 4; // min repeat count
  17816. if (nextlen === 0) {
  17817. max_count = 138;
  17818. min_count = 3;
  17819. }
  17820. for (n = 0; n <= max_code; n++) {
  17821. curlen = nextlen;
  17822. nextlen = tree[(n + 1) * 2 + 1];
  17823. if (++count < max_count && curlen == nextlen) {
  17824. continue;
  17825. } else if (count < min_count) {
  17826. do {
  17827. send_code(curlen, bl_tree);
  17828. } while (--count !== 0);
  17829. } else if (curlen !== 0) {
  17830. if (curlen != prevlen) {
  17831. send_code(curlen, bl_tree);
  17832. count--;
  17833. }
  17834. send_code(REP_3_6, bl_tree);
  17835. send_bits(count - 3, 2);
  17836. } else if (count <= 10) {
  17837. send_code(REPZ_3_10, bl_tree);
  17838. send_bits(count - 3, 3);
  17839. } else {
  17840. send_code(REPZ_11_138, bl_tree);
  17841. send_bits(count - 11, 7);
  17842. }
  17843. count = 0;
  17844. prevlen = curlen;
  17845. if (nextlen === 0) {
  17846. max_count = 138;
  17847. min_count = 3;
  17848. } else if (curlen == nextlen) {
  17849. max_count = 6;
  17850. min_count = 3;
  17851. } else {
  17852. max_count = 7;
  17853. min_count = 4;
  17854. }
  17855. }
  17856. } // Send the header for a block using dynamic Huffman trees: the counts, the
  17857. // lengths of the bit length codes, the literal tree and the distance tree.
  17858. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17859. function send_all_trees(lcodes, dcodes, blcodes) {
  17860. var rank; // index in bl_order
  17861. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  17862. send_bits(dcodes - 1, 5);
  17863. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  17864. for (rank = 0; rank < blcodes; rank++) {
  17865. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  17866. }
  17867. send_tree(dyn_ltree, lcodes - 1); // literal tree
  17868. send_tree(dyn_dtree, dcodes - 1); // distance tree
  17869. } // Flush the bit buffer, keeping at most 7 bits in it.
  17870. function bi_flush() {
  17871. if (bi_valid == 16) {
  17872. put_short(bi_buf);
  17873. bi_buf = 0;
  17874. bi_valid = 0;
  17875. } else if (bi_valid >= 8) {
  17876. put_byte(bi_buf & 0xff);
  17877. bi_buf >>>= 8;
  17878. bi_valid -= 8;
  17879. }
  17880. } // Send one empty static block to give enough lookahead for inflate.
  17881. // This takes 10 bits, of which 7 may remain in the bit buffer.
  17882. // The current inflate code requires 9 bits of lookahead. If the
  17883. // last two codes for the previous block (real code plus EOB) were coded
  17884. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  17885. // the last real code. In this case we send two empty static blocks instead
  17886. // of one. (There are no problems if the previous block is stored or fixed.)
  17887. // To simplify the code, we assume the worst case of last real code encoded
  17888. // on one bit only.
  17889. function _tr_align() {
  17890. send_bits(STATIC_TREES << 1, 3);
  17891. send_code(END_BLOCK, StaticTree.static_ltree);
  17892. bi_flush(); // Of the 10 bits for the empty block, we have already sent
  17893. // (10 - bi_valid) bits. The lookahead for the last real code (before
  17894. // the EOB of the previous block) was thus at least one plus the length
  17895. // of the EOB plus what we have just sent of the empty static block.
  17896. if (1 + last_eob_len + 10 - bi_valid < 9) {
  17897. send_bits(STATIC_TREES << 1, 3);
  17898. send_code(END_BLOCK, StaticTree.static_ltree);
  17899. bi_flush();
  17900. }
  17901. last_eob_len = 7;
  17902. } // Save the match info and tally the frequency counts. Return true if
  17903. // the current block must be flushed.
  17904. function _tr_tally(dist, // distance of matched string
  17905. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  17906. ) {
  17907. var out_length, in_length, dcode;
  17908. that.pending_buf[d_buf + last_lit * 2] = dist >>> 8 & 0xff;
  17909. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  17910. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  17911. last_lit++;
  17912. if (dist === 0) {
  17913. // lc is the unmatched char
  17914. dyn_ltree[lc * 2]++;
  17915. } else {
  17916. matches++; // Here, lc is the match length - MIN_MATCH
  17917. dist--; // dist = match distance - 1
  17918. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  17919. dyn_dtree[Tree.d_code(dist) * 2]++;
  17920. }
  17921. if ((last_lit & 0x1fff) === 0 && level > 2) {
  17922. // Compute an upper bound for the compressed length
  17923. out_length = last_lit * 8;
  17924. in_length = strstart - block_start;
  17925. for (dcode = 0; dcode < D_CODES; dcode++) {
  17926. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  17927. }
  17928. out_length >>>= 3;
  17929. if (matches < Math.floor(last_lit / 2) && out_length < Math.floor(in_length / 2)) return true;
  17930. }
  17931. return last_lit == lit_bufsize - 1; // We avoid equality with lit_bufsize because of wraparound at 64K
  17932. // on 16 bit machines and because stored blocks are restricted to
  17933. // 64K-1 bytes.
  17934. } // Send the block data compressed using the given Huffman trees
  17935. function compress_block(ltree, dtree) {
  17936. var dist; // distance of matched string
  17937. var lc; // match length or unmatched char (if dist === 0)
  17938. var lx = 0; // running index in l_buf
  17939. var code; // the code to send
  17940. var extra; // number of extra bits to send
  17941. if (last_lit !== 0) {
  17942. do {
  17943. dist = that.pending_buf[d_buf + lx * 2] << 8 & 0xff00 | that.pending_buf[d_buf + lx * 2 + 1] & 0xff;
  17944. lc = that.pending_buf[l_buf + lx] & 0xff;
  17945. lx++;
  17946. if (dist === 0) {
  17947. send_code(lc, ltree); // send a literal byte
  17948. } else {
  17949. // Here, lc is the match length - MIN_MATCH
  17950. code = Tree._length_code[lc];
  17951. send_code(code + LITERALS + 1, ltree); // send the length
  17952. // code
  17953. extra = Tree.extra_lbits[code];
  17954. if (extra !== 0) {
  17955. lc -= Tree.base_length[code];
  17956. send_bits(lc, extra); // send the extra length bits
  17957. }
  17958. dist--; // dist is now the match distance - 1
  17959. code = Tree.d_code(dist);
  17960. send_code(code, dtree); // send the distance code
  17961. extra = Tree.extra_dbits[code];
  17962. if (extra !== 0) {
  17963. dist -= Tree.base_dist[code];
  17964. send_bits(dist, extra); // send the extra distance bits
  17965. }
  17966. } // literal or match pair ?
  17967. // Check that the overlay between pending_buf and d_buf+l_buf is
  17968. // ok:
  17969. } while (lx < last_lit);
  17970. }
  17971. send_code(END_BLOCK, ltree);
  17972. last_eob_len = ltree[END_BLOCK * 2 + 1];
  17973. } // Flush the bit buffer and align the output on a byte boundary
  17974. function bi_windup() {
  17975. if (bi_valid > 8) {
  17976. put_short(bi_buf);
  17977. } else if (bi_valid > 0) {
  17978. put_byte(bi_buf & 0xff);
  17979. }
  17980. bi_buf = 0;
  17981. bi_valid = 0;
  17982. } // Copy a stored block, storing first the length and its
  17983. // one's complement if requested.
  17984. function copy_block(buf, // the input data
  17985. len, // its length
  17986. header // true if block header must be written
  17987. ) {
  17988. bi_windup(); // align on byte boundary
  17989. last_eob_len = 8; // enough lookahead for inflate
  17990. if (header) {
  17991. put_short(len);
  17992. put_short(~len);
  17993. }
  17994. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  17995. that.pending += len;
  17996. } // Send a stored block
  17997. function _tr_stored_block(buf, // input block
  17998. stored_len, // length of input block
  17999. eof // true if this is the last block for a file
  18000. ) {
  18001. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  18002. copy_block(buf, stored_len, true); // with header
  18003. } // Determine the best encoding for the current block: dynamic trees, static
  18004. // trees or store, and output the encoded block to the zip file.
  18005. function _tr_flush_block(buf, // input block, or NULL if too old
  18006. stored_len, // length of input block
  18007. eof // true if this is the last block for a file
  18008. ) {
  18009. var opt_lenb, static_lenb; // opt_len and static_len in bytes
  18010. var max_blindex = 0; // index of last bit length code of non zero freq
  18011. // Build the Huffman trees unless a stored block is forced
  18012. if (level > 0) {
  18013. // Construct the literal and distance trees
  18014. l_desc.build_tree(that);
  18015. d_desc.build_tree(that); // At this point, opt_len and static_len are the total bit lengths
  18016. // of
  18017. // the compressed block data, excluding the tree representations.
  18018. // Build the bit length tree for the above two trees, and get the
  18019. // index
  18020. // in bl_order of the last bit length code to send.
  18021. max_blindex = build_bl_tree(); // Determine the best encoding. Compute first the block length in
  18022. // bytes
  18023. opt_lenb = that.opt_len + 3 + 7 >>> 3;
  18024. static_lenb = that.static_len + 3 + 7 >>> 3;
  18025. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  18026. } else {
  18027. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  18028. }
  18029. if (stored_len + 4 <= opt_lenb && buf != -1) {
  18030. // 4: two words for the lengths
  18031. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18032. // Otherwise we can't have processed more than WSIZE input bytes
  18033. // since
  18034. // the last block flush, because compression would have been
  18035. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18036. // transform a block into a stored block.
  18037. _tr_stored_block(buf, stored_len, eof);
  18038. } else if (static_lenb == opt_lenb) {
  18039. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  18040. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  18041. } else {
  18042. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  18043. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  18044. compress_block(dyn_ltree, dyn_dtree);
  18045. } // The above check is made mod 2^32, for files larger than 512 MB
  18046. // and uLong implemented on 32 bits.
  18047. init_block();
  18048. if (eof) {
  18049. bi_windup();
  18050. }
  18051. }
  18052. function flush_block_only(eof) {
  18053. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  18054. block_start = strstart;
  18055. strm.flush_pending();
  18056. } // Fill the window when the lookahead becomes insufficient.
  18057. // Updates strstart and lookahead.
  18058. //
  18059. // IN assertion: lookahead < MIN_LOOKAHEAD
  18060. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18061. // At least one byte has been read, or avail_in === 0; reads are
  18062. // performed for at least two bytes (required for the zip translate_eol
  18063. // option -- not supported here).
  18064. function fill_window() {
  18065. var n, m;
  18066. var p;
  18067. var more; // Amount of free space at the end of the window.
  18068. do {
  18069. more = window_size - lookahead - strstart; // Deal with !@#$% 64K limit:
  18070. if (more === 0 && strstart === 0 && lookahead === 0) {
  18071. more = w_size;
  18072. } else if (more == -1) {
  18073. // Very unlikely, but possible on 16 bit machine if strstart ==
  18074. // 0
  18075. // and lookahead == 1 (input done one byte at time)
  18076. more--; // If the window is almost full and there is insufficient
  18077. // lookahead,
  18078. // move the upper half to the lower one to make room in the
  18079. // upper half.
  18080. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  18081. window.set(window.subarray(w_size, w_size + w_size), 0);
  18082. match_start -= w_size;
  18083. strstart -= w_size; // we now have strstart >= MAX_DIST
  18084. block_start -= w_size; // Slide the hash table (could be avoided with 32 bit values
  18085. // at the expense of memory usage). We slide even when level ==
  18086. // 0
  18087. // to keep the hash table consistent if we switch back to level
  18088. // > 0
  18089. // later. (Using level 0 permanently is not an optimal usage of
  18090. // zlib, so we don't care about this pathological case.)
  18091. n = hash_size;
  18092. p = n;
  18093. do {
  18094. m = head[--p] & 0xffff;
  18095. head[p] = m >= w_size ? m - w_size : 0;
  18096. } while (--n !== 0);
  18097. n = w_size;
  18098. p = n;
  18099. do {
  18100. m = prev[--p] & 0xffff;
  18101. prev[p] = m >= w_size ? m - w_size : 0; // If n is not on any hash chain, prev[n] is garbage but
  18102. // its value will never be used.
  18103. } while (--n !== 0);
  18104. more += w_size;
  18105. }
  18106. if (strm.avail_in === 0) return; // If there was no sliding:
  18107. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18108. // more == window_size - lookahead - strstart
  18109. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18110. // => more >= window_size - 2*WSIZE + 2
  18111. // In the BIG_MEM or MMAP case (not yet supported),
  18112. // window_size == input_size + MIN_LOOKAHEAD &&
  18113. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18114. // Otherwise, window_size == 2*WSIZE so more >= 2.
  18115. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18116. n = strm.read_buf(window, strstart + lookahead, more);
  18117. lookahead += n; // Initialize the hash value now that we have some input:
  18118. if (lookahead >= MIN_MATCH) {
  18119. ins_h = window[strstart] & 0xff;
  18120. ins_h = (ins_h << hash_shift ^ window[strstart + 1] & 0xff) & hash_mask;
  18121. } // If the whole input has less than MIN_MATCH bytes, ins_h is
  18122. // garbage,
  18123. // but this is not important since only literal bytes will be
  18124. // emitted.
  18125. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  18126. } // Copy without compression as much as possible from the input stream,
  18127. // return
  18128. // the current block state.
  18129. // This function does not insert new strings in the dictionary since
  18130. // uncompressible data is probably not useful. This function is used
  18131. // only for the level=0 compression option.
  18132. // NOTE: this function should be optimized to avoid extra copying from
  18133. // window to pending_buf.
  18134. function deflate_stored(flush) {
  18135. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18136. // to pending_buf_size, and each stored block has a 5 byte header:
  18137. var max_block_size = 0xffff;
  18138. var max_start;
  18139. if (max_block_size > pending_buf_size - 5) {
  18140. max_block_size = pending_buf_size - 5;
  18141. } // Copy as much as possible from input to output:
  18142. while (true) {
  18143. // Fill the window as much as possible:
  18144. if (lookahead <= 1) {
  18145. fill_window();
  18146. if (lookahead === 0 && flush == Z_NO_FLUSH) return NeedMore;
  18147. if (lookahead === 0) break; // flush the current block
  18148. }
  18149. strstart += lookahead;
  18150. lookahead = 0; // Emit a stored block if pending_buf will be full:
  18151. max_start = block_start + max_block_size;
  18152. if (strstart === 0 || strstart >= max_start) {
  18153. // strstart === 0 is possible when wraparound on 16-bit machine
  18154. lookahead = strstart - max_start;
  18155. strstart = max_start;
  18156. flush_block_only(false);
  18157. if (strm.avail_out === 0) return NeedMore;
  18158. } // Flush if we may have to slide, otherwise block_start may become
  18159. // negative and the data will be gone:
  18160. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  18161. flush_block_only(false);
  18162. if (strm.avail_out === 0) return NeedMore;
  18163. }
  18164. }
  18165. flush_block_only(flush == Z_FINISH);
  18166. if (strm.avail_out === 0) return flush == Z_FINISH ? FinishStarted : NeedMore;
  18167. return flush == Z_FINISH ? FinishDone : BlockDone;
  18168. }
  18169. function longest_match(cur_match) {
  18170. var chain_length = max_chain_length; // max hash chain length
  18171. var scan = strstart; // current string
  18172. var match; // matched string
  18173. var len; // length of current match
  18174. var best_len = prev_length; // best match length so far
  18175. var limit = strstart > w_size - MIN_LOOKAHEAD ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  18176. var _nice_match = nice_match; // Stop when cur_match becomes <= limit. To simplify the code,
  18177. // we prevent matches with the string of window index 0.
  18178. var wmask = w_mask;
  18179. var strend = strstart + MAX_MATCH;
  18180. var scan_end1 = window[scan + best_len - 1];
  18181. var scan_end = window[scan + best_len]; // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  18182. // 16.
  18183. // It is easy to get rid of this optimization if necessary.
  18184. // Do not waste too much time if we already have a good match:
  18185. if (prev_length >= good_match) {
  18186. chain_length >>= 2;
  18187. } // Do not look for matches beyond the end of the input. This is
  18188. // necessary
  18189. // to make deflate deterministic.
  18190. if (_nice_match > lookahead) _nice_match = lookahead;
  18191. do {
  18192. match = cur_match; // Skip to next match if the match length cannot increase
  18193. // or if the match length is less than 2:
  18194. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1]) continue; // The check at best_len-1 can be removed because it will be made
  18195. // again later. (This heuristic is not always a win.)
  18196. // It is not necessary to compare scan[2] and match[2] since they
  18197. // are always equal when the other bytes match, given that
  18198. // the hash keys are equal and that HASH_BITS >= 8.
  18199. scan += 2;
  18200. match++; // We check for insufficient lookahead only every 8th comparison;
  18201. // the 256th check will be made at strstart+258.
  18202. do {} while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  18203. len = MAX_MATCH - (strend - scan);
  18204. scan = strend - MAX_MATCH;
  18205. if (len > best_len) {
  18206. match_start = cur_match;
  18207. best_len = len;
  18208. if (len >= _nice_match) break;
  18209. scan_end1 = window[scan + best_len - 1];
  18210. scan_end = window[scan + best_len];
  18211. }
  18212. } while ((cur_match = prev[cur_match & wmask] & 0xffff) > limit && --chain_length !== 0);
  18213. if (best_len <= lookahead) return best_len;
  18214. return lookahead;
  18215. } // Compress as much as possible from the input stream, return the current
  18216. // block state.
  18217. // This function does not perform lazy evaluation of matches and inserts
  18218. // new strings in the dictionary only for unmatched strings or for short
  18219. // matches. It is used only for the fast compression options.
  18220. function deflate_fast(flush) {
  18221. // short hash_head = 0; // head of the hash chain
  18222. var hash_head = 0; // head of the hash chain
  18223. var bflush; // set if current block must be flushed
  18224. while (true) {
  18225. // Make sure that we always have enough lookahead, except
  18226. // at the end of the input file. We need MAX_MATCH bytes
  18227. // for the next match, plus MIN_MATCH bytes to insert the
  18228. // string following the next match.
  18229. if (lookahead < MIN_LOOKAHEAD) {
  18230. fill_window();
  18231. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  18232. return NeedMore;
  18233. }
  18234. if (lookahead === 0) break; // flush the current block
  18235. } // Insert the string window[strstart .. strstart+2] in the
  18236. // dictionary, and set hash_head to the head of the hash chain:
  18237. if (lookahead >= MIN_MATCH) {
  18238. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  18239. hash_head = head[ins_h] & 0xffff;
  18240. prev[strstart & w_mask] = head[ins_h];
  18241. head[ins_h] = strstart;
  18242. } // Find the longest match, discarding those <= prev_length.
  18243. // At this point we have always match_length < MIN_MATCH
  18244. if (hash_head !== 0 && (strstart - hash_head & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  18245. // To simplify the code, we prevent matches with the string
  18246. // of window index 0 (in particular we have to avoid a match
  18247. // of the string with itself at the start of the input file).
  18248. if (strategy != Z_HUFFMAN_ONLY) {
  18249. match_length = longest_match(hash_head);
  18250. } // longest_match() sets match_start
  18251. }
  18252. if (match_length >= MIN_MATCH) {
  18253. // check_match(strstart, match_start, match_length);
  18254. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  18255. lookahead -= match_length; // Insert new strings in the hash table only if the match length
  18256. // is not too large. This saves time but degrades compression.
  18257. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  18258. match_length--; // string at strstart already in hash table
  18259. do {
  18260. strstart++;
  18261. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  18262. hash_head = head[ins_h] & 0xffff;
  18263. prev[strstart & w_mask] = head[ins_h];
  18264. head[ins_h] = strstart; // strstart never exceeds WSIZE-MAX_MATCH, so there are
  18265. // always MIN_MATCH bytes ahead.
  18266. } while (--match_length !== 0);
  18267. strstart++;
  18268. } else {
  18269. strstart += match_length;
  18270. match_length = 0;
  18271. ins_h = window[strstart] & 0xff;
  18272. ins_h = (ins_h << hash_shift ^ window[strstart + 1] & 0xff) & hash_mask; // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  18273. // not
  18274. // matter since it will be recomputed at next deflate call.
  18275. }
  18276. } else {
  18277. // No match, output a literal byte
  18278. bflush = _tr_tally(0, window[strstart] & 0xff);
  18279. lookahead--;
  18280. strstart++;
  18281. }
  18282. if (bflush) {
  18283. flush_block_only(false);
  18284. if (strm.avail_out === 0) return NeedMore;
  18285. }
  18286. }
  18287. flush_block_only(flush == Z_FINISH);
  18288. if (strm.avail_out === 0) {
  18289. if (flush == Z_FINISH) return FinishStarted;else return NeedMore;
  18290. }
  18291. return flush == Z_FINISH ? FinishDone : BlockDone;
  18292. } // Same as above, but achieves better compression. We use a lazy
  18293. // evaluation for matches: a match is finally adopted only if there is
  18294. // no better match at the next window position.
  18295. function deflate_slow(flush) {
  18296. // short hash_head = 0; // head of hash chain
  18297. var hash_head = 0; // head of hash chain
  18298. var bflush; // set if current block must be flushed
  18299. var max_insert; // Process the input block.
  18300. while (true) {
  18301. // Make sure that we always have enough lookahead, except
  18302. // at the end of the input file. We need MAX_MATCH bytes
  18303. // for the next match, plus MIN_MATCH bytes to insert the
  18304. // string following the next match.
  18305. if (lookahead < MIN_LOOKAHEAD) {
  18306. fill_window();
  18307. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  18308. return NeedMore;
  18309. }
  18310. if (lookahead === 0) break; // flush the current block
  18311. } // Insert the string window[strstart .. strstart+2] in the
  18312. // dictionary, and set hash_head to the head of the hash chain:
  18313. if (lookahead >= MIN_MATCH) {
  18314. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  18315. hash_head = head[ins_h] & 0xffff;
  18316. prev[strstart & w_mask] = head[ins_h];
  18317. head[ins_h] = strstart;
  18318. } // Find the longest match, discarding those <= prev_length.
  18319. prev_length = match_length;
  18320. prev_match = match_start;
  18321. match_length = MIN_MATCH - 1;
  18322. if (hash_head !== 0 && prev_length < max_lazy_match && (strstart - hash_head & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  18323. // To simplify the code, we prevent matches with the string
  18324. // of window index 0 (in particular we have to avoid a match
  18325. // of the string with itself at the start of the input file).
  18326. if (strategy != Z_HUFFMAN_ONLY) {
  18327. match_length = longest_match(hash_head);
  18328. } // longest_match() sets match_start
  18329. if (match_length <= 5 && (strategy == Z_FILTERED || match_length == MIN_MATCH && strstart - match_start > 4096)) {
  18330. // If prev_match is also MIN_MATCH, match_start is garbage
  18331. // but we will ignore the current match anyway.
  18332. match_length = MIN_MATCH - 1;
  18333. }
  18334. } // If there was a match at the previous step and the current
  18335. // match is not better, output the previous match:
  18336. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  18337. max_insert = strstart + lookahead - MIN_MATCH; // Do not insert strings in hash table beyond this.
  18338. // check_match(strstart-1, prev_match, prev_length);
  18339. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); // Insert in hash table all strings up to the end of the match.
  18340. // strstart-1 and strstart are already inserted. If there is not
  18341. // enough lookahead, the last two strings are not inserted in
  18342. // the hash table.
  18343. lookahead -= prev_length - 1;
  18344. prev_length -= 2;
  18345. do {
  18346. if (++strstart <= max_insert) {
  18347. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  18348. hash_head = head[ins_h] & 0xffff;
  18349. prev[strstart & w_mask] = head[ins_h];
  18350. head[ins_h] = strstart;
  18351. }
  18352. } while (--prev_length !== 0);
  18353. match_available = 0;
  18354. match_length = MIN_MATCH - 1;
  18355. strstart++;
  18356. if (bflush) {
  18357. flush_block_only(false);
  18358. if (strm.avail_out === 0) return NeedMore;
  18359. }
  18360. } else if (match_available !== 0) {
  18361. // If there was no match at the previous position, output a
  18362. // single literal. If there was a match but the current match
  18363. // is longer, truncate the previous match to a single literal.
  18364. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  18365. if (bflush) {
  18366. flush_block_only(false);
  18367. }
  18368. strstart++;
  18369. lookahead--;
  18370. if (strm.avail_out === 0) return NeedMore;
  18371. } else {
  18372. // There is no previous match to compare with, wait for
  18373. // the next step to decide.
  18374. match_available = 1;
  18375. strstart++;
  18376. lookahead--;
  18377. }
  18378. }
  18379. if (match_available !== 0) {
  18380. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  18381. match_available = 0;
  18382. }
  18383. flush_block_only(flush == Z_FINISH);
  18384. if (strm.avail_out === 0) {
  18385. if (flush == Z_FINISH) return FinishStarted;else return NeedMore;
  18386. }
  18387. return flush == Z_FINISH ? FinishDone : BlockDone;
  18388. }
  18389. function deflateReset(strm) {
  18390. strm.total_in = strm.total_out = 0;
  18391. strm.msg = null; //
  18392. that.pending = 0;
  18393. that.pending_out = 0;
  18394. status = BUSY_STATE;
  18395. last_flush = Z_NO_FLUSH;
  18396. tr_init();
  18397. lm_init();
  18398. return Z_OK;
  18399. }
  18400. that.deflateInit = function (strm, _level, bits, _method, memLevel, _strategy) {
  18401. if (!_method) _method = Z_DEFLATED;
  18402. if (!memLevel) memLevel = DEF_MEM_LEVEL;
  18403. if (!_strategy) _strategy = Z_DEFAULT_STRATEGY; // byte[] my_version=ZLIB_VERSION;
  18404. //
  18405. // if (!version || version[0] != my_version[0]
  18406. // || stream_size != sizeof(z_stream)) {
  18407. // return Z_VERSION_ERROR;
  18408. // }
  18409. strm.msg = null;
  18410. if (_level == Z_DEFAULT_COMPRESSION) _level = 6;
  18411. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  18412. return Z_STREAM_ERROR;
  18413. }
  18414. strm.dstate = that;
  18415. w_bits = bits;
  18416. w_size = 1 << w_bits;
  18417. w_mask = w_size - 1;
  18418. hash_bits = memLevel + 7;
  18419. hash_size = 1 << hash_bits;
  18420. hash_mask = hash_size - 1;
  18421. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18422. window = new Uint8Array(w_size * 2);
  18423. prev = [];
  18424. head = [];
  18425. lit_bufsize = 1 << memLevel + 6; // 16K elements by default
  18426. // We overlay pending_buf and d_buf+l_buf. This works since the average
  18427. // output size for (length,distance) codes is <= 24 bits.
  18428. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  18429. pending_buf_size = lit_bufsize * 4;
  18430. d_buf = Math.floor(lit_bufsize / 2);
  18431. l_buf = (1 + 2) * lit_bufsize;
  18432. level = _level;
  18433. strategy = _strategy;
  18434. return deflateReset(strm);
  18435. };
  18436. that.deflateEnd = function () {
  18437. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  18438. return Z_STREAM_ERROR;
  18439. } // Deallocate in reverse order of allocations:
  18440. that.pending_buf = null;
  18441. head = null;
  18442. prev = null;
  18443. window = null; // free
  18444. that.dstate = null;
  18445. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  18446. };
  18447. that.deflateParams = function (strm, _level, _strategy) {
  18448. var err = Z_OK;
  18449. if (_level == Z_DEFAULT_COMPRESSION) {
  18450. _level = 6;
  18451. }
  18452. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  18453. return Z_STREAM_ERROR;
  18454. }
  18455. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  18456. // Flush the last buffer:
  18457. err = strm.deflate(Z_PARTIAL_FLUSH);
  18458. }
  18459. if (level != _level) {
  18460. level = _level;
  18461. max_lazy_match = config_table[level].max_lazy;
  18462. good_match = config_table[level].good_length;
  18463. nice_match = config_table[level].nice_length;
  18464. max_chain_length = config_table[level].max_chain;
  18465. }
  18466. strategy = _strategy;
  18467. return err;
  18468. };
  18469. that.deflateSetDictionary = function (strm, dictionary, dictLength) {
  18470. var length = dictLength;
  18471. var n,
  18472. index = 0;
  18473. if (!dictionary || status != INIT_STATE) return Z_STREAM_ERROR;
  18474. if (length < MIN_MATCH) return Z_OK;
  18475. if (length > w_size - MIN_LOOKAHEAD) {
  18476. length = w_size - MIN_LOOKAHEAD;
  18477. index = dictLength - length; // use the tail of the dictionary
  18478. }
  18479. window.set(dictionary.subarray(index, index + length), 0);
  18480. strstart = length;
  18481. block_start = length; // Insert all strings in the hash table (except for the last two bytes).
  18482. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  18483. // call of fill_window.
  18484. ins_h = window[0] & 0xff;
  18485. ins_h = (ins_h << hash_shift ^ window[1] & 0xff) & hash_mask;
  18486. for (n = 0; n <= length - MIN_MATCH; n++) {
  18487. ins_h = (ins_h << hash_shift ^ window[n + (MIN_MATCH - 1)] & 0xff) & hash_mask;
  18488. prev[n & w_mask] = head[ins_h];
  18489. head[ins_h] = n;
  18490. }
  18491. return Z_OK;
  18492. };
  18493. that.deflate = function (_strm, flush) {
  18494. var i, header, level_flags, old_flush, bstate;
  18495. if (flush > Z_FINISH || flush < 0) {
  18496. return Z_STREAM_ERROR;
  18497. }
  18498. if (!_strm.next_out || !_strm.next_in && _strm.avail_in !== 0 || status == FINISH_STATE && flush != Z_FINISH) {
  18499. _strm.msg = z_errmsg[Z_NEED_DICT - Z_STREAM_ERROR];
  18500. return Z_STREAM_ERROR;
  18501. }
  18502. if (_strm.avail_out === 0) {
  18503. _strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  18504. return Z_BUF_ERROR;
  18505. }
  18506. strm = _strm; // just in case
  18507. old_flush = last_flush;
  18508. last_flush = flush; // Write the zlib header
  18509. if (status == INIT_STATE) {
  18510. header = Z_DEFLATED + (w_bits - 8 << 4) << 8;
  18511. level_flags = (level - 1 & 0xff) >> 1;
  18512. if (level_flags > 3) level_flags = 3;
  18513. header |= level_flags << 6;
  18514. if (strstart !== 0) header |= PRESET_DICT;
  18515. header += 31 - header % 31;
  18516. status = BUSY_STATE;
  18517. putShortMSB(header);
  18518. } // Flush as much pending output as possible
  18519. if (that.pending !== 0) {
  18520. strm.flush_pending();
  18521. if (strm.avail_out === 0) {
  18522. // console.log(" avail_out==0");
  18523. // Since avail_out is 0, deflate will be called again with
  18524. // more output space, but possibly with both pending and
  18525. // avail_in equal to zero. There won't be anything to do,
  18526. // but this is not an error situation so make sure we
  18527. // return OK instead of BUF_ERROR at next call of deflate:
  18528. last_flush = -1;
  18529. return Z_OK;
  18530. } // Make sure there is something to do and avoid duplicate
  18531. // consecutive
  18532. // flushes. For repeated and useless calls with Z_FINISH, we keep
  18533. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  18534. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  18535. strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  18536. return Z_BUF_ERROR;
  18537. } // User must not provide more input after the first FINISH:
  18538. if (status == FINISH_STATE && strm.avail_in !== 0) {
  18539. _strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  18540. return Z_BUF_ERROR;
  18541. } // Start a new block or continue the current one.
  18542. if (strm.avail_in !== 0 || lookahead !== 0 || flush != Z_NO_FLUSH && status != FINISH_STATE) {
  18543. bstate = -1;
  18544. switch (config_table[level].func) {
  18545. case STORED:
  18546. bstate = deflate_stored(flush);
  18547. break;
  18548. case FAST:
  18549. bstate = deflate_fast(flush);
  18550. break;
  18551. case SLOW:
  18552. bstate = deflate_slow(flush);
  18553. break;
  18554. default:
  18555. }
  18556. if (bstate == FinishStarted || bstate == FinishDone) {
  18557. status = FINISH_STATE;
  18558. }
  18559. if (bstate == NeedMore || bstate == FinishStarted) {
  18560. if (strm.avail_out === 0) {
  18561. last_flush = -1; // avoid BUF_ERROR next call, see above
  18562. }
  18563. return Z_OK; // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  18564. // of deflate should use the same flush parameter to make sure
  18565. // that the flush is complete. So we don't have to output an
  18566. // empty block here, this will be done at next call. This also
  18567. // ensures that for a very small output buffer, we emit at most
  18568. // one empty block.
  18569. }
  18570. if (bstate == BlockDone) {
  18571. if (flush == Z_PARTIAL_FLUSH) {
  18572. _tr_align();
  18573. } else {
  18574. // FULL_FLUSH or SYNC_FLUSH
  18575. _tr_stored_block(0, 0, false); // For a full flush, this empty block will be recognized
  18576. // as a special marker by inflate_sync().
  18577. if (flush == Z_FULL_FLUSH) {
  18578. // state.head[s.hash_size-1]=0;
  18579. for (i = 0; i < hash_size
  18580. /*-1*/
  18581. ; i++) {
  18582. // forget history
  18583. head[i] = 0;
  18584. }
  18585. }
  18586. }
  18587. strm.flush_pending();
  18588. if (strm.avail_out === 0) {
  18589. last_flush = -1; // avoid BUF_ERROR at next call, see above
  18590. return Z_OK;
  18591. }
  18592. }
  18593. }
  18594. if (flush != Z_FINISH) return Z_OK;
  18595. return Z_STREAM_END;
  18596. };
  18597. } // ZStream
  18598. function ZStream() {
  18599. var that = this;
  18600. that.next_in_index = 0;
  18601. that.next_out_index = 0; // that.next_in; // next input byte
  18602. that.avail_in = 0; // number of bytes available at next_in
  18603. that.total_in = 0; // total nb of input bytes read so far
  18604. // that.next_out; // next output byte should be put there
  18605. that.avail_out = 0; // remaining free space at next_out
  18606. that.total_out = 0; // total nb of bytes output so far
  18607. // that.msg;
  18608. // that.dstate;
  18609. }
  18610. ZStream.prototype = {
  18611. deflateInit: function deflateInit(level, bits) {
  18612. var that = this;
  18613. that.dstate = new Deflate();
  18614. if (!bits) bits = MAX_BITS;
  18615. return that.dstate.deflateInit(that, level, bits);
  18616. },
  18617. deflate: function deflate(flush) {
  18618. var that = this;
  18619. if (!that.dstate) {
  18620. return Z_STREAM_ERROR;
  18621. }
  18622. return that.dstate.deflate(that, flush);
  18623. },
  18624. deflateEnd: function deflateEnd() {
  18625. var that = this;
  18626. if (!that.dstate) return Z_STREAM_ERROR;
  18627. var ret = that.dstate.deflateEnd();
  18628. that.dstate = null;
  18629. return ret;
  18630. },
  18631. deflateParams: function deflateParams(level, strategy) {
  18632. var that = this;
  18633. if (!that.dstate) return Z_STREAM_ERROR;
  18634. return that.dstate.deflateParams(that, level, strategy);
  18635. },
  18636. deflateSetDictionary: function deflateSetDictionary(dictionary, dictLength) {
  18637. var that = this;
  18638. if (!that.dstate) return Z_STREAM_ERROR;
  18639. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  18640. },
  18641. // Read a new buffer from the current input stream, update the
  18642. // total number of bytes read. All deflate() input goes through
  18643. // this function so some applications may wish to modify it to avoid
  18644. // allocating a large strm->next_in buffer and copying from it.
  18645. // (See also flush_pending()).
  18646. read_buf: function read_buf(buf, start, size) {
  18647. var that = this;
  18648. var len = that.avail_in;
  18649. if (len > size) len = size;
  18650. if (len === 0) return 0;
  18651. that.avail_in -= len;
  18652. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  18653. that.next_in_index += len;
  18654. that.total_in += len;
  18655. return len;
  18656. },
  18657. // Flush as much pending output as possible. All deflate() output goes
  18658. // through this function so some applications may wish to modify it
  18659. // to avoid allocating a large strm->next_out buffer and copying into it.
  18660. // (See also read_buf()).
  18661. flush_pending: function flush_pending() {
  18662. var that = this;
  18663. var len = that.dstate.pending;
  18664. if (len > that.avail_out) len = that.avail_out;
  18665. if (len === 0) return; // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  18666. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  18667. // len)) {
  18668. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  18669. // that.next_out_index + ", " + len);
  18670. // console.log("avail_out=" + that.avail_out);
  18671. // }
  18672. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  18673. that.next_out_index += len;
  18674. that.dstate.pending_out += len;
  18675. that.total_out += len;
  18676. that.avail_out -= len;
  18677. that.dstate.pending -= len;
  18678. if (that.dstate.pending === 0) {
  18679. that.dstate.pending_out = 0;
  18680. }
  18681. }
  18682. }; // Deflater
  18683. function Deflater(options) {
  18684. var that = this;
  18685. var z = new ZStream();
  18686. var bufsize = 512;
  18687. var flush = Z_NO_FLUSH;
  18688. var buf = new Uint8Array(bufsize);
  18689. var level = options ? options.level : Z_DEFAULT_COMPRESSION;
  18690. if (typeof level == "undefined") level = Z_DEFAULT_COMPRESSION;
  18691. z.deflateInit(level);
  18692. z.next_out = buf;
  18693. that.append = function (data, onprogress) {
  18694. var err,
  18695. buffers = [],
  18696. lastIndex = 0,
  18697. bufferIndex = 0,
  18698. bufferSize = 0,
  18699. array;
  18700. if (!data.length) return;
  18701. z.next_in_index = 0;
  18702. z.next_in = data;
  18703. z.avail_in = data.length;
  18704. do {
  18705. z.next_out_index = 0;
  18706. z.avail_out = bufsize;
  18707. err = z.deflate(flush);
  18708. if (err != Z_OK) throw new Error("deflating: " + z.msg);
  18709. if (z.next_out_index) if (z.next_out_index == bufsize) buffers.push(new Uint8Array(buf));else buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  18710. bufferSize += z.next_out_index;
  18711. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  18712. onprogress(z.next_in_index);
  18713. lastIndex = z.next_in_index;
  18714. }
  18715. } while (z.avail_in > 0 || z.avail_out === 0);
  18716. array = new Uint8Array(bufferSize);
  18717. buffers.forEach(function (chunk) {
  18718. array.set(chunk, bufferIndex);
  18719. bufferIndex += chunk.length;
  18720. });
  18721. return array;
  18722. };
  18723. that.flush = function () {
  18724. var err,
  18725. buffers = [],
  18726. bufferIndex = 0,
  18727. bufferSize = 0,
  18728. array;
  18729. do {
  18730. z.next_out_index = 0;
  18731. z.avail_out = bufsize;
  18732. err = z.deflate(Z_FINISH);
  18733. if (err != Z_STREAM_END && err != Z_OK) throw new Error("deflating: " + z.msg);
  18734. if (bufsize - z.avail_out > 0) buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  18735. bufferSize += z.next_out_index;
  18736. } while (z.avail_in > 0 || z.avail_out === 0);
  18737. z.deflateEnd();
  18738. array = new Uint8Array(bufferSize);
  18739. buffers.forEach(function (chunk) {
  18740. array.set(chunk, bufferIndex);
  18741. bufferIndex += chunk.length;
  18742. });
  18743. return array;
  18744. };
  18745. } // 'zip' may not be defined in z-worker and some tests
  18746. var env = global.zip || global;
  18747. env.Deflater = env._jzlib_Deflater = Deflater;
  18748. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  18749. // while `this` is nsIContentFrameMessageManager
  18750. // with an attribute `content` that corresponds to the window
  18751. /**
  18752. * A class to parse color values
  18753. * @author Stoyan Stefanov <sstoo@gmail.com>
  18754. * {@link http://www.phpied.com/rgb-color-parser-in-javascript/}
  18755. * @license Use it if you like it
  18756. */
  18757. (function (global) {
  18758. function RGBColor(color_string) {
  18759. color_string = color_string || '';
  18760. this.ok = false; // strip any leading #
  18761. if (color_string.charAt(0) == '#') {
  18762. // remove # if any
  18763. color_string = color_string.substr(1, 6);
  18764. }
  18765. color_string = color_string.replace(/ /g, '');
  18766. color_string = color_string.toLowerCase();
  18767. var channels; // before getting into regexps, try simple matches
  18768. // and overwrite the input
  18769. var simple_colors = {
  18770. aliceblue: 'f0f8ff',
  18771. antiquewhite: 'faebd7',
  18772. aqua: '00ffff',
  18773. aquamarine: '7fffd4',
  18774. azure: 'f0ffff',
  18775. beige: 'f5f5dc',
  18776. bisque: 'ffe4c4',
  18777. black: '000000',
  18778. blanchedalmond: 'ffebcd',
  18779. blue: '0000ff',
  18780. blueviolet: '8a2be2',
  18781. brown: 'a52a2a',
  18782. burlywood: 'deb887',
  18783. cadetblue: '5f9ea0',
  18784. chartreuse: '7fff00',
  18785. chocolate: 'd2691e',
  18786. coral: 'ff7f50',
  18787. cornflowerblue: '6495ed',
  18788. cornsilk: 'fff8dc',
  18789. crimson: 'dc143c',
  18790. cyan: '00ffff',
  18791. darkblue: '00008b',
  18792. darkcyan: '008b8b',
  18793. darkgoldenrod: 'b8860b',
  18794. darkgray: 'a9a9a9',
  18795. darkgreen: '006400',
  18796. darkkhaki: 'bdb76b',
  18797. darkmagenta: '8b008b',
  18798. darkolivegreen: '556b2f',
  18799. darkorange: 'ff8c00',
  18800. darkorchid: '9932cc',
  18801. darkred: '8b0000',
  18802. darksalmon: 'e9967a',
  18803. darkseagreen: '8fbc8f',
  18804. darkslateblue: '483d8b',
  18805. darkslategray: '2f4f4f',
  18806. darkturquoise: '00ced1',
  18807. darkviolet: '9400d3',
  18808. deeppink: 'ff1493',
  18809. deepskyblue: '00bfff',
  18810. dimgray: '696969',
  18811. dodgerblue: '1e90ff',
  18812. feldspar: 'd19275',
  18813. firebrick: 'b22222',
  18814. floralwhite: 'fffaf0',
  18815. forestgreen: '228b22',
  18816. fuchsia: 'ff00ff',
  18817. gainsboro: 'dcdcdc',
  18818. ghostwhite: 'f8f8ff',
  18819. gold: 'ffd700',
  18820. goldenrod: 'daa520',
  18821. gray: '808080',
  18822. green: '008000',
  18823. greenyellow: 'adff2f',
  18824. honeydew: 'f0fff0',
  18825. hotpink: 'ff69b4',
  18826. indianred: 'cd5c5c',
  18827. indigo: '4b0082',
  18828. ivory: 'fffff0',
  18829. khaki: 'f0e68c',
  18830. lavender: 'e6e6fa',
  18831. lavenderblush: 'fff0f5',
  18832. lawngreen: '7cfc00',
  18833. lemonchiffon: 'fffacd',
  18834. lightblue: 'add8e6',
  18835. lightcoral: 'f08080',
  18836. lightcyan: 'e0ffff',
  18837. lightgoldenrodyellow: 'fafad2',
  18838. lightgrey: 'd3d3d3',
  18839. lightgreen: '90ee90',
  18840. lightpink: 'ffb6c1',
  18841. lightsalmon: 'ffa07a',
  18842. lightseagreen: '20b2aa',
  18843. lightskyblue: '87cefa',
  18844. lightslateblue: '8470ff',
  18845. lightslategray: '778899',
  18846. lightsteelblue: 'b0c4de',
  18847. lightyellow: 'ffffe0',
  18848. lime: '00ff00',
  18849. limegreen: '32cd32',
  18850. linen: 'faf0e6',
  18851. magenta: 'ff00ff',
  18852. maroon: '800000',
  18853. mediumaquamarine: '66cdaa',
  18854. mediumblue: '0000cd',
  18855. mediumorchid: 'ba55d3',
  18856. mediumpurple: '9370d8',
  18857. mediumseagreen: '3cb371',
  18858. mediumslateblue: '7b68ee',
  18859. mediumspringgreen: '00fa9a',
  18860. mediumturquoise: '48d1cc',
  18861. mediumvioletred: 'c71585',
  18862. midnightblue: '191970',
  18863. mintcream: 'f5fffa',
  18864. mistyrose: 'ffe4e1',
  18865. moccasin: 'ffe4b5',
  18866. navajowhite: 'ffdead',
  18867. navy: '000080',
  18868. oldlace: 'fdf5e6',
  18869. olive: '808000',
  18870. olivedrab: '6b8e23',
  18871. orange: 'ffa500',
  18872. orangered: 'ff4500',
  18873. orchid: 'da70d6',
  18874. palegoldenrod: 'eee8aa',
  18875. palegreen: '98fb98',
  18876. paleturquoise: 'afeeee',
  18877. palevioletred: 'd87093',
  18878. papayawhip: 'ffefd5',
  18879. peachpuff: 'ffdab9',
  18880. peru: 'cd853f',
  18881. pink: 'ffc0cb',
  18882. plum: 'dda0dd',
  18883. powderblue: 'b0e0e6',
  18884. purple: '800080',
  18885. red: 'ff0000',
  18886. rosybrown: 'bc8f8f',
  18887. royalblue: '4169e1',
  18888. saddlebrown: '8b4513',
  18889. salmon: 'fa8072',
  18890. sandybrown: 'f4a460',
  18891. seagreen: '2e8b57',
  18892. seashell: 'fff5ee',
  18893. sienna: 'a0522d',
  18894. silver: 'c0c0c0',
  18895. skyblue: '87ceeb',
  18896. slateblue: '6a5acd',
  18897. slategray: '708090',
  18898. snow: 'fffafa',
  18899. springgreen: '00ff7f',
  18900. steelblue: '4682b4',
  18901. tan: 'd2b48c',
  18902. teal: '008080',
  18903. thistle: 'd8bfd8',
  18904. tomato: 'ff6347',
  18905. turquoise: '40e0d0',
  18906. violet: 'ee82ee',
  18907. violetred: 'd02090',
  18908. wheat: 'f5deb3',
  18909. white: 'ffffff',
  18910. whitesmoke: 'f5f5f5',
  18911. yellow: 'ffff00',
  18912. yellowgreen: '9acd32'
  18913. };
  18914. for (var key in simple_colors) {
  18915. if (color_string == key) {
  18916. color_string = simple_colors[key];
  18917. }
  18918. } // emd of simple type-in colors
  18919. // array of color definition objects
  18920. var color_defs = [{
  18921. re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
  18922. example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
  18923. process: function process(bits) {
  18924. return [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])];
  18925. }
  18926. }, {
  18927. re: /^(\w{2})(\w{2})(\w{2})$/,
  18928. example: ['#00ff00', '336699'],
  18929. process: function process(bits) {
  18930. return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)];
  18931. }
  18932. }, {
  18933. re: /^(\w{1})(\w{1})(\w{1})$/,
  18934. example: ['#fb0', 'f0f'],
  18935. process: function process(bits) {
  18936. return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)];
  18937. }
  18938. }]; // search through the definitions to find a match
  18939. for (var i = 0; i < color_defs.length; i++) {
  18940. var re = color_defs[i].re;
  18941. var processor = color_defs[i].process;
  18942. var bits = re.exec(color_string);
  18943. if (bits) {
  18944. channels = processor(bits);
  18945. this.r = channels[0];
  18946. this.g = channels[1];
  18947. this.b = channels[2];
  18948. this.ok = true;
  18949. }
  18950. } // validate/cleanup values
  18951. this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r;
  18952. this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g;
  18953. this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; // some getters
  18954. this.toRGB = function () {
  18955. return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
  18956. };
  18957. this.toHex = function () {
  18958. var r = this.r.toString(16);
  18959. var g = this.g.toString(16);
  18960. var b = this.b.toString(16);
  18961. if (r.length == 1) r = '0' + r;
  18962. if (g.length == 1) g = '0' + g;
  18963. if (b.length == 1) b = '0' + b;
  18964. return '#' + r + g + b;
  18965. };
  18966. }
  18967. global.RGBColor = RGBColor;
  18968. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  18969. // while `this` is nsIContentFrameMessageManager
  18970. // with an attribute `content` that corresponds to the window
  18971. /************************************************
  18972. * Title : custom font *
  18973. * Start Data : 2017. 01. 22. *
  18974. * Comment : TEXT API *
  18975. ************************************************/
  18976. /******************************
  18977. * jsPDF extension API Design *
  18978. * ****************************/
  18979. (function (jsPDF) {
  18980. var PLUS = '+'.charCodeAt(0);
  18981. var SLASH = '/'.charCodeAt(0);
  18982. var NUMBER = '0'.charCodeAt(0);
  18983. var LOWER = 'a'.charCodeAt(0);
  18984. var UPPER = 'A'.charCodeAt(0);
  18985. var PLUS_URL_SAFE = '-'.charCodeAt(0);
  18986. var SLASH_URL_SAFE = '_'.charCodeAt(0);
  18987. /*****************************************************************/
  18988. /* function : b64ToByteArray */
  18989. /* comment : Base64 encoded TTF file contents (b64) are decoded */
  18990. /* by Byte array and stored. */
  18991. /*****************************************************************/
  18992. var b64ToByteArray = function b64ToByteArray(b64) {
  18993. var i, j, l, tmp, placeHolders, arr;
  18994. if (b64.length % 4 > 0) {
  18995. throw new Error('Invalid string. Length must be a multiple of 4');
  18996. } // the number of equal signs (place holders)
  18997. // if there are two placeholders, than the two characters before it
  18998. // represent one byte
  18999. // if there is only one, then the three characters before it represent 2 bytes
  19000. // this is just a cheap hack to not do indexOf twice
  19001. var len = b64.length;
  19002. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
  19003. arr = new Uint8Array(b64.length * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
  19004. l = placeHolders > 0 ? b64.length - 4 : b64.length;
  19005. var L = 0;
  19006. function push(v) {
  19007. arr[L++] = v;
  19008. }
  19009. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  19010. tmp = decode(b64.charAt(i)) << 18 | decode(b64.charAt(i + 1)) << 12 | decode(b64.charAt(i + 2)) << 6 | decode(b64.charAt(i + 3));
  19011. push((tmp & 0xFF0000) >> 16);
  19012. push((tmp & 0xFF00) >> 8);
  19013. push(tmp & 0xFF);
  19014. }
  19015. if (placeHolders === 2) {
  19016. tmp = decode(b64.charAt(i)) << 2 | decode(b64.charAt(i + 1)) >> 4;
  19017. push(tmp & 0xFF);
  19018. } else if (placeHolders === 1) {
  19019. tmp = decode(b64.charAt(i)) << 10 | decode(b64.charAt(i + 1)) << 4 | decode(b64.charAt(i + 2)) >> 2;
  19020. push(tmp >> 8 & 0xFF);
  19021. push(tmp & 0xFF);
  19022. }
  19023. return arr;
  19024. };
  19025. /***************************************************************/
  19026. /* function : decode */
  19027. /* comment : Change the base64 encoded font's content to match */
  19028. /* the base64 index value. */
  19029. /***************************************************************/
  19030. var decode = function decode(elt) {
  19031. var code = elt.charCodeAt(0);
  19032. if (code === PLUS || code === PLUS_URL_SAFE) return 62; // '+'
  19033. if (code === SLASH || code === SLASH_URL_SAFE) return 63; // '/'
  19034. if (code < NUMBER) return -1; //no match
  19035. if (code < NUMBER + 10) return code - NUMBER + 26 + 26;
  19036. if (code < UPPER + 26) return code - UPPER;
  19037. if (code < LOWER + 26) return code - LOWER + 26;
  19038. };
  19039. jsPDF.API.TTFFont = function () {
  19040. /************************************************************************/
  19041. /* function : open */
  19042. /* comment : Decode the encoded ttf content and create a TTFFont object. */
  19043. /************************************************************************/
  19044. TTFFont.open = function (filename, name, vfs, encoding) {
  19045. var contents;
  19046. if (typeof vfs !== "string") {
  19047. throw new Error('Invalid argument supplied in TTFFont.open');
  19048. }
  19049. contents = b64ToByteArray(vfs);
  19050. return new TTFFont(contents, name, encoding);
  19051. };
  19052. /***************************************************************/
  19053. /* function : TTFFont gernerator */
  19054. /* comment : Decode TTF contents are parsed, Data, */
  19055. /* Subset object is created, and registerTTF function is called.*/
  19056. /***************************************************************/
  19057. function TTFFont(rawData, name, encoding) {
  19058. var data;
  19059. this.rawData = rawData;
  19060. data = this.contents = new Data(rawData);
  19061. this.contents.pos = 4;
  19062. if (data.readString(4) === 'ttcf') {
  19063. if (!name) {
  19064. throw new Error("Must specify a font name for TTC files.");
  19065. }
  19066. throw new Error("Font " + name + " not found in TTC file.");
  19067. } else {
  19068. data.pos = 0;
  19069. this.parse();
  19070. this.subset = new Subset(this);
  19071. this.registerTTF();
  19072. }
  19073. }
  19074. /********************************************************/
  19075. /* function : parse */
  19076. /* comment : TTF Parses the file contents by each table.*/
  19077. /********************************************************/
  19078. TTFFont.prototype.parse = function () {
  19079. this.directory = new Directory(this.contents);
  19080. this.head = new HeadTable(this);
  19081. this.name = new NameTable(this);
  19082. this.cmap = new CmapTable(this);
  19083. this.toUnicode = new Map();
  19084. this.hhea = new HheaTable(this);
  19085. this.maxp = new MaxpTable(this);
  19086. this.hmtx = new HmtxTable(this);
  19087. this.post = new PostTable(this);
  19088. this.os2 = new OS2Table(this);
  19089. this.loca = new LocaTable(this);
  19090. this.glyf = new GlyfTable(this);
  19091. this.ascender = this.os2.exists && this.os2.ascender || this.hhea.ascender;
  19092. this.decender = this.os2.exists && this.os2.decender || this.hhea.decender;
  19093. this.lineGap = this.os2.exists && this.os2.lineGap || this.hhea.lineGap;
  19094. return this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax];
  19095. };
  19096. /***************************************************************/
  19097. /* function : registerTTF */
  19098. /* comment : Get the value to assign pdf font descriptors. */
  19099. /***************************************************************/
  19100. TTFFont.prototype.registerTTF = function () {
  19101. var e, hi, low, raw, _ref;
  19102. this.scaleFactor = 1000.0 / this.head.unitsPerEm;
  19103. this.bbox = function () {
  19104. var _i, _len, _ref, _results;
  19105. _ref = this.bbox;
  19106. _results = [];
  19107. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  19108. e = _ref[_i];
  19109. _results.push(Math.round(e * this.scaleFactor));
  19110. }
  19111. return _results;
  19112. }.call(this);
  19113. this.stemV = 0;
  19114. if (this.post.exists) {
  19115. raw = this.post.italic_angle;
  19116. hi = raw >> 16;
  19117. low = raw & 0xFF;
  19118. if (hi & 0x8000 !== 0) {
  19119. hi = -((hi ^ 0xFFFF) + 1);
  19120. }
  19121. this.italicAngle = +("" + hi + "." + low);
  19122. } else {
  19123. this.italicAngle = 0;
  19124. }
  19125. this.ascender = Math.round(this.ascender * this.scaleFactor);
  19126. this.decender = Math.round(this.decender * this.scaleFactor);
  19127. this.lineGap = Math.round(this.lineGap * this.scaleFactor);
  19128. this.capHeight = this.os2.exists && this.os2.capHeight || this.ascender;
  19129. this.xHeight = this.os2.exists && this.os2.xHeight || 0;
  19130. this.familyClass = (this.os2.exists && this.os2.familyClass || 0) >> 8;
  19131. this.isSerif = (_ref = this.familyClass) === 1 || _ref === 2 || _ref === 3 || _ref === 4 || _ref === 5 || _ref === 7;
  19132. this.isScript = this.familyClass === 10;
  19133. this.flags = 0;
  19134. if (this.post.isFixedPitch) {
  19135. this.flags |= 1 << 0;
  19136. }
  19137. if (this.isSerif) {
  19138. this.flags |= 1 << 1;
  19139. }
  19140. if (this.isScript) {
  19141. this.flags |= 1 << 3;
  19142. }
  19143. if (this.italicAngle !== 0) {
  19144. this.flags |= 1 << 6;
  19145. }
  19146. this.flags |= 1 << 5;
  19147. if (!this.cmap.unicode) {
  19148. throw new Error('No unicode cmap for font');
  19149. }
  19150. };
  19151. TTFFont.prototype.characterToGlyph = function (character) {
  19152. var _ref;
  19153. return ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) || 0;
  19154. };
  19155. TTFFont.prototype.widthOfGlyph = function (glyph) {
  19156. var scale;
  19157. scale = 1000.0 / this.head.unitsPerEm;
  19158. return this.hmtx.forGlyph(glyph).advance * scale;
  19159. };
  19160. TTFFont.prototype.widthOfString = function (string, size, charSpace) {
  19161. var charCode, i, scale, width, _i, _ref, charSpace;
  19162. string = '' + string;
  19163. width = 0;
  19164. for (i = _i = 0, _ref = string.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19165. charCode = string.charCodeAt(i);
  19166. width += this.widthOfGlyph(this.characterToGlyph(charCode)) + charSpace * (1000 / size) || 0;
  19167. }
  19168. scale = size / 1000;
  19169. return width * scale;
  19170. };
  19171. TTFFont.prototype.lineHeight = function (size, includeGap) {
  19172. var gap;
  19173. if (includeGap == null) {
  19174. includeGap = false;
  19175. }
  19176. gap = includeGap ? this.lineGap : 0;
  19177. return (this.ascender + gap - this.decender) / 1000 * size;
  19178. };
  19179. return TTFFont;
  19180. }();
  19181. /************************************************************************************************/
  19182. /* function : Data */
  19183. /* comment : The ttf data decoded and stored in an array is read and written to the Data object.*/
  19184. /************************************************************************************************/
  19185. var Data = function () {
  19186. function Data(data) {
  19187. this.data = data != null ? data : [];
  19188. this.pos = 0;
  19189. this.length = this.data.length;
  19190. }
  19191. Data.prototype.readByte = function () {
  19192. return this.data[this.pos++];
  19193. };
  19194. Data.prototype.writeByte = function (byte) {
  19195. return this.data[this.pos++] = byte;
  19196. };
  19197. Data.prototype.readUInt32 = function () {
  19198. var b1, b2, b3, b4;
  19199. b1 = this.readByte() * 0x1000000;
  19200. b2 = this.readByte() << 16;
  19201. b3 = this.readByte() << 8;
  19202. b4 = this.readByte();
  19203. return b1 + b2 + b3 + b4;
  19204. };
  19205. Data.prototype.writeUInt32 = function (val) {
  19206. this.writeByte(val >>> 24 & 0xff);
  19207. this.writeByte(val >> 16 & 0xff);
  19208. this.writeByte(val >> 8 & 0xff);
  19209. return this.writeByte(val & 0xff);
  19210. };
  19211. Data.prototype.readInt32 = function () {
  19212. var int;
  19213. int = this.readUInt32();
  19214. if (int >= 0x80000000) {
  19215. return int - 0x100000000;
  19216. } else {
  19217. return int;
  19218. }
  19219. };
  19220. Data.prototype.writeInt32 = function (val) {
  19221. if (val < 0) {
  19222. val += 0x100000000;
  19223. }
  19224. return this.writeUInt32(val);
  19225. };
  19226. Data.prototype.readUInt16 = function () {
  19227. var b1, b2;
  19228. b1 = this.readByte() << 8;
  19229. b2 = this.readByte();
  19230. return b1 | b2;
  19231. };
  19232. Data.prototype.writeUInt16 = function (val) {
  19233. this.writeByte(val >> 8 & 0xff);
  19234. return this.writeByte(val & 0xff);
  19235. };
  19236. Data.prototype.readInt16 = function () {
  19237. var int;
  19238. int = this.readUInt16();
  19239. if (int >= 0x8000) {
  19240. return int - 0x10000;
  19241. } else {
  19242. return int;
  19243. }
  19244. };
  19245. Data.prototype.writeInt16 = function (val) {
  19246. if (val < 0) {
  19247. val += 0x10000;
  19248. }
  19249. return this.writeUInt16(val);
  19250. };
  19251. Data.prototype.readString = function (length) {
  19252. var i, ret, _i;
  19253. ret = [];
  19254. for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
  19255. ret[i] = String.fromCharCode(this.readByte());
  19256. }
  19257. return ret.join('');
  19258. };
  19259. Data.prototype.writeString = function (val) {
  19260. var i, _i, _ref, _results;
  19261. _results = [];
  19262. for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19263. _results.push(this.writeByte(val.charCodeAt(i)));
  19264. }
  19265. return _results;
  19266. };
  19267. /*Data.prototype.stringAt = function (pos, length) {
  19268. this.pos = pos;
  19269. return this.readString(length);
  19270. };*/
  19271. Data.prototype.readShort = function () {
  19272. return this.readInt16();
  19273. };
  19274. Data.prototype.writeShort = function (val) {
  19275. return this.writeInt16(val);
  19276. };
  19277. Data.prototype.readLongLong = function () {
  19278. var b1, b2, b3, b4, b5, b6, b7, b8;
  19279. b1 = this.readByte();
  19280. b2 = this.readByte();
  19281. b3 = this.readByte();
  19282. b4 = this.readByte();
  19283. b5 = this.readByte();
  19284. b6 = this.readByte();
  19285. b7 = this.readByte();
  19286. b8 = this.readByte();
  19287. if (b1 & 0x80) {
  19288. 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;
  19289. }
  19290. return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8;
  19291. };
  19292. Data.prototype.writeLongLong = function (val) {
  19293. var high, low;
  19294. high = Math.floor(val / 0x100000000);
  19295. low = val & 0xffffffff;
  19296. this.writeByte(high >> 24 & 0xff);
  19297. this.writeByte(high >> 16 & 0xff);
  19298. this.writeByte(high >> 8 & 0xff);
  19299. this.writeByte(high & 0xff);
  19300. this.writeByte(low >> 24 & 0xff);
  19301. this.writeByte(low >> 16 & 0xff);
  19302. this.writeByte(low >> 8 & 0xff);
  19303. return this.writeByte(low & 0xff);
  19304. };
  19305. Data.prototype.readInt = function () {
  19306. return this.readInt32();
  19307. };
  19308. Data.prototype.writeInt = function (val) {
  19309. return this.writeInt32(val);
  19310. };
  19311. /*Data.prototype.slice = function (start, end) {
  19312. return this.data.slice(start, end);
  19313. };*/
  19314. Data.prototype.read = function (bytes) {
  19315. var buf, i, _i;
  19316. buf = [];
  19317. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  19318. buf.push(this.readByte());
  19319. }
  19320. return buf;
  19321. };
  19322. Data.prototype.write = function (bytes) {
  19323. var byte, _i, _len, _results;
  19324. _results = [];
  19325. for (_i = 0, _len = bytes.length; _i < _len; _i++) {
  19326. byte = bytes[_i];
  19327. _results.push(this.writeByte(byte));
  19328. }
  19329. return _results;
  19330. };
  19331. return Data;
  19332. }();
  19333. var Directory = function () {
  19334. var checksum;
  19335. /*****************************************************************************************************/
  19336. /* function : Directory generator */
  19337. /* comment : Initialize the offset, tag, length, and checksum for each table for the font to be used.*/
  19338. /*****************************************************************************************************/
  19339. function Directory(data) {
  19340. var entry, i, _i, _ref;
  19341. this.scalarType = data.readInt();
  19342. this.tableCount = data.readShort();
  19343. this.searchRange = data.readShort();
  19344. this.entrySelector = data.readShort();
  19345. this.rangeShift = data.readShort();
  19346. this.tables = {};
  19347. for (i = _i = 0, _ref = this.tableCount; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19348. entry = {
  19349. tag: data.readString(4),
  19350. checksum: data.readInt(),
  19351. offset: data.readInt(),
  19352. length: data.readInt()
  19353. };
  19354. this.tables[entry.tag] = entry;
  19355. }
  19356. }
  19357. /********************************************************************************************************/
  19358. /* function : encode */
  19359. /* comment : It encodes and stores the font table object and information used for the directory object. */
  19360. /********************************************************************************************************/
  19361. Directory.prototype.encode = function (tables) {
  19362. var adjustment, directory, directoryLength, entrySelector, headOffset, log2, offset, rangeShift, searchRange, sum, table, tableCount, tableData, tag;
  19363. tableCount = Object.keys(tables).length;
  19364. log2 = Math.log(2);
  19365. searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
  19366. entrySelector = Math.floor(searchRange / log2);
  19367. rangeShift = tableCount * 16 - searchRange;
  19368. directory = new Data();
  19369. directory.writeInt(this.scalarType);
  19370. directory.writeShort(tableCount);
  19371. directory.writeShort(searchRange);
  19372. directory.writeShort(entrySelector);
  19373. directory.writeShort(rangeShift);
  19374. directoryLength = tableCount * 16;
  19375. offset = directory.pos + directoryLength;
  19376. headOffset = null;
  19377. tableData = [];
  19378. for (tag in tables) {
  19379. table = tables[tag];
  19380. directory.writeString(tag);
  19381. directory.writeInt(checksum(table));
  19382. directory.writeInt(offset);
  19383. directory.writeInt(table.length);
  19384. tableData = tableData.concat(table);
  19385. if (tag === 'head') {
  19386. headOffset = offset;
  19387. }
  19388. offset += table.length;
  19389. while (offset % 4) {
  19390. tableData.push(0);
  19391. offset++;
  19392. }
  19393. }
  19394. directory.write(tableData);
  19395. sum = checksum(directory.data);
  19396. adjustment = 0xB1B0AFBA - sum;
  19397. directory.pos = headOffset + 8;
  19398. directory.writeUInt32(adjustment);
  19399. return directory.data;
  19400. };
  19401. /***************************************************************/
  19402. /* function : checksum */
  19403. /* comment : Duplicate the table for the tag. */
  19404. /***************************************************************/
  19405. checksum = function checksum(data) {
  19406. var i, sum, tmp, _i, _ref;
  19407. data = __slice.call(data);
  19408. while (data.length % 4) {
  19409. data.push(0);
  19410. }
  19411. tmp = new Data(data);
  19412. sum = 0;
  19413. for (i = _i = 0, _ref = data.length; _i < _ref; i = _i += 4) {
  19414. sum += tmp.readUInt32();
  19415. }
  19416. return sum & 0xFFFFFFFF;
  19417. };
  19418. return Directory;
  19419. }();
  19420. var Table,
  19421. __hasProp = {}.hasOwnProperty,
  19422. __extends = function __extends(child, parent) {
  19423. for (var key in parent) {
  19424. if (__hasProp.call(parent, key)) child[key] = parent[key];
  19425. }
  19426. function ctor() {
  19427. this.constructor = child;
  19428. }
  19429. ctor.prototype = parent.prototype;
  19430. child.prototype = new ctor();
  19431. child.__super__ = parent.prototype;
  19432. return child;
  19433. };
  19434. /***************************************************************/
  19435. /* function : Table */
  19436. /* comment : Save info for each table, and parse the table. */
  19437. /***************************************************************/
  19438. Table = function () {
  19439. function Table(file) {
  19440. var info;
  19441. this.file = file;
  19442. info = this.file.directory.tables[this.tag];
  19443. this.exists = !!info;
  19444. if (info) {
  19445. this.offset = info.offset, this.length = info.length;
  19446. this.parse(this.file.contents);
  19447. }
  19448. }
  19449. Table.prototype.parse = function () {};
  19450. Table.prototype.encode = function () {};
  19451. Table.prototype.raw = function () {
  19452. if (!this.exists) {
  19453. return null;
  19454. }
  19455. this.file.contents.pos = this.offset;
  19456. return this.file.contents.read(this.length);
  19457. };
  19458. return Table;
  19459. }();
  19460. var HeadTable = function (_super) {
  19461. __extends(HeadTable, _super);
  19462. function HeadTable() {
  19463. return HeadTable.__super__.constructor.apply(this, arguments);
  19464. }
  19465. HeadTable.prototype.tag = 'head';
  19466. HeadTable.prototype.parse = function (data) {
  19467. data.pos = this.offset;
  19468. this.version = data.readInt();
  19469. this.revision = data.readInt();
  19470. this.checkSumAdjustment = data.readInt();
  19471. this.magicNumber = data.readInt();
  19472. this.flags = data.readShort();
  19473. this.unitsPerEm = data.readShort();
  19474. this.created = data.readLongLong();
  19475. this.modified = data.readLongLong();
  19476. this.xMin = data.readShort();
  19477. this.yMin = data.readShort();
  19478. this.xMax = data.readShort();
  19479. this.yMax = data.readShort();
  19480. this.macStyle = data.readShort();
  19481. this.lowestRecPPEM = data.readShort();
  19482. this.fontDirectionHint = data.readShort();
  19483. this.indexToLocFormat = data.readShort();
  19484. return this.glyphDataFormat = data.readShort();
  19485. };
  19486. HeadTable.prototype.encode = function (indexToLocFormat) {
  19487. var table;
  19488. table = new Data();
  19489. table.writeInt(this.version);
  19490. table.writeInt(this.revision);
  19491. table.writeInt(this.checkSumAdjustment);
  19492. table.writeInt(this.magicNumber);
  19493. table.writeShort(this.flags);
  19494. table.writeShort(this.unitsPerEm);
  19495. table.writeLongLong(this.created);
  19496. table.writeLongLong(this.modified);
  19497. table.writeShort(this.xMin);
  19498. table.writeShort(this.yMin);
  19499. table.writeShort(this.xMax);
  19500. table.writeShort(this.yMax);
  19501. table.writeShort(this.macStyle);
  19502. table.writeShort(this.lowestRecPPEM);
  19503. table.writeShort(this.fontDirectionHint);
  19504. table.writeShort(indexToLocFormat);
  19505. table.writeShort(this.glyphDataFormat);
  19506. return table.data;
  19507. };
  19508. return HeadTable;
  19509. }(Table);
  19510. /************************************************************************************/
  19511. /* function : CmapEntry */
  19512. /* comment : Cmap Initializes and encodes object information (required by pdf spec).*/
  19513. /************************************************************************************/
  19514. var CmapEntry = function () {
  19515. function CmapEntry(data, offset) {
  19516. var code, count, endCode, glyphId, glyphIds, i, idDelta, idRangeOffset, index, saveOffset, segCount, segCountX2, start, startCode, tail, _i, _j, _k, _len;
  19517. this.platformID = data.readUInt16();
  19518. this.encodingID = data.readShort();
  19519. this.offset = offset + data.readInt();
  19520. saveOffset = data.pos;
  19521. data.pos = this.offset;
  19522. this.format = data.readUInt16();
  19523. this.length = data.readUInt16();
  19524. this.language = data.readUInt16();
  19525. this.isUnicode = this.platformID === 3 && this.encodingID === 1 && this.format === 4 || this.platformID === 0 && this.format === 4;
  19526. this.codeMap = {};
  19527. switch (this.format) {
  19528. case 0:
  19529. for (i = _i = 0; _i < 256; i = ++_i) {
  19530. this.codeMap[i] = data.readByte();
  19531. }
  19532. break;
  19533. case 4:
  19534. segCountX2 = data.readUInt16();
  19535. segCount = segCountX2 / 2;
  19536. data.pos += 6;
  19537. endCode = function () {
  19538. var _j, _results;
  19539. _results = [];
  19540. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  19541. _results.push(data.readUInt16());
  19542. }
  19543. return _results;
  19544. }();
  19545. data.pos += 2;
  19546. startCode = function () {
  19547. var _j, _results;
  19548. _results = [];
  19549. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  19550. _results.push(data.readUInt16());
  19551. }
  19552. return _results;
  19553. }();
  19554. idDelta = function () {
  19555. var _j, _results;
  19556. _results = [];
  19557. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  19558. _results.push(data.readUInt16());
  19559. }
  19560. return _results;
  19561. }();
  19562. idRangeOffset = function () {
  19563. var _j, _results;
  19564. _results = [];
  19565. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  19566. _results.push(data.readUInt16());
  19567. }
  19568. return _results;
  19569. }();
  19570. count = (this.length - data.pos + this.offset) / 2;
  19571. glyphIds = function () {
  19572. var _j, _results;
  19573. _results = [];
  19574. for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
  19575. _results.push(data.readUInt16());
  19576. }
  19577. return _results;
  19578. }();
  19579. for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
  19580. tail = endCode[i];
  19581. start = startCode[i];
  19582. for (code = _k = start; start <= tail ? _k <= tail : _k >= tail; code = start <= tail ? ++_k : --_k) {
  19583. if (idRangeOffset[i] === 0) {
  19584. glyphId = code + idDelta[i];
  19585. } else {
  19586. index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
  19587. glyphId = glyphIds[index] || 0;
  19588. if (glyphId !== 0) {
  19589. glyphId += idDelta[i];
  19590. }
  19591. }
  19592. this.codeMap[code] = glyphId & 0xFFFF;
  19593. }
  19594. }
  19595. }
  19596. data.pos = saveOffset;
  19597. }
  19598. CmapEntry.encode = function (charmap, encoding) {
  19599. 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;
  19600. subtable = new Data();
  19601. codes = Object.keys(charmap).sort(function (a, b) {
  19602. return a - b;
  19603. });
  19604. switch (encoding) {
  19605. case 'macroman':
  19606. id = 0;
  19607. indexes = function () {
  19608. var _i, _results;
  19609. _results = [];
  19610. for (i = _i = 0; _i < 256; i = ++_i) {
  19611. _results.push(0);
  19612. }
  19613. return _results;
  19614. }();
  19615. map = {
  19616. 0: 0
  19617. };
  19618. codeMap = {};
  19619. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  19620. code = codes[_i];
  19621. if (map[_name = charmap[code]] == null) {
  19622. map[_name] = ++id;
  19623. }
  19624. codeMap[code] = {
  19625. old: charmap[code],
  19626. "new": map[charmap[code]]
  19627. };
  19628. indexes[code] = map[charmap[code]];
  19629. }
  19630. subtable.writeUInt16(1);
  19631. subtable.writeUInt16(0);
  19632. subtable.writeUInt32(12);
  19633. subtable.writeUInt16(0);
  19634. subtable.writeUInt16(262);
  19635. subtable.writeUInt16(0);
  19636. subtable.write(indexes);
  19637. return result = {
  19638. charMap: codeMap,
  19639. subtable: subtable.data,
  19640. maxGlyphID: id + 1
  19641. };
  19642. case 'unicode':
  19643. startCodes = [];
  19644. endCodes = [];
  19645. nextID = 0;
  19646. map = {};
  19647. charMap = {};
  19648. last = diff = null;
  19649. for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
  19650. code = codes[_j];
  19651. old = charmap[code];
  19652. if (map[old] == null) {
  19653. map[old] = ++nextID;
  19654. }
  19655. charMap[code] = {
  19656. old: old,
  19657. "new": map[old]
  19658. };
  19659. delta = map[old] - code;
  19660. if (last == null || delta !== diff) {
  19661. if (last) {
  19662. endCodes.push(last);
  19663. }
  19664. startCodes.push(code);
  19665. diff = delta;
  19666. }
  19667. last = code;
  19668. }
  19669. if (last) {
  19670. endCodes.push(last);
  19671. }
  19672. endCodes.push(0xFFFF);
  19673. startCodes.push(0xFFFF);
  19674. segCount = startCodes.length;
  19675. segCountX2 = segCount * 2;
  19676. searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
  19677. entrySelector = Math.log(searchRange / 2) / Math.LN2;
  19678. rangeShift = 2 * segCount - searchRange;
  19679. deltas = [];
  19680. rangeOffsets = [];
  19681. glyphIDs = [];
  19682. for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
  19683. startCode = startCodes[i];
  19684. endCode = endCodes[i];
  19685. if (startCode === 0xFFFF) {
  19686. deltas.push(0);
  19687. rangeOffsets.push(0);
  19688. break;
  19689. }
  19690. startGlyph = charMap[startCode]["new"];
  19691. if (startCode - startGlyph >= 0x8000) {
  19692. deltas.push(0);
  19693. rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
  19694. for (code = _l = startCode; startCode <= endCode ? _l <= endCode : _l >= endCode; code = startCode <= endCode ? ++_l : --_l) {
  19695. glyphIDs.push(charMap[code]["new"]);
  19696. }
  19697. } else {
  19698. deltas.push(startGlyph - startCode);
  19699. rangeOffsets.push(0);
  19700. }
  19701. }
  19702. subtable.writeUInt16(3);
  19703. subtable.writeUInt16(1);
  19704. subtable.writeUInt32(12);
  19705. subtable.writeUInt16(4);
  19706. subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
  19707. subtable.writeUInt16(0);
  19708. subtable.writeUInt16(segCountX2);
  19709. subtable.writeUInt16(searchRange);
  19710. subtable.writeUInt16(entrySelector);
  19711. subtable.writeUInt16(rangeShift);
  19712. for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
  19713. code = endCodes[_m];
  19714. subtable.writeUInt16(code);
  19715. }
  19716. subtable.writeUInt16(0);
  19717. for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
  19718. code = startCodes[_n];
  19719. subtable.writeUInt16(code);
  19720. }
  19721. for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
  19722. delta = deltas[_o];
  19723. subtable.writeUInt16(delta);
  19724. }
  19725. for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
  19726. offset = rangeOffsets[_p];
  19727. subtable.writeUInt16(offset);
  19728. }
  19729. for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
  19730. id = glyphIDs[_q];
  19731. subtable.writeUInt16(id);
  19732. }
  19733. return result = {
  19734. charMap: charMap,
  19735. subtable: subtable.data,
  19736. maxGlyphID: nextID + 1
  19737. };
  19738. }
  19739. };
  19740. return CmapEntry;
  19741. }();
  19742. var CmapTable = function (_super) {
  19743. __extends(CmapTable, _super);
  19744. function CmapTable() {
  19745. return CmapTable.__super__.constructor.apply(this, arguments);
  19746. }
  19747. CmapTable.prototype.tag = 'cmap';
  19748. CmapTable.prototype.parse = function (data) {
  19749. var entry, i, tableCount, _i;
  19750. data.pos = this.offset;
  19751. this.version = data.readUInt16();
  19752. tableCount = data.readUInt16();
  19753. this.tables = [];
  19754. this.unicode = null;
  19755. for (i = _i = 0; 0 <= tableCount ? _i < tableCount : _i > tableCount; i = 0 <= tableCount ? ++_i : --_i) {
  19756. entry = new CmapEntry(data, this.offset);
  19757. this.tables.push(entry);
  19758. if (entry.isUnicode) {
  19759. if (this.unicode == null) {
  19760. this.unicode = entry;
  19761. }
  19762. }
  19763. }
  19764. return true;
  19765. };
  19766. /*************************************************************************/
  19767. /* function : encode */
  19768. /* comment : Encode the cmap table corresponding to the input character. */
  19769. /*************************************************************************/
  19770. CmapTable.encode = function (charmap, encoding) {
  19771. var result, table;
  19772. if (encoding == null) {
  19773. encoding = 'macroman';
  19774. }
  19775. result = CmapEntry.encode(charmap, encoding);
  19776. table = new Data();
  19777. table.writeUInt16(0);
  19778. table.writeUInt16(1);
  19779. result.table = table.data.concat(result.subtable);
  19780. return result;
  19781. };
  19782. return CmapTable;
  19783. }(Table);
  19784. var HheaTable = function (_super) {
  19785. __extends(HheaTable, _super);
  19786. function HheaTable() {
  19787. return HheaTable.__super__.constructor.apply(this, arguments);
  19788. }
  19789. HheaTable.prototype.tag = 'hhea';
  19790. HheaTable.prototype.parse = function (data) {
  19791. data.pos = this.offset;
  19792. this.version = data.readInt();
  19793. this.ascender = data.readShort();
  19794. this.decender = data.readShort();
  19795. this.lineGap = data.readShort();
  19796. this.advanceWidthMax = data.readShort();
  19797. this.minLeftSideBearing = data.readShort();
  19798. this.minRightSideBearing = data.readShort();
  19799. this.xMaxExtent = data.readShort();
  19800. this.caretSlopeRise = data.readShort();
  19801. this.caretSlopeRun = data.readShort();
  19802. this.caretOffset = data.readShort();
  19803. data.pos += 4 * 2;
  19804. this.metricDataFormat = data.readShort();
  19805. return this.numberOfMetrics = data.readUInt16();
  19806. };
  19807. /*HheaTable.prototype.encode = function (ids) {
  19808. var i, table, _i, _ref;
  19809. table = new Data;
  19810. table.writeInt(this.version);
  19811. table.writeShort(this.ascender);
  19812. table.writeShort(this.decender);
  19813. table.writeShort(this.lineGap);
  19814. table.writeShort(this.advanceWidthMax);
  19815. table.writeShort(this.minLeftSideBearing);
  19816. table.writeShort(this.minRightSideBearing);
  19817. table.writeShort(this.xMaxExtent);
  19818. table.writeShort(this.caretSlopeRise);
  19819. table.writeShort(this.caretSlopeRun);
  19820. table.writeShort(this.caretOffset);
  19821. for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  19822. table.writeByte(0);
  19823. }
  19824. table.writeShort(this.metricDataFormat);
  19825. table.writeUInt16(ids.length);
  19826. return table.data;
  19827. };*/
  19828. return HheaTable;
  19829. }(Table);
  19830. var OS2Table = function (_super) {
  19831. __extends(OS2Table, _super);
  19832. function OS2Table() {
  19833. return OS2Table.__super__.constructor.apply(this, arguments);
  19834. }
  19835. OS2Table.prototype.tag = 'OS/2';
  19836. OS2Table.prototype.parse = function (data) {
  19837. var i;
  19838. data.pos = this.offset;
  19839. this.version = data.readUInt16();
  19840. this.averageCharWidth = data.readShort();
  19841. this.weightClass = data.readUInt16();
  19842. this.widthClass = data.readUInt16();
  19843. this.type = data.readShort();
  19844. this.ySubscriptXSize = data.readShort();
  19845. this.ySubscriptYSize = data.readShort();
  19846. this.ySubscriptXOffset = data.readShort();
  19847. this.ySubscriptYOffset = data.readShort();
  19848. this.ySuperscriptXSize = data.readShort();
  19849. this.ySuperscriptYSize = data.readShort();
  19850. this.ySuperscriptXOffset = data.readShort();
  19851. this.ySuperscriptYOffset = data.readShort();
  19852. this.yStrikeoutSize = data.readShort();
  19853. this.yStrikeoutPosition = data.readShort();
  19854. this.familyClass = data.readShort();
  19855. this.panose = function () {
  19856. var _i, _results;
  19857. _results = [];
  19858. for (i = _i = 0; _i < 10; i = ++_i) {
  19859. _results.push(data.readByte());
  19860. }
  19861. return _results;
  19862. }();
  19863. this.charRange = function () {
  19864. var _i, _results;
  19865. _results = [];
  19866. for (i = _i = 0; _i < 4; i = ++_i) {
  19867. _results.push(data.readInt());
  19868. }
  19869. return _results;
  19870. }();
  19871. this.vendorID = data.readString(4);
  19872. this.selection = data.readShort();
  19873. this.firstCharIndex = data.readShort();
  19874. this.lastCharIndex = data.readShort();
  19875. if (this.version > 0) {
  19876. this.ascent = data.readShort();
  19877. this.descent = data.readShort();
  19878. this.lineGap = data.readShort();
  19879. this.winAscent = data.readShort();
  19880. this.winDescent = data.readShort();
  19881. this.codePageRange = function () {
  19882. var _i, _results;
  19883. _results = [];
  19884. for (i = _i = 0; _i < 2; i = ++_i) {
  19885. _results.push(data.readInt());
  19886. }
  19887. return _results;
  19888. }();
  19889. if (this.version > 1) {
  19890. this.xHeight = data.readShort();
  19891. this.capHeight = data.readShort();
  19892. this.defaultChar = data.readShort();
  19893. this.breakChar = data.readShort();
  19894. return this.maxContext = data.readShort();
  19895. }
  19896. }
  19897. };
  19898. /*OS2Table.prototype.encode = function () {
  19899. return this.raw();
  19900. };*/
  19901. return OS2Table;
  19902. }(Table);
  19903. var PostTable = function (_super) {
  19904. __extends(PostTable, _super);
  19905. function PostTable() {
  19906. return PostTable.__super__.constructor.apply(this, arguments);
  19907. }
  19908. PostTable.prototype.tag = 'post';
  19909. PostTable.prototype.parse = function (data) {
  19910. var i, length, numberOfGlyphs, _i, _results;
  19911. data.pos = this.offset;
  19912. this.format = data.readInt();
  19913. this.italicAngle = data.readInt();
  19914. this.underlinePosition = data.readShort();
  19915. this.underlineThickness = data.readShort();
  19916. this.isFixedPitch = data.readInt();
  19917. this.minMemType42 = data.readInt();
  19918. this.maxMemType42 = data.readInt();
  19919. this.minMemType1 = data.readInt();
  19920. this.maxMemType1 = data.readInt();
  19921. switch (this.format) {
  19922. case 0x00010000:
  19923. break;
  19924. case 0x00020000:
  19925. numberOfGlyphs = data.readUInt16();
  19926. this.glyphNameIndex = [];
  19927. for (i = _i = 0; 0 <= numberOfGlyphs ? _i < numberOfGlyphs : _i > numberOfGlyphs; i = 0 <= numberOfGlyphs ? ++_i : --_i) {
  19928. this.glyphNameIndex.push(data.readUInt16());
  19929. }
  19930. this.names = [];
  19931. _results = [];
  19932. while (data.pos < this.offset + this.length) {
  19933. length = data.readByte();
  19934. _results.push(this.names.push(data.readString(length)));
  19935. }
  19936. return _results;
  19937. break;
  19938. case 0x00025000:
  19939. numberOfGlyphs = data.readUInt16();
  19940. return this.offsets = data.read(numberOfGlyphs);
  19941. case 0x00030000:
  19942. break;
  19943. case 0x00040000:
  19944. return this.map = function () {
  19945. var _j, _ref, _results1;
  19946. _results1 = [];
  19947. for (i = _j = 0, _ref = this.file.maxp.numGlyphs; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
  19948. _results1.push(data.readUInt32());
  19949. }
  19950. return _results1;
  19951. }.call(this);
  19952. }
  19953. };
  19954. return PostTable;
  19955. }(Table);
  19956. /*********************************************************************************************************/
  19957. /* function : NameEntry */
  19958. /* comment : Store copyright information, platformID, encodingID, and languageID in the NameEntry object.*/
  19959. /*********************************************************************************************************/
  19960. var NameEntry = function () {
  19961. function NameEntry(raw, entry) {
  19962. this.raw = raw;
  19963. this.length = raw.length;
  19964. this.platformID = entry.platformID;
  19965. this.encodingID = entry.encodingID;
  19966. this.languageID = entry.languageID;
  19967. }
  19968. return NameEntry;
  19969. }();
  19970. var NameTable = function (_super) {
  19971. __extends(NameTable, _super);
  19972. function NameTable() {
  19973. return NameTable.__super__.constructor.apply(this, arguments);
  19974. }
  19975. NameTable.prototype.tag = 'name';
  19976. NameTable.prototype.parse = function (data) {
  19977. var count, entries, entry, format, i, name, stringOffset, strings, text, _i, _j, _len, _name;
  19978. data.pos = this.offset;
  19979. format = data.readShort();
  19980. count = data.readShort();
  19981. stringOffset = data.readShort();
  19982. entries = [];
  19983. for (i = _i = 0; 0 <= count ? _i < count : _i > count; i = 0 <= count ? ++_i : --_i) {
  19984. entries.push({
  19985. platformID: data.readShort(),
  19986. encodingID: data.readShort(),
  19987. languageID: data.readShort(),
  19988. nameID: data.readShort(),
  19989. length: data.readShort(),
  19990. offset: this.offset + stringOffset + data.readShort()
  19991. });
  19992. }
  19993. strings = {};
  19994. for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
  19995. entry = entries[i];
  19996. data.pos = entry.offset;
  19997. text = data.readString(entry.length);
  19998. name = new NameEntry(text, entry);
  19999. if (strings[_name = entry.nameID] == null) {
  20000. strings[_name] = [];
  20001. }
  20002. strings[entry.nameID].push(name);
  20003. }
  20004. this.strings = strings;
  20005. this.copyright = strings[0];
  20006. this.fontFamily = strings[1];
  20007. this.fontSubfamily = strings[2];
  20008. this.uniqueSubfamily = strings[3];
  20009. this.fontName = strings[4];
  20010. this.version = strings[5];
  20011. try {
  20012. this.postscriptName = strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
  20013. } catch (e) {
  20014. this.postscriptName = strings[4][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
  20015. }
  20016. this.trademark = strings[7];
  20017. this.manufacturer = strings[8];
  20018. this.designer = strings[9];
  20019. this.description = strings[10];
  20020. this.vendorUrl = strings[11];
  20021. this.designerUrl = strings[12];
  20022. this.license = strings[13];
  20023. this.licenseUrl = strings[14];
  20024. this.preferredFamily = strings[15];
  20025. this.preferredSubfamily = strings[17];
  20026. this.compatibleFull = strings[18];
  20027. return this.sampleText = strings[19];
  20028. };
  20029. /*NameTable.prototype.encode = function () {
  20030. var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
  20031. strings = {};
  20032. _ref = this.strings;
  20033. for (id in _ref) {
  20034. val = _ref[id];
  20035. strings[id] = val;
  20036. }
  20037. postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
  20038. platformID: 1
  20039. , encodingID: 0
  20040. , languageID: 0
  20041. });
  20042. strings[6] = [postscriptName];
  20043. subsetTag = successorOf(subsetTag);
  20044. strCount = 0;
  20045. for (id in strings) {
  20046. list = strings[id];
  20047. if (list != null) {
  20048. strCount += list.length;
  20049. }
  20050. }
  20051. table = new Data;
  20052. strTable = new Data;
  20053. table.writeShort(0);
  20054. table.writeShort(strCount);
  20055. table.writeShort(6 + 12 * strCount);
  20056. for (nameID in strings) {
  20057. list = strings[nameID];
  20058. if (list != null) {
  20059. for (_i = 0, _len = list.length; _i < _len; _i++) {
  20060. string = list[_i];
  20061. table.writeShort(string.platformID);
  20062. table.writeShort(string.encodingID);
  20063. table.writeShort(string.languageID);
  20064. table.writeShort(nameID);
  20065. table.writeShort(string.length);
  20066. table.writeShort(strTable.pos);
  20067. strTable.writeString(string.raw);
  20068. }
  20069. }
  20070. }
  20071. return nameTable = {
  20072. postscriptName: postscriptName.raw
  20073. , table: table.data.concat(strTable.data)
  20074. };
  20075. };*/
  20076. return NameTable;
  20077. }(Table);
  20078. var MaxpTable = function (_super) {
  20079. __extends(MaxpTable, _super);
  20080. function MaxpTable() {
  20081. return MaxpTable.__super__.constructor.apply(this, arguments);
  20082. }
  20083. MaxpTable.prototype.tag = 'maxp';
  20084. MaxpTable.prototype.parse = function (data) {
  20085. data.pos = this.offset;
  20086. this.version = data.readInt();
  20087. this.numGlyphs = data.readUInt16();
  20088. this.maxPoints = data.readUInt16();
  20089. this.maxContours = data.readUInt16();
  20090. this.maxCompositePoints = data.readUInt16();
  20091. this.maxComponentContours = data.readUInt16();
  20092. this.maxZones = data.readUInt16();
  20093. this.maxTwilightPoints = data.readUInt16();
  20094. this.maxStorage = data.readUInt16();
  20095. this.maxFunctionDefs = data.readUInt16();
  20096. this.maxInstructionDefs = data.readUInt16();
  20097. this.maxStackElements = data.readUInt16();
  20098. this.maxSizeOfInstructions = data.readUInt16();
  20099. this.maxComponentElements = data.readUInt16();
  20100. return this.maxComponentDepth = data.readUInt16();
  20101. };
  20102. /*MaxpTable.prototype.encode = function (ids) {
  20103. var table;
  20104. table = new Data;
  20105. table.writeInt(this.version);
  20106. table.writeUInt16(ids.length);
  20107. table.writeUInt16(this.maxPoints);
  20108. table.writeUInt16(this.maxContours);
  20109. table.writeUInt16(this.maxCompositePoints);
  20110. table.writeUInt16(this.maxComponentContours);
  20111. table.writeUInt16(this.maxZones);
  20112. table.writeUInt16(this.maxTwilightPoints);
  20113. table.writeUInt16(this.maxStorage);
  20114. table.writeUInt16(this.maxFunctionDefs);
  20115. table.writeUInt16(this.maxInstructionDefs);
  20116. table.writeUInt16(this.maxStackElements);
  20117. table.writeUInt16(this.maxSizeOfInstructions);
  20118. table.writeUInt16(this.maxComponentElements);
  20119. table.writeUInt16(this.maxComponentDepth);
  20120. return table.data;
  20121. };*/
  20122. return MaxpTable;
  20123. }(Table);
  20124. var HmtxTable = function (_super) {
  20125. __extends(HmtxTable, _super);
  20126. function HmtxTable() {
  20127. return HmtxTable.__super__.constructor.apply(this, arguments);
  20128. }
  20129. HmtxTable.prototype.tag = 'hmtx';
  20130. HmtxTable.prototype.parse = function (data) {
  20131. var i, last, lsbCount, m, _i, _j, _ref, _results;
  20132. data.pos = this.offset;
  20133. this.metrics = [];
  20134. for (i = _i = 0, _ref = this.file.hhea.numberOfMetrics; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  20135. this.metrics.push({
  20136. advance: data.readUInt16(),
  20137. lsb: data.readInt16()
  20138. });
  20139. }
  20140. lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
  20141. this.leftSideBearings = function () {
  20142. var _j, _results;
  20143. _results = [];
  20144. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  20145. _results.push(data.readInt16());
  20146. }
  20147. return _results;
  20148. }();
  20149. this.widths = function () {
  20150. var _j, _len, _ref1, _results;
  20151. _ref1 = this.metrics;
  20152. _results = [];
  20153. for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
  20154. m = _ref1[_j];
  20155. _results.push(m.advance);
  20156. }
  20157. return _results;
  20158. }.call(this);
  20159. last = this.widths[this.widths.length - 1];
  20160. _results = [];
  20161. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  20162. _results.push(this.widths.push(last));
  20163. }
  20164. return _results;
  20165. };
  20166. /***************************************************************/
  20167. /* function : forGlyph */
  20168. /* comment : Returns the advance width and lsb for this glyph. */
  20169. /***************************************************************/
  20170. HmtxTable.prototype.forGlyph = function (id) {
  20171. var metrics;
  20172. if (id in this.metrics) {
  20173. return this.metrics[id];
  20174. }
  20175. return metrics = {
  20176. advance: this.metrics[this.metrics.length - 1].advance,
  20177. lsb: this.leftSideBearings[id - this.metrics.length]
  20178. };
  20179. };
  20180. /*HmtxTable.prototype.encode = function (mapping) {
  20181. var id, metric, table, _i, _len;
  20182. table = new Data;
  20183. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  20184. id = mapping[_i];
  20185. metric = this.forGlyph(id);
  20186. table.writeUInt16(metric.advance);
  20187. table.writeUInt16(metric.lsb);
  20188. }
  20189. return table.data;
  20190. };*/
  20191. return HmtxTable;
  20192. }(Table);
  20193. var __slice = [].slice;
  20194. var GlyfTable = function (_super) {
  20195. __extends(GlyfTable, _super);
  20196. function GlyfTable() {
  20197. return GlyfTable.__super__.constructor.apply(this, arguments);
  20198. }
  20199. GlyfTable.prototype.tag = 'glyf';
  20200. GlyfTable.prototype.parse = function (data) {
  20201. return this.cache = {};
  20202. };
  20203. GlyfTable.prototype.glyphFor = function (id) {
  20204. id = id;
  20205. var data, index, length, loca, numberOfContours, raw, xMax, xMin, yMax, yMin;
  20206. if (id in this.cache) {
  20207. return this.cache[id];
  20208. }
  20209. loca = this.file.loca;
  20210. data = this.file.contents;
  20211. index = loca.indexOf(id);
  20212. length = loca.lengthOf(id);
  20213. if (length === 0) {
  20214. return this.cache[id] = null;
  20215. }
  20216. data.pos = this.offset + index;
  20217. raw = new Data(data.read(length));
  20218. numberOfContours = raw.readShort();
  20219. xMin = raw.readShort();
  20220. yMin = raw.readShort();
  20221. xMax = raw.readShort();
  20222. yMax = raw.readShort();
  20223. if (numberOfContours === -1) {
  20224. this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
  20225. } else {
  20226. this.cache[id] = new SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax);
  20227. }
  20228. return this.cache[id];
  20229. };
  20230. GlyfTable.prototype.encode = function (glyphs, mapping, old2new) {
  20231. var glyph, id, offsets, table, _i, _len;
  20232. table = [];
  20233. offsets = [];
  20234. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  20235. id = mapping[_i];
  20236. glyph = glyphs[id];
  20237. offsets.push(table.length);
  20238. if (glyph) {
  20239. table = table.concat(glyph.encode(old2new));
  20240. }
  20241. }
  20242. offsets.push(table.length);
  20243. return {
  20244. table: table,
  20245. offsets: offsets
  20246. };
  20247. };
  20248. return GlyfTable;
  20249. }(Table);
  20250. var SimpleGlyph = function () {
  20251. /**************************************************************************/
  20252. /* function : SimpleGlyph */
  20253. /* comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph.*/
  20254. /**************************************************************************/
  20255. function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
  20256. this.raw = raw;
  20257. this.numberOfContours = numberOfContours;
  20258. this.xMin = xMin;
  20259. this.yMin = yMin;
  20260. this.xMax = xMax;
  20261. this.yMax = yMax;
  20262. this.compound = false;
  20263. }
  20264. SimpleGlyph.prototype.encode = function () {
  20265. return this.raw.data;
  20266. };
  20267. return SimpleGlyph;
  20268. }();
  20269. var CompoundGlyph = function () {
  20270. 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;
  20271. ARG_1_AND_2_ARE_WORDS = 0x0001;
  20272. WE_HAVE_A_SCALE = 0x0008;
  20273. MORE_COMPONENTS = 0x0020;
  20274. WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
  20275. WE_HAVE_A_TWO_BY_TWO = 0x0080;
  20276. /********************************************************************************************************************/
  20277. /* function : CompoundGlypg generator */
  20278. /* comment : It stores raw, xMin, yMin, xMax, yMax, glyph id, and glyph offset for the corresponding compound glyph.*/
  20279. /********************************************************************************************************************/
  20280. function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
  20281. var data, flags;
  20282. this.raw = raw;
  20283. this.xMin = xMin;
  20284. this.yMin = yMin;
  20285. this.xMax = xMax;
  20286. this.yMax = yMax;
  20287. this.compound = true;
  20288. this.glyphIDs = [];
  20289. this.glyphOffsets = [];
  20290. data = this.raw;
  20291. while (true) {
  20292. flags = data.readShort();
  20293. this.glyphOffsets.push(data.pos);
  20294. this.glyphIDs.push(data.readShort());
  20295. if (!(flags & MORE_COMPONENTS)) {
  20296. break;
  20297. }
  20298. if (flags & ARG_1_AND_2_ARE_WORDS) {
  20299. data.pos += 4;
  20300. } else {
  20301. data.pos += 2;
  20302. }
  20303. if (flags & WE_HAVE_A_TWO_BY_TWO) {
  20304. data.pos += 8;
  20305. } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
  20306. data.pos += 4;
  20307. } else if (flags & WE_HAVE_A_SCALE) {
  20308. data.pos += 2;
  20309. }
  20310. }
  20311. }
  20312. /****************************************************************************************************************/
  20313. /* function : CompoundGlypg encode */
  20314. /* comment : After creating a table for the characters you typed, you call directory.encode to encode the table.*/
  20315. /****************************************************************************************************************/
  20316. CompoundGlyph.prototype.encode = function (mapping) {
  20317. var i, id, result, _i, _len, _ref;
  20318. result = new Data(__slice.call(this.raw.data));
  20319. _ref = this.glyphIDs;
  20320. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  20321. id = _ref[i];
  20322. result.pos = this.glyphOffsets[i];
  20323. }
  20324. return result.data;
  20325. };
  20326. return CompoundGlyph;
  20327. }();
  20328. var LocaTable = function (_super) {
  20329. __extends(LocaTable, _super);
  20330. function LocaTable() {
  20331. return LocaTable.__super__.constructor.apply(this, arguments);
  20332. }
  20333. LocaTable.prototype.tag = 'loca';
  20334. LocaTable.prototype.parse = function (data) {
  20335. var format, i;
  20336. data.pos = this.offset;
  20337. format = this.file.head.indexToLocFormat;
  20338. if (format === 0) {
  20339. return this.offsets = function () {
  20340. var _i, _ref, _results;
  20341. _results = [];
  20342. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 2) {
  20343. _results.push(data.readUInt16() * 2);
  20344. }
  20345. return _results;
  20346. }.call(this);
  20347. } else {
  20348. return this.offsets = function () {
  20349. var _i, _ref, _results;
  20350. _results = [];
  20351. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 4) {
  20352. _results.push(data.readUInt32());
  20353. }
  20354. return _results;
  20355. }.call(this);
  20356. }
  20357. };
  20358. LocaTable.prototype.indexOf = function (id) {
  20359. return this.offsets[id];
  20360. };
  20361. LocaTable.prototype.lengthOf = function (id) {
  20362. return this.offsets[id + 1] - this.offsets[id];
  20363. };
  20364. LocaTable.prototype.encode = function (offsets, activeGlyphs) {
  20365. var LocaTable = new Uint32Array(this.offsets.length);
  20366. var glyfPtr = 0;
  20367. var listGlyf = 0;
  20368. for (var k = 0; k < LocaTable.length; ++k) {
  20369. LocaTable[k] = glyfPtr;
  20370. if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
  20371. ++listGlyf;
  20372. LocaTable[k] = glyfPtr;
  20373. var start = this.offsets[k];
  20374. var len = this.offsets[k + 1] - start;
  20375. if (len > 0) {
  20376. glyfPtr += len;
  20377. }
  20378. }
  20379. }
  20380. var newLocaTable = new Array(LocaTable.length * 4);
  20381. for (var j = 0; j < LocaTable.length; ++j) {
  20382. newLocaTable[4 * j + 3] = LocaTable[j] & 0x000000ff;
  20383. newLocaTable[4 * j + 2] = (LocaTable[j] & 0x0000ff00) >> 8;
  20384. newLocaTable[4 * j + 1] = (LocaTable[j] & 0x00ff0000) >> 16;
  20385. newLocaTable[4 * j] = (LocaTable[j] & 0xff000000) >> 24;
  20386. }
  20387. return newLocaTable;
  20388. };
  20389. return LocaTable;
  20390. }(Table);
  20391. /************************************************************************************/
  20392. /* function : invert */
  20393. /* comment : Change the object's (key: value) to create an object with (value: key).*/
  20394. /************************************************************************************/
  20395. var invert = function invert(object) {
  20396. var key, ret, val;
  20397. ret = {};
  20398. for (key in object) {
  20399. val = object[key];
  20400. ret[val] = key;
  20401. }
  20402. return ret;
  20403. };
  20404. /*var successorOf = function (input) {
  20405. var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
  20406. alphabet = 'abcdefghijklmnopqrstuvwxyz';
  20407. length = alphabet.length;
  20408. result = input;
  20409. i = input.length;
  20410. while (i >= 0) {
  20411. last = input.charAt(--i);
  20412. if (isNaN(last)) {
  20413. index = alphabet.indexOf(last.toLowerCase());
  20414. if (index === -1) {
  20415. next = last;
  20416. carry = true;
  20417. }
  20418. else {
  20419. next = alphabet.charAt((index + 1) % length);
  20420. isUpperCase = last === last.toUpperCase();
  20421. if (isUpperCase) {
  20422. next = next.toUpperCase();
  20423. }
  20424. carry = index + 1 >= length;
  20425. if (carry && i === 0) {
  20426. added = isUpperCase ? 'A' : 'a';
  20427. result = added + next + result.slice(1);
  20428. break;
  20429. }
  20430. }
  20431. }
  20432. else {
  20433. next = +last + 1;
  20434. carry = next > 9;
  20435. if (carry) {
  20436. next = 0;
  20437. }
  20438. if (carry && i === 0) {
  20439. result = '1' + next + result.slice(1);
  20440. break;
  20441. }
  20442. }
  20443. result = result.slice(0, i) + next + result.slice(i + 1);
  20444. if (!carry) {
  20445. break;
  20446. }
  20447. }
  20448. return result;
  20449. };*/
  20450. var Subset = function () {
  20451. function Subset(font) {
  20452. this.font = font;
  20453. this.subset = {};
  20454. this.unicodes = {};
  20455. this.next = 33;
  20456. }
  20457. /*Subset.prototype.use = function (character) {
  20458. var i, _i, _ref;
  20459. if (typeof character === 'string') {
  20460. for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  20461. this.use(character.charCodeAt(i));
  20462. }
  20463. return;
  20464. }
  20465. if (!this.unicodes[character]) {
  20466. this.subset[this.next] = character;
  20467. return this.unicodes[character] = this.next++;
  20468. }
  20469. };*/
  20470. /*Subset.prototype.encodeText = function (text) {
  20471. var char, i, string, _i, _ref;
  20472. string = '';
  20473. for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  20474. char = this.unicodes[text.charCodeAt(i)];
  20475. string += String.fromCharCode(char);
  20476. }
  20477. return string;
  20478. };*/
  20479. /***************************************************************/
  20480. /* function : generateCmap */
  20481. /* comment : Returns the unicode cmap for this font. */
  20482. /***************************************************************/
  20483. Subset.prototype.generateCmap = function () {
  20484. var mapping, roman, unicode, unicodeCmap, _ref;
  20485. unicodeCmap = this.font.cmap.tables[0].codeMap;
  20486. mapping = {};
  20487. _ref = this.subset;
  20488. for (roman in _ref) {
  20489. unicode = _ref[roman];
  20490. mapping[roman] = unicodeCmap[unicode];
  20491. }
  20492. return mapping;
  20493. };
  20494. /*Subset.prototype.glyphIDs = function () {
  20495. var ret, roman, unicode, unicodeCmap, val, _ref;
  20496. unicodeCmap = this.font.cmap.tables[0].codeMap;
  20497. ret = [0];
  20498. _ref = this.subset;
  20499. for (roman in _ref) {
  20500. unicode = _ref[roman];
  20501. val = unicodeCmap[unicode];
  20502. if ((val != null) && __indexOf.call(ret, val) < 0) {
  20503. ret.push(val);
  20504. }
  20505. }
  20506. return ret.sort();
  20507. };*/
  20508. /******************************************************************/
  20509. /* function : glyphsFor */
  20510. /* comment : Returns simple glyph objects for the input character.*/
  20511. /******************************************************************/
  20512. Subset.prototype.glyphsFor = function (glyphIDs) {
  20513. var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
  20514. glyphs = {};
  20515. for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
  20516. id = glyphIDs[_i];
  20517. glyphs[id] = this.font.glyf.glyphFor(id);
  20518. }
  20519. additionalIDs = [];
  20520. for (id in glyphs) {
  20521. glyph = glyphs[id];
  20522. if (glyph != null ? glyph.compound : void 0) {
  20523. additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
  20524. }
  20525. }
  20526. if (additionalIDs.length > 0) {
  20527. _ref = this.glyphsFor(additionalIDs);
  20528. for (id in _ref) {
  20529. glyph = _ref[id];
  20530. glyphs[id] = glyph;
  20531. }
  20532. }
  20533. return glyphs;
  20534. };
  20535. /***************************************************************/
  20536. /* function : encode */
  20537. /* comment : Encode various tables for the characters you use. */
  20538. /***************************************************************/
  20539. Subset.prototype.encode = function (glyID, indexToLocFormat) {
  20540. var cmap, code, glyf, glyphs, id, ids, loca, new2old, newIDs, nextGlyphID, old2new, oldID, oldIDs, tables, _ref;
  20541. cmap = CmapTable.encode(this.generateCmap(), 'unicode');
  20542. glyphs = this.glyphsFor(glyID);
  20543. old2new = {
  20544. 0: 0
  20545. };
  20546. _ref = cmap.charMap;
  20547. for (code in _ref) {
  20548. ids = _ref[code];
  20549. old2new[ids.old] = ids["new"];
  20550. }
  20551. nextGlyphID = cmap.maxGlyphID;
  20552. for (oldID in glyphs) {
  20553. if (!(oldID in old2new)) {
  20554. old2new[oldID] = nextGlyphID++;
  20555. }
  20556. }
  20557. new2old = invert(old2new);
  20558. newIDs = Object.keys(new2old).sort(function (a, b) {
  20559. return a - b;
  20560. });
  20561. oldIDs = function () {
  20562. var _i, _len, _results;
  20563. _results = [];
  20564. for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
  20565. id = newIDs[_i];
  20566. _results.push(new2old[id]);
  20567. }
  20568. return _results;
  20569. }();
  20570. glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
  20571. loca = this.font.loca.encode(glyf.offsets, oldIDs);
  20572. tables = {
  20573. cmap: this.font.cmap.raw(),
  20574. glyf: glyf.table,
  20575. loca: loca,
  20576. hmtx: this.font.hmtx.raw(),
  20577. hhea: this.font.hhea.raw(),
  20578. maxp: this.font.maxp.raw(),
  20579. post: this.font.post.raw(),
  20580. name: this.font.name.raw(),
  20581. head: this.font.head.encode(indexToLocFormat)
  20582. };
  20583. if (this.font.os2.exists) {
  20584. tables['OS/2'] = this.font.os2.raw();
  20585. }
  20586. return this.font.directory.encode(tables);
  20587. };
  20588. return Subset;
  20589. }();
  20590. jsPDF.API.PDFObject = function () {
  20591. var pad;
  20592. function PDFObject() {}
  20593. pad = function pad(str, length) {
  20594. return (Array(length + 1).join('0') + str).slice(-length);
  20595. };
  20596. /*****************************************************************************/
  20597. /* function : convert */
  20598. /* comment :Converts pdf tag's / FontBBox and array values in / W to strings */
  20599. /*****************************************************************************/
  20600. PDFObject.convert = function (object) {
  20601. var e, items, key, out, val;
  20602. if (Array.isArray(object)) {
  20603. items = function () {
  20604. var _i, _len, _results;
  20605. _results = [];
  20606. for (_i = 0, _len = object.length; _i < _len; _i++) {
  20607. e = object[_i];
  20608. _results.push(PDFObject.convert(e));
  20609. }
  20610. return _results;
  20611. }().join(' ');
  20612. return '[' + items + ']';
  20613. } else if (typeof object === 'string') {
  20614. return '/' + object;
  20615. } else if (object != null ? object.isString : void 0) {
  20616. return '(' + object + ')';
  20617. } else if (object instanceof Date) {
  20618. 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)';
  20619. } else if ({}.toString.call(object) === '[object Object]') {
  20620. out = ['<<'];
  20621. for (key in object) {
  20622. val = object[key];
  20623. out.push('/' + key + ' ' + PDFObject.convert(val));
  20624. }
  20625. out.push('>>');
  20626. return out.join('\n');
  20627. } else {
  20628. return '' + object;
  20629. }
  20630. };
  20631. return PDFObject;
  20632. }();
  20633. })(jsPDF);
  20634. // Generated by CoffeeScript 1.4.0
  20635. /*
  20636. # PNG.js
  20637. # Copyright (c) 2011 Devon Govett
  20638. # MIT LICENSE
  20639. #
  20640. #
  20641. */
  20642. (function (global) {
  20643. var PNG;
  20644. PNG = function () {
  20645. var APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  20646. PNG.load = function (url, canvas, callback) {
  20647. var xhr;
  20648. if (typeof canvas === 'function') {
  20649. callback = canvas;
  20650. }
  20651. xhr = new XMLHttpRequest();
  20652. xhr.open("GET", url, true);
  20653. xhr.responseType = "arraybuffer";
  20654. xhr.onload = function () {
  20655. var data, png;
  20656. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  20657. png = new PNG(data);
  20658. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  20659. png.render(canvas);
  20660. }
  20661. return typeof callback === "function" ? callback(png) : void 0;
  20662. };
  20663. return xhr.send(null);
  20664. };
  20665. APNG_DISPOSE_OP_BACKGROUND = 1;
  20666. APNG_DISPOSE_OP_PREVIOUS = 2;
  20667. APNG_BLEND_OP_SOURCE = 0;
  20668. function PNG(data) {
  20669. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  20670. this.data = data;
  20671. this.pos = 8;
  20672. this.palette = [];
  20673. this.imgData = [];
  20674. this.transparency = {};
  20675. this.animation = null;
  20676. this.text = {};
  20677. frame = null;
  20678. while (true) {
  20679. chunkSize = this.readUInt32();
  20680. section = function () {
  20681. var _i, _results;
  20682. _results = [];
  20683. for (i = _i = 0; _i < 4; i = ++_i) {
  20684. _results.push(String.fromCharCode(this.data[this.pos++]));
  20685. }
  20686. return _results;
  20687. }.call(this).join('');
  20688. switch (section) {
  20689. case 'IHDR':
  20690. this.width = this.readUInt32();
  20691. this.height = this.readUInt32();
  20692. this.bits = this.data[this.pos++];
  20693. this.colorType = this.data[this.pos++];
  20694. this.compressionMethod = this.data[this.pos++];
  20695. this.filterMethod = this.data[this.pos++];
  20696. this.interlaceMethod = this.data[this.pos++];
  20697. break;
  20698. case 'acTL':
  20699. this.animation = {
  20700. numFrames: this.readUInt32(),
  20701. numPlays: this.readUInt32() || Infinity,
  20702. frames: []
  20703. };
  20704. break;
  20705. case 'PLTE':
  20706. this.palette = this.read(chunkSize);
  20707. break;
  20708. case 'fcTL':
  20709. if (frame) {
  20710. this.animation.frames.push(frame);
  20711. }
  20712. this.pos += 4;
  20713. frame = {
  20714. width: this.readUInt32(),
  20715. height: this.readUInt32(),
  20716. xOffset: this.readUInt32(),
  20717. yOffset: this.readUInt32()
  20718. };
  20719. delayNum = this.readUInt16();
  20720. delayDen = this.readUInt16() || 100;
  20721. frame.delay = 1000 * delayNum / delayDen;
  20722. frame.disposeOp = this.data[this.pos++];
  20723. frame.blendOp = this.data[this.pos++];
  20724. frame.data = [];
  20725. break;
  20726. case 'IDAT':
  20727. case 'fdAT':
  20728. if (section === 'fdAT') {
  20729. this.pos += 4;
  20730. chunkSize -= 4;
  20731. }
  20732. data = (frame != null ? frame.data : void 0) || this.imgData;
  20733. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  20734. data.push(this.data[this.pos++]);
  20735. }
  20736. break;
  20737. case 'tRNS':
  20738. this.transparency = {};
  20739. switch (this.colorType) {
  20740. case 3:
  20741. palLen = this.palette.length / 3;
  20742. this.transparency.indexed = this.read(chunkSize);
  20743. if (this.transparency.indexed.length > palLen) throw new Error('More transparent colors than palette size');
  20744. /*
  20745. * According to the PNG spec trns should be increased to the same size as palette if shorter
  20746. */
  20747. //palShort = 255 - this.transparency.indexed.length;
  20748. palShort = palLen - this.transparency.indexed.length;
  20749. if (palShort > 0) {
  20750. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  20751. this.transparency.indexed.push(255);
  20752. }
  20753. }
  20754. break;
  20755. case 0:
  20756. this.transparency.grayscale = this.read(chunkSize)[0];
  20757. break;
  20758. case 2:
  20759. this.transparency.rgb = this.read(chunkSize);
  20760. }
  20761. break;
  20762. case 'tEXt':
  20763. text = this.read(chunkSize);
  20764. index = text.indexOf(0);
  20765. key = String.fromCharCode.apply(String, text.slice(0, index));
  20766. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  20767. break;
  20768. case 'IEND':
  20769. if (frame) {
  20770. this.animation.frames.push(frame);
  20771. }
  20772. this.colors = function () {
  20773. switch (this.colorType) {
  20774. case 0:
  20775. case 3:
  20776. case 4:
  20777. return 1;
  20778. case 2:
  20779. case 6:
  20780. return 3;
  20781. }
  20782. }.call(this);
  20783. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  20784. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  20785. this.pixelBitlength = this.bits * colors;
  20786. this.colorSpace = function () {
  20787. switch (this.colors) {
  20788. case 1:
  20789. return 'DeviceGray';
  20790. case 3:
  20791. return 'DeviceRGB';
  20792. }
  20793. }.call(this);
  20794. this.imgData = new Uint8Array(this.imgData);
  20795. return;
  20796. default:
  20797. this.pos += chunkSize;
  20798. }
  20799. this.pos += 4;
  20800. if (this.pos > this.data.length) {
  20801. throw new Error("Incomplete or corrupt PNG file");
  20802. }
  20803. }
  20804. return;
  20805. }
  20806. PNG.prototype.read = function (bytes) {
  20807. var i, _i, _results;
  20808. _results = [];
  20809. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  20810. _results.push(this.data[this.pos++]);
  20811. }
  20812. return _results;
  20813. };
  20814. PNG.prototype.readUInt32 = function () {
  20815. var b1, b2, b3, b4;
  20816. b1 = this.data[this.pos++] << 24;
  20817. b2 = this.data[this.pos++] << 16;
  20818. b3 = this.data[this.pos++] << 8;
  20819. b4 = this.data[this.pos++];
  20820. return b1 | b2 | b3 | b4;
  20821. };
  20822. PNG.prototype.readUInt16 = function () {
  20823. var b1, b2;
  20824. b1 = this.data[this.pos++] << 8;
  20825. b2 = this.data[this.pos++];
  20826. return b1 | b2;
  20827. };
  20828. PNG.prototype.decodePixels = function (data) {
  20829. var pixelBytes = this.pixelBitlength / 8;
  20830. var fullPixels = new Uint8Array(this.width * this.height * pixelBytes);
  20831. var pos = 0;
  20832. var _this = this;
  20833. if (data == null) {
  20834. data = this.imgData;
  20835. }
  20836. if (data.length === 0) {
  20837. return new Uint8Array(0);
  20838. }
  20839. data = new FlateStream(data);
  20840. data = data.getBytes();
  20841. function pass(x0, y0, dx, dy) {
  20842. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixels, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  20843. var w = Math.ceil((_this.width - x0) / dx),
  20844. h = Math.ceil((_this.height - y0) / dy);
  20845. var isFull = _this.width == w && _this.height == h;
  20846. scanlineLength = pixelBytes * w;
  20847. pixels = isFull ? fullPixels : new Uint8Array(scanlineLength * h);
  20848. length = data.length;
  20849. row = 0;
  20850. c = 0;
  20851. while (row < h && pos < length) {
  20852. switch (data[pos++]) {
  20853. case 0:
  20854. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  20855. pixels[c++] = data[pos++];
  20856. }
  20857. break;
  20858. case 1:
  20859. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  20860. abyte = data[pos++];
  20861. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  20862. pixels[c++] = (abyte + left) % 256;
  20863. }
  20864. break;
  20865. case 2:
  20866. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  20867. abyte = data[pos++];
  20868. col = (i - i % pixelBytes) / pixelBytes;
  20869. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  20870. pixels[c++] = (upper + abyte) % 256;
  20871. }
  20872. break;
  20873. case 3:
  20874. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  20875. abyte = data[pos++];
  20876. col = (i - i % pixelBytes) / pixelBytes;
  20877. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  20878. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  20879. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  20880. }
  20881. break;
  20882. case 4:
  20883. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  20884. abyte = data[pos++];
  20885. col = (i - i % pixelBytes) / pixelBytes;
  20886. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  20887. if (row === 0) {
  20888. upper = upperLeft = 0;
  20889. } else {
  20890. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  20891. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes];
  20892. }
  20893. p = left + upper - upperLeft;
  20894. pa = Math.abs(p - left);
  20895. pb = Math.abs(p - upper);
  20896. pc = Math.abs(p - upperLeft);
  20897. if (pa <= pb && pa <= pc) {
  20898. paeth = left;
  20899. } else if (pb <= pc) {
  20900. paeth = upper;
  20901. } else {
  20902. paeth = upperLeft;
  20903. }
  20904. pixels[c++] = (abyte + paeth) % 256;
  20905. }
  20906. break;
  20907. default:
  20908. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  20909. }
  20910. if (!isFull) {
  20911. var fullPos = ((y0 + row * dy) * _this.width + x0) * pixelBytes;
  20912. var partPos = row * scanlineLength;
  20913. for (i = 0; i < w; i += 1) {
  20914. for (var j = 0; j < pixelBytes; j += 1) {
  20915. fullPixels[fullPos++] = pixels[partPos++];
  20916. }
  20917. fullPos += (dx - 1) * pixelBytes;
  20918. }
  20919. }
  20920. row++;
  20921. }
  20922. }
  20923. if (_this.interlaceMethod == 1) {
  20924. /*
  20925. 1 6 4 6 2 6 4 6
  20926. 7 7 7 7 7 7 7 7
  20927. 5 6 5 6 5 6 5 6
  20928. 7 7 7 7 7 7 7 7
  20929. 3 6 4 6 3 6 4 6
  20930. 7 7 7 7 7 7 7 7
  20931. 5 6 5 6 5 6 5 6
  20932. 7 7 7 7 7 7 7 7
  20933. */
  20934. pass(0, 0, 8, 8); // 1
  20935. /* NOTE these seem to follow the pattern:
  20936. * pass(x, 0, 2*x, 2*x);
  20937. * pass(0, x, x, 2*x);
  20938. * with x being 4, 2, 1.
  20939. */
  20940. pass(4, 0, 8, 8); // 2
  20941. pass(0, 4, 4, 8); // 3
  20942. pass(2, 0, 4, 4); // 4
  20943. pass(0, 2, 2, 4); // 5
  20944. pass(1, 0, 2, 2); // 6
  20945. pass(0, 1, 1, 2); // 7
  20946. } else {
  20947. pass(0, 0, 1, 1);
  20948. }
  20949. return fullPixels;
  20950. };
  20951. PNG.prototype.decodePalette = function () {
  20952. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  20953. palette = this.palette;
  20954. transparency = this.transparency.indexed || [];
  20955. ret = new Uint8Array((transparency.length || 0) + palette.length);
  20956. pos = 0;
  20957. length = palette.length;
  20958. c = 0;
  20959. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  20960. ret[pos++] = palette[i];
  20961. ret[pos++] = palette[i + 1];
  20962. ret[pos++] = palette[i + 2];
  20963. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  20964. }
  20965. return ret;
  20966. };
  20967. PNG.prototype.copyToImageData = function (imageData, pixels) {
  20968. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  20969. colors = this.colors;
  20970. palette = null;
  20971. alpha = this.hasAlphaChannel;
  20972. if (this.palette.length) {
  20973. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  20974. colors = 4;
  20975. alpha = true;
  20976. }
  20977. data = imageData.data || imageData;
  20978. length = data.length;
  20979. input = palette || pixels;
  20980. i = j = 0;
  20981. if (colors === 1) {
  20982. while (i < length) {
  20983. k = palette ? pixels[i / 4] * 4 : j;
  20984. v = input[k++];
  20985. data[i++] = v;
  20986. data[i++] = v;
  20987. data[i++] = v;
  20988. data[i++] = alpha ? input[k++] : 255;
  20989. j = k;
  20990. }
  20991. } else {
  20992. while (i < length) {
  20993. k = palette ? pixels[i / 4] * 4 : j;
  20994. data[i++] = input[k++];
  20995. data[i++] = input[k++];
  20996. data[i++] = input[k++];
  20997. data[i++] = alpha ? input[k++] : 255;
  20998. j = k;
  20999. }
  21000. }
  21001. };
  21002. PNG.prototype.decode = function () {
  21003. var ret;
  21004. ret = new Uint8Array(this.width * this.height * 4);
  21005. this.copyToImageData(ret, this.decodePixels());
  21006. return ret;
  21007. };
  21008. try {
  21009. scratchCanvas = global.document.createElement('canvas');
  21010. scratchCtx = scratchCanvas.getContext('2d');
  21011. } catch (e) {
  21012. return -1;
  21013. }
  21014. makeImage = function makeImage(imageData) {
  21015. var img;
  21016. scratchCtx.width = imageData.width;
  21017. scratchCtx.height = imageData.height;
  21018. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  21019. scratchCtx.putImageData(imageData, 0, 0);
  21020. img = new Image();
  21021. img.src = scratchCanvas.toDataURL();
  21022. return img;
  21023. };
  21024. PNG.prototype.decodeFrames = function (ctx) {
  21025. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  21026. if (!this.animation) {
  21027. return;
  21028. }
  21029. _ref = this.animation.frames;
  21030. _results = [];
  21031. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  21032. frame = _ref[i];
  21033. imageData = ctx.createImageData(frame.width, frame.height);
  21034. pixels = this.decodePixels(new Uint8Array(frame.data));
  21035. this.copyToImageData(imageData, pixels);
  21036. frame.imageData = imageData;
  21037. _results.push(frame.image = makeImage(imageData));
  21038. }
  21039. return _results;
  21040. };
  21041. PNG.prototype.renderFrame = function (ctx, number) {
  21042. var frame, frames, prev;
  21043. frames = this.animation.frames;
  21044. frame = frames[number];
  21045. prev = frames[number - 1];
  21046. if (number === 0) {
  21047. ctx.clearRect(0, 0, this.width, this.height);
  21048. }
  21049. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  21050. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  21051. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  21052. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  21053. }
  21054. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  21055. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  21056. }
  21057. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  21058. };
  21059. PNG.prototype.animate = function (ctx) {
  21060. var _doFrame,
  21061. frameNumber,
  21062. frames,
  21063. numFrames,
  21064. numPlays,
  21065. _ref,
  21066. _this = this;
  21067. frameNumber = 0;
  21068. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  21069. return (_doFrame = function doFrame() {
  21070. var f, frame;
  21071. f = frameNumber++ % numFrames;
  21072. frame = frames[f];
  21073. _this.renderFrame(ctx, f);
  21074. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  21075. return _this.animation._timeout = setTimeout(_doFrame, frame.delay);
  21076. }
  21077. })();
  21078. };
  21079. PNG.prototype.stopAnimation = function () {
  21080. var _ref;
  21081. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  21082. };
  21083. PNG.prototype.render = function (canvas) {
  21084. var ctx, data;
  21085. if (canvas._png) {
  21086. canvas._png.stopAnimation();
  21087. }
  21088. canvas._png = this;
  21089. canvas.width = this.width;
  21090. canvas.height = this.height;
  21091. ctx = canvas.getContext("2d");
  21092. if (this.animation) {
  21093. this.decodeFrames(ctx);
  21094. return this.animate(ctx);
  21095. } else {
  21096. data = ctx.createImageData(this.width, this.height);
  21097. this.copyToImageData(data, this.decodePixels());
  21098. return ctx.putImageData(data, 0, 0);
  21099. }
  21100. };
  21101. return PNG;
  21102. }();
  21103. global.PNG = PNG;
  21104. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  21105. // while `this` is nsIContentFrameMessageManager
  21106. // with an attribute `content` that corresponds to the window
  21107. /*
  21108. * Extracted from pdf.js
  21109. * https://github.com/andreasgal/pdf.js
  21110. *
  21111. * Copyright (c) 2011 Mozilla Foundation
  21112. *
  21113. * Contributors: Andreas Gal <gal@mozilla.com>
  21114. * Chris G Jones <cjones@mozilla.com>
  21115. * Shaon Barman <shaon.barman@gmail.com>
  21116. * Vivien Nicolas <21@vingtetun.org>
  21117. * Justin D'Arcangelo <justindarc@gmail.com>
  21118. * Yury Delendik
  21119. *
  21120. *
  21121. */
  21122. var DecodeStream = function () {
  21123. function constructor() {
  21124. this.pos = 0;
  21125. this.bufferLength = 0;
  21126. this.eof = false;
  21127. this.buffer = null;
  21128. }
  21129. constructor.prototype = {
  21130. ensureBuffer: function decodestream_ensureBuffer(requested) {
  21131. var buffer = this.buffer;
  21132. var current = buffer ? buffer.byteLength : 0;
  21133. if (requested < current) return buffer;
  21134. var size = 512;
  21135. while (size < requested) {
  21136. size <<= 1;
  21137. }
  21138. var buffer2 = new Uint8Array(size);
  21139. for (var i = 0; i < current; ++i) {
  21140. buffer2[i] = buffer[i];
  21141. }
  21142. return this.buffer = buffer2;
  21143. },
  21144. getByte: function decodestream_getByte() {
  21145. var pos = this.pos;
  21146. while (this.bufferLength <= pos) {
  21147. if (this.eof) return null;
  21148. this.readBlock();
  21149. }
  21150. return this.buffer[this.pos++];
  21151. },
  21152. getBytes: function decodestream_getBytes(length) {
  21153. var pos = this.pos;
  21154. if (length) {
  21155. this.ensureBuffer(pos + length);
  21156. var end = pos + length;
  21157. while (!this.eof && this.bufferLength < end) {
  21158. this.readBlock();
  21159. }
  21160. var bufEnd = this.bufferLength;
  21161. if (end > bufEnd) end = bufEnd;
  21162. } else {
  21163. while (!this.eof) {
  21164. this.readBlock();
  21165. }
  21166. var end = this.bufferLength;
  21167. }
  21168. this.pos = end;
  21169. return this.buffer.subarray(pos, end);
  21170. },
  21171. lookChar: function decodestream_lookChar() {
  21172. var pos = this.pos;
  21173. while (this.bufferLength <= pos) {
  21174. if (this.eof) return null;
  21175. this.readBlock();
  21176. }
  21177. return String.fromCharCode(this.buffer[this.pos]);
  21178. },
  21179. getChar: function decodestream_getChar() {
  21180. var pos = this.pos;
  21181. while (this.bufferLength <= pos) {
  21182. if (this.eof) return null;
  21183. this.readBlock();
  21184. }
  21185. return String.fromCharCode(this.buffer[this.pos++]);
  21186. },
  21187. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  21188. var end = start + length;
  21189. while (this.bufferLength <= end && !this.eof) {
  21190. this.readBlock();
  21191. }
  21192. return new Stream(this.buffer, start, length, dict);
  21193. },
  21194. skip: function decodestream_skip(n) {
  21195. if (!n) n = 1;
  21196. this.pos += n;
  21197. },
  21198. reset: function decodestream_reset() {
  21199. this.pos = 0;
  21200. }
  21201. };
  21202. return constructor;
  21203. }();
  21204. var FlateStream = function () {
  21205. if (typeof Uint32Array === 'undefined') {
  21206. return undefined;
  21207. }
  21208. var codeLenCodeMap = new Uint32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
  21209. var lengthDecode = new Uint32Array([0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102]);
  21210. var distDecode = new Uint32Array([0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001]);
  21211. var fixedLitCodeTab = [new Uint32Array([0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8, 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8, 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8, 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4, 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec, 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc, 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2, 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2, 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da, 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6, 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6, 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6, 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe, 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1, 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1, 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1, 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5, 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5, 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5, 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd, 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3, 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3, 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb, 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb, 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7, 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf, 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef, 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df, 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff]), 9];
  21212. var fixedDistCodeTab = [new Uint32Array([0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000]), 5];
  21213. function error(e) {
  21214. throw new Error(e);
  21215. }
  21216. function constructor(bytes) {
  21217. //var bytes = stream.getBytes();
  21218. var bytesPos = 0;
  21219. var cmf = bytes[bytesPos++];
  21220. var flg = bytes[bytesPos++];
  21221. if (cmf == -1 || flg == -1) error('Invalid header in flate stream');
  21222. if ((cmf & 0x0f) != 0x08) error('Unknown compression method in flate stream');
  21223. if (((cmf << 8) + flg) % 31 != 0) error('Bad FCHECK in flate stream');
  21224. if (flg & 0x20) error('FDICT bit set in flate stream');
  21225. this.bytes = bytes;
  21226. this.bytesPos = bytesPos;
  21227. this.codeSize = 0;
  21228. this.codeBuf = 0;
  21229. DecodeStream.call(this);
  21230. }
  21231. constructor.prototype = Object.create(DecodeStream.prototype);
  21232. constructor.prototype.getBits = function (bits) {
  21233. var codeSize = this.codeSize;
  21234. var codeBuf = this.codeBuf;
  21235. var bytes = this.bytes;
  21236. var bytesPos = this.bytesPos;
  21237. var b;
  21238. while (codeSize < bits) {
  21239. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad encoding in flate stream');
  21240. codeBuf |= b << codeSize;
  21241. codeSize += 8;
  21242. }
  21243. b = codeBuf & (1 << bits) - 1;
  21244. this.codeBuf = codeBuf >> bits;
  21245. this.codeSize = codeSize -= bits;
  21246. this.bytesPos = bytesPos;
  21247. return b;
  21248. };
  21249. constructor.prototype.getCode = function (table) {
  21250. var codes = table[0];
  21251. var maxLen = table[1];
  21252. var codeSize = this.codeSize;
  21253. var codeBuf = this.codeBuf;
  21254. var bytes = this.bytes;
  21255. var bytesPos = this.bytesPos;
  21256. while (codeSize < maxLen) {
  21257. var b;
  21258. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad encoding in flate stream');
  21259. codeBuf |= b << codeSize;
  21260. codeSize += 8;
  21261. }
  21262. var code = codes[codeBuf & (1 << maxLen) - 1];
  21263. var codeLen = code >> 16;
  21264. var codeVal = code & 0xffff;
  21265. if (codeSize == 0 || codeSize < codeLen || codeLen == 0) error('Bad encoding in flate stream');
  21266. this.codeBuf = codeBuf >> codeLen;
  21267. this.codeSize = codeSize - codeLen;
  21268. this.bytesPos = bytesPos;
  21269. return codeVal;
  21270. };
  21271. constructor.prototype.generateHuffmanTable = function (lengths) {
  21272. var n = lengths.length; // find max code length
  21273. var maxLen = 0;
  21274. for (var i = 0; i < n; ++i) {
  21275. if (lengths[i] > maxLen) maxLen = lengths[i];
  21276. } // build the table
  21277. var size = 1 << maxLen;
  21278. var codes = new Uint32Array(size);
  21279. for (var len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) {
  21280. for (var val = 0; val < n; ++val) {
  21281. if (lengths[val] == len) {
  21282. // bit-reverse the code
  21283. var code2 = 0;
  21284. var t = code;
  21285. for (var i = 0; i < len; ++i) {
  21286. code2 = code2 << 1 | t & 1;
  21287. t >>= 1;
  21288. } // fill the table entries
  21289. for (var i = code2; i < size; i += skip) {
  21290. codes[i] = len << 16 | val;
  21291. }
  21292. ++code;
  21293. }
  21294. }
  21295. }
  21296. return [codes, maxLen];
  21297. };
  21298. constructor.prototype.readBlock = function () {
  21299. function repeat(stream, array, len, offset, what) {
  21300. var repeat = stream.getBits(len) + offset;
  21301. while (repeat-- > 0) {
  21302. array[i++] = what;
  21303. }
  21304. } // read block header
  21305. var hdr = this.getBits(3);
  21306. if (hdr & 1) this.eof = true;
  21307. hdr >>= 1;
  21308. if (hdr == 0) {
  21309. // uncompressed block
  21310. var bytes = this.bytes;
  21311. var bytesPos = this.bytesPos;
  21312. var b;
  21313. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  21314. var blockLen = b;
  21315. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  21316. blockLen |= b << 8;
  21317. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  21318. var check = b;
  21319. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  21320. check |= b << 8;
  21321. if (check != (~blockLen & 0xffff)) error('Bad uncompressed block length in flate stream');
  21322. this.codeBuf = 0;
  21323. this.codeSize = 0;
  21324. var bufferLength = this.bufferLength;
  21325. var buffer = this.ensureBuffer(bufferLength + blockLen);
  21326. var end = bufferLength + blockLen;
  21327. this.bufferLength = end;
  21328. for (var n = bufferLength; n < end; ++n) {
  21329. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  21330. this.eof = true;
  21331. break;
  21332. }
  21333. buffer[n] = b;
  21334. }
  21335. this.bytesPos = bytesPos;
  21336. return;
  21337. }
  21338. var litCodeTable;
  21339. var distCodeTable;
  21340. if (hdr == 1) {
  21341. // compressed block, fixed codes
  21342. litCodeTable = fixedLitCodeTab;
  21343. distCodeTable = fixedDistCodeTab;
  21344. } else if (hdr == 2) {
  21345. // compressed block, dynamic codes
  21346. var numLitCodes = this.getBits(5) + 257;
  21347. var numDistCodes = this.getBits(5) + 1;
  21348. var numCodeLenCodes = this.getBits(4) + 4; // build the code lengths code table
  21349. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  21350. var i = 0;
  21351. while (i < numCodeLenCodes) {
  21352. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  21353. }
  21354. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths); // build the literal and distance code tables
  21355. var len = 0;
  21356. var i = 0;
  21357. var codes = numLitCodes + numDistCodes;
  21358. var codeLengths = new Array(codes);
  21359. while (i < codes) {
  21360. var code = this.getCode(codeLenCodeTab);
  21361. if (code == 16) {
  21362. repeat(this, codeLengths, 2, 3, len);
  21363. } else if (code == 17) {
  21364. repeat(this, codeLengths, 3, 3, len = 0);
  21365. } else if (code == 18) {
  21366. repeat(this, codeLengths, 7, 11, len = 0);
  21367. } else {
  21368. codeLengths[i++] = len = code;
  21369. }
  21370. }
  21371. litCodeTable = this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  21372. distCodeTable = this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  21373. } else {
  21374. error('Unknown block type in flate stream');
  21375. }
  21376. var buffer = this.buffer;
  21377. var limit = buffer ? buffer.length : 0;
  21378. var pos = this.bufferLength;
  21379. while (true) {
  21380. var code1 = this.getCode(litCodeTable);
  21381. if (code1 < 256) {
  21382. if (pos + 1 >= limit) {
  21383. buffer = this.ensureBuffer(pos + 1);
  21384. limit = buffer.length;
  21385. }
  21386. buffer[pos++] = code1;
  21387. continue;
  21388. }
  21389. if (code1 == 256) {
  21390. this.bufferLength = pos;
  21391. return;
  21392. }
  21393. code1 -= 257;
  21394. code1 = lengthDecode[code1];
  21395. var code2 = code1 >> 16;
  21396. if (code2 > 0) code2 = this.getBits(code2);
  21397. var len = (code1 & 0xffff) + code2;
  21398. code1 = this.getCode(distCodeTable);
  21399. code1 = distDecode[code1];
  21400. code2 = code1 >> 16;
  21401. if (code2 > 0) code2 = this.getBits(code2);
  21402. var dist = (code1 & 0xffff) + code2;
  21403. if (pos + len >= limit) {
  21404. buffer = this.ensureBuffer(pos + len);
  21405. limit = buffer.length;
  21406. }
  21407. for (var k = 0; k < len; ++k, ++pos) {
  21408. buffer[pos] = buffer[pos - dist];
  21409. }
  21410. }
  21411. };
  21412. return constructor;
  21413. }();
  21414. /*rollup-keeper-start*/
  21415. window.tmp = FlateStream;
  21416. /*rollup-keeper-end*/
  21417. }));
  21418. try {
  21419. module.exports = jsPDF;
  21420. }
  21421. catch (e) {}