pdf.js 275 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. // Initializing PDFJS global object (if still undefined)
  19. if (typeof PDFJS === 'undefined') {
  20. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  21. }
  22. PDFJS.version = '1.0.229';
  23. PDFJS.build = '7079992';
  24. (function pdfjsWrapper() {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  28. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  29. /* Copyright 2012 Mozilla Foundation
  30. *
  31. * Licensed under the Apache License, Version 2.0 (the "License");
  32. * you may not use this file except in compliance with the License.
  33. * You may obtain a copy of the License at
  34. *
  35. * http://www.apache.org/licenses/LICENSE-2.0
  36. *
  37. * Unless required by applicable law or agreed to in writing, software
  38. * distributed under the License is distributed on an "AS IS" BASIS,
  39. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40. * See the License for the specific language governing permissions and
  41. * limitations under the License.
  42. */
  43. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  44. Promise */
  45. 'use strict';
  46. var globalScope = (typeof window === 'undefined') ? this : window;
  47. var isWorker = (typeof window == 'undefined');
  48. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  49. var TextRenderingMode = {
  50. FILL: 0,
  51. STROKE: 1,
  52. FILL_STROKE: 2,
  53. INVISIBLE: 3,
  54. FILL_ADD_TO_PATH: 4,
  55. STROKE_ADD_TO_PATH: 5,
  56. FILL_STROKE_ADD_TO_PATH: 6,
  57. ADD_TO_PATH: 7,
  58. FILL_STROKE_MASK: 3,
  59. ADD_TO_PATH_FLAG: 4
  60. };
  61. var ImageKind = {
  62. GRAYSCALE_1BPP: 1,
  63. RGB_24BPP: 2,
  64. RGBA_32BPP: 3
  65. };
  66. // The global PDFJS object exposes the API
  67. // In production, it will be declared outside a global wrapper
  68. // In development, it will be declared here
  69. if (!globalScope.PDFJS) {
  70. globalScope.PDFJS = {};
  71. }
  72. globalScope.PDFJS.pdfBug = false;
  73. PDFJS.VERBOSITY_LEVELS = {
  74. errors: 0,
  75. warnings: 1,
  76. infos: 5
  77. };
  78. // All the possible operations for an operator list.
  79. var OPS = PDFJS.OPS = {
  80. // Intentionally start from 1 so it is easy to spot bad operators that will be
  81. // 0's.
  82. dependency: 1,
  83. setLineWidth: 2,
  84. setLineCap: 3,
  85. setLineJoin: 4,
  86. setMiterLimit: 5,
  87. setDash: 6,
  88. setRenderingIntent: 7,
  89. setFlatness: 8,
  90. setGState: 9,
  91. save: 10,
  92. restore: 11,
  93. transform: 12,
  94. moveTo: 13,
  95. lineTo: 14,
  96. curveTo: 15,
  97. curveTo2: 16,
  98. curveTo3: 17,
  99. closePath: 18,
  100. rectangle: 19,
  101. stroke: 20,
  102. closeStroke: 21,
  103. fill: 22,
  104. eoFill: 23,
  105. fillStroke: 24,
  106. eoFillStroke: 25,
  107. closeFillStroke: 26,
  108. closeEOFillStroke: 27,
  109. endPath: 28,
  110. clip: 29,
  111. eoClip: 30,
  112. beginText: 31,
  113. endText: 32,
  114. setCharSpacing: 33,
  115. setWordSpacing: 34,
  116. setHScale: 35,
  117. setLeading: 36,
  118. setFont: 37,
  119. setTextRenderingMode: 38,
  120. setTextRise: 39,
  121. moveText: 40,
  122. setLeadingMoveText: 41,
  123. setTextMatrix: 42,
  124. nextLine: 43,
  125. showText: 44,
  126. showSpacedText: 45,
  127. nextLineShowText: 46,
  128. nextLineSetSpacingShowText: 47,
  129. setCharWidth: 48,
  130. setCharWidthAndBounds: 49,
  131. setStrokeColorSpace: 50,
  132. setFillColorSpace: 51,
  133. setStrokeColor: 52,
  134. setStrokeColorN: 53,
  135. setFillColor: 54,
  136. setFillColorN: 55,
  137. setStrokeGray: 56,
  138. setFillGray: 57,
  139. setStrokeRGBColor: 58,
  140. setFillRGBColor: 59,
  141. setStrokeCMYKColor: 60,
  142. setFillCMYKColor: 61,
  143. shadingFill: 62,
  144. beginInlineImage: 63,
  145. beginImageData: 64,
  146. endInlineImage: 65,
  147. paintXObject: 66,
  148. markPoint: 67,
  149. markPointProps: 68,
  150. beginMarkedContent: 69,
  151. beginMarkedContentProps: 70,
  152. endMarkedContent: 71,
  153. beginCompat: 72,
  154. endCompat: 73,
  155. paintFormXObjectBegin: 74,
  156. paintFormXObjectEnd: 75,
  157. beginGroup: 76,
  158. endGroup: 77,
  159. beginAnnotations: 78,
  160. endAnnotations: 79,
  161. beginAnnotation: 80,
  162. endAnnotation: 81,
  163. paintJpegXObject: 82,
  164. paintImageMaskXObject: 83,
  165. paintImageMaskXObjectGroup: 84,
  166. paintImageXObject: 85,
  167. paintInlineImageXObject: 86,
  168. paintInlineImageXObjectGroup: 87,
  169. paintImageXObjectRepeat: 88,
  170. paintImageMaskXObjectRepeat: 89,
  171. paintSolidColorImageMask: 90,
  172. constructPath: 91
  173. };
  174. // A notice for devs. These are good for things that are helpful to devs, such
  175. // as warning that Workers were disabled, which is important to devs but not
  176. // end users.
  177. function info(msg) {
  178. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  179. console.log('Info: ' + msg);
  180. }
  181. }
  182. // Non-fatal warnings.
  183. function warn(msg) {
  184. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  185. console.log('Warning: ' + msg);
  186. }
  187. }
  188. // Fatal errors that should trigger the fallback UI and halt execution by
  189. // throwing an exception.
  190. function error(msg) {
  191. // If multiple arguments were passed, pass them all to the log function.
  192. if (arguments.length > 1) {
  193. var logArguments = ['Error:'];
  194. logArguments.push.apply(logArguments, arguments);
  195. console.log.apply(console, logArguments);
  196. // Join the arguments into a single string for the lines below.
  197. msg = [].join.call(arguments, ' ');
  198. } else {
  199. console.log('Error: ' + msg);
  200. }
  201. console.log(backtrace());
  202. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  203. throw new Error(msg);
  204. }
  205. function backtrace() {
  206. try {
  207. throw new Error();
  208. } catch (e) {
  209. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  210. }
  211. }
  212. function assert(cond, msg) {
  213. if (!cond) {
  214. error(msg);
  215. }
  216. }
  217. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  218. unknown: 'unknown',
  219. forms: 'forms',
  220. javaScript: 'javaScript',
  221. smask: 'smask',
  222. shadingPattern: 'shadingPattern',
  223. font: 'font'
  224. };
  225. var UnsupportedManager = PDFJS.UnsupportedManager =
  226. (function UnsupportedManagerClosure() {
  227. var listeners = [];
  228. return {
  229. listen: function (cb) {
  230. listeners.push(cb);
  231. },
  232. notify: function (featureId) {
  233. warn('Unsupported feature "' + featureId + '"');
  234. for (var i = 0, ii = listeners.length; i < ii; i++) {
  235. listeners[i](featureId);
  236. }
  237. }
  238. };
  239. })();
  240. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  241. // absolute URL, it will be returned as is.
  242. function combineUrl(baseUrl, url) {
  243. if (!url) {
  244. return baseUrl;
  245. }
  246. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  247. return url;
  248. }
  249. var i;
  250. if (url.charAt(0) == '/') {
  251. // absolute path
  252. i = baseUrl.indexOf('://');
  253. if (url.charAt(1) === '/') {
  254. ++i;
  255. } else {
  256. i = baseUrl.indexOf('/', i + 3);
  257. }
  258. return baseUrl.substring(0, i) + url;
  259. } else {
  260. // relative path
  261. var pathLength = baseUrl.length;
  262. i = baseUrl.lastIndexOf('#');
  263. pathLength = i >= 0 ? i : pathLength;
  264. i = baseUrl.lastIndexOf('?', pathLength);
  265. pathLength = i >= 0 ? i : pathLength;
  266. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  267. return baseUrl.substring(0, prefixLength + 1) + url;
  268. }
  269. }
  270. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  271. function isValidUrl(url, allowRelative) {
  272. if (!url) {
  273. return false;
  274. }
  275. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  276. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  277. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  278. if (!protocol) {
  279. return allowRelative;
  280. }
  281. protocol = protocol[0].toLowerCase();
  282. switch (protocol) {
  283. case 'http':
  284. case 'https':
  285. case 'ftp':
  286. case 'mailto':
  287. return true;
  288. default:
  289. return false;
  290. }
  291. }
  292. PDFJS.isValidUrl = isValidUrl;
  293. function shadow(obj, prop, value) {
  294. Object.defineProperty(obj, prop, { value: value,
  295. enumerable: true,
  296. configurable: true,
  297. writable: false });
  298. return value;
  299. }
  300. var PasswordResponses = PDFJS.PasswordResponses = {
  301. NEED_PASSWORD: 1,
  302. INCORRECT_PASSWORD: 2
  303. };
  304. var PasswordException = (function PasswordExceptionClosure() {
  305. function PasswordException(msg, code) {
  306. this.name = 'PasswordException';
  307. this.message = msg;
  308. this.code = code;
  309. }
  310. PasswordException.prototype = new Error();
  311. PasswordException.constructor = PasswordException;
  312. return PasswordException;
  313. })();
  314. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  315. function UnknownErrorException(msg, details) {
  316. this.name = 'UnknownErrorException';
  317. this.message = msg;
  318. this.details = details;
  319. }
  320. UnknownErrorException.prototype = new Error();
  321. UnknownErrorException.constructor = UnknownErrorException;
  322. return UnknownErrorException;
  323. })();
  324. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  325. function InvalidPDFException(msg) {
  326. this.name = 'InvalidPDFException';
  327. this.message = msg;
  328. }
  329. InvalidPDFException.prototype = new Error();
  330. InvalidPDFException.constructor = InvalidPDFException;
  331. return InvalidPDFException;
  332. })();
  333. var MissingPDFException = (function MissingPDFExceptionClosure() {
  334. function MissingPDFException(msg) {
  335. this.name = 'MissingPDFException';
  336. this.message = msg;
  337. }
  338. MissingPDFException.prototype = new Error();
  339. MissingPDFException.constructor = MissingPDFException;
  340. return MissingPDFException;
  341. })();
  342. var NotImplementedException = (function NotImplementedExceptionClosure() {
  343. function NotImplementedException(msg) {
  344. this.message = msg;
  345. }
  346. NotImplementedException.prototype = new Error();
  347. NotImplementedException.prototype.name = 'NotImplementedException';
  348. NotImplementedException.constructor = NotImplementedException;
  349. return NotImplementedException;
  350. })();
  351. var MissingDataException = (function MissingDataExceptionClosure() {
  352. function MissingDataException(begin, end) {
  353. this.begin = begin;
  354. this.end = end;
  355. this.message = 'Missing data [' + begin + ', ' + end + ')';
  356. }
  357. MissingDataException.prototype = new Error();
  358. MissingDataException.prototype.name = 'MissingDataException';
  359. MissingDataException.constructor = MissingDataException;
  360. return MissingDataException;
  361. })();
  362. var XRefParseException = (function XRefParseExceptionClosure() {
  363. function XRefParseException(msg) {
  364. this.message = msg;
  365. }
  366. XRefParseException.prototype = new Error();
  367. XRefParseException.prototype.name = 'XRefParseException';
  368. XRefParseException.constructor = XRefParseException;
  369. return XRefParseException;
  370. })();
  371. function bytesToString(bytes) {
  372. var length = bytes.length;
  373. var MAX_ARGUMENT_COUNT = 8192;
  374. if (length < MAX_ARGUMENT_COUNT) {
  375. return String.fromCharCode.apply(null, bytes);
  376. }
  377. var strBuf = [];
  378. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  379. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  380. var chunk = bytes.subarray(i, chunkEnd);
  381. strBuf.push(String.fromCharCode.apply(null, chunk));
  382. }
  383. return strBuf.join('');
  384. }
  385. function stringToArray(str) {
  386. var length = str.length;
  387. var array = [];
  388. for (var i = 0; i < length; ++i) {
  389. array[i] = str.charCodeAt(i);
  390. }
  391. return array;
  392. }
  393. function stringToBytes(str) {
  394. var length = str.length;
  395. var bytes = new Uint8Array(length);
  396. for (var i = 0; i < length; ++i) {
  397. bytes[i] = str.charCodeAt(i) & 0xFF;
  398. }
  399. return bytes;
  400. }
  401. function string32(value) {
  402. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  403. (value >> 8) & 0xff, value & 0xff);
  404. }
  405. function log2(x) {
  406. var n = 1, i = 0;
  407. while (x > n) {
  408. n <<= 1;
  409. i++;
  410. }
  411. return i;
  412. }
  413. function readInt8(data, start) {
  414. return (data[start] << 24) >> 24;
  415. }
  416. function readUint16(data, offset) {
  417. return (data[offset] << 8) | data[offset + 1];
  418. }
  419. function readUint32(data, offset) {
  420. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  421. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  422. }
  423. // Lazy test the endianness of the platform
  424. // NOTE: This will be 'true' for simulated TypedArrays
  425. function isLittleEndian() {
  426. var buffer8 = new Uint8Array(2);
  427. buffer8[0] = 1;
  428. var buffer16 = new Uint16Array(buffer8.buffer);
  429. return (buffer16[0] === 1);
  430. }
  431. Object.defineProperty(PDFJS, 'isLittleEndian', {
  432. configurable: true,
  433. get: function PDFJS_isLittleEndian() {
  434. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  435. }
  436. });
  437. // Lazy test if the userAgant support CanvasTypedArrays
  438. function hasCanvasTypedArrays() {
  439. var canvas = document.createElement('canvas');
  440. canvas.width = canvas.height = 1;
  441. var ctx = canvas.getContext('2d');
  442. var imageData = ctx.createImageData(1, 1);
  443. return (typeof imageData.data.buffer !== 'undefined');
  444. }
  445. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  446. configurable: true,
  447. get: function PDFJS_hasCanvasTypedArrays() {
  448. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  449. }
  450. });
  451. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  452. function Uint32ArrayView(buffer, length) {
  453. this.buffer = buffer;
  454. this.byteLength = buffer.length;
  455. this.length = length === undefined ? (this.byteLength >> 2) : length;
  456. ensureUint32ArrayViewProps(this.length);
  457. }
  458. Uint32ArrayView.prototype = Object.create(null);
  459. var uint32ArrayViewSetters = 0;
  460. function createUint32ArrayProp(index) {
  461. return {
  462. get: function () {
  463. var buffer = this.buffer, offset = index << 2;
  464. return (buffer[offset] | (buffer[offset + 1] << 8) |
  465. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  466. },
  467. set: function (value) {
  468. var buffer = this.buffer, offset = index << 2;
  469. buffer[offset] = value & 255;
  470. buffer[offset + 1] = (value >> 8) & 255;
  471. buffer[offset + 2] = (value >> 16) & 255;
  472. buffer[offset + 3] = (value >>> 24) & 255;
  473. }
  474. };
  475. }
  476. function ensureUint32ArrayViewProps(length) {
  477. while (uint32ArrayViewSetters < length) {
  478. Object.defineProperty(Uint32ArrayView.prototype,
  479. uint32ArrayViewSetters,
  480. createUint32ArrayProp(uint32ArrayViewSetters));
  481. uint32ArrayViewSetters++;
  482. }
  483. }
  484. return Uint32ArrayView;
  485. })();
  486. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  487. var Util = PDFJS.Util = (function UtilClosure() {
  488. function Util() {}
  489. Util.makeCssRgb = function Util_makeCssRgb(rgb) {
  490. return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  491. };
  492. Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) {
  493. var rgb = ColorSpace.singletons.cmyk.getRgb(cmyk, 0);
  494. return Util.makeCssRgb(rgb);
  495. };
  496. // Concatenates two transformation matrices together and returns the result.
  497. Util.transform = function Util_transform(m1, m2) {
  498. return [
  499. m1[0] * m2[0] + m1[2] * m2[1],
  500. m1[1] * m2[0] + m1[3] * m2[1],
  501. m1[0] * m2[2] + m1[2] * m2[3],
  502. m1[1] * m2[2] + m1[3] * m2[3],
  503. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  504. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  505. ];
  506. };
  507. // For 2d affine transforms
  508. Util.applyTransform = function Util_applyTransform(p, m) {
  509. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  510. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  511. return [xt, yt];
  512. };
  513. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  514. var d = m[0] * m[3] - m[1] * m[2];
  515. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  516. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  517. return [xt, yt];
  518. };
  519. // Applies the transform to the rectangle and finds the minimum axially
  520. // aligned bounding box.
  521. Util.getAxialAlignedBoundingBox =
  522. function Util_getAxialAlignedBoundingBox(r, m) {
  523. var p1 = Util.applyTransform(r, m);
  524. var p2 = Util.applyTransform(r.slice(2, 4), m);
  525. var p3 = Util.applyTransform([r[0], r[3]], m);
  526. var p4 = Util.applyTransform([r[2], r[1]], m);
  527. return [
  528. Math.min(p1[0], p2[0], p3[0], p4[0]),
  529. Math.min(p1[1], p2[1], p3[1], p4[1]),
  530. Math.max(p1[0], p2[0], p3[0], p4[0]),
  531. Math.max(p1[1], p2[1], p3[1], p4[1])
  532. ];
  533. };
  534. Util.inverseTransform = function Util_inverseTransform(m) {
  535. var d = m[0] * m[3] - m[1] * m[2];
  536. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  537. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  538. };
  539. // Apply a generic 3d matrix M on a 3-vector v:
  540. // | a b c | | X |
  541. // | d e f | x | Y |
  542. // | g h i | | Z |
  543. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  544. // with v as [X,Y,Z]
  545. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  546. return [
  547. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  548. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  549. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  550. ];
  551. };
  552. // This calculation uses Singular Value Decomposition.
  553. // The SVD can be represented with formula A = USV. We are interested in the
  554. // matrix S here because it represents the scale values.
  555. Util.singularValueDecompose2dScale =
  556. function Util_singularValueDecompose2dScale(m) {
  557. var transpose = [m[0], m[2], m[1], m[3]];
  558. // Multiply matrix m with its transpose.
  559. var a = m[0] * transpose[0] + m[1] * transpose[2];
  560. var b = m[0] * transpose[1] + m[1] * transpose[3];
  561. var c = m[2] * transpose[0] + m[3] * transpose[2];
  562. var d = m[2] * transpose[1] + m[3] * transpose[3];
  563. // Solve the second degree polynomial to get roots.
  564. var first = (a + d) / 2;
  565. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  566. var sx = first + second || 1;
  567. var sy = first - second || 1;
  568. // Scale values are the square roots of the eigenvalues.
  569. return [Math.sqrt(sx), Math.sqrt(sy)];
  570. };
  571. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  572. // For coordinate systems whose origin lies in the bottom-left, this
  573. // means normalization to (BL,TR) ordering. For systems with origin in the
  574. // top-left, this means (TL,BR) ordering.
  575. Util.normalizeRect = function Util_normalizeRect(rect) {
  576. var r = rect.slice(0); // clone rect
  577. if (rect[0] > rect[2]) {
  578. r[0] = rect[2];
  579. r[2] = rect[0];
  580. }
  581. if (rect[1] > rect[3]) {
  582. r[1] = rect[3];
  583. r[3] = rect[1];
  584. }
  585. return r;
  586. };
  587. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  588. // intersection of rect1 and rect2. If no intersection, returns 'false'
  589. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  590. Util.intersect = function Util_intersect(rect1, rect2) {
  591. function compare(a, b) {
  592. return a - b;
  593. }
  594. // Order points along the axes
  595. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  596. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  597. result = [];
  598. rect1 = Util.normalizeRect(rect1);
  599. rect2 = Util.normalizeRect(rect2);
  600. // X: first and second points belong to different rectangles?
  601. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  602. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  603. // Intersection must be between second and third points
  604. result[0] = orderedX[1];
  605. result[2] = orderedX[2];
  606. } else {
  607. return false;
  608. }
  609. // Y: first and second points belong to different rectangles?
  610. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  611. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  612. // Intersection must be between second and third points
  613. result[1] = orderedY[1];
  614. result[3] = orderedY[2];
  615. } else {
  616. return false;
  617. }
  618. return result;
  619. };
  620. Util.sign = function Util_sign(num) {
  621. return num < 0 ? -1 : 1;
  622. };
  623. // TODO(mack): Rename appendToArray
  624. Util.concatenateToArray = function concatenateToArray(arr1, arr2) {
  625. Array.prototype.push.apply(arr1, arr2);
  626. };
  627. Util.prependToArray = function concatenateToArray(arr1, arr2) {
  628. Array.prototype.unshift.apply(arr1, arr2);
  629. };
  630. Util.extendObj = function extendObj(obj1, obj2) {
  631. for (var key in obj2) {
  632. obj1[key] = obj2[key];
  633. }
  634. };
  635. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  636. name) {
  637. while (dict && !dict.has(name)) {
  638. dict = dict.get('Parent');
  639. }
  640. if (!dict) {
  641. return null;
  642. }
  643. return dict.get(name);
  644. };
  645. Util.inherit = function Util_inherit(sub, base, prototype) {
  646. sub.prototype = Object.create(base.prototype);
  647. sub.prototype.constructor = sub;
  648. for (var prop in prototype) {
  649. sub.prototype[prop] = prototype[prop];
  650. }
  651. };
  652. Util.loadScript = function Util_loadScript(src, callback) {
  653. var script = document.createElement('script');
  654. var loaded = false;
  655. script.setAttribute('src', src);
  656. if (callback) {
  657. script.onload = function() {
  658. if (!loaded) {
  659. callback();
  660. }
  661. loaded = true;
  662. };
  663. }
  664. document.getElementsByTagName('head')[0].appendChild(script);
  665. };
  666. return Util;
  667. })();
  668. /**
  669. * PDF page viewport created based on scale, rotation and offset.
  670. * @class
  671. * @alias PDFJS.PageViewport
  672. */
  673. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  674. /**
  675. * @constructor
  676. * @private
  677. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  678. * @param scale {number} scale of the viewport.
  679. * @param rotation {number} rotations of the viewport in degrees.
  680. * @param offsetX {number} offset X
  681. * @param offsetY {number} offset Y
  682. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  683. */
  684. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  685. this.viewBox = viewBox;
  686. this.scale = scale;
  687. this.rotation = rotation;
  688. this.offsetX = offsetX;
  689. this.offsetY = offsetY;
  690. // creating transform to convert pdf coordinate system to the normal
  691. // canvas like coordinates taking in account scale and rotation
  692. var centerX = (viewBox[2] + viewBox[0]) / 2;
  693. var centerY = (viewBox[3] + viewBox[1]) / 2;
  694. var rotateA, rotateB, rotateC, rotateD;
  695. rotation = rotation % 360;
  696. rotation = rotation < 0 ? rotation + 360 : rotation;
  697. switch (rotation) {
  698. case 180:
  699. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  700. break;
  701. case 90:
  702. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  703. break;
  704. case 270:
  705. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  706. break;
  707. //case 0:
  708. default:
  709. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  710. break;
  711. }
  712. if (dontFlip) {
  713. rotateC = -rotateC; rotateD = -rotateD;
  714. }
  715. var offsetCanvasX, offsetCanvasY;
  716. var width, height;
  717. if (rotateA === 0) {
  718. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  719. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  720. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  721. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  722. } else {
  723. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  724. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  725. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  726. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  727. }
  728. // creating transform for the following operations:
  729. // translate(-centerX, -centerY), rotate and flip vertically,
  730. // scale, and translate(offsetCanvasX, offsetCanvasY)
  731. this.transform = [
  732. rotateA * scale,
  733. rotateB * scale,
  734. rotateC * scale,
  735. rotateD * scale,
  736. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  737. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  738. ];
  739. this.width = width;
  740. this.height = height;
  741. this.fontScale = scale;
  742. }
  743. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  744. /**
  745. * Clones viewport with additional properties.
  746. * @param args {Object} (optional) If specified, may contain the 'scale' or
  747. * 'rotation' properties to override the corresponding properties in
  748. * the cloned viewport.
  749. * @returns {PDFJS.PageViewport} Cloned viewport.
  750. */
  751. clone: function PageViewPort_clone(args) {
  752. args = args || {};
  753. var scale = 'scale' in args ? args.scale : this.scale;
  754. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  755. return new PageViewport(this.viewBox.slice(), scale, rotation,
  756. this.offsetX, this.offsetY, args.dontFlip);
  757. },
  758. /**
  759. * Converts PDF point to the viewport coordinates. For examples, useful for
  760. * converting PDF location into canvas pixel coordinates.
  761. * @param x {number} X coordinate.
  762. * @param y {number} Y coordinate.
  763. * @returns {Object} Object that contains 'x' and 'y' properties of the
  764. * point in the viewport coordinate space.
  765. * @see {@link convertToPdfPoint}
  766. * @see {@link convertToViewportRectangle}
  767. */
  768. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  769. return Util.applyTransform([x, y], this.transform);
  770. },
  771. /**
  772. * Converts PDF rectangle to the viewport coordinates.
  773. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  774. * @returns {Array} Contains corresponding coordinates of the rectangle
  775. * in the viewport coordinate space.
  776. * @see {@link convertToViewportPoint}
  777. */
  778. convertToViewportRectangle:
  779. function PageViewport_convertToViewportRectangle(rect) {
  780. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  781. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  782. return [tl[0], tl[1], br[0], br[1]];
  783. },
  784. /**
  785. * Converts viewport coordinates to the PDF location. For examples, useful
  786. * for converting canvas pixel location into PDF one.
  787. * @param x {number} X coordinate.
  788. * @param y {number} Y coordinate.
  789. * @returns {Object} Object that contains 'x' and 'y' properties of the
  790. * point in the PDF coordinate space.
  791. * @see {@link convertToViewportPoint}
  792. */
  793. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  794. return Util.applyInverseTransform([x, y], this.transform);
  795. }
  796. };
  797. return PageViewport;
  798. })();
  799. var PDFStringTranslateTable = [
  800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  801. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  806. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  807. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  808. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  809. ];
  810. function stringToPDFString(str) {
  811. var i, n = str.length, strBuf = [];
  812. if (str[0] === '\xFE' && str[1] === '\xFF') {
  813. // UTF16BE BOM
  814. for (i = 2; i < n; i += 2) {
  815. strBuf.push(String.fromCharCode(
  816. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  817. }
  818. } else {
  819. for (i = 0; i < n; ++i) {
  820. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  821. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  822. }
  823. }
  824. return strBuf.join('');
  825. }
  826. function stringToUTF8String(str) {
  827. return decodeURIComponent(escape(str));
  828. }
  829. function isEmptyObj(obj) {
  830. for (var key in obj) {
  831. return false;
  832. }
  833. return true;
  834. }
  835. function isBool(v) {
  836. return typeof v == 'boolean';
  837. }
  838. function isInt(v) {
  839. return typeof v == 'number' && ((v | 0) == v);
  840. }
  841. function isNum(v) {
  842. return typeof v == 'number';
  843. }
  844. function isString(v) {
  845. return typeof v == 'string';
  846. }
  847. function isNull(v) {
  848. return v === null;
  849. }
  850. function isName(v) {
  851. return v instanceof Name;
  852. }
  853. function isCmd(v, cmd) {
  854. return v instanceof Cmd && (!cmd || v.cmd == cmd);
  855. }
  856. function isDict(v, type) {
  857. if (!(v instanceof Dict)) {
  858. return false;
  859. }
  860. if (!type) {
  861. return true;
  862. }
  863. var dictType = v.get('Type');
  864. return isName(dictType) && dictType.name == type;
  865. }
  866. function isArray(v) {
  867. return v instanceof Array;
  868. }
  869. function isStream(v) {
  870. return typeof v == 'object' && v !== null && v !== undefined &&
  871. ('getBytes' in v);
  872. }
  873. function isArrayBuffer(v) {
  874. return typeof v == 'object' && v !== null && v !== undefined &&
  875. ('byteLength' in v);
  876. }
  877. function isRef(v) {
  878. return v instanceof Ref;
  879. }
  880. function isPDFFunction(v) {
  881. var fnDict;
  882. if (typeof v != 'object') {
  883. return false;
  884. } else if (isDict(v)) {
  885. fnDict = v;
  886. } else if (isStream(v)) {
  887. fnDict = v.dict;
  888. } else {
  889. return false;
  890. }
  891. return fnDict.has('FunctionType');
  892. }
  893. /**
  894. * Promise Capability object.
  895. *
  896. * @typedef {Object} PromiseCapability
  897. * @property {Promise} promise - A promise object.
  898. * @property {function} resolve - Fullfills the promise.
  899. * @property {function} reject - Rejects the promise.
  900. */
  901. /**
  902. * Creates a promise capability object.
  903. * @alias PDFJS.createPromiseCapability
  904. *
  905. * @return {PromiseCapability} A capability object contains:
  906. * - a Promise, resolve and reject methods.
  907. */
  908. function createPromiseCapability() {
  909. var capability = {};
  910. capability.promise = new Promise(function (resolve, reject) {
  911. capability.resolve = resolve;
  912. capability.reject = reject;
  913. });
  914. return capability;
  915. }
  916. PDFJS.createPromiseCapability = createPromiseCapability;
  917. /**
  918. * Polyfill for Promises:
  919. * The following promise implementation tries to generally implment the
  920. * Promise/A+ spec. Some notable differences from other promise libaries are:
  921. * - There currently isn't a seperate deferred and promise object.
  922. * - Unhandled rejections eventually show an error if they aren't handled.
  923. *
  924. * Based off of the work in:
  925. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  926. */
  927. (function PromiseClosure() {
  928. if (globalScope.Promise) {
  929. // Promises existing in the DOM/Worker, checking presence of all/resolve
  930. if (typeof globalScope.Promise.all !== 'function') {
  931. globalScope.Promise.all = function (iterable) {
  932. var count = 0, results = [], resolve, reject;
  933. var promise = new globalScope.Promise(function (resolve_, reject_) {
  934. resolve = resolve_;
  935. reject = reject_;
  936. });
  937. iterable.forEach(function (p, i) {
  938. count++;
  939. p.then(function (result) {
  940. results[i] = result;
  941. count--;
  942. if (count === 0) {
  943. resolve(results);
  944. }
  945. }, reject);
  946. });
  947. if (count === 0) {
  948. resolve(results);
  949. }
  950. return promise;
  951. };
  952. }
  953. if (typeof globalScope.Promise.resolve !== 'function') {
  954. globalScope.Promise.resolve = function (value) {
  955. return new globalScope.Promise(function (resolve) { resolve(value); });
  956. };
  957. }
  958. if (typeof globalScope.Promise.reject !== 'function') {
  959. globalScope.Promise.reject = function (reason) {
  960. return new globalScope.Promise(function (resolve, reject) {
  961. reject(reason);
  962. });
  963. };
  964. }
  965. return;
  966. }
  967. var STATUS_PENDING = 0;
  968. var STATUS_RESOLVED = 1;
  969. var STATUS_REJECTED = 2;
  970. // In an attempt to avoid silent exceptions, unhandled rejections are
  971. // tracked and if they aren't handled in a certain amount of time an
  972. // error is logged.
  973. var REJECTION_TIMEOUT = 500;
  974. var HandlerManager = {
  975. handlers: [],
  976. running: false,
  977. unhandledRejections: [],
  978. pendingRejectionCheck: false,
  979. scheduleHandlers: function scheduleHandlers(promise) {
  980. if (promise._status == STATUS_PENDING) {
  981. return;
  982. }
  983. this.handlers = this.handlers.concat(promise._handlers);
  984. promise._handlers = [];
  985. if (this.running) {
  986. return;
  987. }
  988. this.running = true;
  989. setTimeout(this.runHandlers.bind(this), 0);
  990. },
  991. runHandlers: function runHandlers() {
  992. var RUN_TIMEOUT = 1; // ms
  993. var timeoutAt = Date.now() + RUN_TIMEOUT;
  994. while (this.handlers.length > 0) {
  995. var handler = this.handlers.shift();
  996. var nextStatus = handler.thisPromise._status;
  997. var nextValue = handler.thisPromise._value;
  998. try {
  999. if (nextStatus === STATUS_RESOLVED) {
  1000. if (typeof(handler.onResolve) == 'function') {
  1001. nextValue = handler.onResolve(nextValue);
  1002. }
  1003. } else if (typeof(handler.onReject) === 'function') {
  1004. nextValue = handler.onReject(nextValue);
  1005. nextStatus = STATUS_RESOLVED;
  1006. if (handler.thisPromise._unhandledRejection) {
  1007. this.removeUnhandeledRejection(handler.thisPromise);
  1008. }
  1009. }
  1010. } catch (ex) {
  1011. nextStatus = STATUS_REJECTED;
  1012. nextValue = ex;
  1013. }
  1014. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1015. if (Date.now() >= timeoutAt) {
  1016. break;
  1017. }
  1018. }
  1019. if (this.handlers.length > 0) {
  1020. setTimeout(this.runHandlers.bind(this), 0);
  1021. return;
  1022. }
  1023. this.running = false;
  1024. },
  1025. addUnhandledRejection: function addUnhandledRejection(promise) {
  1026. this.unhandledRejections.push({
  1027. promise: promise,
  1028. time: Date.now()
  1029. });
  1030. this.scheduleRejectionCheck();
  1031. },
  1032. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1033. promise._unhandledRejection = false;
  1034. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1035. if (this.unhandledRejections[i].promise === promise) {
  1036. this.unhandledRejections.splice(i);
  1037. i--;
  1038. }
  1039. }
  1040. },
  1041. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1042. if (this.pendingRejectionCheck) {
  1043. return;
  1044. }
  1045. this.pendingRejectionCheck = true;
  1046. setTimeout(function rejectionCheck() {
  1047. this.pendingRejectionCheck = false;
  1048. var now = Date.now();
  1049. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1050. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1051. var unhandled = this.unhandledRejections[i].promise._value;
  1052. var msg = 'Unhandled rejection: ' + unhandled;
  1053. if (unhandled.stack) {
  1054. msg += '\n' + unhandled.stack;
  1055. }
  1056. warn(msg);
  1057. this.unhandledRejections.splice(i);
  1058. i--;
  1059. }
  1060. }
  1061. if (this.unhandledRejections.length) {
  1062. this.scheduleRejectionCheck();
  1063. }
  1064. }.bind(this), REJECTION_TIMEOUT);
  1065. }
  1066. };
  1067. function Promise(resolver) {
  1068. this._status = STATUS_PENDING;
  1069. this._handlers = [];
  1070. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1071. }
  1072. /**
  1073. * Builds a promise that is resolved when all the passed in promises are
  1074. * resolved.
  1075. * @param {array} array of data and/or promises to wait for.
  1076. * @return {Promise} New dependant promise.
  1077. */
  1078. Promise.all = function Promise_all(promises) {
  1079. var resolveAll, rejectAll;
  1080. var deferred = new Promise(function (resolve, reject) {
  1081. resolveAll = resolve;
  1082. rejectAll = reject;
  1083. });
  1084. var unresolved = promises.length;
  1085. var results = [];
  1086. if (unresolved === 0) {
  1087. resolveAll(results);
  1088. return deferred;
  1089. }
  1090. function reject(reason) {
  1091. if (deferred._status === STATUS_REJECTED) {
  1092. return;
  1093. }
  1094. results = [];
  1095. rejectAll(reason);
  1096. }
  1097. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1098. var promise = promises[i];
  1099. var resolve = (function(i) {
  1100. return function(value) {
  1101. if (deferred._status === STATUS_REJECTED) {
  1102. return;
  1103. }
  1104. results[i] = value;
  1105. unresolved--;
  1106. if (unresolved === 0) {
  1107. resolveAll(results);
  1108. }
  1109. };
  1110. })(i);
  1111. if (Promise.isPromise(promise)) {
  1112. promise.then(resolve, reject);
  1113. } else {
  1114. resolve(promise);
  1115. }
  1116. }
  1117. return deferred;
  1118. };
  1119. /**
  1120. * Checks if the value is likely a promise (has a 'then' function).
  1121. * @return {boolean} true if value is thenable
  1122. */
  1123. Promise.isPromise = function Promise_isPromise(value) {
  1124. return value && typeof value.then === 'function';
  1125. };
  1126. /**
  1127. * Creates resolved promise
  1128. * @param value resolve value
  1129. * @returns {Promise}
  1130. */
  1131. Promise.resolve = function Promise_resolve(value) {
  1132. return new Promise(function (resolve) { resolve(value); });
  1133. };
  1134. /**
  1135. * Creates rejected promise
  1136. * @param reason rejection value
  1137. * @returns {Promise}
  1138. */
  1139. Promise.reject = function Promise_reject(reason) {
  1140. return new Promise(function (resolve, reject) { reject(reason); });
  1141. };
  1142. Promise.prototype = {
  1143. _status: null,
  1144. _value: null,
  1145. _handlers: null,
  1146. _unhandledRejection: null,
  1147. _updateStatus: function Promise__updateStatus(status, value) {
  1148. if (this._status === STATUS_RESOLVED ||
  1149. this._status === STATUS_REJECTED) {
  1150. return;
  1151. }
  1152. if (status == STATUS_RESOLVED &&
  1153. Promise.isPromise(value)) {
  1154. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1155. this._updateStatus.bind(this, STATUS_REJECTED));
  1156. return;
  1157. }
  1158. this._status = status;
  1159. this._value = value;
  1160. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1161. this._unhandledRejection = true;
  1162. HandlerManager.addUnhandledRejection(this);
  1163. }
  1164. HandlerManager.scheduleHandlers(this);
  1165. },
  1166. _resolve: function Promise_resolve(value) {
  1167. this._updateStatus(STATUS_RESOLVED, value);
  1168. },
  1169. _reject: function Promise_reject(reason) {
  1170. this._updateStatus(STATUS_REJECTED, reason);
  1171. },
  1172. then: function Promise_then(onResolve, onReject) {
  1173. var nextPromise = new Promise(function (resolve, reject) {
  1174. this.resolve = reject;
  1175. this.reject = reject;
  1176. });
  1177. this._handlers.push({
  1178. thisPromise: this,
  1179. onResolve: onResolve,
  1180. onReject: onReject,
  1181. nextPromise: nextPromise
  1182. });
  1183. HandlerManager.scheduleHandlers(this);
  1184. return nextPromise;
  1185. }
  1186. };
  1187. globalScope.Promise = Promise;
  1188. })();
  1189. var StatTimer = (function StatTimerClosure() {
  1190. function rpad(str, pad, length) {
  1191. while (str.length < length) {
  1192. str += pad;
  1193. }
  1194. return str;
  1195. }
  1196. function StatTimer() {
  1197. this.started = {};
  1198. this.times = [];
  1199. this.enabled = true;
  1200. }
  1201. StatTimer.prototype = {
  1202. time: function StatTimer_time(name) {
  1203. if (!this.enabled) {
  1204. return;
  1205. }
  1206. if (name in this.started) {
  1207. warn('Timer is already running for ' + name);
  1208. }
  1209. this.started[name] = Date.now();
  1210. },
  1211. timeEnd: function StatTimer_timeEnd(name) {
  1212. if (!this.enabled) {
  1213. return;
  1214. }
  1215. if (!(name in this.started)) {
  1216. warn('Timer has not been started for ' + name);
  1217. }
  1218. this.times.push({
  1219. 'name': name,
  1220. 'start': this.started[name],
  1221. 'end': Date.now()
  1222. });
  1223. // Remove timer from started so it can be called again.
  1224. delete this.started[name];
  1225. },
  1226. toString: function StatTimer_toString() {
  1227. var i, ii;
  1228. var times = this.times;
  1229. var out = '';
  1230. // Find the longest name for padding purposes.
  1231. var longest = 0;
  1232. for (i = 0, ii = times.length; i < ii; ++i) {
  1233. var name = times[i]['name'];
  1234. if (name.length > longest) {
  1235. longest = name.length;
  1236. }
  1237. }
  1238. for (i = 0, ii = times.length; i < ii; ++i) {
  1239. var span = times[i];
  1240. var duration = span.end - span.start;
  1241. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1242. }
  1243. return out;
  1244. }
  1245. };
  1246. return StatTimer;
  1247. })();
  1248. PDFJS.createBlob = function createBlob(data, contentType) {
  1249. if (typeof Blob !== 'undefined') {
  1250. return new Blob([data], { type: contentType });
  1251. }
  1252. // Blob builder is deprecated in FF14 and removed in FF18.
  1253. var bb = new MozBlobBuilder();
  1254. bb.append(data);
  1255. return bb.getBlob(contentType);
  1256. };
  1257. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1258. // Blob/createObjectURL is not available, falling back to data schema.
  1259. var digits =
  1260. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1261. return function createObjectURL(data, contentType) {
  1262. if (!PDFJS.disableCreateObjectURL &&
  1263. typeof URL !== 'undefined' && URL.createObjectURL) {
  1264. var blob = PDFJS.createBlob(data, contentType);
  1265. return URL.createObjectURL(blob);
  1266. }
  1267. var buffer = 'data:' + contentType + ';base64,';
  1268. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1269. var b1 = data[i] & 0xFF;
  1270. var b2 = data[i + 1] & 0xFF;
  1271. var b3 = data[i + 2] & 0xFF;
  1272. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1273. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1274. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1275. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1276. }
  1277. return buffer;
  1278. };
  1279. })();
  1280. function MessageHandler(name, comObj) {
  1281. this.name = name;
  1282. this.comObj = comObj;
  1283. this.callbackIndex = 1;
  1284. this.postMessageTransfers = true;
  1285. var callbacksCapabilities = this.callbacksCapabilities = {};
  1286. var ah = this.actionHandler = {};
  1287. ah['console_log'] = [function ahConsoleLog(data) {
  1288. console.log.apply(console, data);
  1289. }];
  1290. ah['console_error'] = [function ahConsoleError(data) {
  1291. console.error.apply(console, data);
  1292. }];
  1293. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1294. UnsupportedManager.notify(data);
  1295. }];
  1296. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1297. var data = event.data;
  1298. if (data.isReply) {
  1299. var callbackId = data.callbackId;
  1300. if (data.callbackId in callbacksCapabilities) {
  1301. var callback = callbacksCapabilities[callbackId];
  1302. delete callbacksCapabilities[callbackId];
  1303. if ('error' in data) {
  1304. callback.reject(data.error);
  1305. } else {
  1306. callback.resolve(data.data);
  1307. }
  1308. } else {
  1309. error('Cannot resolve callback ' + callbackId);
  1310. }
  1311. } else if (data.action in ah) {
  1312. var action = ah[data.action];
  1313. if (data.callbackId) {
  1314. Promise.resolve().then(function () {
  1315. return action[0].call(action[1], data.data);
  1316. }).then(function (result) {
  1317. comObj.postMessage({
  1318. isReply: true,
  1319. callbackId: data.callbackId,
  1320. data: result
  1321. });
  1322. }, function (reason) {
  1323. comObj.postMessage({
  1324. isReply: true,
  1325. callbackId: data.callbackId,
  1326. error: reason
  1327. });
  1328. });
  1329. } else {
  1330. action[0].call(action[1], data.data);
  1331. }
  1332. } else {
  1333. error('Unknown action from worker: ' + data.action);
  1334. }
  1335. };
  1336. }
  1337. MessageHandler.prototype = {
  1338. on: function messageHandlerOn(actionName, handler, scope) {
  1339. var ah = this.actionHandler;
  1340. if (ah[actionName]) {
  1341. error('There is already an actionName called "' + actionName + '"');
  1342. }
  1343. ah[actionName] = [handler, scope];
  1344. },
  1345. /**
  1346. * Sends a message to the comObj to invoke the action with the supplied data.
  1347. * @param {String} actionName Action to call.
  1348. * @param {JSON} data JSON data to send.
  1349. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1350. */
  1351. send: function messageHandlerSend(actionName, data, transfers) {
  1352. var message = {
  1353. action: actionName,
  1354. data: data
  1355. };
  1356. this.postMessage(message, transfers);
  1357. },
  1358. /**
  1359. * Sends a message to the comObj to invoke the action with the supplied data.
  1360. * Expects that other side will callback with the response.
  1361. * @param {String} actionName Action to call.
  1362. * @param {JSON} data JSON data to send.
  1363. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1364. * @returns {Promise} Promise to be resolved with response data.
  1365. */
  1366. sendWithPromise:
  1367. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1368. var callbackId = this.callbackIndex++;
  1369. var message = {
  1370. action: actionName,
  1371. data: data,
  1372. callbackId: callbackId
  1373. };
  1374. var capability = createPromiseCapability();
  1375. this.callbacksCapabilities[callbackId] = capability;
  1376. try {
  1377. this.postMessage(message, transfers);
  1378. } catch (e) {
  1379. capability.reject(e);
  1380. }
  1381. return capability.promise;
  1382. },
  1383. /**
  1384. * Sends raw message to the comObj.
  1385. * @private
  1386. * @param message {Object} Raw message.
  1387. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1388. */
  1389. postMessage: function (message, transfers) {
  1390. if (transfers && this.postMessageTransfers) {
  1391. this.comObj.postMessage(message, transfers);
  1392. } else {
  1393. this.comObj.postMessage(message);
  1394. }
  1395. }
  1396. };
  1397. function loadJpegStream(id, imageUrl, objs) {
  1398. var img = new Image();
  1399. img.onload = (function loadJpegStream_onloadClosure() {
  1400. objs.resolve(id, img);
  1401. });
  1402. img.src = imageUrl;
  1403. }
  1404. var ColorSpace = (function ColorSpaceClosure() {
  1405. // Constructor should define this.numComps, this.defaultColor, this.name
  1406. function ColorSpace() {
  1407. error('should not call ColorSpace constructor');
  1408. }
  1409. ColorSpace.prototype = {
  1410. /**
  1411. * Converts the color value to the RGB color. The color components are
  1412. * located in the src array starting from the srcOffset. Returns the array
  1413. * of the rgb components, each value ranging from [0,255].
  1414. */
  1415. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  1416. var rgb = new Uint8Array(3);
  1417. this.getRgbItem(src, srcOffset, rgb, 0);
  1418. return rgb;
  1419. },
  1420. /**
  1421. * Converts the color value to the RGB color, similar to the getRgb method.
  1422. * The result placed into the dest array starting from the destOffset.
  1423. */
  1424. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  1425. dest, destOffset) {
  1426. error('Should not call ColorSpace.getRgbItem');
  1427. },
  1428. /**
  1429. * Converts the specified number of the color values to the RGB colors.
  1430. * The colors are located in the src array starting from the srcOffset.
  1431. * The result is placed into the dest array starting from the destOffset.
  1432. * The src array items shall be in [0,2^bits) range, the dest array items
  1433. * will be in [0,255] range. alpha01 indicates how many alpha components
  1434. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  1435. * array).
  1436. */
  1437. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  1438. dest, destOffset, bits,
  1439. alpha01) {
  1440. error('Should not call ColorSpace.getRgbBuffer');
  1441. },
  1442. /**
  1443. * Determines the number of bytes required to store the result of the
  1444. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  1445. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  1446. */
  1447. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  1448. alpha01) {
  1449. error('Should not call ColorSpace.getOutputLength');
  1450. },
  1451. /**
  1452. * Returns true if source data will be equal the result/output data.
  1453. */
  1454. isPassthrough: function ColorSpace_isPassthrough(bits) {
  1455. return false;
  1456. },
  1457. /**
  1458. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  1459. * how many alpha components there are in the dest array; it will be either
  1460. * 0 (RGB array) or 1 (RGBA array).
  1461. */
  1462. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  1463. originalHeight, width, height,
  1464. actualHeight, bpc, comps, alpha01) {
  1465. var count = originalWidth * originalHeight;
  1466. var rgbBuf = null;
  1467. var numComponentColors = 1 << bpc;
  1468. var needsResizing = originalHeight != height || originalWidth != width;
  1469. var i, ii;
  1470. if (this.isPassthrough(bpc)) {
  1471. rgbBuf = comps;
  1472. } else if (this.numComps === 1 && count > numComponentColors &&
  1473. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  1474. // Optimization: create a color map when there is just one component and
  1475. // we are converting more colors than the size of the color map. We
  1476. // don't build the map if the colorspace is gray or rgb since those
  1477. // methods are faster than building a map. This mainly offers big speed
  1478. // ups for indexed and alternate colorspaces.
  1479. //
  1480. // TODO it may be worth while to cache the color map. While running
  1481. // testing I never hit a cache so I will leave that out for now (perhaps
  1482. // we are reparsing colorspaces too much?).
  1483. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  1484. new Uint16Array(numComponentColors);
  1485. var key;
  1486. for (i = 0; i < numComponentColors; i++) {
  1487. allColors[i] = i;
  1488. }
  1489. var colorMap = new Uint8Array(numComponentColors * 3);
  1490. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  1491. /* alpha01 = */ 0);
  1492. var destPos, rgbPos;
  1493. if (!needsResizing) {
  1494. // Fill in the RGB values directly into |dest|.
  1495. destPos = 0;
  1496. for (i = 0; i < count; ++i) {
  1497. key = comps[i] * 3;
  1498. dest[destPos++] = colorMap[key];
  1499. dest[destPos++] = colorMap[key + 1];
  1500. dest[destPos++] = colorMap[key + 2];
  1501. destPos += alpha01;
  1502. }
  1503. } else {
  1504. rgbBuf = new Uint8Array(count * 3);
  1505. rgbPos = 0;
  1506. for (i = 0; i < count; ++i) {
  1507. key = comps[i] * 3;
  1508. rgbBuf[rgbPos++] = colorMap[key];
  1509. rgbBuf[rgbPos++] = colorMap[key + 1];
  1510. rgbBuf[rgbPos++] = colorMap[key + 2];
  1511. }
  1512. }
  1513. } else {
  1514. if (!needsResizing) {
  1515. // Fill in the RGB values directly into |dest|.
  1516. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  1517. alpha01);
  1518. } else {
  1519. rgbBuf = new Uint8Array(count * 3);
  1520. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  1521. /* alpha01 = */ 0);
  1522. }
  1523. }
  1524. if (rgbBuf) {
  1525. if (needsResizing) {
  1526. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  1527. height, dest, alpha01);
  1528. } else {
  1529. rgbPos = 0;
  1530. destPos = 0;
  1531. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  1532. dest[destPos++] = rgbBuf[rgbPos++];
  1533. dest[destPos++] = rgbBuf[rgbPos++];
  1534. dest[destPos++] = rgbBuf[rgbPos++];
  1535. destPos += alpha01;
  1536. }
  1537. }
  1538. }
  1539. },
  1540. /**
  1541. * True if the colorspace has components in the default range of [0, 1].
  1542. * This should be true for all colorspaces except for lab color spaces
  1543. * which are [0,100], [-128, 127], [-128, 127].
  1544. */
  1545. usesZeroToOneRange: true
  1546. };
  1547. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  1548. var IR = ColorSpace.parseToIR(cs, xref, res);
  1549. if (IR instanceof AlternateCS) {
  1550. return IR;
  1551. }
  1552. return ColorSpace.fromIR(IR);
  1553. };
  1554. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  1555. var name = isArray(IR) ? IR[0] : IR;
  1556. var whitePoint, blackPoint;
  1557. switch (name) {
  1558. case 'DeviceGrayCS':
  1559. return this.singletons.gray;
  1560. case 'DeviceRgbCS':
  1561. return this.singletons.rgb;
  1562. case 'DeviceCmykCS':
  1563. return this.singletons.cmyk;
  1564. case 'CalGrayCS':
  1565. whitePoint = IR[1].WhitePoint;
  1566. blackPoint = IR[1].BlackPoint;
  1567. var gamma = IR[1].Gamma;
  1568. return new CalGrayCS(whitePoint, blackPoint, gamma);
  1569. case 'PatternCS':
  1570. var basePatternCS = IR[1];
  1571. if (basePatternCS) {
  1572. basePatternCS = ColorSpace.fromIR(basePatternCS);
  1573. }
  1574. return new PatternCS(basePatternCS);
  1575. case 'IndexedCS':
  1576. var baseIndexedCS = IR[1];
  1577. var hiVal = IR[2];
  1578. var lookup = IR[3];
  1579. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  1580. case 'AlternateCS':
  1581. var numComps = IR[1];
  1582. var alt = IR[2];
  1583. var tintFnIR = IR[3];
  1584. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  1585. PDFFunction.fromIR(tintFnIR));
  1586. case 'LabCS':
  1587. whitePoint = IR[1].WhitePoint;
  1588. blackPoint = IR[1].BlackPoint;
  1589. var range = IR[1].Range;
  1590. return new LabCS(whitePoint, blackPoint, range);
  1591. default:
  1592. error('Unkown name ' + name);
  1593. }
  1594. return null;
  1595. };
  1596. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  1597. if (isName(cs)) {
  1598. var colorSpaces = res.get('ColorSpace');
  1599. if (isDict(colorSpaces)) {
  1600. var refcs = colorSpaces.get(cs.name);
  1601. if (refcs) {
  1602. cs = refcs;
  1603. }
  1604. }
  1605. }
  1606. cs = xref.fetchIfRef(cs);
  1607. var mode;
  1608. if (isName(cs)) {
  1609. mode = cs.name;
  1610. this.mode = mode;
  1611. switch (mode) {
  1612. case 'DeviceGray':
  1613. case 'G':
  1614. return 'DeviceGrayCS';
  1615. case 'DeviceRGB':
  1616. case 'RGB':
  1617. return 'DeviceRgbCS';
  1618. case 'DeviceCMYK':
  1619. case 'CMYK':
  1620. return 'DeviceCmykCS';
  1621. case 'Pattern':
  1622. return ['PatternCS', null];
  1623. default:
  1624. error('unrecognized colorspace ' + mode);
  1625. }
  1626. } else if (isArray(cs)) {
  1627. mode = cs[0].name;
  1628. this.mode = mode;
  1629. var numComps, params;
  1630. switch (mode) {
  1631. case 'DeviceGray':
  1632. case 'G':
  1633. return 'DeviceGrayCS';
  1634. case 'DeviceRGB':
  1635. case 'RGB':
  1636. return 'DeviceRgbCS';
  1637. case 'DeviceCMYK':
  1638. case 'CMYK':
  1639. return 'DeviceCmykCS';
  1640. case 'CalGray':
  1641. params = cs[1].getAll();
  1642. return ['CalGrayCS', params];
  1643. case 'CalRGB':
  1644. return 'DeviceRgbCS';
  1645. case 'ICCBased':
  1646. var stream = xref.fetchIfRef(cs[1]);
  1647. var dict = stream.dict;
  1648. numComps = dict.get('N');
  1649. if (numComps == 1) {
  1650. return 'DeviceGrayCS';
  1651. } else if (numComps == 3) {
  1652. return 'DeviceRgbCS';
  1653. } else if (numComps == 4) {
  1654. return 'DeviceCmykCS';
  1655. }
  1656. break;
  1657. case 'Pattern':
  1658. var basePatternCS = cs[1];
  1659. if (basePatternCS) {
  1660. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  1661. }
  1662. return ['PatternCS', basePatternCS];
  1663. case 'Indexed':
  1664. case 'I':
  1665. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  1666. var hiVal = cs[2] + 1;
  1667. var lookup = xref.fetchIfRef(cs[3]);
  1668. if (isStream(lookup)) {
  1669. lookup = lookup.getBytes();
  1670. }
  1671. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  1672. case 'Separation':
  1673. case 'DeviceN':
  1674. var name = cs[1];
  1675. numComps = 1;
  1676. if (isName(name)) {
  1677. numComps = 1;
  1678. } else if (isArray(name)) {
  1679. numComps = name.length;
  1680. }
  1681. var alt = ColorSpace.parseToIR(cs[2], xref, res);
  1682. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  1683. return ['AlternateCS', numComps, alt, tintFnIR];
  1684. case 'Lab':
  1685. params = cs[1].getAll();
  1686. return ['LabCS', params];
  1687. default:
  1688. error('unimplemented color space object "' + mode + '"');
  1689. }
  1690. } else {
  1691. error('unrecognized color space object: "' + cs + '"');
  1692. }
  1693. return null;
  1694. };
  1695. /**
  1696. * Checks if a decode map matches the default decode map for a color space.
  1697. * This handles the general decode maps where there are two values per
  1698. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  1699. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  1700. * slightly different.
  1701. * @param {Array} decode Decode map (usually from an image).
  1702. * @param {Number} n Number of components the color space has.
  1703. */
  1704. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  1705. if (!decode) {
  1706. return true;
  1707. }
  1708. if (n * 2 !== decode.length) {
  1709. warn('The decode map is not the correct length');
  1710. return true;
  1711. }
  1712. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  1713. if (decode[i] !== 0 || decode[i + 1] != 1) {
  1714. return false;
  1715. }
  1716. }
  1717. return true;
  1718. };
  1719. ColorSpace.singletons = {
  1720. get gray() {
  1721. return shadow(this, 'gray', new DeviceGrayCS());
  1722. },
  1723. get rgb() {
  1724. return shadow(this, 'rgb', new DeviceRgbCS());
  1725. },
  1726. get cmyk() {
  1727. return shadow(this, 'cmyk', new DeviceCmykCS());
  1728. }
  1729. };
  1730. return ColorSpace;
  1731. })();
  1732. /**
  1733. * Alternate color space handles both Separation and DeviceN color spaces. A
  1734. * Separation color space is actually just a DeviceN with one color component.
  1735. * Both color spaces use a tinting function to convert colors to a base color
  1736. * space.
  1737. */
  1738. var AlternateCS = (function AlternateCSClosure() {
  1739. function AlternateCS(numComps, base, tintFn) {
  1740. this.name = 'Alternate';
  1741. this.numComps = numComps;
  1742. this.defaultColor = new Float32Array(numComps);
  1743. for (var i = 0; i < numComps; ++i) {
  1744. this.defaultColor[i] = 1;
  1745. }
  1746. this.base = base;
  1747. this.tintFn = tintFn;
  1748. }
  1749. AlternateCS.prototype = {
  1750. getRgb: ColorSpace.prototype.getRgb,
  1751. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  1752. dest, destOffset) {
  1753. var baseNumComps = this.base.numComps;
  1754. var input = 'subarray' in src ?
  1755. src.subarray(srcOffset, srcOffset + this.numComps) :
  1756. Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps);
  1757. var tinted = this.tintFn(input);
  1758. this.base.getRgbItem(tinted, 0, dest, destOffset);
  1759. },
  1760. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  1761. dest, destOffset, bits,
  1762. alpha01) {
  1763. var tinted;
  1764. var tintFn = this.tintFn;
  1765. var base = this.base;
  1766. var scale = 1 / ((1 << bits) - 1);
  1767. var baseNumComps = base.numComps;
  1768. var usesZeroToOneRange = base.usesZeroToOneRange;
  1769. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  1770. alpha01 === 0;
  1771. var pos = isPassthrough ? destOffset : 0;
  1772. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  1773. var numComps = this.numComps;
  1774. var scaled = new Float32Array(numComps);
  1775. var i, j;
  1776. if (usesZeroToOneRange) {
  1777. for (i = 0; i < count; i++) {
  1778. for (j = 0; j < numComps; j++) {
  1779. scaled[j] = src[srcOffset++] * scale;
  1780. }
  1781. tinted = tintFn(scaled);
  1782. for (j = 0; j < baseNumComps; j++) {
  1783. baseBuf[pos++] = tinted[j] * 255;
  1784. }
  1785. }
  1786. } else {
  1787. for (i = 0; i < count; i++) {
  1788. for (j = 0; j < numComps; j++) {
  1789. scaled[j] = src[srcOffset++] * scale;
  1790. }
  1791. tinted = tintFn(scaled);
  1792. base.getRgbItem(tinted, 0, baseBuf, pos);
  1793. pos += baseNumComps;
  1794. }
  1795. }
  1796. if (!isPassthrough) {
  1797. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  1798. }
  1799. },
  1800. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  1801. alpha01) {
  1802. return this.base.getOutputLength(inputLength *
  1803. this.base.numComps / this.numComps,
  1804. alpha01);
  1805. },
  1806. isPassthrough: ColorSpace.prototype.isPassthrough,
  1807. fillRgb: ColorSpace.prototype.fillRgb,
  1808. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  1809. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1810. },
  1811. usesZeroToOneRange: true
  1812. };
  1813. return AlternateCS;
  1814. })();
  1815. var PatternCS = (function PatternCSClosure() {
  1816. function PatternCS(baseCS) {
  1817. this.name = 'Pattern';
  1818. this.base = baseCS;
  1819. }
  1820. PatternCS.prototype = {};
  1821. return PatternCS;
  1822. })();
  1823. var IndexedCS = (function IndexedCSClosure() {
  1824. function IndexedCS(base, highVal, lookup) {
  1825. this.name = 'Indexed';
  1826. this.numComps = 1;
  1827. this.defaultColor = new Uint8Array([0]);
  1828. this.base = base;
  1829. this.highVal = highVal;
  1830. var baseNumComps = base.numComps;
  1831. var length = baseNumComps * highVal;
  1832. var lookupArray;
  1833. if (isStream(lookup)) {
  1834. lookupArray = new Uint8Array(length);
  1835. var bytes = lookup.getBytes(length);
  1836. lookupArray.set(bytes);
  1837. } else if (isString(lookup)) {
  1838. lookupArray = new Uint8Array(length);
  1839. for (var i = 0; i < length; ++i) {
  1840. lookupArray[i] = lookup.charCodeAt(i);
  1841. }
  1842. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  1843. lookupArray = lookup;
  1844. } else {
  1845. error('Unrecognized lookup table: ' + lookup);
  1846. }
  1847. this.lookup = lookupArray;
  1848. }
  1849. IndexedCS.prototype = {
  1850. getRgb: ColorSpace.prototype.getRgb,
  1851. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  1852. dest, destOffset) {
  1853. var numComps = this.base.numComps;
  1854. var start = src[srcOffset] * numComps;
  1855. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  1856. },
  1857. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  1858. dest, destOffset, bits,
  1859. alpha01) {
  1860. var base = this.base;
  1861. var numComps = base.numComps;
  1862. var outputDelta = base.getOutputLength(numComps, alpha01);
  1863. var lookup = this.lookup;
  1864. for (var i = 0; i < count; ++i) {
  1865. var lookupPos = src[srcOffset++] * numComps;
  1866. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  1867. destOffset += outputDelta;
  1868. }
  1869. },
  1870. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  1871. return this.base.getOutputLength(inputLength * this.base.numComps,
  1872. alpha01);
  1873. },
  1874. isPassthrough: ColorSpace.prototype.isPassthrough,
  1875. fillRgb: ColorSpace.prototype.fillRgb,
  1876. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  1877. // indexed color maps shouldn't be changed
  1878. return true;
  1879. },
  1880. usesZeroToOneRange: true
  1881. };
  1882. return IndexedCS;
  1883. })();
  1884. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  1885. function DeviceGrayCS() {
  1886. this.name = 'DeviceGray';
  1887. this.numComps = 1;
  1888. this.defaultColor = new Float32Array([0]);
  1889. }
  1890. DeviceGrayCS.prototype = {
  1891. getRgb: ColorSpace.prototype.getRgb,
  1892. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  1893. dest, destOffset) {
  1894. var c = (src[srcOffset] * 255) | 0;
  1895. c = c < 0 ? 0 : c > 255 ? 255 : c;
  1896. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  1897. },
  1898. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  1899. dest, destOffset, bits,
  1900. alpha01) {
  1901. var scale = 255 / ((1 << bits) - 1);
  1902. var j = srcOffset, q = destOffset;
  1903. for (var i = 0; i < count; ++i) {
  1904. var c = (scale * src[j++]) | 0;
  1905. dest[q++] = c;
  1906. dest[q++] = c;
  1907. dest[q++] = c;
  1908. q += alpha01;
  1909. }
  1910. },
  1911. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  1912. alpha01) {
  1913. return inputLength * (3 + alpha01);
  1914. },
  1915. isPassthrough: ColorSpace.prototype.isPassthrough,
  1916. fillRgb: ColorSpace.prototype.fillRgb,
  1917. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  1918. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1919. },
  1920. usesZeroToOneRange: true
  1921. };
  1922. return DeviceGrayCS;
  1923. })();
  1924. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  1925. function DeviceRgbCS() {
  1926. this.name = 'DeviceRGB';
  1927. this.numComps = 3;
  1928. this.defaultColor = new Float32Array([0, 0, 0]);
  1929. }
  1930. DeviceRgbCS.prototype = {
  1931. getRgb: ColorSpace.prototype.getRgb,
  1932. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  1933. dest, destOffset) {
  1934. var r = (src[srcOffset] * 255) | 0;
  1935. var g = (src[srcOffset + 1] * 255) | 0;
  1936. var b = (src[srcOffset + 2] * 255) | 0;
  1937. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  1938. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  1939. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  1940. },
  1941. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  1942. dest, destOffset, bits,
  1943. alpha01) {
  1944. if (bits === 8 && alpha01 === 0) {
  1945. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  1946. return;
  1947. }
  1948. var scale = 255 / ((1 << bits) - 1);
  1949. var j = srcOffset, q = destOffset;
  1950. for (var i = 0; i < count; ++i) {
  1951. dest[q++] = (scale * src[j++]) | 0;
  1952. dest[q++] = (scale * src[j++]) | 0;
  1953. dest[q++] = (scale * src[j++]) | 0;
  1954. q += alpha01;
  1955. }
  1956. },
  1957. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  1958. alpha01) {
  1959. return (inputLength * (3 + alpha01) / 3) | 0;
  1960. },
  1961. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  1962. return bits == 8;
  1963. },
  1964. fillRgb: ColorSpace.prototype.fillRgb,
  1965. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  1966. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  1967. },
  1968. usesZeroToOneRange: true
  1969. };
  1970. return DeviceRgbCS;
  1971. })();
  1972. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  1973. // The coefficients below was found using numerical analysis: the method of
  1974. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  1975. // where color_value is the tabular value from the table of sampled RGB colors
  1976. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  1977. // CMYK color conversion using the estimation below:
  1978. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  1979. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  1980. var c = src[srcOffset + 0] * srcScale;
  1981. var m = src[srcOffset + 1] * srcScale;
  1982. var y = src[srcOffset + 2] * srcScale;
  1983. var k = src[srcOffset + 3] * srcScale;
  1984. var r =
  1985. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  1986. 18.82290502165302 * y + 212.25662451639585 * k +
  1987. -285.2331026137004) +
  1988. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  1989. -17.873870861415444 * k - 5.497006427196366) +
  1990. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  1991. 17.5119270841813) +
  1992. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  1993. var g =
  1994. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  1995. 6.871425592049007 * y + 31.159100130055922 * k +
  1996. -79.2970844816548) +
  1997. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  1998. 131.35250912493976 * k - 190.9453302588951) +
  1999. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  2000. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  2001. var b =
  2002. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  2003. 30.89978309703729 * y - 0.23883238689178934 * k +
  2004. -14.183576799673286) +
  2005. m * (10.49593273432072 * m + 63.02378494754052 * y +
  2006. 50.606957656360734 * k - 112.23884253719248) +
  2007. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  2008. -193.58209356861505) +
  2009. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  2010. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  2011. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  2012. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  2013. }
  2014. function DeviceCmykCS() {
  2015. this.name = 'DeviceCMYK';
  2016. this.numComps = 4;
  2017. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  2018. }
  2019. DeviceCmykCS.prototype = {
  2020. getRgb: ColorSpace.prototype.getRgb,
  2021. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  2022. dest, destOffset) {
  2023. convertToRgb(src, srcOffset, 1, dest, destOffset);
  2024. },
  2025. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  2026. dest, destOffset, bits,
  2027. alpha01) {
  2028. var scale = 1 / ((1 << bits) - 1);
  2029. for (var i = 0; i < count; i++) {
  2030. convertToRgb(src, srcOffset, scale, dest, destOffset);
  2031. srcOffset += 4;
  2032. destOffset += 3 + alpha01;
  2033. }
  2034. },
  2035. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  2036. alpha01) {
  2037. return (inputLength / 4 * (3 + alpha01)) | 0;
  2038. },
  2039. isPassthrough: ColorSpace.prototype.isPassthrough,
  2040. fillRgb: ColorSpace.prototype.fillRgb,
  2041. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  2042. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  2043. },
  2044. usesZeroToOneRange: true
  2045. };
  2046. return DeviceCmykCS;
  2047. })();
  2048. //
  2049. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  2050. //
  2051. var CalGrayCS = (function CalGrayCSClosure() {
  2052. function CalGrayCS(whitePoint, blackPoint, gamma) {
  2053. this.name = 'CalGray';
  2054. this.numComps = 1;
  2055. this.defaultColor = new Float32Array([0]);
  2056. if (!whitePoint) {
  2057. error('WhitePoint missing - required for color space CalGray');
  2058. }
  2059. blackPoint = blackPoint || [0, 0, 0];
  2060. gamma = gamma || 1;
  2061. // Translate arguments to spec variables.
  2062. this.XW = whitePoint[0];
  2063. this.YW = whitePoint[1];
  2064. this.ZW = whitePoint[2];
  2065. this.XB = blackPoint[0];
  2066. this.YB = blackPoint[1];
  2067. this.ZB = blackPoint[2];
  2068. this.G = gamma;
  2069. // Validate variables as per spec.
  2070. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  2071. error('Invalid WhitePoint components for ' + this.name +
  2072. ', no fallback available');
  2073. }
  2074. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  2075. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  2076. this.XB = this.YB = this.ZB = 0;
  2077. }
  2078. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  2079. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  2080. ', ZB: ' + this.ZB + ', only default values are supported.');
  2081. }
  2082. if (this.G < 1) {
  2083. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  2084. ', falling back to default');
  2085. this.G = 1;
  2086. }
  2087. }
  2088. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  2089. // A represents a gray component of a calibrated gray space.
  2090. // A <---> AG in the spec
  2091. var A = src[srcOffset] * scale;
  2092. var AG = Math.pow(A, cs.G);
  2093. // Computes L as per spec. ( = cs.YW * AG )
  2094. // Except if other than default BlackPoint values are used.
  2095. var L = cs.YW * AG;
  2096. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  2097. // Convert values to rgb range [0, 255].
  2098. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  2099. dest[destOffset] = val;
  2100. dest[destOffset + 1] = val;
  2101. dest[destOffset + 2] = val;
  2102. }
  2103. CalGrayCS.prototype = {
  2104. getRgb: ColorSpace.prototype.getRgb,
  2105. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  2106. dest, destOffset) {
  2107. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  2108. },
  2109. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  2110. dest, destOffset, bits,
  2111. alpha01) {
  2112. var scale = 1 / ((1 << bits) - 1);
  2113. for (var i = 0; i < count; ++i) {
  2114. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  2115. srcOffset += 1;
  2116. destOffset += 3 + alpha01;
  2117. }
  2118. },
  2119. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  2120. return inputLength * (3 + alpha01);
  2121. },
  2122. isPassthrough: ColorSpace.prototype.isPassthrough,
  2123. fillRgb: ColorSpace.prototype.fillRgb,
  2124. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  2125. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  2126. },
  2127. usesZeroToOneRange: true
  2128. };
  2129. return CalGrayCS;
  2130. })();
  2131. //
  2132. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  2133. //
  2134. var LabCS = (function LabCSClosure() {
  2135. function LabCS(whitePoint, blackPoint, range) {
  2136. this.name = 'Lab';
  2137. this.numComps = 3;
  2138. this.defaultColor = new Float32Array([0, 0, 0]);
  2139. if (!whitePoint) {
  2140. error('WhitePoint missing - required for color space Lab');
  2141. }
  2142. blackPoint = blackPoint || [0, 0, 0];
  2143. range = range || [-100, 100, -100, 100];
  2144. // Translate args to spec variables
  2145. this.XW = whitePoint[0];
  2146. this.YW = whitePoint[1];
  2147. this.ZW = whitePoint[2];
  2148. this.amin = range[0];
  2149. this.amax = range[1];
  2150. this.bmin = range[2];
  2151. this.bmax = range[3];
  2152. // These are here just for completeness - the spec doesn't offer any
  2153. // formulas that use BlackPoint in Lab
  2154. this.XB = blackPoint[0];
  2155. this.YB = blackPoint[1];
  2156. this.ZB = blackPoint[2];
  2157. // Validate vars as per spec
  2158. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  2159. error('Invalid WhitePoint components, no fallback available');
  2160. }
  2161. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  2162. info('Invalid BlackPoint, falling back to default');
  2163. this.XB = this.YB = this.ZB = 0;
  2164. }
  2165. if (this.amin > this.amax || this.bmin > this.bmax) {
  2166. info('Invalid Range, falling back to defaults');
  2167. this.amin = -100;
  2168. this.amax = 100;
  2169. this.bmin = -100;
  2170. this.bmax = 100;
  2171. }
  2172. }
  2173. // Function g(x) from spec
  2174. function fn_g(x) {
  2175. if (x >= 6 / 29) {
  2176. return x * x * x;
  2177. } else {
  2178. return (108 / 841) * (x - 4 / 29);
  2179. }
  2180. }
  2181. function decode(value, high1, low2, high2) {
  2182. return low2 + (value) * (high2 - low2) / (high1);
  2183. }
  2184. // If decoding is needed maxVal should be 2^bits per component - 1.
  2185. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  2186. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  2187. // not the usual [0, 1]. If a command like setFillColor is used the src
  2188. // values will already be within the correct range. However, if we are
  2189. // converting an image we have to map the values to the correct range given
  2190. // above.
  2191. // Ls,as,bs <---> L*,a*,b* in the spec
  2192. var Ls = src[srcOffset];
  2193. var as = src[srcOffset + 1];
  2194. var bs = src[srcOffset + 2];
  2195. if (maxVal !== false) {
  2196. Ls = decode(Ls, maxVal, 0, 100);
  2197. as = decode(as, maxVal, cs.amin, cs.amax);
  2198. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  2199. }
  2200. // Adjust limits of 'as' and 'bs'
  2201. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  2202. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  2203. // Computes intermediate variables X,Y,Z as per spec
  2204. var M = (Ls + 16) / 116;
  2205. var L = M + (as / 500);
  2206. var N = M - (bs / 200);
  2207. var X = cs.XW * fn_g(L);
  2208. var Y = cs.YW * fn_g(M);
  2209. var Z = cs.ZW * fn_g(N);
  2210. var r, g, b;
  2211. // Using different conversions for D50 and D65 white points,
  2212. // per http://www.color.org/srgb.pdf
  2213. if (cs.ZW < 1) {
  2214. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  2215. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  2216. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  2217. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  2218. } else {
  2219. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  2220. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  2221. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  2222. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  2223. }
  2224. // clamp color values to [0,1] range then convert to [0,255] range.
  2225. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  2226. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  2227. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  2228. }
  2229. LabCS.prototype = {
  2230. getRgb: ColorSpace.prototype.getRgb,
  2231. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  2232. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  2233. },
  2234. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  2235. dest, destOffset, bits,
  2236. alpha01) {
  2237. var maxVal = (1 << bits) - 1;
  2238. for (var i = 0; i < count; i++) {
  2239. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  2240. srcOffset += 3;
  2241. destOffset += 3 + alpha01;
  2242. }
  2243. },
  2244. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  2245. return (inputLength * (3 + alpha01) / 3) | 0;
  2246. },
  2247. isPassthrough: ColorSpace.prototype.isPassthrough,
  2248. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  2249. // XXX: Decoding is handled with the lab conversion because of the strange
  2250. // ranges that are used.
  2251. return true;
  2252. },
  2253. usesZeroToOneRange: false
  2254. };
  2255. return LabCS;
  2256. })();
  2257. var PDFFunction = (function PDFFunctionClosure() {
  2258. var CONSTRUCT_SAMPLED = 0;
  2259. var CONSTRUCT_INTERPOLATED = 2;
  2260. var CONSTRUCT_STICHED = 3;
  2261. var CONSTRUCT_POSTSCRIPT = 4;
  2262. return {
  2263. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  2264. str) {
  2265. var i, ii;
  2266. var length = 1;
  2267. for (i = 0, ii = size.length; i < ii; i++) {
  2268. length *= size[i];
  2269. }
  2270. length *= outputSize;
  2271. var array = [];
  2272. var codeSize = 0;
  2273. var codeBuf = 0;
  2274. // 32 is a valid bps so shifting won't work
  2275. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  2276. var strBytes = str.getBytes((length * bps + 7) / 8);
  2277. var strIdx = 0;
  2278. for (i = 0; i < length; i++) {
  2279. while (codeSize < bps) {
  2280. codeBuf <<= 8;
  2281. codeBuf |= strBytes[strIdx++];
  2282. codeSize += 8;
  2283. }
  2284. codeSize -= bps;
  2285. array.push((codeBuf >> codeSize) * sampleMul);
  2286. codeBuf &= (1 << codeSize) - 1;
  2287. }
  2288. return array;
  2289. },
  2290. getIR: function PDFFunction_getIR(xref, fn) {
  2291. var dict = fn.dict;
  2292. if (!dict) {
  2293. dict = fn;
  2294. }
  2295. var types = [this.constructSampled,
  2296. null,
  2297. this.constructInterpolated,
  2298. this.constructStiched,
  2299. this.constructPostScript];
  2300. var typeNum = dict.get('FunctionType');
  2301. var typeFn = types[typeNum];
  2302. if (!typeFn) {
  2303. error('Unknown type of function');
  2304. }
  2305. return typeFn.call(this, fn, dict, xref);
  2306. },
  2307. fromIR: function PDFFunction_fromIR(IR) {
  2308. var type = IR[0];
  2309. switch (type) {
  2310. case CONSTRUCT_SAMPLED:
  2311. return this.constructSampledFromIR(IR);
  2312. case CONSTRUCT_INTERPOLATED:
  2313. return this.constructInterpolatedFromIR(IR);
  2314. case CONSTRUCT_STICHED:
  2315. return this.constructStichedFromIR(IR);
  2316. //case CONSTRUCT_POSTSCRIPT:
  2317. default:
  2318. return this.constructPostScriptFromIR(IR);
  2319. }
  2320. },
  2321. parse: function PDFFunction_parse(xref, fn) {
  2322. var IR = this.getIR(xref, fn);
  2323. return this.fromIR(IR);
  2324. },
  2325. constructSampled: function PDFFunction_constructSampled(str, dict) {
  2326. function toMultiArray(arr) {
  2327. var inputLength = arr.length;
  2328. var out = [];
  2329. var index = 0;
  2330. for (var i = 0; i < inputLength; i += 2) {
  2331. out[index] = [arr[i], arr[i + 1]];
  2332. ++index;
  2333. }
  2334. return out;
  2335. }
  2336. var domain = dict.get('Domain');
  2337. var range = dict.get('Range');
  2338. if (!domain || !range) {
  2339. error('No domain or range');
  2340. }
  2341. var inputSize = domain.length / 2;
  2342. var outputSize = range.length / 2;
  2343. domain = toMultiArray(domain);
  2344. range = toMultiArray(range);
  2345. var size = dict.get('Size');
  2346. var bps = dict.get('BitsPerSample');
  2347. var order = dict.get('Order') || 1;
  2348. if (order !== 1) {
  2349. // No description how cubic spline interpolation works in PDF32000:2008
  2350. // As in poppler, ignoring order, linear interpolation may work as good
  2351. info('No support for cubic spline interpolation: ' + order);
  2352. }
  2353. var encode = dict.get('Encode');
  2354. if (!encode) {
  2355. encode = [];
  2356. for (var i = 0; i < inputSize; ++i) {
  2357. encode.push(0);
  2358. encode.push(size[i] - 1);
  2359. }
  2360. }
  2361. encode = toMultiArray(encode);
  2362. var decode = dict.get('Decode');
  2363. if (!decode) {
  2364. decode = range;
  2365. } else {
  2366. decode = toMultiArray(decode);
  2367. }
  2368. var samples = this.getSampleArray(size, outputSize, bps, str);
  2369. return [
  2370. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  2371. outputSize, Math.pow(2, bps) - 1, range
  2372. ];
  2373. },
  2374. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  2375. // See chapter 3, page 109 of the PDF reference
  2376. function interpolate(x, xmin, xmax, ymin, ymax) {
  2377. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  2378. }
  2379. return function constructSampledFromIRResult(args) {
  2380. // See chapter 3, page 110 of the PDF reference.
  2381. var m = IR[1];
  2382. var domain = IR[2];
  2383. var encode = IR[3];
  2384. var decode = IR[4];
  2385. var samples = IR[5];
  2386. var size = IR[6];
  2387. var n = IR[7];
  2388. //var mask = IR[8];
  2389. var range = IR[9];
  2390. if (m != args.length) {
  2391. error('Incorrect number of arguments: ' + m + ' != ' +
  2392. args.length);
  2393. }
  2394. var x = args;
  2395. // Building the cube vertices: its part and sample index
  2396. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  2397. var cubeVertices = 1 << m;
  2398. var cubeN = new Float64Array(cubeVertices);
  2399. var cubeVertex = new Uint32Array(cubeVertices);
  2400. var i, j;
  2401. for (j = 0; j < cubeVertices; j++) {
  2402. cubeN[j] = 1;
  2403. }
  2404. var k = n, pos = 1;
  2405. // Map x_i to y_j for 0 <= i < m using the sampled function.
  2406. for (i = 0; i < m; ++i) {
  2407. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  2408. var domain_2i = domain[i][0];
  2409. var domain_2i_1 = domain[i][1];
  2410. var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);
  2411. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  2412. // Encode_2i, Encode_2i+1)
  2413. var e = interpolate(xi, domain_2i, domain_2i_1,
  2414. encode[i][0], encode[i][1]);
  2415. // e_i' = min(max(e_i, 0), Size_i - 1)
  2416. var size_i = size[i];
  2417. e = Math.min(Math.max(e, 0), size_i - 1);
  2418. // Adjusting the cube: N and vertex sample index
  2419. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  2420. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  2421. var n1 = e - e0; // (e - e0) / (e1 - e0);
  2422. var offset0 = e0 * k;
  2423. var offset1 = offset0 + k; // e1 * k
  2424. for (j = 0; j < cubeVertices; j++) {
  2425. if (j & pos) {
  2426. cubeN[j] *= n1;
  2427. cubeVertex[j] += offset1;
  2428. } else {
  2429. cubeN[j] *= n0;
  2430. cubeVertex[j] += offset0;
  2431. }
  2432. }
  2433. k *= size_i;
  2434. pos <<= 1;
  2435. }
  2436. var y = new Float64Array(n);
  2437. for (j = 0; j < n; ++j) {
  2438. // Sum all cube vertices' samples portions
  2439. var rj = 0;
  2440. for (i = 0; i < cubeVertices; i++) {
  2441. rj += samples[cubeVertex[i] + j] * cubeN[i];
  2442. }
  2443. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  2444. // Decode_2j, Decode_2j+1)
  2445. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  2446. // y_j = min(max(r_j, range_2j), range_2j+1)
  2447. y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  2448. }
  2449. return y;
  2450. };
  2451. },
  2452. constructInterpolated: function PDFFunction_constructInterpolated(str,
  2453. dict) {
  2454. var c0 = dict.get('C0') || [0];
  2455. var c1 = dict.get('C1') || [1];
  2456. var n = dict.get('N');
  2457. if (!isArray(c0) || !isArray(c1)) {
  2458. error('Illegal dictionary for interpolated function');
  2459. }
  2460. var length = c0.length;
  2461. var diff = [];
  2462. for (var i = 0; i < length; ++i) {
  2463. diff.push(c1[i] - c0[i]);
  2464. }
  2465. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  2466. },
  2467. constructInterpolatedFromIR:
  2468. function PDFFunction_constructInterpolatedFromIR(IR) {
  2469. var c0 = IR[1];
  2470. var diff = IR[2];
  2471. var n = IR[3];
  2472. var length = diff.length;
  2473. return function constructInterpolatedFromIRResult(args) {
  2474. var x = n == 1 ? args[0] : Math.pow(args[0], n);
  2475. var out = [];
  2476. for (var j = 0; j < length; ++j) {
  2477. out.push(c0[j] + (x * diff[j]));
  2478. }
  2479. return out;
  2480. };
  2481. },
  2482. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  2483. var domain = dict.get('Domain');
  2484. if (!domain) {
  2485. error('No domain');
  2486. }
  2487. var inputSize = domain.length / 2;
  2488. if (inputSize != 1) {
  2489. error('Bad domain for stiched function');
  2490. }
  2491. var fnRefs = dict.get('Functions');
  2492. var fns = [];
  2493. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  2494. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  2495. }
  2496. var bounds = dict.get('Bounds');
  2497. var encode = dict.get('Encode');
  2498. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  2499. },
  2500. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  2501. var domain = IR[1];
  2502. var bounds = IR[2];
  2503. var encode = IR[3];
  2504. var fnsIR = IR[4];
  2505. var fns = [];
  2506. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  2507. fns.push(PDFFunction.fromIR(fnsIR[i]));
  2508. }
  2509. return function constructStichedFromIRResult(args) {
  2510. var clip = function constructStichedFromIRClip(v, min, max) {
  2511. if (v > max) {
  2512. v = max;
  2513. } else if (v < min) {
  2514. v = min;
  2515. }
  2516. return v;
  2517. };
  2518. // clip to domain
  2519. var v = clip(args[0], domain[0], domain[1]);
  2520. // calulate which bound the value is in
  2521. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  2522. if (v < bounds[i]) {
  2523. break;
  2524. }
  2525. }
  2526. // encode value into domain of function
  2527. var dmin = domain[0];
  2528. if (i > 0) {
  2529. dmin = bounds[i - 1];
  2530. }
  2531. var dmax = domain[1];
  2532. if (i < bounds.length) {
  2533. dmax = bounds[i];
  2534. }
  2535. var rmin = encode[2 * i];
  2536. var rmax = encode[2 * i + 1];
  2537. var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  2538. // call the appropriate function
  2539. return fns[i]([v2]);
  2540. };
  2541. },
  2542. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  2543. xref) {
  2544. var domain = dict.get('Domain');
  2545. var range = dict.get('Range');
  2546. if (!domain) {
  2547. error('No domain.');
  2548. }
  2549. if (!range) {
  2550. error('No range.');
  2551. }
  2552. var lexer = new PostScriptLexer(fn);
  2553. var parser = new PostScriptParser(lexer);
  2554. var code = parser.parse();
  2555. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  2556. },
  2557. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  2558. IR) {
  2559. var domain = IR[1];
  2560. var range = IR[2];
  2561. var code = IR[3];
  2562. var numOutputs = range.length >> 1;
  2563. var numInputs = domain.length >> 1;
  2564. var evaluator = new PostScriptEvaluator(code);
  2565. // Cache the values for a big speed up, the cache size is limited though
  2566. // since the number of possible values can be huge from a PS function.
  2567. var cache = {};
  2568. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  2569. // seen in our tests.
  2570. var MAX_CACHE_SIZE = 2048 * 4;
  2571. var cache_available = MAX_CACHE_SIZE;
  2572. return function constructPostScriptFromIRResult(args) {
  2573. var i, value;
  2574. var key = '';
  2575. var input = new Array(numInputs);
  2576. for (i = 0; i < numInputs; i++) {
  2577. value = args[i];
  2578. input[i] = value;
  2579. key += value + '_';
  2580. }
  2581. var cachedValue = cache[key];
  2582. if (cachedValue !== undefined) {
  2583. return cachedValue;
  2584. }
  2585. var output = new Array(numOutputs);
  2586. var stack = evaluator.execute(input);
  2587. var stackIndex = stack.length - numOutputs;
  2588. for (i = 0; i < numOutputs; i++) {
  2589. value = stack[stackIndex + i];
  2590. var bound = range[i * 2];
  2591. if (value < bound) {
  2592. value = bound;
  2593. } else {
  2594. bound = range[i * 2 +1];
  2595. if (value > bound) {
  2596. value = bound;
  2597. }
  2598. }
  2599. output[i] = value;
  2600. }
  2601. if (cache_available > 0) {
  2602. cache_available--;
  2603. cache[key] = output;
  2604. }
  2605. return output;
  2606. };
  2607. }
  2608. };
  2609. })();
  2610. var PostScriptStack = (function PostScriptStackClosure() {
  2611. var MAX_STACK_SIZE = 100;
  2612. function PostScriptStack(initialStack) {
  2613. this.stack = initialStack || [];
  2614. }
  2615. PostScriptStack.prototype = {
  2616. push: function PostScriptStack_push(value) {
  2617. if (this.stack.length >= MAX_STACK_SIZE) {
  2618. error('PostScript function stack overflow.');
  2619. }
  2620. this.stack.push(value);
  2621. },
  2622. pop: function PostScriptStack_pop() {
  2623. if (this.stack.length <= 0) {
  2624. error('PostScript function stack underflow.');
  2625. }
  2626. return this.stack.pop();
  2627. },
  2628. copy: function PostScriptStack_copy(n) {
  2629. if (this.stack.length + n >= MAX_STACK_SIZE) {
  2630. error('PostScript function stack overflow.');
  2631. }
  2632. var stack = this.stack;
  2633. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  2634. stack.push(stack[i]);
  2635. }
  2636. },
  2637. index: function PostScriptStack_index(n) {
  2638. this.push(this.stack[this.stack.length - n - 1]);
  2639. },
  2640. // rotate the last n stack elements p times
  2641. roll: function PostScriptStack_roll(n, p) {
  2642. var stack = this.stack;
  2643. var l = stack.length - n;
  2644. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  2645. for (i = l, j = r; i < j; i++, j--) {
  2646. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2647. }
  2648. for (i = l, j = c - 1; i < j; i++, j--) {
  2649. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2650. }
  2651. for (i = c, j = r; i < j; i++, j--) {
  2652. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  2653. }
  2654. }
  2655. };
  2656. return PostScriptStack;
  2657. })();
  2658. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  2659. function PostScriptEvaluator(operators) {
  2660. this.operators = operators;
  2661. }
  2662. PostScriptEvaluator.prototype = {
  2663. execute: function PostScriptEvaluator_execute(initialStack) {
  2664. var stack = new PostScriptStack(initialStack);
  2665. var counter = 0;
  2666. var operators = this.operators;
  2667. var length = operators.length;
  2668. var operator, a, b;
  2669. while (counter < length) {
  2670. operator = operators[counter++];
  2671. if (typeof operator == 'number') {
  2672. // Operator is really an operand and should be pushed to the stack.
  2673. stack.push(operator);
  2674. continue;
  2675. }
  2676. switch (operator) {
  2677. // non standard ps operators
  2678. case 'jz': // jump if false
  2679. b = stack.pop();
  2680. a = stack.pop();
  2681. if (!a) {
  2682. counter = b;
  2683. }
  2684. break;
  2685. case 'j': // jump
  2686. a = stack.pop();
  2687. counter = a;
  2688. break;
  2689. // all ps operators in alphabetical order (excluding if/ifelse)
  2690. case 'abs':
  2691. a = stack.pop();
  2692. stack.push(Math.abs(a));
  2693. break;
  2694. case 'add':
  2695. b = stack.pop();
  2696. a = stack.pop();
  2697. stack.push(a + b);
  2698. break;
  2699. case 'and':
  2700. b = stack.pop();
  2701. a = stack.pop();
  2702. if (isBool(a) && isBool(b)) {
  2703. stack.push(a && b);
  2704. } else {
  2705. stack.push(a & b);
  2706. }
  2707. break;
  2708. case 'atan':
  2709. a = stack.pop();
  2710. stack.push(Math.atan(a));
  2711. break;
  2712. case 'bitshift':
  2713. b = stack.pop();
  2714. a = stack.pop();
  2715. if (a > 0) {
  2716. stack.push(a << b);
  2717. } else {
  2718. stack.push(a >> b);
  2719. }
  2720. break;
  2721. case 'ceiling':
  2722. a = stack.pop();
  2723. stack.push(Math.ceil(a));
  2724. break;
  2725. case 'copy':
  2726. a = stack.pop();
  2727. stack.copy(a);
  2728. break;
  2729. case 'cos':
  2730. a = stack.pop();
  2731. stack.push(Math.cos(a));
  2732. break;
  2733. case 'cvi':
  2734. a = stack.pop() | 0;
  2735. stack.push(a);
  2736. break;
  2737. case 'cvr':
  2738. // noop
  2739. break;
  2740. case 'div':
  2741. b = stack.pop();
  2742. a = stack.pop();
  2743. stack.push(a / b);
  2744. break;
  2745. case 'dup':
  2746. stack.copy(1);
  2747. break;
  2748. case 'eq':
  2749. b = stack.pop();
  2750. a = stack.pop();
  2751. stack.push(a == b);
  2752. break;
  2753. case 'exch':
  2754. stack.roll(2, 1);
  2755. break;
  2756. case 'exp':
  2757. b = stack.pop();
  2758. a = stack.pop();
  2759. stack.push(Math.pow(a, b));
  2760. break;
  2761. case 'false':
  2762. stack.push(false);
  2763. break;
  2764. case 'floor':
  2765. a = stack.pop();
  2766. stack.push(Math.floor(a));
  2767. break;
  2768. case 'ge':
  2769. b = stack.pop();
  2770. a = stack.pop();
  2771. stack.push(a >= b);
  2772. break;
  2773. case 'gt':
  2774. b = stack.pop();
  2775. a = stack.pop();
  2776. stack.push(a > b);
  2777. break;
  2778. case 'idiv':
  2779. b = stack.pop();
  2780. a = stack.pop();
  2781. stack.push((a / b) | 0);
  2782. break;
  2783. case 'index':
  2784. a = stack.pop();
  2785. stack.index(a);
  2786. break;
  2787. case 'le':
  2788. b = stack.pop();
  2789. a = stack.pop();
  2790. stack.push(a <= b);
  2791. break;
  2792. case 'ln':
  2793. a = stack.pop();
  2794. stack.push(Math.log(a));
  2795. break;
  2796. case 'log':
  2797. a = stack.pop();
  2798. stack.push(Math.log(a) / Math.LN10);
  2799. break;
  2800. case 'lt':
  2801. b = stack.pop();
  2802. a = stack.pop();
  2803. stack.push(a < b);
  2804. break;
  2805. case 'mod':
  2806. b = stack.pop();
  2807. a = stack.pop();
  2808. stack.push(a % b);
  2809. break;
  2810. case 'mul':
  2811. b = stack.pop();
  2812. a = stack.pop();
  2813. stack.push(a * b);
  2814. break;
  2815. case 'ne':
  2816. b = stack.pop();
  2817. a = stack.pop();
  2818. stack.push(a != b);
  2819. break;
  2820. case 'neg':
  2821. a = stack.pop();
  2822. stack.push(-a);
  2823. break;
  2824. case 'not':
  2825. a = stack.pop();
  2826. if (isBool(a)) {
  2827. stack.push(!a);
  2828. } else {
  2829. stack.push(~a);
  2830. }
  2831. break;
  2832. case 'or':
  2833. b = stack.pop();
  2834. a = stack.pop();
  2835. if (isBool(a) && isBool(b)) {
  2836. stack.push(a || b);
  2837. } else {
  2838. stack.push(a | b);
  2839. }
  2840. break;
  2841. case 'pop':
  2842. stack.pop();
  2843. break;
  2844. case 'roll':
  2845. b = stack.pop();
  2846. a = stack.pop();
  2847. stack.roll(a, b);
  2848. break;
  2849. case 'round':
  2850. a = stack.pop();
  2851. stack.push(Math.round(a));
  2852. break;
  2853. case 'sin':
  2854. a = stack.pop();
  2855. stack.push(Math.sin(a));
  2856. break;
  2857. case 'sqrt':
  2858. a = stack.pop();
  2859. stack.push(Math.sqrt(a));
  2860. break;
  2861. case 'sub':
  2862. b = stack.pop();
  2863. a = stack.pop();
  2864. stack.push(a - b);
  2865. break;
  2866. case 'true':
  2867. stack.push(true);
  2868. break;
  2869. case 'truncate':
  2870. a = stack.pop();
  2871. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  2872. stack.push(a);
  2873. break;
  2874. case 'xor':
  2875. b = stack.pop();
  2876. a = stack.pop();
  2877. if (isBool(a) && isBool(b)) {
  2878. stack.push(a != b);
  2879. } else {
  2880. stack.push(a ^ b);
  2881. }
  2882. break;
  2883. default:
  2884. error('Unknown operator ' + operator);
  2885. break;
  2886. }
  2887. }
  2888. return stack.stack;
  2889. }
  2890. };
  2891. return PostScriptEvaluator;
  2892. })();
  2893. var DEFAULT_ICON_SIZE = 22; // px
  2894. var HIGHLIGHT_OFFSET = 4; // px
  2895. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  2896. var Annotation = (function AnnotationClosure() {
  2897. // 12.5.5: Algorithm: Appearance streams
  2898. function getTransformMatrix(rect, bbox, matrix) {
  2899. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  2900. var minX = bounds[0];
  2901. var minY = bounds[1];
  2902. var maxX = bounds[2];
  2903. var maxY = bounds[3];
  2904. if (minX === maxX || minY === maxY) {
  2905. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  2906. // just apply the transform for rect
  2907. return [1, 0, 0, 1, rect[0], rect[1]];
  2908. }
  2909. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  2910. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  2911. return [
  2912. xRatio,
  2913. 0,
  2914. 0,
  2915. yRatio,
  2916. rect[0] - minX * xRatio,
  2917. rect[1] - minY * yRatio
  2918. ];
  2919. }
  2920. function getDefaultAppearance(dict) {
  2921. var appearanceState = dict.get('AP');
  2922. if (!isDict(appearanceState)) {
  2923. return;
  2924. }
  2925. var appearance;
  2926. var appearances = appearanceState.get('N');
  2927. if (isDict(appearances)) {
  2928. var as = dict.get('AS');
  2929. if (as && appearances.has(as.name)) {
  2930. appearance = appearances.get(as.name);
  2931. }
  2932. } else {
  2933. appearance = appearances;
  2934. }
  2935. return appearance;
  2936. }
  2937. function Annotation(params) {
  2938. if (params.data) {
  2939. this.data = params.data;
  2940. return;
  2941. }
  2942. var dict = params.dict;
  2943. var data = this.data = {};
  2944. data.subtype = dict.get('Subtype').name;
  2945. var rect = dict.get('Rect') || [0, 0, 0, 0];
  2946. data.rect = Util.normalizeRect(rect);
  2947. data.annotationFlags = dict.get('F');
  2948. var color = dict.get('C');
  2949. if (isArray(color) && color.length === 3) {
  2950. // TODO(mack): currently only supporting rgb; need support different
  2951. // colorspaces
  2952. data.color = color;
  2953. } else {
  2954. data.color = [0, 0, 0];
  2955. }
  2956. // Some types of annotations have border style dict which has more
  2957. // info than the border array
  2958. if (dict.has('BS')) {
  2959. var borderStyle = dict.get('BS');
  2960. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  2961. } else {
  2962. var borderArray = dict.get('Border') || [0, 0, 1];
  2963. data.borderWidth = borderArray[2] || 0;
  2964. // TODO: implement proper support for annotations with line dash patterns.
  2965. var dashArray = borderArray[3];
  2966. if (data.borderWidth > 0 && dashArray) {
  2967. if (!isArray(dashArray)) {
  2968. // Ignore the border if dashArray is not actually an array,
  2969. // this is consistent with the behaviour in Adobe Reader.
  2970. data.borderWidth = 0;
  2971. } else {
  2972. var dashArrayLength = dashArray.length;
  2973. if (dashArrayLength > 0) {
  2974. // According to the PDF specification: the elements in a dashArray
  2975. // shall be numbers that are nonnegative and not all equal to zero.
  2976. var isInvalid = false;
  2977. var numPositive = 0;
  2978. for (var i = 0; i < dashArrayLength; i++) {
  2979. var validNumber = (+dashArray[i] >= 0);
  2980. if (!validNumber) {
  2981. isInvalid = true;
  2982. break;
  2983. } else if (dashArray[i] > 0) {
  2984. numPositive++;
  2985. }
  2986. }
  2987. if (isInvalid || numPositive === 0) {
  2988. data.borderWidth = 0;
  2989. }
  2990. }
  2991. }
  2992. }
  2993. }
  2994. this.appearance = getDefaultAppearance(dict);
  2995. data.hasAppearance = !!this.appearance;
  2996. data.id = params.ref.num;
  2997. }
  2998. Annotation.prototype = {
  2999. getData: function Annotation_getData() {
  3000. return this.data;
  3001. },
  3002. hasHtml: function Annotation_hasHtml() {
  3003. return false;
  3004. },
  3005. getHtmlElement: function Annotation_getHtmlElement(commonObjs) {
  3006. throw new NotImplementedException(
  3007. 'getHtmlElement() should be implemented in subclass');
  3008. },
  3009. // TODO(mack): Remove this, it's not really that helpful.
  3010. getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect,
  3011. borderWidth) {
  3012. assert(!isWorker,
  3013. 'getEmptyContainer() should be called from main thread');
  3014. var bWidth = borderWidth || 0;
  3015. rect = rect || this.data.rect;
  3016. var element = document.createElement(tagName);
  3017. element.style.borderWidth = bWidth + 'px';
  3018. var width = rect[2] - rect[0] - 2 * bWidth;
  3019. var height = rect[3] - rect[1] - 2 * bWidth;
  3020. element.style.width = width + 'px';
  3021. element.style.height = height + 'px';
  3022. return element;
  3023. },
  3024. isInvisible: function Annotation_isInvisible() {
  3025. var data = this.data;
  3026. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  3027. return false;
  3028. } else {
  3029. return !!(data &&
  3030. data.annotationFlags && // Default: not invisible
  3031. data.annotationFlags & 0x1); // Invisible
  3032. }
  3033. },
  3034. isViewable: function Annotation_isViewable() {
  3035. var data = this.data;
  3036. return !!(!this.isInvisible() &&
  3037. data &&
  3038. (!data.annotationFlags ||
  3039. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  3040. data.rect); // rectangle is nessessary
  3041. },
  3042. isPrintable: function Annotation_isPrintable() {
  3043. var data = this.data;
  3044. return !!(!this.isInvisible() &&
  3045. data &&
  3046. data.annotationFlags && // Default: not printable
  3047. data.annotationFlags & 0x4 && // Print
  3048. data.rect); // rectangle is nessessary
  3049. },
  3050. loadResources: function Annotation_loadResources(keys) {
  3051. return new Promise(function (resolve, reject) {
  3052. this.appearance.dict.getAsync('Resources').then(function (resources) {
  3053. if (!resources) {
  3054. resolve();
  3055. return;
  3056. }
  3057. var objectLoader = new ObjectLoader(resources.map,
  3058. keys,
  3059. resources.xref);
  3060. objectLoader.load().then(function() {
  3061. resolve(resources);
  3062. }, reject);
  3063. }, reject);
  3064. }.bind(this));
  3065. },
  3066. getOperatorList: function Annotation_getOperatorList(evaluator) {
  3067. if (!this.appearance) {
  3068. return Promise.resolve(new OperatorList());
  3069. }
  3070. var data = this.data;
  3071. var appearanceDict = this.appearance.dict;
  3072. var resourcesPromise = this.loadResources([
  3073. 'ExtGState',
  3074. 'ColorSpace',
  3075. 'Pattern',
  3076. 'Shading',
  3077. 'XObject',
  3078. 'Font'
  3079. // ProcSet
  3080. // Properties
  3081. ]);
  3082. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  3083. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  3084. var transform = getTransformMatrix(data.rect, bbox, matrix);
  3085. var self = this;
  3086. return resourcesPromise.then(function(resources) {
  3087. var opList = new OperatorList();
  3088. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  3089. return evaluator.getOperatorList(self.appearance, resources, opList).
  3090. then(function () {
  3091. opList.addOp(OPS.endAnnotation, []);
  3092. self.appearance.reset();
  3093. return opList;
  3094. });
  3095. });
  3096. }
  3097. };
  3098. Annotation.getConstructor =
  3099. function Annotation_getConstructor(subtype, fieldType) {
  3100. if (!subtype) {
  3101. return;
  3102. }
  3103. // TODO(mack): Implement FreeText annotations
  3104. if (subtype === 'Link') {
  3105. return LinkAnnotation;
  3106. } else if (subtype === 'Text') {
  3107. return TextAnnotation;
  3108. } else if (subtype === 'Widget') {
  3109. if (!fieldType) {
  3110. return;
  3111. }
  3112. if (fieldType === 'Tx') {
  3113. return TextWidgetAnnotation;
  3114. } else {
  3115. return WidgetAnnotation;
  3116. }
  3117. } else {
  3118. return Annotation;
  3119. }
  3120. };
  3121. // TODO(mack): Support loading annotation from data
  3122. Annotation.fromData = function Annotation_fromData(data) {
  3123. var subtype = data.subtype;
  3124. var fieldType = data.fieldType;
  3125. var Constructor = Annotation.getConstructor(subtype, fieldType);
  3126. if (Constructor) {
  3127. return new Constructor({ data: data });
  3128. }
  3129. };
  3130. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  3131. var dict = xref.fetchIfRef(ref);
  3132. if (!isDict(dict)) {
  3133. return;
  3134. }
  3135. var subtype = dict.get('Subtype');
  3136. subtype = isName(subtype) ? subtype.name : '';
  3137. if (!subtype) {
  3138. return;
  3139. }
  3140. var fieldType = Util.getInheritableProperty(dict, 'FT');
  3141. fieldType = isName(fieldType) ? fieldType.name : '';
  3142. var Constructor = Annotation.getConstructor(subtype, fieldType);
  3143. if (!Constructor) {
  3144. return;
  3145. }
  3146. var params = {
  3147. dict: dict,
  3148. ref: ref,
  3149. };
  3150. var annotation = new Constructor(params);
  3151. if (annotation.isViewable() || annotation.isPrintable()) {
  3152. return annotation;
  3153. } else {
  3154. warn('unimplemented annotation type: ' + subtype);
  3155. }
  3156. };
  3157. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  3158. annotations, opList, pdfManager, partialEvaluator, intent) {
  3159. function reject(e) {
  3160. annotationsReadyCapability.reject(e);
  3161. }
  3162. var annotationsReadyCapability = createPromiseCapability();
  3163. var annotationPromises = [];
  3164. for (var i = 0, n = annotations.length; i < n; ++i) {
  3165. if (intent === 'display' && annotations[i].isViewable() ||
  3166. intent === 'print' && annotations[i].isPrintable()) {
  3167. annotationPromises.push(
  3168. annotations[i].getOperatorList(partialEvaluator));
  3169. }
  3170. }
  3171. Promise.all(annotationPromises).then(function(datas) {
  3172. opList.addOp(OPS.beginAnnotations, []);
  3173. for (var i = 0, n = datas.length; i < n; ++i) {
  3174. var annotOpList = datas[i];
  3175. opList.addOpList(annotOpList);
  3176. }
  3177. opList.addOp(OPS.endAnnotations, []);
  3178. annotationsReadyCapability.resolve();
  3179. }, reject);
  3180. return annotationsReadyCapability.promise;
  3181. };
  3182. return Annotation;
  3183. })();
  3184. PDFJS.Annotation = Annotation;
  3185. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  3186. function WidgetAnnotation(params) {
  3187. Annotation.call(this, params);
  3188. if (params.data) {
  3189. return;
  3190. }
  3191. var dict = params.dict;
  3192. var data = this.data;
  3193. data.fieldValue = stringToPDFString(
  3194. Util.getInheritableProperty(dict, 'V') || '');
  3195. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  3196. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  3197. var fieldType = Util.getInheritableProperty(dict, 'FT');
  3198. data.fieldType = isName(fieldType) ? fieldType.name : '';
  3199. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  3200. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  3201. // Building the full field name by collecting the field and
  3202. // its ancestors 'T' data and joining them using '.'.
  3203. var fieldName = [];
  3204. var namedItem = dict;
  3205. var ref = params.ref;
  3206. while (namedItem) {
  3207. var parent = namedItem.get('Parent');
  3208. var parentRef = namedItem.getRaw('Parent');
  3209. var name = namedItem.get('T');
  3210. if (name) {
  3211. fieldName.unshift(stringToPDFString(name));
  3212. } else {
  3213. // The field name is absent, that means more than one field
  3214. // with the same name may exist. Replacing the empty name
  3215. // with the '`' plus index in the parent's 'Kids' array.
  3216. // This is not in the PDF spec but necessary to id the
  3217. // the input controls.
  3218. var kids = parent.get('Kids');
  3219. var j, jj;
  3220. for (j = 0, jj = kids.length; j < jj; j++) {
  3221. var kidRef = kids[j];
  3222. if (kidRef.num == ref.num && kidRef.gen == ref.gen) {
  3223. break;
  3224. }
  3225. }
  3226. fieldName.unshift('`' + j);
  3227. }
  3228. namedItem = parent;
  3229. ref = parentRef;
  3230. }
  3231. data.fullName = fieldName.join('.');
  3232. }
  3233. var parent = Annotation.prototype;
  3234. Util.inherit(WidgetAnnotation, Annotation, {
  3235. isViewable: function WidgetAnnotation_isViewable() {
  3236. if (this.data.fieldType === 'Sig') {
  3237. warn('unimplemented annotation type: Widget signature');
  3238. return false;
  3239. }
  3240. return parent.isViewable.call(this);
  3241. }
  3242. });
  3243. return WidgetAnnotation;
  3244. })();
  3245. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  3246. function TextWidgetAnnotation(params) {
  3247. WidgetAnnotation.call(this, params);
  3248. if (params.data) {
  3249. return;
  3250. }
  3251. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  3252. }
  3253. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  3254. function setTextStyles(element, item, fontObj) {
  3255. var style = element.style;
  3256. style.fontSize = item.fontSize + 'px';
  3257. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  3258. if (!fontObj) {
  3259. return;
  3260. }
  3261. style.fontWeight = fontObj.black ?
  3262. (fontObj.bold ? 'bolder' : 'bold') :
  3263. (fontObj.bold ? 'bold' : 'normal');
  3264. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  3265. var fontName = fontObj.loadedName;
  3266. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  3267. // Use a reasonable default font if the font doesn't specify a fallback
  3268. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  3269. style.fontFamily = fontFamily + fallbackName;
  3270. }
  3271. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  3272. hasHtml: function TextWidgetAnnotation_hasHtml() {
  3273. return !this.data.hasAppearance && !!this.data.fieldValue;
  3274. },
  3275. getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {
  3276. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  3277. var item = this.data;
  3278. var element = this.getEmptyContainer('div');
  3279. element.style.display = 'table';
  3280. var content = document.createElement('div');
  3281. content.textContent = item.fieldValue;
  3282. var textAlignment = item.textAlignment;
  3283. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  3284. content.style.verticalAlign = 'middle';
  3285. content.style.display = 'table-cell';
  3286. var fontObj = item.fontRefName ?
  3287. commonObjs.getData(item.fontRefName) : null;
  3288. setTextStyles(content, item, fontObj);
  3289. element.appendChild(content);
  3290. return element;
  3291. },
  3292. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  3293. if (this.appearance) {
  3294. return Annotation.prototype.getOperatorList.call(this, evaluator);
  3295. }
  3296. var opList = new OperatorList();
  3297. var data = this.data;
  3298. // Even if there is an appearance stream, ignore it. This is the
  3299. // behaviour used by Adobe Reader.
  3300. if (!data.defaultAppearance) {
  3301. return Promise.resolve(opList);
  3302. }
  3303. var stream = new Stream(stringToBytes(data.defaultAppearance));
  3304. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  3305. then(function () {
  3306. return opList;
  3307. });
  3308. }
  3309. });
  3310. return TextWidgetAnnotation;
  3311. })();
  3312. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  3313. function InteractiveAnnotation(params) {
  3314. Annotation.call(this, params);
  3315. }
  3316. Util.inherit(InteractiveAnnotation, Annotation, {
  3317. hasHtml: function InteractiveAnnotation_hasHtml() {
  3318. return true;
  3319. },
  3320. highlight: function InteractiveAnnotation_highlight() {
  3321. if (this.highlightElement &&
  3322. this.highlightElement.hasAttribute('hidden')) {
  3323. this.highlightElement.removeAttribute('hidden');
  3324. }
  3325. },
  3326. unhighlight: function InteractiveAnnotation_unhighlight() {
  3327. if (this.highlightElement &&
  3328. !this.highlightElement.hasAttribute('hidden')) {
  3329. this.highlightElement.setAttribute('hidden', true);
  3330. }
  3331. },
  3332. initContainer: function InteractiveAnnotation_initContainer() {
  3333. var item = this.data;
  3334. var rect = item.rect;
  3335. var container = this.getEmptyContainer('section', rect, item.borderWidth);
  3336. container.style.backgroundColor = item.color;
  3337. var color = item.color;
  3338. var rgb = [];
  3339. for (var i = 0; i < 3; ++i) {
  3340. rgb[i] = Math.round(color[i] * 255);
  3341. }
  3342. item.colorCssRgb = Util.makeCssRgb(rgb);
  3343. var highlight = document.createElement('div');
  3344. highlight.className = 'annotationHighlight';
  3345. highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
  3346. highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
  3347. highlight.setAttribute('hidden', true);
  3348. this.highlightElement = highlight;
  3349. container.appendChild(this.highlightElement);
  3350. return container;
  3351. }
  3352. });
  3353. return InteractiveAnnotation;
  3354. })();
  3355. var TextAnnotation = (function TextAnnotationClosure() {
  3356. function TextAnnotation(params) {
  3357. InteractiveAnnotation.call(this, params);
  3358. if (params.data) {
  3359. return;
  3360. }
  3361. var dict = params.dict;
  3362. var data = this.data;
  3363. var content = dict.get('Contents');
  3364. var title = dict.get('T');
  3365. data.content = stringToPDFString(content || '');
  3366. data.title = stringToPDFString(title || '');
  3367. if (data.hasAppearance) {
  3368. data.name = 'NoIcon';
  3369. } else {
  3370. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  3371. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  3372. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  3373. }
  3374. if (dict.has('C')) {
  3375. data.hasBgColor = true;
  3376. }
  3377. }
  3378. var ANNOT_MIN_SIZE = 10;
  3379. Util.inherit(TextAnnotation, InteractiveAnnotation, {
  3380. getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {
  3381. assert(!isWorker, 'getHtmlElement() shall be called from main thread');
  3382. var item = this.data;
  3383. var rect = item.rect;
  3384. // sanity check because of OOo-generated PDFs
  3385. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  3386. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  3387. }
  3388. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  3389. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  3390. }
  3391. var container = this.initContainer();
  3392. container.className = 'annotText';
  3393. var image = document.createElement('img');
  3394. image.style.height = container.style.height;
  3395. image.style.width = container.style.width;
  3396. var iconName = item.name;
  3397. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  3398. iconName.toLowerCase() + '.svg';
  3399. image.alt = '[{{type}} Annotation]';
  3400. image.dataset.l10nId = 'text_annotation_type';
  3401. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  3402. var contentWrapper = document.createElement('div');
  3403. contentWrapper.className = 'annotTextContentWrapper';
  3404. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  3405. contentWrapper.style.top = '-10px';
  3406. var content = document.createElement('div');
  3407. content.className = 'annotTextContent';
  3408. content.setAttribute('hidden', true);
  3409. var i, ii;
  3410. if (item.hasBgColor) {
  3411. var color = item.color;
  3412. var rgb = [];
  3413. for (i = 0; i < 3; ++i) {
  3414. // Enlighten the color (70%)
  3415. var c = Math.round(color[i] * 255);
  3416. rgb[i] = Math.round((255 - c) * 0.7) + c;
  3417. }
  3418. content.style.backgroundColor = Util.makeCssRgb(rgb);
  3419. }
  3420. var title = document.createElement('h1');
  3421. var text = document.createElement('p');
  3422. title.textContent = item.title;
  3423. if (!item.content && !item.title) {
  3424. content.setAttribute('hidden', true);
  3425. } else {
  3426. var e = document.createElement('span');
  3427. var lines = item.content.split(/(?:\r\n?|\n)/);
  3428. for (i = 0, ii = lines.length; i < ii; ++i) {
  3429. var line = lines[i];
  3430. e.appendChild(document.createTextNode(line));
  3431. if (i < (ii - 1)) {
  3432. e.appendChild(document.createElement('br'));
  3433. }
  3434. }
  3435. text.appendChild(e);
  3436. var pinned = false;
  3437. var showAnnotation = function showAnnotation(pin) {
  3438. if (pin) {
  3439. pinned = true;
  3440. }
  3441. if (content.hasAttribute('hidden')) {
  3442. container.style.zIndex += 1;
  3443. content.removeAttribute('hidden');
  3444. }
  3445. };
  3446. var hideAnnotation = function hideAnnotation(unpin) {
  3447. if (unpin) {
  3448. pinned = false;
  3449. }
  3450. if (!content.hasAttribute('hidden') && !pinned) {
  3451. container.style.zIndex -= 1;
  3452. content.setAttribute('hidden', true);
  3453. }
  3454. };
  3455. var toggleAnnotation = function toggleAnnotation() {
  3456. if (pinned) {
  3457. hideAnnotation(true);
  3458. } else {
  3459. showAnnotation(true);
  3460. }
  3461. };
  3462. image.addEventListener('click', function image_clickHandler() {
  3463. toggleAnnotation();
  3464. }, false);
  3465. image.addEventListener('mouseover', function image_mouseOverHandler() {
  3466. showAnnotation();
  3467. }, false);
  3468. image.addEventListener('mouseout', function image_mouseOutHandler() {
  3469. hideAnnotation();
  3470. }, false);
  3471. content.addEventListener('click', function content_clickHandler() {
  3472. hideAnnotation(true);
  3473. }, false);
  3474. }
  3475. content.appendChild(title);
  3476. content.appendChild(text);
  3477. contentWrapper.appendChild(content);
  3478. container.appendChild(image);
  3479. container.appendChild(contentWrapper);
  3480. return container;
  3481. }
  3482. });
  3483. return TextAnnotation;
  3484. })();
  3485. var LinkAnnotation = (function LinkAnnotationClosure() {
  3486. function LinkAnnotation(params) {
  3487. InteractiveAnnotation.call(this, params);
  3488. if (params.data) {
  3489. return;
  3490. }
  3491. var dict = params.dict;
  3492. var data = this.data;
  3493. var action = dict.get('A');
  3494. if (action) {
  3495. var linkType = action.get('S').name;
  3496. if (linkType === 'URI') {
  3497. var url = action.get('URI');
  3498. if (isName(url)) {
  3499. // Some bad PDFs do not put parentheses around relative URLs.
  3500. url = '/' + url.name;
  3501. } else if (url) {
  3502. url = addDefaultProtocolToUrl(url);
  3503. }
  3504. // TODO: pdf spec mentions urls can be relative to a Base
  3505. // entry in the dictionary.
  3506. if (!isValidUrl(url, false)) {
  3507. url = '';
  3508. }
  3509. data.url = url;
  3510. } else if (linkType === 'GoTo') {
  3511. data.dest = action.get('D');
  3512. } else if (linkType === 'GoToR') {
  3513. var urlDict = action.get('F');
  3514. if (isDict(urlDict)) {
  3515. // We assume that the 'url' is a Filspec dictionary
  3516. // and fetch the url without checking any further
  3517. url = urlDict.get('F') || '';
  3518. }
  3519. // TODO: pdf reference says that GoToR
  3520. // can also have 'NewWindow' attribute
  3521. if (!isValidUrl(url, false)) {
  3522. url = '';
  3523. }
  3524. data.url = url;
  3525. data.dest = action.get('D');
  3526. } else if (linkType === 'Named') {
  3527. data.action = action.get('N').name;
  3528. } else {
  3529. warn('unrecognized link type: ' + linkType);
  3530. }
  3531. } else if (dict.has('Dest')) {
  3532. // simple destination link
  3533. var dest = dict.get('Dest');
  3534. data.dest = isName(dest) ? dest.name : dest;
  3535. }
  3536. }
  3537. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  3538. function addDefaultProtocolToUrl(url) {
  3539. if (url && url.indexOf('www.') === 0) {
  3540. return ('http://' + url);
  3541. }
  3542. return url;
  3543. }
  3544. Util.inherit(LinkAnnotation, InteractiveAnnotation, {
  3545. hasOperatorList: function LinkAnnotation_hasOperatorList() {
  3546. return false;
  3547. },
  3548. getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {
  3549. var container = this.initContainer();
  3550. container.className = 'annotLink';
  3551. var item = this.data;
  3552. container.style.borderColor = item.colorCssRgb;
  3553. container.style.borderStyle = 'solid';
  3554. var link = document.createElement('a');
  3555. link.href = link.title = this.data.url || '';
  3556. container.appendChild(link);
  3557. return container;
  3558. }
  3559. });
  3560. return LinkAnnotation;
  3561. })();
  3562. /**
  3563. * The maximum allowed image size in total pixels e.g. width * height. Images
  3564. * above this value will not be drawn. Use -1 for no limit.
  3565. * @var {number}
  3566. */
  3567. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  3568. -1 : PDFJS.maxImageSize);
  3569. /**
  3570. * The url of where the predefined Adobe CMaps are located. Include trailing
  3571. * slash.
  3572. * @var {string}
  3573. */
  3574. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  3575. /**
  3576. * Specifies if CMaps are binary packed.
  3577. * @var {boolean}
  3578. */
  3579. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  3580. /*
  3581. * By default fonts are converted to OpenType fonts and loaded via font face
  3582. * rules. If disabled, the font will be rendered using a built in font renderer
  3583. * that constructs the glyphs with primitive path commands.
  3584. * @var {boolean}
  3585. */
  3586. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  3587. false : PDFJS.disableFontFace);
  3588. /**
  3589. * Path for image resources, mainly for annotation icons. Include trailing
  3590. * slash.
  3591. * @var {string}
  3592. */
  3593. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  3594. '' : PDFJS.imageResourcesPath);
  3595. /**
  3596. * Disable the web worker and run all code on the main thread. This will happen
  3597. * automatically if the browser doesn't support workers or sending typed arrays
  3598. * to workers.
  3599. * @var {boolean}
  3600. */
  3601. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  3602. false : PDFJS.disableWorker);
  3603. /**
  3604. * Path and filename of the worker file. Required when the worker is enabled in
  3605. * development mode. If unspecified in the production build, the worker will be
  3606. * loaded based on the location of the pdf.js file.
  3607. * @var {string}
  3608. */
  3609. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  3610. /**
  3611. * Disable range request loading of PDF files. When enabled and if the server
  3612. * supports partial content requests then the PDF will be fetched in chunks.
  3613. * Enabled (false) by default.
  3614. * @var {boolean}
  3615. */
  3616. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  3617. false : PDFJS.disableRange);
  3618. /**
  3619. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  3620. * will automatically keep fetching more data even if it isn't needed to display
  3621. * the current page. This default behavior can be disabled.
  3622. * @var {boolean}
  3623. */
  3624. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  3625. false : PDFJS.disableAutoFetch);
  3626. /**
  3627. * Enables special hooks for debugging PDF.js.
  3628. * @var {boolean}
  3629. */
  3630. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  3631. /**
  3632. * Enables transfer usage in postMessage for ArrayBuffers.
  3633. * @var {boolean}
  3634. */
  3635. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  3636. true : PDFJS.postMessageTransfers);
  3637. /**
  3638. * Disables URL.createObjectURL usage.
  3639. * @var {boolean}
  3640. */
  3641. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  3642. false : PDFJS.disableCreateObjectURL);
  3643. /**
  3644. * Disables WebGL usage.
  3645. * @var {boolean}
  3646. */
  3647. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  3648. true : PDFJS.disableWebGL);
  3649. /**
  3650. * Controls the logging level.
  3651. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  3652. * - errors
  3653. * - warnings [default]
  3654. * - infos
  3655. * @var {number}
  3656. */
  3657. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  3658. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  3659. /**
  3660. * Document initialization / loading parameters object.
  3661. *
  3662. * @typedef {Object} DocumentInitParameters
  3663. * @property {string} url - The URL of the PDF.
  3664. * @property {TypedArray} data - A typed array with PDF data.
  3665. * @property {Object} httpHeaders - Basic authentication headers.
  3666. * @property {boolean} withCredentials - Indicates whether or not cross-site
  3667. * Access-Control requests should be made using credentials such as cookies
  3668. * or authorization headers. The default is false.
  3669. * @property {string} password - For decrypting password-protected PDFs.
  3670. * @property {TypedArray} initialData - A typed array with the first portion or
  3671. * all of the pdf data. Used by the extension since some data is already
  3672. * loaded before the switch to range requests.
  3673. */
  3674. /**
  3675. * This is the main entry point for loading a PDF and interacting with it.
  3676. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  3677. * is used, which means it must follow the same origin rules that any XHR does
  3678. * e.g. No cross domain requests without CORS.
  3679. *
  3680. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  3681. * where a PDF is located, a typed array (Uint8Array) already populated with
  3682. * data or parameter object.
  3683. *
  3684. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  3685. * to manually serve range requests for data in the PDF. See viewer.js for
  3686. * an example of pdfDataRangeTransport's interface.
  3687. *
  3688. * @param {function} passwordCallback is optional. It is used to request a
  3689. * password if wrong or no password was provided. The callback receives two
  3690. * parameters: function that needs to be called with new password and reason
  3691. * (see {PasswordResponses}).
  3692. *
  3693. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  3694. * object.
  3695. */
  3696. PDFJS.getDocument = function getDocument(source,
  3697. pdfDataRangeTransport,
  3698. passwordCallback,
  3699. progressCallback) {
  3700. var workerInitializedCapability, workerReadyCapability, transport;
  3701. if (typeof source === 'string') {
  3702. source = { url: source };
  3703. } else if (isArrayBuffer(source)) {
  3704. source = { data: source };
  3705. } else if (typeof source !== 'object') {
  3706. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  3707. 'string or a parameter object');
  3708. }
  3709. if (!source.url && !source.data) {
  3710. error('Invalid parameter array, need either .data or .url');
  3711. }
  3712. // copy/use all keys as is except 'url' -- full path is required
  3713. var params = {};
  3714. for (var key in source) {
  3715. if (key === 'url' && typeof window !== 'undefined') {
  3716. params[key] = combineUrl(window.location.href, source[key]);
  3717. continue;
  3718. }
  3719. params[key] = source[key];
  3720. }
  3721. workerInitializedCapability = createPromiseCapability();
  3722. workerReadyCapability = createPromiseCapability();
  3723. transport = new WorkerTransport(workerInitializedCapability,
  3724. workerReadyCapability, pdfDataRangeTransport,
  3725. progressCallback);
  3726. workerInitializedCapability.promise.then(function transportInitialized() {
  3727. transport.passwordCallback = passwordCallback;
  3728. transport.fetchDocument(params);
  3729. });
  3730. return workerReadyCapability.promise;
  3731. };
  3732. /**
  3733. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  3734. * properties that can be read synchronously.
  3735. * @class
  3736. */
  3737. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  3738. function PDFDocumentProxy(pdfInfo, transport) {
  3739. this.pdfInfo = pdfInfo;
  3740. this.transport = transport;
  3741. }
  3742. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  3743. /**
  3744. * @return {number} Total number of pages the PDF contains.
  3745. */
  3746. get numPages() {
  3747. return this.pdfInfo.numPages;
  3748. },
  3749. /**
  3750. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  3751. * unique.
  3752. */
  3753. get fingerprint() {
  3754. return this.pdfInfo.fingerprint;
  3755. },
  3756. /**
  3757. * @param {number} pageNumber The page number to get. The first page is 1.
  3758. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  3759. * object.
  3760. */
  3761. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  3762. return this.transport.getPage(pageNumber);
  3763. },
  3764. /**
  3765. * @param {{num: number, gen: number}} ref The page reference. Must have
  3766. * the 'num' and 'gen' properties.
  3767. * @return {Promise} A promise that is resolved with the page index that is
  3768. * associated with the reference.
  3769. */
  3770. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  3771. return this.transport.getPageIndex(ref);
  3772. },
  3773. /**
  3774. * @return {Promise} A promise that is resolved with a lookup table for
  3775. * mapping named destinations to reference numbers.
  3776. */
  3777. getDestinations: function PDFDocumentProxy_getDestinations() {
  3778. return this.transport.getDestinations();
  3779. },
  3780. /**
  3781. * @return {Promise} A promise that is resolved with a lookup table for
  3782. * mapping named attachments to their content.
  3783. */
  3784. getAttachments: function PDFDocumentProxy_getAttachments() {
  3785. return this.transport.getAttachments();
  3786. },
  3787. /**
  3788. * @return {Promise} A promise that is resolved with an array of all the
  3789. * JavaScript strings in the name tree.
  3790. */
  3791. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  3792. return this.transport.getJavaScript();
  3793. },
  3794. /**
  3795. * @return {Promise} A promise that is resolved with an {Array} that is a
  3796. * tree outline (if it has one) of the PDF. The tree is in the format of:
  3797. * [
  3798. * {
  3799. * title: string,
  3800. * bold: boolean,
  3801. * italic: boolean,
  3802. * color: rgb array,
  3803. * dest: dest obj,
  3804. * items: array of more items like this
  3805. * },
  3806. * ...
  3807. * ].
  3808. */
  3809. getOutline: function PDFDocumentProxy_getOutline() {
  3810. return this.transport.getOutline();
  3811. },
  3812. /**
  3813. * @return {Promise} A promise that is resolved with an {Object} that has
  3814. * info and metadata properties. Info is an {Object} filled with anything
  3815. * available in the information dictionary and similarly metadata is a
  3816. * {Metadata} object with information from the metadata section of the PDF.
  3817. */
  3818. getMetadata: function PDFDocumentProxy_getMetadata() {
  3819. return this.transport.getMetadata();
  3820. },
  3821. /**
  3822. * @return {Promise} A promise that is resolved with a TypedArray that has
  3823. * the raw data from the PDF.
  3824. */
  3825. getData: function PDFDocumentProxy_getData() {
  3826. return this.transport.getData();
  3827. },
  3828. /**
  3829. * @return {Promise} A promise that is resolved when the document's data
  3830. * is loaded. It is resolved with an {Object} that contains the length
  3831. * property that indicates size of the PDF data in bytes.
  3832. */
  3833. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  3834. return this.transport.downloadInfoCapability.promise;
  3835. },
  3836. /**
  3837. * Cleans up resources allocated by the document, e.g. created @font-face.
  3838. */
  3839. cleanup: function PDFDocumentProxy_cleanup() {
  3840. this.transport.startCleanup();
  3841. },
  3842. /**
  3843. * Destroys current document instance and terminates worker.
  3844. */
  3845. destroy: function PDFDocumentProxy_destroy() {
  3846. this.transport.destroy();
  3847. }
  3848. };
  3849. return PDFDocumentProxy;
  3850. })();
  3851. /**
  3852. * Page text content.
  3853. *
  3854. * @typedef {Object} TextContent
  3855. * @property {array} items - array of {@link TextItem}
  3856. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  3857. * name.
  3858. */
  3859. /**
  3860. * Page text content part.
  3861. *
  3862. * @typedef {Object} TextItem
  3863. * @property {string} str - text content.
  3864. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  3865. * @property {array} transform - transformation matrix.
  3866. * @property {number} width - width in device space.
  3867. * @property {number} height - height in device space.
  3868. * @property {string} fontName - font name used by pdf.js for converted font.
  3869. */
  3870. /**
  3871. * Text style.
  3872. *
  3873. * @typedef {Object} TextStyle
  3874. * @property {number} ascent - font ascent.
  3875. * @property {number} descent - font descent.
  3876. * @property {boolean} vertical - text is in vertical mode.
  3877. * @property {string} fontFamily - possible font family
  3878. */
  3879. /**
  3880. * Page render parameters.
  3881. *
  3882. * @typedef {Object} RenderParameters
  3883. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  3884. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  3885. * calling of PDFPage.getViewport method.
  3886. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  3887. * (default value is 'display').
  3888. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  3889. * endLayout and appendImage functions.
  3890. * @property {function} continueCallback - (optional) A function that will be
  3891. * called each time the rendering is paused. To continue
  3892. * rendering call the function that is the first argument
  3893. * to the callback.
  3894. */
  3895. /**
  3896. * Proxy to a PDFPage in the worker thread.
  3897. * @class
  3898. */
  3899. var PDFPageProxy = (function PDFPageProxyClosure() {
  3900. function PDFPageProxy(pageIndex, pageInfo, transport) {
  3901. this.pageIndex = pageIndex;
  3902. this.pageInfo = pageInfo;
  3903. this.transport = transport;
  3904. this.stats = new StatTimer();
  3905. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  3906. this.commonObjs = transport.commonObjs;
  3907. this.objs = new PDFObjects();
  3908. this.cleanupAfterRender = false;
  3909. this.pendingDestroy = false;
  3910. this.intentStates = {};
  3911. }
  3912. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  3913. /**
  3914. * @return {number} Page number of the page. First page is 1.
  3915. */
  3916. get pageNumber() {
  3917. return this.pageIndex + 1;
  3918. },
  3919. /**
  3920. * @return {number} The number of degrees the page is rotated clockwise.
  3921. */
  3922. get rotate() {
  3923. return this.pageInfo.rotate;
  3924. },
  3925. /**
  3926. * @return {Object} The reference that points to this page. It has 'num' and
  3927. * 'gen' properties.
  3928. */
  3929. get ref() {
  3930. return this.pageInfo.ref;
  3931. },
  3932. /**
  3933. * @return {Array} An array of the visible portion of the PDF page in the
  3934. * user space units - [x1, y1, x2, y2].
  3935. */
  3936. get view() {
  3937. return this.pageInfo.view;
  3938. },
  3939. /**
  3940. * @param {number} scale The desired scale of the viewport.
  3941. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  3942. * defaults to the page rotation.
  3943. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  3944. * along with transforms required for rendering.
  3945. */
  3946. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  3947. if (arguments.length < 2) {
  3948. rotate = this.rotate;
  3949. }
  3950. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  3951. },
  3952. /**
  3953. * @return {Promise} A promise that is resolved with an {Array} of the
  3954. * annotation objects.
  3955. */
  3956. getAnnotations: function PDFPageProxy_getAnnotations() {
  3957. if (this.annotationsPromise) {
  3958. return this.annotationsPromise;
  3959. }
  3960. var promise = this.transport.getAnnotations(this.pageIndex);
  3961. this.annotationsPromise = promise;
  3962. return promise;
  3963. },
  3964. /**
  3965. * Begins the process of rendering a page to the desired context.
  3966. * @param {RenderParameters} params Page render parameters.
  3967. * @return {RenderTask} An object that contains the promise, which
  3968. * is resolved when the page finishes rendering.
  3969. */
  3970. render: function PDFPageProxy_render(params) {
  3971. var stats = this.stats;
  3972. stats.time('Overall');
  3973. // If there was a pending destroy cancel it so no cleanup happens during
  3974. // this call to render.
  3975. this.pendingDestroy = false;
  3976. var renderingIntent = ('intent' in params ?
  3977. (params.intent == 'print' ? 'print' : 'display') : 'display');
  3978. if (!this.intentStates[renderingIntent]) {
  3979. this.intentStates[renderingIntent] = {};
  3980. }
  3981. var intentState = this.intentStates[renderingIntent];
  3982. // If there's no displayReadyCapability yet, then the operatorList
  3983. // was never requested before. Make the request and create the promise.
  3984. if (!intentState.displayReadyCapability) {
  3985. intentState.receivingOperatorList = true;
  3986. intentState.displayReadyCapability = createPromiseCapability();
  3987. intentState.operatorList = {
  3988. fnArray: [],
  3989. argsArray: [],
  3990. lastChunk: false
  3991. };
  3992. this.stats.time('Page Request');
  3993. this.transport.messageHandler.send('RenderPageRequest', {
  3994. pageIndex: this.pageNumber - 1,
  3995. intent: renderingIntent
  3996. });
  3997. }
  3998. var internalRenderTask = new InternalRenderTask(complete, params,
  3999. this.objs,
  4000. this.commonObjs,
  4001. intentState.operatorList,
  4002. this.pageNumber);
  4003. if (!intentState.renderTasks) {
  4004. intentState.renderTasks = [];
  4005. }
  4006. intentState.renderTasks.push(internalRenderTask);
  4007. var renderTask = new RenderTask(internalRenderTask);
  4008. var self = this;
  4009. intentState.displayReadyCapability.promise.then(
  4010. function pageDisplayReadyPromise(transparency) {
  4011. if (self.pendingDestroy) {
  4012. complete();
  4013. return;
  4014. }
  4015. stats.time('Rendering');
  4016. internalRenderTask.initalizeGraphics(transparency);
  4017. internalRenderTask.operatorListChanged();
  4018. },
  4019. function pageDisplayReadPromiseError(reason) {
  4020. complete(reason);
  4021. }
  4022. );
  4023. function complete(error) {
  4024. var i = intentState.renderTasks.indexOf(internalRenderTask);
  4025. if (i >= 0) {
  4026. intentState.renderTasks.splice(i, 1);
  4027. }
  4028. if (self.cleanupAfterRender) {
  4029. self.pendingDestroy = true;
  4030. }
  4031. self._tryDestroy();
  4032. if (error) {
  4033. internalRenderTask.capability.reject(error);
  4034. } else {
  4035. internalRenderTask.capability.resolve();
  4036. }
  4037. stats.timeEnd('Rendering');
  4038. stats.timeEnd('Overall');
  4039. }
  4040. return renderTask;
  4041. },
  4042. /**
  4043. * @return {Promise} That is resolved a {@link TextContent}
  4044. * object that represent the page text content.
  4045. */
  4046. getTextContent: function PDFPageProxy_getTextContent() {
  4047. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  4048. pageIndex: this.pageNumber - 1
  4049. });
  4050. },
  4051. /**
  4052. * Destroys resources allocated by the page.
  4053. */
  4054. destroy: function PDFPageProxy_destroy() {
  4055. this.pendingDestroy = true;
  4056. this._tryDestroy();
  4057. },
  4058. /**
  4059. * For internal use only. Attempts to clean up if rendering is in a state
  4060. * where that's possible.
  4061. * @ignore
  4062. */
  4063. _tryDestroy: function PDFPageProxy__destroy() {
  4064. if (!this.pendingDestroy ||
  4065. Object.keys(this.intentStates).some(function(intent) {
  4066. var intentState = this.intentStates[intent];
  4067. return (intentState.renderTasks.length !== 0 ||
  4068. intentState.receivingOperatorList);
  4069. }, this)) {
  4070. return;
  4071. }
  4072. Object.keys(this.intentStates).forEach(function(intent) {
  4073. delete this.intentStates[intent];
  4074. }, this);
  4075. this.objs.clear();
  4076. this.annotationsPromise = null;
  4077. this.pendingDestroy = false;
  4078. },
  4079. /**
  4080. * For internal use only.
  4081. * @ignore
  4082. */
  4083. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  4084. intent) {
  4085. var intentState = this.intentStates[intent];
  4086. intentState.displayReadyCapability.resolve(transparency);
  4087. },
  4088. /**
  4089. * For internal use only.
  4090. * @ignore
  4091. */
  4092. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  4093. intent) {
  4094. var intentState = this.intentStates[intent];
  4095. var i, ii;
  4096. // Add the new chunk to the current operator list.
  4097. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  4098. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  4099. intentState.operatorList.argsArray.push(
  4100. operatorListChunk.argsArray[i]);
  4101. }
  4102. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  4103. // Notify all the rendering tasks there are more operators to be consumed.
  4104. for (i = 0; i < intentState.renderTasks.length; i++) {
  4105. intentState.renderTasks[i].operatorListChanged();
  4106. }
  4107. if (operatorListChunk.lastChunk) {
  4108. intentState.receivingOperatorList = false;
  4109. this._tryDestroy();
  4110. }
  4111. }
  4112. };
  4113. return PDFPageProxy;
  4114. })();
  4115. /**
  4116. * For internal use only.
  4117. * @ignore
  4118. */
  4119. var WorkerTransport = (function WorkerTransportClosure() {
  4120. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  4121. pdfDataRangeTransport, progressCallback) {
  4122. this.pdfDataRangeTransport = pdfDataRangeTransport;
  4123. this.workerReadyCapability = workerReadyCapability;
  4124. this.progressCallback = progressCallback;
  4125. this.commonObjs = new PDFObjects();
  4126. this.pageCache = [];
  4127. this.pagePromises = [];
  4128. this.downloadInfoCapability = createPromiseCapability();
  4129. this.passwordCallback = null;
  4130. // If worker support isn't disabled explicit and the browser has worker
  4131. // support, create a new web worker and test if it/the browser fullfills
  4132. // all requirements to run parts of pdf.js in a web worker.
  4133. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  4134. // as it arrives on the worker. Chrome added this with version 15.
  4135. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  4136. var workerSrc = PDFJS.workerSrc;
  4137. if (!workerSrc) {
  4138. error('No PDFJS.workerSrc specified');
  4139. }
  4140. try {
  4141. // Some versions of FF can't create a worker on localhost, see:
  4142. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  4143. var worker = new Worker(workerSrc);
  4144. var messageHandler = new MessageHandler('main', worker);
  4145. this.messageHandler = messageHandler;
  4146. messageHandler.on('test', function transportTest(data) {
  4147. var supportTypedArray = data && data.supportTypedArray;
  4148. if (supportTypedArray) {
  4149. this.worker = worker;
  4150. if (!data.supportTransfers) {
  4151. PDFJS.postMessageTransfers = false;
  4152. }
  4153. this.setupMessageHandler(messageHandler);
  4154. workerInitializedCapability.resolve();
  4155. } else {
  4156. globalScope.PDFJS.disableWorker = true;
  4157. this.loadFakeWorkerFiles().then(function() {
  4158. this.setupFakeWorker();
  4159. workerInitializedCapability.resolve();
  4160. }.bind(this));
  4161. }
  4162. }.bind(this));
  4163. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  4164. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  4165. // typed array. Also, checking if we can use transfers.
  4166. try {
  4167. messageHandler.send('test', testObj, [testObj.buffer]);
  4168. } catch (ex) {
  4169. info('Cannot use postMessage transfers');
  4170. testObj[0] = 0;
  4171. messageHandler.send('test', testObj);
  4172. }
  4173. return;
  4174. } catch (e) {
  4175. info('The worker has been disabled.');
  4176. }
  4177. }
  4178. // Either workers are disabled, not supported or have thrown an exception.
  4179. // Thus, we fallback to a faked worker.
  4180. globalScope.PDFJS.disableWorker = true;
  4181. this.loadFakeWorkerFiles().then(function() {
  4182. this.setupFakeWorker();
  4183. workerInitializedCapability.resolve();
  4184. }.bind(this));
  4185. }
  4186. WorkerTransport.prototype = {
  4187. destroy: function WorkerTransport_destroy() {
  4188. this.pageCache = [];
  4189. this.pagePromises = [];
  4190. var self = this;
  4191. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  4192. FontLoader.clear();
  4193. if (self.worker) {
  4194. self.worker.terminate();
  4195. }
  4196. });
  4197. },
  4198. loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {
  4199. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  4200. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  4201. // In the developer build load worker_loader which in turn loads all the
  4202. // other files and resolves the promise. In production only the
  4203. // pdf.worker.js file is needed.
  4204. Util.loadScript(PDFJS.workerSrc, function() {
  4205. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  4206. });
  4207. }
  4208. return PDFJS.fakeWorkerFilesLoadedCapability.promise;
  4209. },
  4210. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  4211. warn('Setting up fake worker.');
  4212. // If we don't use a worker, just post/sendMessage to the main thread.
  4213. var fakeWorker = {
  4214. postMessage: function WorkerTransport_postMessage(obj) {
  4215. fakeWorker.onmessage({data: obj});
  4216. },
  4217. terminate: function WorkerTransport_terminate() {}
  4218. };
  4219. var messageHandler = new MessageHandler('main', fakeWorker);
  4220. this.setupMessageHandler(messageHandler);
  4221. // If the main thread is our worker, setup the handling for the messages
  4222. // the main thread sends to it self.
  4223. PDFJS.WorkerMessageHandler.setup(messageHandler);
  4224. },
  4225. setupMessageHandler:
  4226. function WorkerTransport_setupMessageHandler(messageHandler) {
  4227. this.messageHandler = messageHandler;
  4228. function updatePassword(password) {
  4229. messageHandler.send('UpdatePassword', password);
  4230. }
  4231. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  4232. if (pdfDataRangeTransport) {
  4233. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  4234. messageHandler.send('OnDataRange', {
  4235. begin: begin,
  4236. chunk: chunk
  4237. });
  4238. });
  4239. pdfDataRangeTransport.addProgressListener(function(loaded) {
  4240. messageHandler.send('OnDataProgress', {
  4241. loaded: loaded
  4242. });
  4243. });
  4244. messageHandler.on('RequestDataRange',
  4245. function transportDataRange(data) {
  4246. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  4247. }, this);
  4248. }
  4249. messageHandler.on('GetDoc', function transportDoc(data) {
  4250. var pdfInfo = data.pdfInfo;
  4251. this.numPages = data.pdfInfo.numPages;
  4252. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  4253. this.pdfDocument = pdfDocument;
  4254. this.workerReadyCapability.resolve(pdfDocument);
  4255. }, this);
  4256. messageHandler.on('NeedPassword', function transportPassword(data) {
  4257. if (this.passwordCallback) {
  4258. return this.passwordCallback(updatePassword,
  4259. PasswordResponses.NEED_PASSWORD);
  4260. }
  4261. this.workerReadyCapability.reject(data.exception.message,
  4262. data.exception);
  4263. }, this);
  4264. messageHandler.on('IncorrectPassword', function transportBadPass(data) {
  4265. if (this.passwordCallback) {
  4266. return this.passwordCallback(updatePassword,
  4267. PasswordResponses.INCORRECT_PASSWORD);
  4268. }
  4269. this.workerReadyCapability.reject(data.exception.message,
  4270. data.exception);
  4271. }, this);
  4272. messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
  4273. this.workerReadyCapability.reject(data.exception.name, data.exception);
  4274. }, this);
  4275. messageHandler.on('MissingPDF', function transportMissingPDF(data) {
  4276. this.workerReadyCapability.reject(data.exception.message,
  4277. data.exception);
  4278. }, this);
  4279. messageHandler.on('UnknownError', function transportUnknownError(data) {
  4280. this.workerReadyCapability.reject(data.exception.message,
  4281. data.exception);
  4282. }, this);
  4283. messageHandler.on('DataLoaded', function transportPage(data) {
  4284. this.downloadInfoCapability.resolve(data);
  4285. }, this);
  4286. messageHandler.on('StartRenderPage', function transportRender(data) {
  4287. var page = this.pageCache[data.pageIndex];
  4288. page.stats.timeEnd('Page Request');
  4289. page._startRenderPage(data.transparency, data.intent);
  4290. }, this);
  4291. messageHandler.on('RenderPageChunk', function transportRender(data) {
  4292. var page = this.pageCache[data.pageIndex];
  4293. page._renderPageChunk(data.operatorList, data.intent);
  4294. }, this);
  4295. messageHandler.on('commonobj', function transportObj(data) {
  4296. var id = data[0];
  4297. var type = data[1];
  4298. if (this.commonObjs.hasData(id)) {
  4299. return;
  4300. }
  4301. switch (type) {
  4302. case 'Font':
  4303. var exportedData = data[2];
  4304. var font;
  4305. if ('error' in exportedData) {
  4306. var error = exportedData.error;
  4307. warn('Error during font loading: ' + error);
  4308. this.commonObjs.resolve(id, error);
  4309. break;
  4310. } else {
  4311. font = new FontFace(exportedData);
  4312. }
  4313. FontLoader.bind(
  4314. [font],
  4315. function fontReady(fontObjs) {
  4316. this.commonObjs.resolve(id, font);
  4317. }.bind(this)
  4318. );
  4319. break;
  4320. case 'FontPath':
  4321. this.commonObjs.resolve(id, data[2]);
  4322. break;
  4323. default:
  4324. error('Got unknown common object type ' + type);
  4325. }
  4326. }, this);
  4327. messageHandler.on('obj', function transportObj(data) {
  4328. var id = data[0];
  4329. var pageIndex = data[1];
  4330. var type = data[2];
  4331. var pageProxy = this.pageCache[pageIndex];
  4332. var imageData;
  4333. if (pageProxy.objs.hasData(id)) {
  4334. return;
  4335. }
  4336. switch (type) {
  4337. case 'JpegStream':
  4338. imageData = data[3];
  4339. loadJpegStream(id, imageData, pageProxy.objs);
  4340. break;
  4341. case 'Image':
  4342. imageData = data[3];
  4343. pageProxy.objs.resolve(id, imageData);
  4344. // heuristics that will allow not to store large data
  4345. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  4346. if (imageData && 'data' in imageData &&
  4347. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  4348. pageProxy.cleanupAfterRender = true;
  4349. }
  4350. break;
  4351. default:
  4352. error('Got unknown object type ' + type);
  4353. }
  4354. }, this);
  4355. messageHandler.on('DocProgress', function transportDocProgress(data) {
  4356. if (this.progressCallback) {
  4357. this.progressCallback({
  4358. loaded: data.loaded,
  4359. total: data.total
  4360. });
  4361. }
  4362. }, this);
  4363. messageHandler.on('DocError', function transportDocError(data) {
  4364. this.workerReadyCapability.reject(data);
  4365. }, this);
  4366. messageHandler.on('PageError', function transportError(data) {
  4367. var page = this.pageCache[data.pageNum - 1];
  4368. var intentState = page.intentStates[data.intent];
  4369. if (intentState.displayReadyCapability.promise) {
  4370. intentState.displayReadyCapability.reject(data.error);
  4371. } else {
  4372. error(data.error);
  4373. }
  4374. }, this);
  4375. messageHandler.on('JpegDecode', function(data) {
  4376. var imageUrl = data[0];
  4377. var components = data[1];
  4378. if (components != 3 && components != 1) {
  4379. return Promise.reject(
  4380. new Error('Only 3 components or 1 component can be returned'));
  4381. }
  4382. return new Promise(function (resolve, reject) {
  4383. var img = new Image();
  4384. img.onload = function () {
  4385. var width = img.width;
  4386. var height = img.height;
  4387. var size = width * height;
  4388. var rgbaLength = size * 4;
  4389. var buf = new Uint8Array(size * components);
  4390. var tmpCanvas = createScratchCanvas(width, height);
  4391. var tmpCtx = tmpCanvas.getContext('2d');
  4392. tmpCtx.drawImage(img, 0, 0);
  4393. var data = tmpCtx.getImageData(0, 0, width, height).data;
  4394. var i, j;
  4395. if (components == 3) {
  4396. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  4397. buf[j] = data[i];
  4398. buf[j + 1] = data[i + 1];
  4399. buf[j + 2] = data[i + 2];
  4400. }
  4401. } else if (components == 1) {
  4402. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  4403. buf[j] = data[i];
  4404. }
  4405. }
  4406. resolve({ data: buf, width: width, height: height});
  4407. };
  4408. img.onerror = function () {
  4409. reject(new Error('JpegDecode failed to load image'));
  4410. };
  4411. img.src = imageUrl;
  4412. });
  4413. });
  4414. },
  4415. fetchDocument: function WorkerTransport_fetchDocument(source) {
  4416. source.disableAutoFetch = PDFJS.disableAutoFetch;
  4417. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  4418. this.messageHandler.send('GetDocRequest', {
  4419. source: source,
  4420. disableRange: PDFJS.disableRange,
  4421. maxImageSize: PDFJS.maxImageSize,
  4422. cMapUrl: PDFJS.cMapUrl,
  4423. cMapPacked: PDFJS.cMapPacked,
  4424. disableFontFace: PDFJS.disableFontFace,
  4425. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  4426. verbosity: PDFJS.verbosity
  4427. });
  4428. },
  4429. getData: function WorkerTransport_getData() {
  4430. return this.messageHandler.sendWithPromise('GetData', null);
  4431. },
  4432. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  4433. if (pageNumber <= 0 || pageNumber > this.numPages ||
  4434. (pageNumber|0) !== pageNumber) {
  4435. return Promise.reject(new Error('Invalid page request'));
  4436. }
  4437. var pageIndex = pageNumber - 1;
  4438. if (pageIndex in this.pagePromises) {
  4439. return this.pagePromises[pageIndex];
  4440. }
  4441. var promise = this.messageHandler.sendWithPromise('GetPage', {
  4442. pageIndex: pageIndex
  4443. }).then(function (pageInfo) {
  4444. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  4445. this.pageCache[pageIndex] = page;
  4446. return page;
  4447. }.bind(this));
  4448. this.pagePromises[pageIndex] = promise;
  4449. return promise;
  4450. },
  4451. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  4452. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  4453. },
  4454. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  4455. return this.messageHandler.sendWithPromise('GetAnnotations',
  4456. { pageIndex: pageIndex });
  4457. },
  4458. getDestinations: function WorkerTransport_getDestinations() {
  4459. return this.messageHandler.sendWithPromise('GetDestinations', null);
  4460. },
  4461. getAttachments: function WorkerTransport_getAttachments() {
  4462. return this.messageHandler.sendWithPromise('GetAttachments', null);
  4463. },
  4464. getJavaScript: function WorkerTransport_getJavaScript() {
  4465. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  4466. },
  4467. getOutline: function WorkerTransport_getOutline() {
  4468. return this.messageHandler.sendWithPromise('GetOutline', null);
  4469. },
  4470. getMetadata: function WorkerTransport_getMetadata() {
  4471. return this.messageHandler.sendWithPromise('GetMetadata', null).
  4472. then(function transportMetadata(results) {
  4473. return {
  4474. info: results[0],
  4475. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  4476. };
  4477. });
  4478. },
  4479. startCleanup: function WorkerTransport_startCleanup() {
  4480. this.messageHandler.sendWithPromise('Cleanup', null).
  4481. then(function endCleanup() {
  4482. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  4483. var page = this.pageCache[i];
  4484. if (page) {
  4485. page.destroy();
  4486. }
  4487. }
  4488. this.commonObjs.clear();
  4489. FontLoader.clear();
  4490. }.bind(this));
  4491. }
  4492. };
  4493. return WorkerTransport;
  4494. })();
  4495. /**
  4496. * A PDF document and page is built of many objects. E.g. there are objects
  4497. * for fonts, images, rendering code and such. These objects might get processed
  4498. * inside of a worker. The `PDFObjects` implements some basic functions to
  4499. * manage these objects.
  4500. * @ignore
  4501. */
  4502. var PDFObjects = (function PDFObjectsClosure() {
  4503. function PDFObjects() {
  4504. this.objs = {};
  4505. }
  4506. PDFObjects.prototype = {
  4507. /**
  4508. * Internal function.
  4509. * Ensures there is an object defined for `objId`.
  4510. */
  4511. ensureObj: function PDFObjects_ensureObj(objId) {
  4512. if (this.objs[objId]) {
  4513. return this.objs[objId];
  4514. }
  4515. var obj = {
  4516. capability: createPromiseCapability(),
  4517. data: null,
  4518. resolved: false
  4519. };
  4520. this.objs[objId] = obj;
  4521. return obj;
  4522. },
  4523. /**
  4524. * If called *without* callback, this returns the data of `objId` but the
  4525. * object needs to be resolved. If it isn't, this function throws.
  4526. *
  4527. * If called *with* a callback, the callback is called with the data of the
  4528. * object once the object is resolved. That means, if you call this
  4529. * function and the object is already resolved, the callback gets called
  4530. * right away.
  4531. */
  4532. get: function PDFObjects_get(objId, callback) {
  4533. // If there is a callback, then the get can be async and the object is
  4534. // not required to be resolved right now
  4535. if (callback) {
  4536. this.ensureObj(objId).capability.promise.then(callback);
  4537. return null;
  4538. }
  4539. // If there isn't a callback, the user expects to get the resolved data
  4540. // directly.
  4541. var obj = this.objs[objId];
  4542. // If there isn't an object yet or the object isn't resolved, then the
  4543. // data isn't ready yet!
  4544. if (!obj || !obj.resolved) {
  4545. error('Requesting object that isn\'t resolved yet ' + objId);
  4546. }
  4547. return obj.data;
  4548. },
  4549. /**
  4550. * Resolves the object `objId` with optional `data`.
  4551. */
  4552. resolve: function PDFObjects_resolve(objId, data) {
  4553. var obj = this.ensureObj(objId);
  4554. obj.resolved = true;
  4555. obj.data = data;
  4556. obj.capability.resolve(data);
  4557. },
  4558. isResolved: function PDFObjects_isResolved(objId) {
  4559. var objs = this.objs;
  4560. if (!objs[objId]) {
  4561. return false;
  4562. } else {
  4563. return objs[objId].resolved;
  4564. }
  4565. },
  4566. hasData: function PDFObjects_hasData(objId) {
  4567. return this.isResolved(objId);
  4568. },
  4569. /**
  4570. * Returns the data of `objId` if object exists, null otherwise.
  4571. */
  4572. getData: function PDFObjects_getData(objId) {
  4573. var objs = this.objs;
  4574. if (!objs[objId] || !objs[objId].resolved) {
  4575. return null;
  4576. } else {
  4577. return objs[objId].data;
  4578. }
  4579. },
  4580. clear: function PDFObjects_clear() {
  4581. this.objs = {};
  4582. }
  4583. };
  4584. return PDFObjects;
  4585. })();
  4586. /**
  4587. * Allows controlling of the rendering tasks.
  4588. * @class
  4589. */
  4590. var RenderTask = (function RenderTaskClosure() {
  4591. function RenderTask(internalRenderTask) {
  4592. this.internalRenderTask = internalRenderTask;
  4593. /**
  4594. * Promise for rendering task completion.
  4595. * @type {Promise}
  4596. */
  4597. this.promise = this.internalRenderTask.capability.promise;
  4598. }
  4599. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  4600. /**
  4601. * Cancels the rendering task. If the task is currently rendering it will
  4602. * not be cancelled until graphics pauses with a timeout. The promise that
  4603. * this object extends will resolved when cancelled.
  4604. */
  4605. cancel: function RenderTask_cancel() {
  4606. this.internalRenderTask.cancel();
  4607. },
  4608. /**
  4609. * Registers callback to indicate the rendering task completion.
  4610. *
  4611. * @param {function} onFulfilled The callback for the rendering completion.
  4612. * @param {function} onRejected The callback for the rendering failure.
  4613. * @return {Promise} A promise that is resolved after the onFulfilled or
  4614. * onRejected callback.
  4615. */
  4616. then: function RenderTask_then(onFulfilled, onRejected) {
  4617. return this.promise.then(onFulfilled, onRejected);
  4618. }
  4619. };
  4620. return RenderTask;
  4621. })();
  4622. /**
  4623. * For internal use only.
  4624. * @ignore
  4625. */
  4626. var InternalRenderTask = (function InternalRenderTaskClosure() {
  4627. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  4628. pageNumber) {
  4629. this.callback = callback;
  4630. this.params = params;
  4631. this.objs = objs;
  4632. this.commonObjs = commonObjs;
  4633. this.operatorListIdx = null;
  4634. this.operatorList = operatorList;
  4635. this.pageNumber = pageNumber;
  4636. this.running = false;
  4637. this.graphicsReadyCallback = null;
  4638. this.graphicsReady = false;
  4639. this.cancelled = false;
  4640. this.capability = createPromiseCapability();
  4641. // caching this-bound methods
  4642. this._continueBound = this._continue.bind(this);
  4643. this._scheduleNextBound = this._scheduleNext.bind(this);
  4644. this._nextBound = this._next.bind(this);
  4645. }
  4646. InternalRenderTask.prototype = {
  4647. initalizeGraphics:
  4648. function InternalRenderTask_initalizeGraphics(transparency) {
  4649. if (this.cancelled) {
  4650. return;
  4651. }
  4652. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  4653. globalScope.StepperManager.enabled) {
  4654. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  4655. this.stepper.init(this.operatorList);
  4656. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  4657. }
  4658. var params = this.params;
  4659. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  4660. this.objs, params.imageLayer);
  4661. this.gfx.beginDrawing(params.viewport, transparency);
  4662. this.operatorListIdx = 0;
  4663. this.graphicsReady = true;
  4664. if (this.graphicsReadyCallback) {
  4665. this.graphicsReadyCallback();
  4666. }
  4667. },
  4668. cancel: function InternalRenderTask_cancel() {
  4669. this.running = false;
  4670. this.cancelled = true;
  4671. this.callback('cancelled');
  4672. },
  4673. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  4674. if (!this.graphicsReady) {
  4675. if (!this.graphicsReadyCallback) {
  4676. this.graphicsReadyCallback = this._continueBound;
  4677. }
  4678. return;
  4679. }
  4680. if (this.stepper) {
  4681. this.stepper.updateOperatorList(this.operatorList);
  4682. }
  4683. if (this.running) {
  4684. return;
  4685. }
  4686. this._continue();
  4687. },
  4688. _continue: function InternalRenderTask__continue() {
  4689. this.running = true;
  4690. if (this.cancelled) {
  4691. return;
  4692. }
  4693. if (this.params.continueCallback) {
  4694. this.params.continueCallback(this._scheduleNextBound);
  4695. } else {
  4696. this._scheduleNext();
  4697. }
  4698. },
  4699. _scheduleNext: function InternalRenderTask__scheduleNext() {
  4700. window.requestAnimationFrame(this._nextBound);
  4701. },
  4702. _next: function InternalRenderTask__next() {
  4703. if (this.cancelled) {
  4704. return;
  4705. }
  4706. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  4707. this.operatorListIdx,
  4708. this._continueBound,
  4709. this.stepper);
  4710. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  4711. this.running = false;
  4712. if (this.operatorList.lastChunk) {
  4713. this.gfx.endDrawing();
  4714. this.callback();
  4715. }
  4716. }
  4717. }
  4718. };
  4719. return InternalRenderTask;
  4720. })();
  4721. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  4722. function fixMetadata(meta) {
  4723. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  4724. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  4725. function(code, d1, d2, d3) {
  4726. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  4727. });
  4728. var chars = '';
  4729. for (var i = 0; i < bytes.length; i += 2) {
  4730. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  4731. chars += code >= 32 && code < 127 && code != 60 && code != 62 &&
  4732. code != 38 && false ? String.fromCharCode(code) :
  4733. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  4734. }
  4735. return '>' + chars;
  4736. });
  4737. }
  4738. function Metadata(meta) {
  4739. if (typeof meta === 'string') {
  4740. // Ghostscript produces invalid metadata
  4741. meta = fixMetadata(meta);
  4742. var parser = new DOMParser();
  4743. meta = parser.parseFromString(meta, 'application/xml');
  4744. } else if (!(meta instanceof Document)) {
  4745. error('Metadata: Invalid metadata object');
  4746. }
  4747. this.metaDocument = meta;
  4748. this.metadata = {};
  4749. this.parse();
  4750. }
  4751. Metadata.prototype = {
  4752. parse: function Metadata_parse() {
  4753. var doc = this.metaDocument;
  4754. var rdf = doc.documentElement;
  4755. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  4756. rdf = rdf.firstChild;
  4757. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  4758. rdf = rdf.nextSibling;
  4759. }
  4760. }
  4761. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  4762. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  4763. return;
  4764. }
  4765. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  4766. for (i = 0, length = children.length; i < length; i++) {
  4767. desc = children[i];
  4768. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  4769. continue;
  4770. }
  4771. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  4772. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  4773. entry = desc.childNodes[ii];
  4774. name = entry.nodeName.toLowerCase();
  4775. this.metadata[name] = entry.textContent.trim();
  4776. }
  4777. }
  4778. }
  4779. },
  4780. get: function Metadata_get(name) {
  4781. return this.metadata[name] || null;
  4782. },
  4783. has: function Metadata_has(name) {
  4784. return typeof this.metadata[name] !== 'undefined';
  4785. }
  4786. };
  4787. return Metadata;
  4788. })();
  4789. // <canvas> contexts store most of the state we need natively.
  4790. // However, PDF needs a bit more state, which we store here.
  4791. // Minimal font size that would be used during canvas fillText operations.
  4792. var MIN_FONT_SIZE = 16;
  4793. var MAX_GROUP_SIZE = 4096;
  4794. var COMPILE_TYPE3_GLYPHS = true;
  4795. function createScratchCanvas(width, height) {
  4796. var canvas = document.createElement('canvas');
  4797. canvas.width = width;
  4798. canvas.height = height;
  4799. return canvas;
  4800. }
  4801. function addContextCurrentTransform(ctx) {
  4802. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  4803. if (!ctx.mozCurrentTransform) {
  4804. // Store the original context
  4805. ctx._scaleX = ctx._scaleX || 1.0;
  4806. ctx._scaleY = ctx._scaleY || 1.0;
  4807. ctx._originalSave = ctx.save;
  4808. ctx._originalRestore = ctx.restore;
  4809. ctx._originalRotate = ctx.rotate;
  4810. ctx._originalScale = ctx.scale;
  4811. ctx._originalTranslate = ctx.translate;
  4812. ctx._originalTransform = ctx.transform;
  4813. ctx._originalSetTransform = ctx.setTransform;
  4814. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  4815. ctx._transformStack = [];
  4816. Object.defineProperty(ctx, 'mozCurrentTransform', {
  4817. get: function getCurrentTransform() {
  4818. return this._transformMatrix;
  4819. }
  4820. });
  4821. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  4822. get: function getCurrentTransformInverse() {
  4823. // Calculation done using WolframAlpha:
  4824. // http://www.wolframalpha.com/input/?
  4825. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  4826. var m = this._transformMatrix;
  4827. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  4828. var ad_bc = a * d - b * c;
  4829. var bc_ad = b * c - a * d;
  4830. return [
  4831. d / ad_bc,
  4832. b / bc_ad,
  4833. c / bc_ad,
  4834. a / ad_bc,
  4835. (d * e - c * f) / bc_ad,
  4836. (b * e - a * f) / ad_bc
  4837. ];
  4838. }
  4839. });
  4840. ctx.save = function ctxSave() {
  4841. var old = this._transformMatrix;
  4842. this._transformStack.push(old);
  4843. this._transformMatrix = old.slice(0, 6);
  4844. this._originalSave();
  4845. };
  4846. ctx.restore = function ctxRestore() {
  4847. var prev = this._transformStack.pop();
  4848. if (prev) {
  4849. this._transformMatrix = prev;
  4850. this._originalRestore();
  4851. }
  4852. };
  4853. ctx.translate = function ctxTranslate(x, y) {
  4854. var m = this._transformMatrix;
  4855. m[4] = m[0] * x + m[2] * y + m[4];
  4856. m[5] = m[1] * x + m[3] * y + m[5];
  4857. this._originalTranslate(x, y);
  4858. };
  4859. ctx.scale = function ctxScale(x, y) {
  4860. var m = this._transformMatrix;
  4861. m[0] = m[0] * x;
  4862. m[1] = m[1] * x;
  4863. m[2] = m[2] * y;
  4864. m[3] = m[3] * y;
  4865. this._originalScale(x, y);
  4866. };
  4867. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  4868. var m = this._transformMatrix;
  4869. this._transformMatrix = [
  4870. m[0] * a + m[2] * b,
  4871. m[1] * a + m[3] * b,
  4872. m[0] * c + m[2] * d,
  4873. m[1] * c + m[3] * d,
  4874. m[0] * e + m[2] * f + m[4],
  4875. m[1] * e + m[3] * f + m[5]
  4876. ];
  4877. ctx._originalTransform(a, b, c, d, e, f);
  4878. };
  4879. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  4880. this._transformMatrix = [a, b, c, d, e, f];
  4881. ctx._originalSetTransform(a, b, c, d, e, f);
  4882. };
  4883. ctx.rotate = function ctxRotate(angle) {
  4884. var cosValue = Math.cos(angle);
  4885. var sinValue = Math.sin(angle);
  4886. var m = this._transformMatrix;
  4887. this._transformMatrix = [
  4888. m[0] * cosValue + m[2] * sinValue,
  4889. m[1] * cosValue + m[3] * sinValue,
  4890. m[0] * (-sinValue) + m[2] * cosValue,
  4891. m[1] * (-sinValue) + m[3] * cosValue,
  4892. m[4],
  4893. m[5]
  4894. ];
  4895. this._originalRotate(angle);
  4896. };
  4897. }
  4898. }
  4899. var CachedCanvases = (function CachedCanvasesClosure() {
  4900. var cache = {};
  4901. return {
  4902. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  4903. trackTransform) {
  4904. var canvasEntry;
  4905. if (id in cache) {
  4906. canvasEntry = cache[id];
  4907. canvasEntry.canvas.width = width;
  4908. canvasEntry.canvas.height = height;
  4909. // reset canvas transform for emulated mozCurrentTransform, if needed
  4910. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  4911. } else {
  4912. var canvas = createScratchCanvas(width, height);
  4913. var ctx = canvas.getContext('2d');
  4914. if (trackTransform) {
  4915. addContextCurrentTransform(ctx);
  4916. }
  4917. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  4918. }
  4919. return canvasEntry;
  4920. },
  4921. clear: function () {
  4922. cache = {};
  4923. }
  4924. };
  4925. })();
  4926. function compileType3Glyph(imgData) {
  4927. var POINT_TO_PROCESS_LIMIT = 1000;
  4928. var width = imgData.width, height = imgData.height;
  4929. var i, j, j0, width1 = width + 1;
  4930. var points = new Uint8Array(width1 * (height + 1));
  4931. var POINT_TYPES =
  4932. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  4933. // decodes bit-packed mask data
  4934. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  4935. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  4936. for (i = 0, ii = data0.length; i < ii; i++) {
  4937. var mask = 128, elem = data0[i];
  4938. while (mask > 0) {
  4939. data[pos++] = (elem & mask) ? 0 : 255;
  4940. mask >>= 1;
  4941. }
  4942. }
  4943. // finding iteresting points: every point is located between mask pixels,
  4944. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  4945. // will have flags assigned based on neighboring mask pixels:
  4946. // 4 | 8
  4947. // --P--
  4948. // 2 | 1
  4949. // We are interested only in points with the flags:
  4950. // - outside corners: 1, 2, 4, 8;
  4951. // - inside corners: 7, 11, 13, 14;
  4952. // - and, intersections: 5, 10.
  4953. var count = 0;
  4954. pos = 0;
  4955. if (data[pos] !== 0) {
  4956. points[0] = 1;
  4957. ++count;
  4958. }
  4959. for (j = 1; j < width; j++) {
  4960. if (data[pos] !== data[pos + 1]) {
  4961. points[j] = data[pos] ? 2 : 1;
  4962. ++count;
  4963. }
  4964. pos++;
  4965. }
  4966. if (data[pos] !== 0) {
  4967. points[j] = 2;
  4968. ++count;
  4969. }
  4970. for (i = 1; i < height; i++) {
  4971. pos = i * lineSize;
  4972. j0 = i * width1;
  4973. if (data[pos - lineSize] !== data[pos]) {
  4974. points[j0] = data[pos] ? 1 : 8;
  4975. ++count;
  4976. }
  4977. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  4978. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  4979. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  4980. for (j = 1; j < width; j++) {
  4981. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  4982. (data[pos - lineSize + 1] ? 8 : 0);
  4983. if (POINT_TYPES[sum]) {
  4984. points[j0 + j] = POINT_TYPES[sum];
  4985. ++count;
  4986. }
  4987. pos++;
  4988. }
  4989. if (data[pos - lineSize] !== data[pos]) {
  4990. points[j0 + j] = data[pos] ? 2 : 4;
  4991. ++count;
  4992. }
  4993. if (count > POINT_TO_PROCESS_LIMIT) {
  4994. return null;
  4995. }
  4996. }
  4997. pos = lineSize * (height - 1);
  4998. j0 = i * width1;
  4999. if (data[pos] !== 0) {
  5000. points[j0] = 8;
  5001. ++count;
  5002. }
  5003. for (j = 1; j < width; j++) {
  5004. if (data[pos] !== data[pos + 1]) {
  5005. points[j0 + j] = data[pos] ? 4 : 8;
  5006. ++count;
  5007. }
  5008. pos++;
  5009. }
  5010. if (data[pos] !== 0) {
  5011. points[j0 + j] = 4;
  5012. ++count;
  5013. }
  5014. if (count > POINT_TO_PROCESS_LIMIT) {
  5015. return null;
  5016. }
  5017. // building outlines
  5018. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  5019. var outlines = [];
  5020. for (i = 0; count && i <= height; i++) {
  5021. var p = i * width1;
  5022. var end = p + width;
  5023. while (p < end && !points[p]) {
  5024. p++;
  5025. }
  5026. if (p === end) {
  5027. continue;
  5028. }
  5029. var coords = [p % width1, i];
  5030. var type = points[p], p0 = p, pp;
  5031. do {
  5032. var step = steps[type];
  5033. do {
  5034. p += step;
  5035. } while (!points[p]);
  5036. pp = points[p];
  5037. if (pp !== 5 && pp !== 10) {
  5038. // set new direction
  5039. type = pp;
  5040. // delete mark
  5041. points[p] = 0;
  5042. } else { // type is 5 or 10, ie, a crossing
  5043. // set new direction
  5044. type = pp & ((0x33 * type) >> 4);
  5045. // set new type for "future hit"
  5046. points[p] &= (type >> 2 | type << 2);
  5047. }
  5048. coords.push(p % width1);
  5049. coords.push((p / width1) | 0);
  5050. --count;
  5051. } while (p0 !== p);
  5052. outlines.push(coords);
  5053. --i;
  5054. }
  5055. var drawOutline = function(c) {
  5056. c.save();
  5057. // the path shall be painted in [0..1]x[0..1] space
  5058. c.scale(1 / width, -1 / height);
  5059. c.translate(0, -height);
  5060. c.beginPath();
  5061. for (var i = 0, ii = outlines.length; i < ii; i++) {
  5062. var o = outlines[i];
  5063. c.moveTo(o[0], o[1]);
  5064. for (var j = 2, jj = o.length; j < jj; j += 2) {
  5065. c.lineTo(o[j], o[j+1]);
  5066. }
  5067. }
  5068. c.fill();
  5069. c.beginPath();
  5070. c.restore();
  5071. };
  5072. return drawOutline;
  5073. }
  5074. var CanvasExtraState = (function CanvasExtraStateClosure() {
  5075. function CanvasExtraState(old) {
  5076. // Are soft masks and alpha values shapes or opacities?
  5077. this.alphaIsShape = false;
  5078. this.fontSize = 0;
  5079. this.fontSizeScale = 1;
  5080. this.textMatrix = IDENTITY_MATRIX;
  5081. this.fontMatrix = FONT_IDENTITY_MATRIX;
  5082. this.leading = 0;
  5083. // Current point (in user coordinates)
  5084. this.x = 0;
  5085. this.y = 0;
  5086. // Start of text line (in text coordinates)
  5087. this.lineX = 0;
  5088. this.lineY = 0;
  5089. // Character and word spacing
  5090. this.charSpacing = 0;
  5091. this.wordSpacing = 0;
  5092. this.textHScale = 1;
  5093. this.textRenderingMode = TextRenderingMode.FILL;
  5094. this.textRise = 0;
  5095. // Color spaces
  5096. this.fillColorSpace = ColorSpace.singletons.gray;
  5097. this.fillColorSpaceObj = null;
  5098. this.strokeColorSpace = ColorSpace.singletons.gray;
  5099. this.strokeColorSpaceObj = null;
  5100. this.fillColorObj = null;
  5101. this.strokeColorObj = null;
  5102. // Default fore and background colors
  5103. this.fillColor = '#000000';
  5104. this.strokeColor = '#000000';
  5105. // Note: fill alpha applies to all non-stroking operations
  5106. this.fillAlpha = 1;
  5107. this.strokeAlpha = 1;
  5108. this.lineWidth = 1;
  5109. this.activeSMask = null; // nonclonable field (see the save method below)
  5110. this.old = old;
  5111. }
  5112. CanvasExtraState.prototype = {
  5113. clone: function CanvasExtraState_clone() {
  5114. return Object.create(this);
  5115. },
  5116. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  5117. this.x = x;
  5118. this.y = y;
  5119. }
  5120. };
  5121. return CanvasExtraState;
  5122. })();
  5123. var CanvasGraphics = (function CanvasGraphicsClosure() {
  5124. // Defines the time the executeOperatorList is going to be executing
  5125. // before it stops and shedules a continue of execution.
  5126. var EXECUTION_TIME = 15;
  5127. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  5128. this.ctx = canvasCtx;
  5129. this.current = new CanvasExtraState();
  5130. this.stateStack = [];
  5131. this.pendingClip = null;
  5132. this.pendingEOFill = false;
  5133. this.res = null;
  5134. this.xobjs = null;
  5135. this.commonObjs = commonObjs;
  5136. this.objs = objs;
  5137. this.imageLayer = imageLayer;
  5138. this.groupStack = [];
  5139. this.processingType3 = null;
  5140. // Patterns are painted relative to the initial page/form transform, see pdf
  5141. // spec 8.7.2 NOTE 1.
  5142. this.baseTransform = null;
  5143. this.baseTransformStack = [];
  5144. this.groupLevel = 0;
  5145. this.smaskStack = [];
  5146. this.smaskCounter = 0;
  5147. this.tempSMask = null;
  5148. if (canvasCtx) {
  5149. addContextCurrentTransform(canvasCtx);
  5150. }
  5151. }
  5152. function putBinaryImageData(ctx, imgData) {
  5153. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  5154. ctx.putImageData(imgData, 0, 0);
  5155. return;
  5156. }
  5157. // Put the image data to the canvas in chunks, rather than putting the
  5158. // whole image at once. This saves JS memory, because the ImageData object
  5159. // is smaller. It also possibly saves C++ memory within the implementation
  5160. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  5161. // the data passed to putImageData()). |n| shouldn't be too small, however,
  5162. // because too many putImageData() calls will slow things down.
  5163. //
  5164. // Note: as written, if the last chunk is partial, the putImageData() call
  5165. // will (conceptually) put pixels past the bounds of the canvas. But
  5166. // that's ok; any such pixels are ignored.
  5167. var height = imgData.height, width = imgData.width;
  5168. var fullChunkHeight = 16;
  5169. var fracChunks = height / fullChunkHeight;
  5170. var fullChunks = Math.floor(fracChunks);
  5171. var totalChunks = Math.ceil(fracChunks);
  5172. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  5173. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  5174. var srcPos = 0, destPos;
  5175. var src = imgData.data;
  5176. var dest = chunkImgData.data;
  5177. var i, j, thisChunkHeight, elemsInThisChunk;
  5178. // There are multiple forms in which the pixel data can be passed, and
  5179. // imgData.kind tells us which one this is.
  5180. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  5181. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  5182. var srcLength = src.byteLength;
  5183. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  5184. new Uint32ArrayView(dest);
  5185. var dest32DataLength = dest32.length;
  5186. var fullSrcDiff = (width + 7) >> 3;
  5187. var white = 0xFFFFFFFF;
  5188. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  5189. 0xFF000000 : 0x000000FF;
  5190. for (i = 0; i < totalChunks; i++) {
  5191. thisChunkHeight =
  5192. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  5193. destPos = 0;
  5194. for (j = 0; j < thisChunkHeight; j++) {
  5195. var srcDiff = srcLength - srcPos;
  5196. var k = 0;
  5197. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  5198. var kEndUnrolled = kEnd & ~7;
  5199. var mask = 0;
  5200. var srcByte = 0;
  5201. for (; k < kEndUnrolled; k += 8) {
  5202. srcByte = src[srcPos++];
  5203. dest32[destPos++] = (srcByte & 128) ? white : black;
  5204. dest32[destPos++] = (srcByte & 64) ? white : black;
  5205. dest32[destPos++] = (srcByte & 32) ? white : black;
  5206. dest32[destPos++] = (srcByte & 16) ? white : black;
  5207. dest32[destPos++] = (srcByte & 8) ? white : black;
  5208. dest32[destPos++] = (srcByte & 4) ? white : black;
  5209. dest32[destPos++] = (srcByte & 2) ? white : black;
  5210. dest32[destPos++] = (srcByte & 1) ? white : black;
  5211. }
  5212. for (; k < kEnd; k++) {
  5213. if (mask === 0) {
  5214. srcByte = src[srcPos++];
  5215. mask = 128;
  5216. }
  5217. dest32[destPos++] = (srcByte & mask) ? white : black;
  5218. mask >>= 1;
  5219. }
  5220. }
  5221. // We ran out of input. Make all remaining pixels transparent.
  5222. while (destPos < dest32DataLength) {
  5223. dest32[destPos++] = 0;
  5224. }
  5225. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5226. }
  5227. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  5228. // RGBA, 32-bits per pixel.
  5229. j = 0;
  5230. elemsInThisChunk = width * fullChunkHeight * 4;
  5231. for (i = 0; i < fullChunks; i++) {
  5232. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5233. srcPos += elemsInThisChunk;
  5234. ctx.putImageData(chunkImgData, 0, j);
  5235. j += fullChunkHeight;
  5236. }
  5237. if (i < totalChunks) {
  5238. elemsInThisChunk = width * partialChunkHeight * 4;
  5239. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  5240. ctx.putImageData(chunkImgData, 0, j);
  5241. }
  5242. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  5243. // RGB, 24-bits per pixel.
  5244. thisChunkHeight = fullChunkHeight;
  5245. elemsInThisChunk = width * thisChunkHeight;
  5246. for (i = 0; i < totalChunks; i++) {
  5247. if (i >= fullChunks) {
  5248. thisChunkHeight =partialChunkHeight;
  5249. elemsInThisChunk = width * thisChunkHeight;
  5250. }
  5251. destPos = 0;
  5252. for (j = elemsInThisChunk; j--;) {
  5253. dest[destPos++] = src[srcPos++];
  5254. dest[destPos++] = src[srcPos++];
  5255. dest[destPos++] = src[srcPos++];
  5256. dest[destPos++] = 255;
  5257. }
  5258. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5259. }
  5260. } else {
  5261. error('bad image kind: ' + imgData.kind);
  5262. }
  5263. }
  5264. function putBinaryImageMask(ctx, imgData) {
  5265. var height = imgData.height, width = imgData.width;
  5266. var fullChunkHeight = 16;
  5267. var fracChunks = height / fullChunkHeight;
  5268. var fullChunks = Math.floor(fracChunks);
  5269. var totalChunks = Math.ceil(fracChunks);
  5270. var partialChunkHeight = height - fullChunks * fullChunkHeight;
  5271. var chunkImgData = ctx.createImageData(width, fullChunkHeight);
  5272. var srcPos = 0;
  5273. var src = imgData.data;
  5274. var dest = chunkImgData.data;
  5275. for (var i = 0; i < totalChunks; i++) {
  5276. var thisChunkHeight =
  5277. (i < fullChunks) ? fullChunkHeight : partialChunkHeight;
  5278. // Expand the mask so it can be used by the canvas. Any required
  5279. // inversion has already been handled.
  5280. var destPos = 3; // alpha component offset
  5281. for (var j = 0; j < thisChunkHeight; j++) {
  5282. var mask = 0;
  5283. for (var k = 0; k < width; k++) {
  5284. if (!mask) {
  5285. var elem = src[srcPos++];
  5286. mask = 128;
  5287. }
  5288. dest[destPos] = (elem & mask) ? 0 : 255;
  5289. destPos += 4;
  5290. mask >>= 1;
  5291. }
  5292. }
  5293. ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
  5294. }
  5295. }
  5296. function copyCtxState(sourceCtx, destCtx) {
  5297. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  5298. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  5299. 'globalCompositeOperation', 'font'];
  5300. for (var i = 0, ii = properties.length; i < ii; i++) {
  5301. var property = properties[i];
  5302. if (property in sourceCtx) {
  5303. destCtx[property] = sourceCtx[property];
  5304. }
  5305. }
  5306. if ('setLineDash' in sourceCtx) {
  5307. destCtx.setLineDash(sourceCtx.getLineDash());
  5308. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  5309. } else if ('mozDash' in sourceCtx) {
  5310. destCtx.mozDash = sourceCtx.mozDash;
  5311. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  5312. }
  5313. }
  5314. function genericComposeSMask(maskCtx, layerCtx, width, height,
  5315. subtype, backdrop) {
  5316. var addBackdropFn;
  5317. if (backdrop) {
  5318. addBackdropFn = function (r0, g0, b0, bytes) {
  5319. var length = bytes.length;
  5320. for (var i = 3; i < length; i += 4) {
  5321. var alpha = bytes[i] / 255;
  5322. if (alpha === 0) {
  5323. bytes[i - 3] = r0;
  5324. bytes[i - 2] = g0;
  5325. bytes[i - 1] = b0;
  5326. } else if (alpha < 1) {
  5327. var alpha_ = 1 - alpha;
  5328. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) | 0;
  5329. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) | 0;
  5330. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) | 0;
  5331. }
  5332. }
  5333. }.bind(null, backdrop[0], backdrop[1], backdrop[2]);
  5334. } else {
  5335. addBackdropFn = function () {};
  5336. }
  5337. var composeFn;
  5338. if (subtype === 'Luminosity') {
  5339. composeFn = function (maskDataBytes, layerDataBytes) {
  5340. var length = maskDataBytes.length;
  5341. for (var i = 3; i < length; i += 4) {
  5342. var y = ((maskDataBytes[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  5343. (maskDataBytes[i - 2] * 152) + // * 0.59 ....
  5344. (maskDataBytes[i - 1] * 28)) | 0; // * 0.11 ....
  5345. layerDataBytes[i] = (layerDataBytes[i] * y) >> 16;
  5346. }
  5347. };
  5348. } else {
  5349. composeFn = function (maskDataBytes, layerDataBytes) {
  5350. var length = maskDataBytes.length;
  5351. for (var i = 3; i < length; i += 4) {
  5352. var alpha = maskDataBytes[i];
  5353. layerDataBytes[i] = (layerDataBytes[i] * alpha / 255) | 0;
  5354. }
  5355. };
  5356. }
  5357. // processing image in chunks to save memory
  5358. var PIXELS_TO_PROCESS = 65536;
  5359. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  5360. for (var row = 0; row < height; row += chunkSize) {
  5361. var chunkHeight = Math.min(chunkSize, height - row);
  5362. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  5363. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  5364. addBackdropFn(maskData.data);
  5365. composeFn(maskData.data, layerData.data);
  5366. maskCtx.putImageData(layerData, 0, row);
  5367. }
  5368. }
  5369. function composeSMask(ctx, smask, layerCtx) {
  5370. var mask = smask.canvas;
  5371. var maskCtx = smask.context;
  5372. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  5373. smask.offsetX, smask.offsetY);
  5374. var backdrop;
  5375. if (smask.backdrop) {
  5376. var cs = smask.colorSpace || ColorSpace.singletons.rgb;
  5377. backdrop = cs.getRgb(smask.backdrop, 0);
  5378. }
  5379. if (WebGLUtils.isEnabled) {
  5380. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  5381. {subtype: smask.subtype, backdrop: backdrop});
  5382. ctx.setTransform(1, 0, 0, 1, 0, 0);
  5383. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  5384. return;
  5385. }
  5386. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  5387. smask.subtype, backdrop);
  5388. ctx.drawImage(mask, 0, 0);
  5389. }
  5390. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  5391. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  5392. var NORMAL_CLIP = {};
  5393. var EO_CLIP = {};
  5394. CanvasGraphics.prototype = {
  5395. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  5396. // For pdfs that use blend modes we have to clear the canvas else certain
  5397. // blend modes can look wrong since we'd be blending with a white
  5398. // backdrop. The problem with a transparent backdrop though is we then
  5399. // don't get sub pixel anti aliasing on text, so we fill with white if
  5400. // we can.
  5401. var width = this.ctx.canvas.width;
  5402. var height = this.ctx.canvas.height;
  5403. if (transparency) {
  5404. this.ctx.clearRect(0, 0, width, height);
  5405. } else {
  5406. this.ctx.mozOpaque = true;
  5407. this.ctx.save();
  5408. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  5409. this.ctx.fillRect(0, 0, width, height);
  5410. this.ctx.restore();
  5411. }
  5412. var transform = viewport.transform;
  5413. this.ctx.save();
  5414. this.ctx.transform.apply(this.ctx, transform);
  5415. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  5416. if (this.imageLayer) {
  5417. this.imageLayer.beginLayout();
  5418. }
  5419. },
  5420. executeOperatorList: function CanvasGraphics_executeOperatorList(
  5421. operatorList,
  5422. executionStartIdx, continueCallback,
  5423. stepper) {
  5424. var argsArray = operatorList.argsArray;
  5425. var fnArray = operatorList.fnArray;
  5426. var i = executionStartIdx || 0;
  5427. var argsArrayLen = argsArray.length;
  5428. // Sometimes the OperatorList to execute is empty.
  5429. if (argsArrayLen == i) {
  5430. return i;
  5431. }
  5432. var endTime = Date.now() + EXECUTION_TIME;
  5433. var commonObjs = this.commonObjs;
  5434. var objs = this.objs;
  5435. var fnId;
  5436. while (true) {
  5437. if (stepper && i === stepper.nextBreakPoint) {
  5438. stepper.breakIt(i, continueCallback);
  5439. return i;
  5440. }
  5441. fnId = fnArray[i];
  5442. if (fnId !== OPS.dependency) {
  5443. this[fnId].apply(this, argsArray[i]);
  5444. } else {
  5445. var deps = argsArray[i];
  5446. for (var n = 0, nn = deps.length; n < nn; n++) {
  5447. var depObjId = deps[n];
  5448. var common = depObjId.substring(0, 2) == 'g_';
  5449. // If the promise isn't resolved yet, add the continueCallback
  5450. // to the promise and bail out.
  5451. if (!common && !objs.isResolved(depObjId)) {
  5452. objs.get(depObjId, continueCallback);
  5453. return i;
  5454. }
  5455. if (common && !commonObjs.isResolved(depObjId)) {
  5456. commonObjs.get(depObjId, continueCallback);
  5457. return i;
  5458. }
  5459. }
  5460. }
  5461. i++;
  5462. // If the entire operatorList was executed, stop as were done.
  5463. if (i == argsArrayLen) {
  5464. return i;
  5465. }
  5466. // If the execution took longer then a certain amount of time and
  5467. // `continueCallback` is specified, interrupt the execution.
  5468. if (continueCallback && Date.now() > endTime) {
  5469. continueCallback();
  5470. return i;
  5471. }
  5472. // If the operatorList isn't executed completely yet OR the execution
  5473. // time was short enough, do another execution round.
  5474. }
  5475. },
  5476. endDrawing: function CanvasGraphics_endDrawing() {
  5477. this.ctx.restore();
  5478. CachedCanvases.clear();
  5479. WebGLUtils.clear();
  5480. if (this.imageLayer) {
  5481. this.imageLayer.endLayout();
  5482. }
  5483. },
  5484. // Graphics state
  5485. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  5486. this.current.lineWidth = width;
  5487. this.ctx.lineWidth = width;
  5488. },
  5489. setLineCap: function CanvasGraphics_setLineCap(style) {
  5490. this.ctx.lineCap = LINE_CAP_STYLES[style];
  5491. },
  5492. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  5493. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  5494. },
  5495. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  5496. this.ctx.miterLimit = limit;
  5497. },
  5498. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  5499. var ctx = this.ctx;
  5500. if ('setLineDash' in ctx) {
  5501. ctx.setLineDash(dashArray);
  5502. ctx.lineDashOffset = dashPhase;
  5503. } else {
  5504. ctx.mozDash = dashArray;
  5505. ctx.mozDashOffset = dashPhase;
  5506. }
  5507. },
  5508. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  5509. // Maybe if we one day fully support color spaces this will be important
  5510. // for now we can ignore.
  5511. // TODO set rendering intent?
  5512. },
  5513. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  5514. // There's no way to control this with canvas, but we can safely ignore.
  5515. // TODO set flatness?
  5516. },
  5517. setGState: function CanvasGraphics_setGState(states) {
  5518. for (var i = 0, ii = states.length; i < ii; i++) {
  5519. var state = states[i];
  5520. var key = state[0];
  5521. var value = state[1];
  5522. switch (key) {
  5523. case 'LW':
  5524. this.setLineWidth(value);
  5525. break;
  5526. case 'LC':
  5527. this.setLineCap(value);
  5528. break;
  5529. case 'LJ':
  5530. this.setLineJoin(value);
  5531. break;
  5532. case 'ML':
  5533. this.setMiterLimit(value);
  5534. break;
  5535. case 'D':
  5536. this.setDash(value[0], value[1]);
  5537. break;
  5538. case 'RI':
  5539. this.setRenderingIntent(value);
  5540. break;
  5541. case 'FL':
  5542. this.setFlatness(value);
  5543. break;
  5544. case 'Font':
  5545. this.setFont(value[0], value[1]);
  5546. break;
  5547. case 'CA':
  5548. this.current.strokeAlpha = state[1];
  5549. break;
  5550. case 'ca':
  5551. this.current.fillAlpha = state[1];
  5552. this.ctx.globalAlpha = state[1];
  5553. break;
  5554. case 'BM':
  5555. if (value && value.name && (value.name !== 'Normal')) {
  5556. var mode = value.name.replace(/([A-Z])/g,
  5557. function(c) {
  5558. return '-' + c.toLowerCase();
  5559. }
  5560. ).substring(1);
  5561. this.ctx.globalCompositeOperation = mode;
  5562. if (this.ctx.globalCompositeOperation !== mode) {
  5563. warn('globalCompositeOperation "' + mode +
  5564. '" is not supported');
  5565. }
  5566. } else {
  5567. this.ctx.globalCompositeOperation = 'source-over';
  5568. }
  5569. break;
  5570. case 'SMask':
  5571. if (this.current.activeSMask) {
  5572. this.endSMaskGroup();
  5573. }
  5574. this.current.activeSMask = value ? this.tempSMask : null;
  5575. if (this.current.activeSMask) {
  5576. this.beginSMaskGroup();
  5577. }
  5578. this.tempSMask = null;
  5579. break;
  5580. }
  5581. }
  5582. },
  5583. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  5584. var activeSMask = this.current.activeSMask;
  5585. var drawnWidth = activeSMask.canvas.width;
  5586. var drawnHeight = activeSMask.canvas.height;
  5587. var cacheId = 'smaskGroupAt' + this.groupLevel;
  5588. var scratchCanvas = CachedCanvases.getCanvas(
  5589. cacheId, drawnWidth, drawnHeight, true);
  5590. var currentCtx = this.ctx;
  5591. var currentTransform = currentCtx.mozCurrentTransform;
  5592. this.ctx.save();
  5593. var groupCtx = scratchCanvas.context;
  5594. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  5595. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  5596. groupCtx.transform.apply(groupCtx, currentTransform);
  5597. copyCtxState(currentCtx, groupCtx);
  5598. this.ctx = groupCtx;
  5599. this.setGState([
  5600. ['BM', 'Normal'],
  5601. ['ca', 1],
  5602. ['CA', 1]
  5603. ]);
  5604. this.groupStack.push(currentCtx);
  5605. this.groupLevel++;
  5606. },
  5607. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  5608. var groupCtx = this.ctx;
  5609. this.groupLevel--;
  5610. this.ctx = this.groupStack.pop();
  5611. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  5612. this.ctx.restore();
  5613. },
  5614. save: function CanvasGraphics_save() {
  5615. this.ctx.save();
  5616. var old = this.current;
  5617. this.stateStack.push(old);
  5618. this.current = old.clone();
  5619. if (this.current.activeSMask) {
  5620. this.current.activeSMask = null;
  5621. }
  5622. },
  5623. restore: function CanvasGraphics_restore() {
  5624. var prev = this.stateStack.pop();
  5625. if (prev) {
  5626. if (this.current.activeSMask) {
  5627. this.endSMaskGroup();
  5628. }
  5629. this.current = prev;
  5630. this.ctx.restore();
  5631. }
  5632. },
  5633. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  5634. this.ctx.transform(a, b, c, d, e, f);
  5635. },
  5636. // Path
  5637. constructPath: function CanvasGraphics_constructPath(ops, args) {
  5638. var ctx = this.ctx;
  5639. var current = this.current;
  5640. var x = current.x, y = current.y;
  5641. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  5642. switch (ops[i] | 0) {
  5643. case OPS.moveTo:
  5644. x = args[j++];
  5645. y = args[j++];
  5646. ctx.moveTo(x, y);
  5647. break;
  5648. case OPS.lineTo:
  5649. x = args[j++];
  5650. y = args[j++];
  5651. ctx.lineTo(x, y);
  5652. break;
  5653. case OPS.curveTo:
  5654. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  5655. args[j + 4], args[j + 5]);
  5656. x = args[j + 4];
  5657. y = args[j + 5];
  5658. j += 6;
  5659. break;
  5660. case OPS.curveTo2:
  5661. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  5662. args[j + 2], args[j + 3]);
  5663. x = args[j + 2];
  5664. y = args[j + 3];
  5665. j += 4;
  5666. break;
  5667. case OPS.curveTo3:
  5668. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  5669. args[j + 2], args[j + 3]);
  5670. x = args[j + 2];
  5671. y = args[j + 3];
  5672. j += 4;
  5673. break;
  5674. case OPS.closePath:
  5675. ctx.closePath();
  5676. break;
  5677. }
  5678. }
  5679. current.setCurrentPoint(x, y);
  5680. },
  5681. closePath: function CanvasGraphics_closePath() {
  5682. this.ctx.closePath();
  5683. },
  5684. rectangle: function CanvasGraphics_rectangle(x, y, width, height) {
  5685. if (width === 0) {
  5686. width = this.getSinglePixelWidth();
  5687. }
  5688. if (height === 0) {
  5689. height = this.getSinglePixelWidth();
  5690. }
  5691. this.ctx.rect(x, y, width, height);
  5692. },
  5693. stroke: function CanvasGraphics_stroke(consumePath) {
  5694. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  5695. var ctx = this.ctx;
  5696. var strokeColor = this.current.strokeColor;
  5697. if (this.current.lineWidth === 0) {
  5698. ctx.lineWidth = this.getSinglePixelWidth();
  5699. }
  5700. // For stroke we want to temporarily change the global alpha to the
  5701. // stroking alpha.
  5702. ctx.globalAlpha = this.current.strokeAlpha;
  5703. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  5704. strokeColor.type === 'Pattern') {
  5705. // for patterns, we transform to pattern space, calculate
  5706. // the pattern, call stroke, and restore to user space
  5707. ctx.save();
  5708. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  5709. ctx.stroke();
  5710. ctx.restore();
  5711. } else {
  5712. ctx.stroke();
  5713. }
  5714. if (consumePath) {
  5715. this.consumePath();
  5716. }
  5717. // Restore the global alpha to the fill alpha
  5718. ctx.globalAlpha = this.current.fillAlpha;
  5719. },
  5720. closeStroke: function CanvasGraphics_closeStroke() {
  5721. this.closePath();
  5722. this.stroke();
  5723. },
  5724. fill: function CanvasGraphics_fill(consumePath) {
  5725. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  5726. var ctx = this.ctx;
  5727. var fillColor = this.current.fillColor;
  5728. var needRestore = false;
  5729. if (fillColor && fillColor.hasOwnProperty('type') &&
  5730. fillColor.type === 'Pattern') {
  5731. ctx.save();
  5732. ctx.fillStyle = fillColor.getPattern(ctx, this);
  5733. needRestore = true;
  5734. }
  5735. if (this.pendingEOFill) {
  5736. if ('mozFillRule' in this.ctx) {
  5737. this.ctx.mozFillRule = 'evenodd';
  5738. this.ctx.fill();
  5739. this.ctx.mozFillRule = 'nonzero';
  5740. } else {
  5741. try {
  5742. this.ctx.fill('evenodd');
  5743. } catch (ex) {
  5744. // shouldn't really happen, but browsers might think differently
  5745. this.ctx.fill();
  5746. }
  5747. }
  5748. this.pendingEOFill = false;
  5749. } else {
  5750. this.ctx.fill();
  5751. }
  5752. if (needRestore) {
  5753. ctx.restore();
  5754. }
  5755. if (consumePath) {
  5756. this.consumePath();
  5757. }
  5758. },
  5759. eoFill: function CanvasGraphics_eoFill() {
  5760. this.pendingEOFill = true;
  5761. this.fill();
  5762. },
  5763. fillStroke: function CanvasGraphics_fillStroke() {
  5764. this.fill(false);
  5765. this.stroke(false);
  5766. this.consumePath();
  5767. },
  5768. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  5769. this.pendingEOFill = true;
  5770. this.fillStroke();
  5771. },
  5772. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  5773. this.closePath();
  5774. this.fillStroke();
  5775. },
  5776. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  5777. this.pendingEOFill = true;
  5778. this.closePath();
  5779. this.fillStroke();
  5780. },
  5781. endPath: function CanvasGraphics_endPath() {
  5782. this.consumePath();
  5783. },
  5784. // Clipping
  5785. clip: function CanvasGraphics_clip() {
  5786. this.pendingClip = NORMAL_CLIP;
  5787. },
  5788. eoClip: function CanvasGraphics_eoClip() {
  5789. this.pendingClip = EO_CLIP;
  5790. },
  5791. // Text
  5792. beginText: function CanvasGraphics_beginText() {
  5793. this.current.textMatrix = IDENTITY_MATRIX;
  5794. this.current.x = this.current.lineX = 0;
  5795. this.current.y = this.current.lineY = 0;
  5796. },
  5797. endText: function CanvasGraphics_endText() {
  5798. if (!('pendingTextPaths' in this)) {
  5799. this.ctx.beginPath();
  5800. return;
  5801. }
  5802. var paths = this.pendingTextPaths;
  5803. var ctx = this.ctx;
  5804. ctx.save();
  5805. ctx.beginPath();
  5806. for (var i = 0; i < paths.length; i++) {
  5807. var path = paths[i];
  5808. ctx.setTransform.apply(ctx, path.transform);
  5809. ctx.translate(path.x, path.y);
  5810. path.addToPath(ctx, path.fontSize);
  5811. }
  5812. ctx.restore();
  5813. ctx.clip();
  5814. ctx.beginPath();
  5815. delete this.pendingTextPaths;
  5816. },
  5817. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  5818. this.current.charSpacing = spacing;
  5819. },
  5820. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  5821. this.current.wordSpacing = spacing;
  5822. },
  5823. setHScale: function CanvasGraphics_setHScale(scale) {
  5824. this.current.textHScale = scale / 100;
  5825. },
  5826. setLeading: function CanvasGraphics_setLeading(leading) {
  5827. this.current.leading = -leading;
  5828. },
  5829. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  5830. var fontObj = this.commonObjs.get(fontRefName);
  5831. var current = this.current;
  5832. if (!fontObj) {
  5833. error('Can\'t find font for ' + fontRefName);
  5834. }
  5835. current.fontMatrix = (fontObj.fontMatrix ?
  5836. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  5837. // A valid matrix needs all main diagonal elements to be non-zero
  5838. // This also ensures we bypass FF bugzilla bug #719844.
  5839. if (current.fontMatrix[0] === 0 ||
  5840. current.fontMatrix[3] === 0) {
  5841. warn('Invalid font matrix for font ' + fontRefName);
  5842. }
  5843. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  5844. // and in some docs this can be negative (inverted x-y axes).
  5845. if (size < 0) {
  5846. size = -size;
  5847. current.fontDirection = -1;
  5848. } else {
  5849. current.fontDirection = 1;
  5850. }
  5851. this.current.font = fontObj;
  5852. this.current.fontSize = size;
  5853. if (fontObj.coded) {
  5854. return; // we don't need ctx.font for Type3 fonts
  5855. }
  5856. var name = fontObj.loadedName || 'sans-serif';
  5857. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  5858. (fontObj.bold ? 'bold' : 'normal');
  5859. var italic = fontObj.italic ? 'italic' : 'normal';
  5860. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  5861. // Some font backends cannot handle fonts below certain size.
  5862. // Keeping the font at minimal size and using the fontSizeScale to change
  5863. // the current transformation matrix before the fillText/strokeText.
  5864. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  5865. var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;
  5866. this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :
  5867. size / MIN_FONT_SIZE;
  5868. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  5869. this.ctx.font = rule;
  5870. },
  5871. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  5872. this.current.textRenderingMode = mode;
  5873. },
  5874. setTextRise: function CanvasGraphics_setTextRise(rise) {
  5875. this.current.textRise = rise;
  5876. },
  5877. moveText: function CanvasGraphics_moveText(x, y) {
  5878. this.current.x = this.current.lineX += x;
  5879. this.current.y = this.current.lineY += y;
  5880. },
  5881. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  5882. this.setLeading(-y);
  5883. this.moveText(x, y);
  5884. },
  5885. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  5886. this.current.textMatrix = [a, b, c, d, e, f];
  5887. this.current.x = this.current.lineX = 0;
  5888. this.current.y = this.current.lineY = 0;
  5889. },
  5890. nextLine: function CanvasGraphics_nextLine() {
  5891. this.moveText(0, this.current.leading);
  5892. },
  5893. applyTextTransforms: function CanvasGraphics_applyTextTransforms() {
  5894. var ctx = this.ctx;
  5895. var current = this.current;
  5896. ctx.transform.apply(ctx, current.textMatrix);
  5897. ctx.translate(current.x, current.y + current.textRise);
  5898. if (current.fontDirection > 0) {
  5899. ctx.scale(current.textHScale, -1);
  5900. } else {
  5901. ctx.scale(-current.textHScale, 1);
  5902. }
  5903. },
  5904. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  5905. var ctx = this.ctx;
  5906. var current = this.current;
  5907. var font = current.font;
  5908. var fontSize = current.fontSize / current.fontSizeScale;
  5909. var textRenderingMode = current.textRenderingMode;
  5910. var fillStrokeMode = textRenderingMode &
  5911. TextRenderingMode.FILL_STROKE_MASK;
  5912. var isAddToPathSet = !!(textRenderingMode &
  5913. TextRenderingMode.ADD_TO_PATH_FLAG);
  5914. var addToPath;
  5915. if (font.disableFontFace || isAddToPathSet) {
  5916. addToPath = font.getPathGenerator(this.commonObjs, character);
  5917. }
  5918. if (font.disableFontFace) {
  5919. ctx.save();
  5920. ctx.translate(x, y);
  5921. ctx.beginPath();
  5922. addToPath(ctx, fontSize);
  5923. if (fillStrokeMode === TextRenderingMode.FILL ||
  5924. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5925. ctx.fill();
  5926. }
  5927. if (fillStrokeMode === TextRenderingMode.STROKE ||
  5928. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5929. ctx.stroke();
  5930. }
  5931. ctx.restore();
  5932. } else {
  5933. if (fillStrokeMode === TextRenderingMode.FILL ||
  5934. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5935. ctx.fillText(character, x, y);
  5936. }
  5937. if (fillStrokeMode === TextRenderingMode.STROKE ||
  5938. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  5939. ctx.strokeText(character, x, y);
  5940. }
  5941. }
  5942. if (isAddToPathSet) {
  5943. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  5944. paths.push({
  5945. transform: ctx.mozCurrentTransform,
  5946. x: x,
  5947. y: y,
  5948. fontSize: fontSize,
  5949. addToPath: addToPath
  5950. });
  5951. }
  5952. },
  5953. get isFontSubpixelAAEnabled() {
  5954. // Checks if anti-aliasing is enabled when scaled text is painted.
  5955. // On Windows GDI scaled fonts looks bad.
  5956. var ctx = document.createElement('canvas').getContext('2d');
  5957. ctx.scale(1.5, 1);
  5958. ctx.fillText('I', 0, 10);
  5959. var data = ctx.getImageData(0, 0, 10, 10).data;
  5960. var enabled = false;
  5961. for (var i = 3; i < data.length; i += 4) {
  5962. if (data[i] > 0 && data[i] < 255) {
  5963. enabled = true;
  5964. break;
  5965. }
  5966. }
  5967. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  5968. },
  5969. showText: function CanvasGraphics_showText(glyphs) {
  5970. var ctx = this.ctx;
  5971. var current = this.current;
  5972. var font = current.font;
  5973. var fontSize = current.fontSize;
  5974. var fontSizeScale = current.fontSizeScale;
  5975. var charSpacing = current.charSpacing;
  5976. var wordSpacing = current.wordSpacing;
  5977. var textHScale = current.textHScale * current.fontDirection;
  5978. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  5979. var glyphsLength = glyphs.length;
  5980. var vertical = font.vertical;
  5981. var defaultVMetrics = font.defaultVMetrics;
  5982. var i, glyph, width;
  5983. if (fontSize === 0) {
  5984. return;
  5985. }
  5986. // Type3 fonts - each glyph is a "mini-PDF"
  5987. if (font.coded) {
  5988. ctx.save();
  5989. ctx.transform.apply(ctx, current.textMatrix);
  5990. ctx.translate(current.x, current.y);
  5991. ctx.scale(textHScale, 1);
  5992. for (i = 0; i < glyphsLength; ++i) {
  5993. glyph = glyphs[i];
  5994. if (glyph === null) {
  5995. // word break
  5996. this.ctx.translate(wordSpacing, 0);
  5997. current.x += wordSpacing * textHScale;
  5998. continue;
  5999. }
  6000. this.processingType3 = glyph;
  6001. this.save();
  6002. ctx.scale(fontSize, fontSize);
  6003. ctx.transform.apply(ctx, fontMatrix);
  6004. this.executeOperatorList(glyph.operatorList);
  6005. this.restore();
  6006. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  6007. width = ((transformed[0] * fontSize + charSpacing) *
  6008. current.fontDirection);
  6009. ctx.translate(width, 0);
  6010. current.x += width * textHScale;
  6011. }
  6012. ctx.restore();
  6013. this.processingType3 = null;
  6014. } else {
  6015. ctx.save();
  6016. this.applyTextTransforms();
  6017. var lineWidth = current.lineWidth;
  6018. var a1 = current.textMatrix[0], b1 = current.textMatrix[1];
  6019. var scale = Math.sqrt(a1 * a1 + b1 * b1);
  6020. if (scale === 0 || lineWidth === 0) {
  6021. lineWidth = this.getSinglePixelWidth();
  6022. } else {
  6023. lineWidth /= scale;
  6024. }
  6025. if (fontSizeScale != 1.0) {
  6026. ctx.scale(fontSizeScale, fontSizeScale);
  6027. lineWidth /= fontSizeScale;
  6028. }
  6029. ctx.lineWidth = lineWidth;
  6030. var x = 0;
  6031. for (i = 0; i < glyphsLength; ++i) {
  6032. glyph = glyphs[i];
  6033. if (glyph === null) {
  6034. // word break
  6035. x += current.fontDirection * wordSpacing;
  6036. continue;
  6037. }
  6038. var restoreNeeded = false;
  6039. var character = glyph.fontChar;
  6040. var vmetric = glyph.vmetric || defaultVMetrics;
  6041. if (vertical) {
  6042. var vx = glyph.vmetric ? vmetric[1] : glyph.width * 0.5;
  6043. vx = -vx * fontSize * current.fontMatrix[0];
  6044. var vy = vmetric[2] * fontSize * current.fontMatrix[0];
  6045. }
  6046. width = vmetric ? -vmetric[0] : glyph.width;
  6047. var charWidth = width * fontSize * current.fontMatrix[0] +
  6048. charSpacing * current.fontDirection;
  6049. var accent = glyph.accent;
  6050. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  6051. if (vertical) {
  6052. scaledX = vx / fontSizeScale;
  6053. scaledY = (x + vy) / fontSizeScale;
  6054. } else {
  6055. scaledX = x / fontSizeScale;
  6056. scaledY = 0;
  6057. }
  6058. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  6059. // some standard fonts may not have the exact width, trying to
  6060. // rescale per character
  6061. var measuredWidth = ctx.measureText(character).width * 1000 /
  6062. current.fontSize * current.fontSizeScale;
  6063. var characterScaleX = width / measuredWidth;
  6064. restoreNeeded = true;
  6065. ctx.save();
  6066. ctx.scale(characterScaleX, 1);
  6067. scaledX /= characterScaleX;
  6068. if (accent) {
  6069. scaledAccentX /= characterScaleX;
  6070. }
  6071. }
  6072. this.paintChar(character, scaledX, scaledY);
  6073. if (accent) {
  6074. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  6075. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  6076. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  6077. }
  6078. x += charWidth;
  6079. if (restoreNeeded) {
  6080. ctx.restore();
  6081. }
  6082. }
  6083. if (vertical) {
  6084. current.y -= x * textHScale;
  6085. } else {
  6086. current.x += x * textHScale;
  6087. }
  6088. ctx.restore();
  6089. }
  6090. },
  6091. showSpacedText: function CanvasGraphics_showSpacedText(arr) {
  6092. var current = this.current;
  6093. var font = current.font;
  6094. var fontSize = current.fontSize;
  6095. // TJ array's number is independent from fontMatrix
  6096. var textHScale = current.textHScale * 0.001 * current.fontDirection;
  6097. var arrLength = arr.length;
  6098. var vertical = font.vertical;
  6099. for (var i = 0; i < arrLength; ++i) {
  6100. var e = arr[i];
  6101. if (isNum(e)) {
  6102. var spacingLength = -e * fontSize * textHScale;
  6103. if (vertical) {
  6104. current.y += spacingLength;
  6105. } else {
  6106. current.x += spacingLength;
  6107. }
  6108. } else {
  6109. this.showText(e);
  6110. }
  6111. }
  6112. },
  6113. nextLineShowText: function CanvasGraphics_nextLineShowText(text) {
  6114. this.nextLine();
  6115. this.showText(text);
  6116. },
  6117. nextLineSetSpacingShowText:
  6118. function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing,
  6119. charSpacing,
  6120. text) {
  6121. this.setWordSpacing(wordSpacing);
  6122. this.setCharSpacing(charSpacing);
  6123. this.nextLineShowText(text);
  6124. },
  6125. // Type3 fonts
  6126. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  6127. // We can safely ignore this since the width should be the same
  6128. // as the width in the Widths array.
  6129. },
  6130. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  6131. yWidth,
  6132. llx,
  6133. lly,
  6134. urx,
  6135. ury) {
  6136. // TODO According to the spec we're also suppose to ignore any operators
  6137. // that set color or include images while processing this type3 font.
  6138. this.rectangle(llx, lly, urx - llx, ury - lly);
  6139. this.clip();
  6140. this.endPath();
  6141. },
  6142. // Color
  6143. setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) {
  6144. this.current.strokeColorSpace = ColorSpace.fromIR(raw);
  6145. },
  6146. setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) {
  6147. this.current.fillColorSpace = ColorSpace.fromIR(raw);
  6148. },
  6149. setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) {
  6150. var cs = this.current.strokeColorSpace;
  6151. var rgbColor = cs.getRgb(arguments, 0);
  6152. var color = Util.makeCssRgb(rgbColor);
  6153. this.ctx.strokeStyle = color;
  6154. this.current.strokeColor = color;
  6155. },
  6156. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) {
  6157. var pattern;
  6158. if (IR[0] == 'TilingPattern') {
  6159. var args = IR[1];
  6160. var base = cs.base;
  6161. var color;
  6162. if (base) {
  6163. color = base.getRgb(args, 0);
  6164. }
  6165. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  6166. this.commonObjs, this.baseTransform);
  6167. } else {
  6168. pattern = getShadingPatternFromIR(IR);
  6169. }
  6170. return pattern;
  6171. },
  6172. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  6173. var cs = this.current.strokeColorSpace;
  6174. if (cs.name == 'Pattern') {
  6175. this.current.strokeColor = this.getColorN_Pattern(arguments, cs);
  6176. } else {
  6177. this.setStrokeColor.apply(this, arguments);
  6178. }
  6179. },
  6180. setFillColor: function CanvasGraphics_setFillColor(/*...*/) {
  6181. var cs = this.current.fillColorSpace;
  6182. var rgbColor = cs.getRgb(arguments, 0);
  6183. var color = Util.makeCssRgb(rgbColor);
  6184. this.ctx.fillStyle = color;
  6185. this.current.fillColor = color;
  6186. },
  6187. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  6188. var cs = this.current.fillColorSpace;
  6189. if (cs.name == 'Pattern') {
  6190. this.current.fillColor = this.getColorN_Pattern(arguments, cs);
  6191. } else {
  6192. this.setFillColor.apply(this, arguments);
  6193. }
  6194. },
  6195. setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {
  6196. this.current.strokeColorSpace = ColorSpace.singletons.gray;
  6197. var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);
  6198. var color = Util.makeCssRgb(rgbColor);
  6199. this.ctx.strokeStyle = color;
  6200. this.current.strokeColor = color;
  6201. },
  6202. setFillGray: function CanvasGraphics_setFillGray(gray) {
  6203. this.current.fillColorSpace = ColorSpace.singletons.gray;
  6204. var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);
  6205. var color = Util.makeCssRgb(rgbColor);
  6206. this.ctx.fillStyle = color;
  6207. this.current.fillColor = color;
  6208. },
  6209. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  6210. this.current.strokeColorSpace = ColorSpace.singletons.rgb;
  6211. var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);
  6212. var color = Util.makeCssRgb(rgbColor);
  6213. this.ctx.strokeStyle = color;
  6214. this.current.strokeColor = color;
  6215. },
  6216. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  6217. this.current.fillColorSpace = ColorSpace.singletons.rgb;
  6218. var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);
  6219. var color = Util.makeCssRgb(rgbColor);
  6220. this.ctx.fillStyle = color;
  6221. this.current.fillColor = color;
  6222. },
  6223. setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) {
  6224. this.current.strokeColorSpace = ColorSpace.singletons.cmyk;
  6225. var color = Util.makeCssCmyk(arguments);
  6226. this.ctx.strokeStyle = color;
  6227. this.current.strokeColor = color;
  6228. },
  6229. setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) {
  6230. this.current.fillColorSpace = ColorSpace.singletons.cmyk;
  6231. var color = Util.makeCssCmyk(arguments);
  6232. this.ctx.fillStyle = color;
  6233. this.current.fillColor = color;
  6234. },
  6235. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  6236. var ctx = this.ctx;
  6237. this.save();
  6238. var pattern = getShadingPatternFromIR(patternIR);
  6239. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  6240. var inv = ctx.mozCurrentTransformInverse;
  6241. if (inv) {
  6242. var canvas = ctx.canvas;
  6243. var width = canvas.width;
  6244. var height = canvas.height;
  6245. var bl = Util.applyTransform([0, 0], inv);
  6246. var br = Util.applyTransform([0, height], inv);
  6247. var ul = Util.applyTransform([width, 0], inv);
  6248. var ur = Util.applyTransform([width, height], inv);
  6249. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  6250. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  6251. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  6252. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  6253. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  6254. } else {
  6255. // HACK to draw the gradient onto an infinite rectangle.
  6256. // PDF gradients are drawn across the entire image while
  6257. // Canvas only allows gradients to be drawn in a rectangle
  6258. // The following bug should allow us to remove this.
  6259. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  6260. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  6261. }
  6262. this.restore();
  6263. },
  6264. // Images
  6265. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  6266. error('Should not call beginInlineImage');
  6267. },
  6268. beginImageData: function CanvasGraphics_beginImageData() {
  6269. error('Should not call beginImageData');
  6270. },
  6271. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  6272. bbox) {
  6273. this.save();
  6274. this.baseTransformStack.push(this.baseTransform);
  6275. if (matrix && isArray(matrix) && 6 == matrix.length) {
  6276. this.transform.apply(this, matrix);
  6277. }
  6278. this.baseTransform = this.ctx.mozCurrentTransform;
  6279. if (bbox && isArray(bbox) && 4 == bbox.length) {
  6280. var width = bbox[2] - bbox[0];
  6281. var height = bbox[3] - bbox[1];
  6282. this.rectangle(bbox[0], bbox[1], width, height);
  6283. this.clip();
  6284. this.endPath();
  6285. }
  6286. },
  6287. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  6288. this.restore();
  6289. this.baseTransform = this.baseTransformStack.pop();
  6290. },
  6291. beginGroup: function CanvasGraphics_beginGroup(group) {
  6292. this.save();
  6293. var currentCtx = this.ctx;
  6294. // TODO non-isolated groups - according to Rik at adobe non-isolated
  6295. // group results aren't usually that different and they even have tools
  6296. // that ignore this setting. Notes from Rik on implmenting:
  6297. // - When you encounter an transparency group, create a new canvas with
  6298. // the dimensions of the bbox
  6299. // - copy the content from the previous canvas to the new canvas
  6300. // - draw as usual
  6301. // - remove the backdrop alpha:
  6302. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  6303. // value of your transparency group and 'alphaBackdrop' the alpha of the
  6304. // backdrop
  6305. // - remove background color:
  6306. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  6307. if (!group.isolated) {
  6308. info('TODO: Support non-isolated groups.');
  6309. }
  6310. // TODO knockout - supposedly possible with the clever use of compositing
  6311. // modes.
  6312. if (group.knockout) {
  6313. warn('Knockout groups not supported.');
  6314. }
  6315. var currentTransform = currentCtx.mozCurrentTransform;
  6316. if (group.matrix) {
  6317. currentCtx.transform.apply(currentCtx, group.matrix);
  6318. }
  6319. assert(group.bbox, 'Bounding box is required.');
  6320. // Based on the current transform figure out how big the bounding box
  6321. // will actually be.
  6322. var bounds = Util.getAxialAlignedBoundingBox(
  6323. group.bbox,
  6324. currentCtx.mozCurrentTransform);
  6325. // Clip the bounding box to the current canvas.
  6326. var canvasBounds = [0,
  6327. 0,
  6328. currentCtx.canvas.width,
  6329. currentCtx.canvas.height];
  6330. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  6331. // Use ceil in case we're between sizes so we don't create canvas that is
  6332. // too small and make the canvas at least 1x1 pixels.
  6333. var offsetX = Math.floor(bounds[0]);
  6334. var offsetY = Math.floor(bounds[1]);
  6335. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  6336. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  6337. var scaleX = 1, scaleY = 1;
  6338. if (drawnWidth > MAX_GROUP_SIZE) {
  6339. scaleX = drawnWidth / MAX_GROUP_SIZE;
  6340. drawnWidth = MAX_GROUP_SIZE;
  6341. }
  6342. if (drawnHeight > MAX_GROUP_SIZE) {
  6343. scaleY = drawnHeight / MAX_GROUP_SIZE;
  6344. drawnHeight = MAX_GROUP_SIZE;
  6345. }
  6346. var cacheId = 'groupAt' + this.groupLevel;
  6347. if (group.smask) {
  6348. // Using two cache entries is case if masks are used one after another.
  6349. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  6350. }
  6351. var scratchCanvas = CachedCanvases.getCanvas(
  6352. cacheId, drawnWidth, drawnHeight, true);
  6353. var groupCtx = scratchCanvas.context;
  6354. // Since we created a new canvas that is just the size of the bounding box
  6355. // we have to translate the group ctx.
  6356. groupCtx.scale(1 / scaleX, 1 / scaleY);
  6357. groupCtx.translate(-offsetX, -offsetY);
  6358. groupCtx.transform.apply(groupCtx, currentTransform);
  6359. if (group.smask) {
  6360. // Saving state and cached mask to be used in setGState.
  6361. this.smaskStack.push({
  6362. canvas: scratchCanvas.canvas,
  6363. context: groupCtx,
  6364. offsetX: offsetX,
  6365. offsetY: offsetY,
  6366. scaleX: scaleX,
  6367. scaleY: scaleY,
  6368. subtype: group.smask.subtype,
  6369. backdrop: group.smask.backdrop,
  6370. colorSpace: group.colorSpace && ColorSpace.fromIR(group.colorSpace)
  6371. });
  6372. } else {
  6373. // Setup the current ctx so when the group is popped we draw it at the
  6374. // right location.
  6375. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  6376. currentCtx.translate(offsetX, offsetY);
  6377. currentCtx.scale(scaleX, scaleY);
  6378. }
  6379. // The transparency group inherits all off the current graphics state
  6380. // except the blend mode, soft mask, and alpha constants.
  6381. copyCtxState(currentCtx, groupCtx);
  6382. this.ctx = groupCtx;
  6383. this.setGState([
  6384. ['BM', 'Normal'],
  6385. ['ca', 1],
  6386. ['CA', 1]
  6387. ]);
  6388. this.groupStack.push(currentCtx);
  6389. this.groupLevel++;
  6390. },
  6391. endGroup: function CanvasGraphics_endGroup(group) {
  6392. this.groupLevel--;
  6393. var groupCtx = this.ctx;
  6394. this.ctx = this.groupStack.pop();
  6395. // Turn off image smoothing to avoid sub pixel interpolation which can
  6396. // look kind of blurry for some pdfs.
  6397. if ('imageSmoothingEnabled' in this.ctx) {
  6398. this.ctx.imageSmoothingEnabled = false;
  6399. } else {
  6400. this.ctx.mozImageSmoothingEnabled = false;
  6401. }
  6402. if (group.smask) {
  6403. this.tempSMask = this.smaskStack.pop();
  6404. } else {
  6405. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  6406. }
  6407. this.restore();
  6408. },
  6409. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  6410. this.save();
  6411. this.current = new CanvasExtraState();
  6412. },
  6413. endAnnotations: function CanvasGraphics_endAnnotations() {
  6414. this.restore();
  6415. },
  6416. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  6417. matrix) {
  6418. this.save();
  6419. if (rect && isArray(rect) && 4 == rect.length) {
  6420. var width = rect[2] - rect[0];
  6421. var height = rect[3] - rect[1];
  6422. this.rectangle(rect[0], rect[1], width, height);
  6423. this.clip();
  6424. this.endPath();
  6425. }
  6426. this.transform.apply(this, transform);
  6427. this.transform.apply(this, matrix);
  6428. },
  6429. endAnnotation: function CanvasGraphics_endAnnotation() {
  6430. this.restore();
  6431. },
  6432. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  6433. var domImage = this.objs.get(objId);
  6434. if (!domImage) {
  6435. warn('Dependent image isn\'t ready yet');
  6436. return;
  6437. }
  6438. this.save();
  6439. var ctx = this.ctx;
  6440. // scale the image to the unit square
  6441. ctx.scale(1 / w, -1 / h);
  6442. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  6443. 0, -h, w, h);
  6444. if (this.imageLayer) {
  6445. var currentTransform = ctx.mozCurrentTransformInverse;
  6446. var position = this.getCanvasPosition(0, 0);
  6447. this.imageLayer.appendImage({
  6448. objId: objId,
  6449. left: position[0],
  6450. top: position[1],
  6451. width: w / currentTransform[0],
  6452. height: h / currentTransform[3]
  6453. });
  6454. }
  6455. this.restore();
  6456. },
  6457. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  6458. var ctx = this.ctx;
  6459. var width = img.width, height = img.height;
  6460. var glyph = this.processingType3;
  6461. if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
  6462. var MAX_SIZE_TO_COMPILE = 1000;
  6463. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  6464. glyph.compiled =
  6465. compileType3Glyph({data: img.data, width: width, height: height});
  6466. } else {
  6467. glyph.compiled = null;
  6468. }
  6469. }
  6470. if (glyph && glyph.compiled) {
  6471. glyph.compiled(ctx);
  6472. return;
  6473. }
  6474. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6475. var maskCtx = maskCanvas.context;
  6476. maskCtx.save();
  6477. putBinaryImageMask(maskCtx, img);
  6478. maskCtx.globalCompositeOperation = 'source-in';
  6479. var fillColor = this.current.fillColor;
  6480. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6481. fillColor.type === 'Pattern') ?
  6482. fillColor.getPattern(maskCtx, this) : fillColor;
  6483. maskCtx.fillRect(0, 0, width, height);
  6484. maskCtx.restore();
  6485. this.paintInlineImageXObject(maskCanvas.canvas);
  6486. },
  6487. paintImageMaskXObjectRepeat:
  6488. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  6489. scaleY, positions) {
  6490. var width = imgData.width;
  6491. var height = imgData.height;
  6492. var ctx = this.ctx;
  6493. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6494. var maskCtx = maskCanvas.context;
  6495. maskCtx.save();
  6496. putBinaryImageMask(maskCtx, imgData);
  6497. maskCtx.globalCompositeOperation = 'source-in';
  6498. var fillColor = this.current.fillColor;
  6499. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6500. fillColor.type === 'Pattern') ?
  6501. fillColor.getPattern(maskCtx, this) : fillColor;
  6502. maskCtx.fillRect(0, 0, width, height);
  6503. maskCtx.restore();
  6504. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  6505. ctx.save();
  6506. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  6507. ctx.scale(1, -1);
  6508. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  6509. 0, -1, 1, 1);
  6510. ctx.restore();
  6511. }
  6512. },
  6513. paintImageMaskXObjectGroup:
  6514. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  6515. var ctx = this.ctx;
  6516. for (var i = 0, ii = images.length; i < ii; i++) {
  6517. var image = images[i];
  6518. var width = image.width, height = image.height;
  6519. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  6520. var maskCtx = maskCanvas.context;
  6521. maskCtx.save();
  6522. putBinaryImageMask(maskCtx, image);
  6523. maskCtx.globalCompositeOperation = 'source-in';
  6524. var fillColor = this.current.fillColor;
  6525. maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
  6526. fillColor.type === 'Pattern') ?
  6527. fillColor.getPattern(maskCtx, this) : fillColor;
  6528. maskCtx.fillRect(0, 0, width, height);
  6529. maskCtx.restore();
  6530. ctx.save();
  6531. ctx.transform.apply(ctx, image.transform);
  6532. ctx.scale(1, -1);
  6533. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  6534. 0, -1, 1, 1);
  6535. ctx.restore();
  6536. }
  6537. },
  6538. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  6539. var imgData = this.objs.get(objId);
  6540. if (!imgData) {
  6541. warn('Dependent image isn\'t ready yet');
  6542. return;
  6543. }
  6544. this.paintInlineImageXObject(imgData);
  6545. },
  6546. paintImageXObjectRepeat:
  6547. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  6548. positions) {
  6549. var imgData = this.objs.get(objId);
  6550. if (!imgData) {
  6551. warn('Dependent image isn\'t ready yet');
  6552. return;
  6553. }
  6554. var width = imgData.width;
  6555. var height = imgData.height;
  6556. var map = [];
  6557. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  6558. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  6559. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  6560. }
  6561. this.paintInlineImageXObjectGroup(imgData, map);
  6562. },
  6563. paintInlineImageXObject:
  6564. function CanvasGraphics_paintInlineImageXObject(imgData) {
  6565. var width = imgData.width;
  6566. var height = imgData.height;
  6567. var ctx = this.ctx;
  6568. this.save();
  6569. // scale the image to the unit square
  6570. ctx.scale(1 / width, -1 / height);
  6571. var currentTransform = ctx.mozCurrentTransformInverse;
  6572. var a = currentTransform[0], b = currentTransform[1];
  6573. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  6574. var c = currentTransform[2], d = currentTransform[3];
  6575. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  6576. var imgToPaint, tmpCanvas;
  6577. // instanceof HTMLElement does not work in jsdom node.js module
  6578. if (imgData instanceof HTMLElement || !imgData.data) {
  6579. imgToPaint = imgData;
  6580. } else {
  6581. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  6582. var tmpCtx = tmpCanvas.context;
  6583. putBinaryImageData(tmpCtx, imgData);
  6584. imgToPaint = tmpCanvas.canvas;
  6585. }
  6586. var paintWidth = width, paintHeight = height;
  6587. var tmpCanvasId = 'prescale1';
  6588. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  6589. // pixels during drawImage operation, painting on the temporary canvas(es)
  6590. // that are twice smaller in size
  6591. while ((widthScale > 2 && paintWidth > 1) ||
  6592. (heightScale > 2 && paintHeight > 1)) {
  6593. var newWidth = paintWidth, newHeight = paintHeight;
  6594. if (widthScale > 2 && paintWidth > 1) {
  6595. newWidth = Math.ceil(paintWidth / 2);
  6596. widthScale /= paintWidth / newWidth;
  6597. }
  6598. if (heightScale > 2 && paintHeight > 1) {
  6599. newHeight = Math.ceil(paintHeight / 2);
  6600. heightScale /= paintHeight / newHeight;
  6601. }
  6602. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  6603. tmpCtx = tmpCanvas.context;
  6604. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  6605. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  6606. 0, 0, newWidth, newHeight);
  6607. imgToPaint = tmpCanvas.canvas;
  6608. paintWidth = newWidth;
  6609. paintHeight = newHeight;
  6610. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  6611. }
  6612. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  6613. 0, -height, width, height);
  6614. if (this.imageLayer) {
  6615. var position = this.getCanvasPosition(0, -height);
  6616. this.imageLayer.appendImage({
  6617. imgData: imgData,
  6618. left: position[0],
  6619. top: position[1],
  6620. width: width / currentTransform[0],
  6621. height: height / currentTransform[3]
  6622. });
  6623. }
  6624. this.restore();
  6625. },
  6626. paintInlineImageXObjectGroup:
  6627. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  6628. var ctx = this.ctx;
  6629. var w = imgData.width;
  6630. var h = imgData.height;
  6631. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  6632. var tmpCtx = tmpCanvas.context;
  6633. putBinaryImageData(tmpCtx, imgData);
  6634. for (var i = 0, ii = map.length; i < ii; i++) {
  6635. var entry = map[i];
  6636. ctx.save();
  6637. ctx.transform.apply(ctx, entry.transform);
  6638. ctx.scale(1, -1);
  6639. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  6640. 0, -1, 1, 1);
  6641. if (this.imageLayer) {
  6642. var position = this.getCanvasPosition(entry.x, entry.y);
  6643. this.imageLayer.appendImage({
  6644. imgData: imgData,
  6645. left: position[0],
  6646. top: position[1],
  6647. width: w,
  6648. height: h
  6649. });
  6650. }
  6651. ctx.restore();
  6652. }
  6653. },
  6654. paintSolidColorImageMask:
  6655. function CanvasGraphics_paintSolidColorImageMask() {
  6656. this.ctx.fillRect(0, 0, 1, 1);
  6657. },
  6658. // Marked content
  6659. markPoint: function CanvasGraphics_markPoint(tag) {
  6660. // TODO Marked content.
  6661. },
  6662. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  6663. // TODO Marked content.
  6664. },
  6665. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  6666. // TODO Marked content.
  6667. },
  6668. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  6669. tag, properties) {
  6670. // TODO Marked content.
  6671. },
  6672. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  6673. // TODO Marked content.
  6674. },
  6675. // Compatibility
  6676. beginCompat: function CanvasGraphics_beginCompat() {
  6677. // TODO ignore undefined operators (should we do that anyway?)
  6678. },
  6679. endCompat: function CanvasGraphics_endCompat() {
  6680. // TODO stop ignoring undefined operators
  6681. },
  6682. // Helper functions
  6683. consumePath: function CanvasGraphics_consumePath() {
  6684. if (this.pendingClip) {
  6685. if (this.pendingClip == EO_CLIP) {
  6686. if ('mozFillRule' in this.ctx) {
  6687. this.ctx.mozFillRule = 'evenodd';
  6688. this.ctx.clip();
  6689. this.ctx.mozFillRule = 'nonzero';
  6690. } else {
  6691. try {
  6692. this.ctx.clip('evenodd');
  6693. } catch (ex) {
  6694. // shouldn't really happen, but browsers might think differently
  6695. this.ctx.clip();
  6696. }
  6697. }
  6698. } else {
  6699. this.ctx.clip();
  6700. }
  6701. this.pendingClip = null;
  6702. }
  6703. this.ctx.beginPath();
  6704. },
  6705. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  6706. var inverse = this.ctx.mozCurrentTransformInverse;
  6707. // max of the current horizontal and vertical scale
  6708. return Math.sqrt(Math.max(
  6709. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  6710. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  6711. },
  6712. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  6713. var transform = this.ctx.mozCurrentTransform;
  6714. return [
  6715. transform[0] * x + transform[2] * y + transform[4],
  6716. transform[1] * x + transform[3] * y + transform[5]
  6717. ];
  6718. }
  6719. };
  6720. for (var op in OPS) {
  6721. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  6722. }
  6723. return CanvasGraphics;
  6724. })();
  6725. var WebGLUtils = (function WebGLUtilsClosure() {
  6726. function loadShader(gl, code, shaderType) {
  6727. var shader = gl.createShader(shaderType);
  6728. gl.shaderSource(shader, code);
  6729. gl.compileShader(shader);
  6730. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  6731. if (!compiled) {
  6732. var errorMsg = gl.getShaderInfoLog(shader);
  6733. throw new Error('Error during shader compilation: ' + errorMsg);
  6734. }
  6735. return shader;
  6736. }
  6737. function createVertexShader(gl, code) {
  6738. return loadShader(gl, code, gl.VERTEX_SHADER);
  6739. }
  6740. function createFragmentShader(gl, code) {
  6741. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  6742. }
  6743. function createProgram(gl, shaders) {
  6744. var program = gl.createProgram();
  6745. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  6746. gl.attachShader(program, shaders[i]);
  6747. }
  6748. gl.linkProgram(program);
  6749. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  6750. if (!linked) {
  6751. var errorMsg = gl.getProgramInfoLog(program);
  6752. throw new Error('Error during program linking: ' + errorMsg);
  6753. }
  6754. return program;
  6755. }
  6756. function createTexture(gl, image, textureId) {
  6757. gl.activeTexture(textureId);
  6758. var texture = gl.createTexture();
  6759. gl.bindTexture(gl.TEXTURE_2D, texture);
  6760. // Set the parameters so we can render any size image.
  6761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6765. // Upload the image into the texture.
  6766. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  6767. return texture;
  6768. }
  6769. var currentGL, currentCanvas;
  6770. function generageGL() {
  6771. if (currentGL) {
  6772. return;
  6773. }
  6774. currentCanvas = document.createElement('canvas');
  6775. currentGL = currentCanvas.getContext('webgl',
  6776. { premultipliedalpha: false });
  6777. }
  6778. var smaskVertexShaderCode = '\
  6779. attribute vec2 a_position; \
  6780. attribute vec2 a_texCoord; \
  6781. \
  6782. uniform vec2 u_resolution; \
  6783. \
  6784. varying vec2 v_texCoord; \
  6785. \
  6786. void main() { \
  6787. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  6788. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  6789. \
  6790. v_texCoord = a_texCoord; \
  6791. } ';
  6792. var smaskFragmentShaderCode = '\
  6793. precision mediump float; \
  6794. \
  6795. uniform vec4 u_backdrop; \
  6796. uniform int u_subtype; \
  6797. uniform sampler2D u_image; \
  6798. uniform sampler2D u_mask; \
  6799. \
  6800. varying vec2 v_texCoord; \
  6801. \
  6802. void main() { \
  6803. vec4 imageColor = texture2D(u_image, v_texCoord); \
  6804. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  6805. if (u_backdrop.a > 0.0) { \
  6806. maskColor.rgb = maskColor.rgb * maskColor.a + \
  6807. u_backdrop.rgb * (1.0 - maskColor.a); \
  6808. } \
  6809. float lum; \
  6810. if (u_subtype == 0) { \
  6811. lum = maskColor.a; \
  6812. } else { \
  6813. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  6814. maskColor.b * 0.11; \
  6815. } \
  6816. imageColor.a *= lum; \
  6817. imageColor.rgb *= imageColor.a; \
  6818. gl_FragColor = imageColor; \
  6819. } ';
  6820. var smaskCache = null;
  6821. function initSmaskGL() {
  6822. var canvas, gl;
  6823. generageGL();
  6824. canvas = currentCanvas;
  6825. currentCanvas = null;
  6826. gl = currentGL;
  6827. currentGL = null;
  6828. // setup a GLSL program
  6829. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  6830. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  6831. var program = createProgram(gl, [vertexShader, fragmentShader]);
  6832. gl.useProgram(program);
  6833. var cache = {};
  6834. cache.gl = gl;
  6835. cache.canvas = canvas;
  6836. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  6837. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  6838. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  6839. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  6840. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  6841. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  6842. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  6843. // provide texture coordinates for the rectangle.
  6844. var texCoordBuffer = gl.createBuffer();
  6845. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  6846. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  6847. 0.0, 0.0,
  6848. 1.0, 0.0,
  6849. 0.0, 1.0,
  6850. 0.0, 1.0,
  6851. 1.0, 0.0,
  6852. 1.0, 1.0]), gl.STATIC_DRAW);
  6853. gl.enableVertexAttribArray(texCoordLocation);
  6854. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  6855. gl.uniform1i(texLayerLocation, 0);
  6856. gl.uniform1i(texMaskLocation, 1);
  6857. smaskCache = cache;
  6858. }
  6859. function composeSMask(layer, mask, properties) {
  6860. var width = layer.width, height = layer.height;
  6861. if (!smaskCache) {
  6862. initSmaskGL();
  6863. }
  6864. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  6865. canvas.width = width;
  6866. canvas.height = height;
  6867. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  6868. gl.uniform2f(cache.resolutionLocation, width, height);
  6869. if (properties.backdrop) {
  6870. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  6871. properties.backdrop[1], properties.backdrop[2], 1);
  6872. } else {
  6873. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  6874. }
  6875. gl.uniform1i(cache.subtypeLocation,
  6876. properties.subtype === 'Luminosity' ? 1 : 0);
  6877. // Create a textures
  6878. var texture = createTexture(gl, layer, gl.TEXTURE0);
  6879. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  6880. // Create a buffer and put a single clipspace rectangle in
  6881. // it (2 triangles)
  6882. var buffer = gl.createBuffer();
  6883. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  6884. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  6885. 0, 0,
  6886. width, 0,
  6887. 0, height,
  6888. 0, height,
  6889. width, 0,
  6890. width, height]), gl.STATIC_DRAW);
  6891. gl.enableVertexAttribArray(cache.positionLocation);
  6892. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  6893. // draw
  6894. gl.clearColor(0, 0, 0, 0);
  6895. gl.enable(gl.BLEND);
  6896. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  6897. gl.clear(gl.COLOR_BUFFER_BIT);
  6898. gl.drawArrays(gl.TRIANGLES, 0, 6);
  6899. gl.flush();
  6900. gl.deleteTexture(texture);
  6901. gl.deleteTexture(maskTexture);
  6902. gl.deleteBuffer(buffer);
  6903. return canvas;
  6904. }
  6905. var figuresVertexShaderCode = '\
  6906. attribute vec2 a_position; \
  6907. attribute vec3 a_color; \
  6908. \
  6909. uniform vec2 u_resolution; \
  6910. uniform vec2 u_scale; \
  6911. uniform vec2 u_offset; \
  6912. \
  6913. varying vec4 v_color; \
  6914. \
  6915. void main() { \
  6916. vec2 position = (a_position + u_offset) * u_scale; \
  6917. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  6918. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  6919. \
  6920. v_color = vec4(a_color / 255.0, 1.0); \
  6921. } ';
  6922. var figuresFragmentShaderCode = '\
  6923. precision mediump float; \
  6924. \
  6925. varying vec4 v_color; \
  6926. \
  6927. void main() { \
  6928. gl_FragColor = v_color; \
  6929. } ';
  6930. var figuresCache = null;
  6931. function initFiguresGL() {
  6932. var canvas, gl;
  6933. generageGL();
  6934. canvas = currentCanvas;
  6935. currentCanvas = null;
  6936. gl = currentGL;
  6937. currentGL = null;
  6938. // setup a GLSL program
  6939. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  6940. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  6941. var program = createProgram(gl, [vertexShader, fragmentShader]);
  6942. gl.useProgram(program);
  6943. var cache = {};
  6944. cache.gl = gl;
  6945. cache.canvas = canvas;
  6946. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  6947. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  6948. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  6949. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  6950. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  6951. figuresCache = cache;
  6952. }
  6953. function drawFigures(width, height, backgroundColor, figures, context) {
  6954. if (!figuresCache) {
  6955. initFiguresGL();
  6956. }
  6957. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  6958. canvas.width = width;
  6959. canvas.height = height;
  6960. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  6961. gl.uniform2f(cache.resolutionLocation, width, height);
  6962. // count triangle points
  6963. var count = 0;
  6964. var i, ii, rows;
  6965. for (i = 0, ii = figures.length; i < ii; i++) {
  6966. switch (figures[i].type) {
  6967. case 'lattice':
  6968. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  6969. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  6970. break;
  6971. case 'triangles':
  6972. count += figures[i].coords.length;
  6973. break;
  6974. }
  6975. }
  6976. // transfer data
  6977. var coords = new Float32Array(count * 2);
  6978. var colors = new Uint8Array(count * 3);
  6979. var coordsMap = context.coords, colorsMap = context.colors;
  6980. var pIndex = 0, cIndex = 0;
  6981. for (i = 0, ii = figures.length; i < ii; i++) {
  6982. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  6983. switch (figure.type) {
  6984. case 'lattice':
  6985. var cols = figure.verticesPerRow;
  6986. rows = (ps.length / cols) | 0;
  6987. for (var row = 1; row < rows; row++) {
  6988. var offset = row * cols + 1;
  6989. for (var col = 1; col < cols; col++, offset++) {
  6990. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  6991. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  6992. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  6993. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  6994. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  6995. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  6996. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  6997. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  6998. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  6999. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  7000. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  7001. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  7002. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  7003. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  7004. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  7005. coords[pIndex + 6] = coords[pIndex + 2];
  7006. coords[pIndex + 7] = coords[pIndex + 3];
  7007. coords[pIndex + 8] = coords[pIndex + 4];
  7008. coords[pIndex + 9] = coords[pIndex + 5];
  7009. coords[pIndex + 10] = coordsMap[ps[offset]];
  7010. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  7011. colors[cIndex + 9] = colors[cIndex + 3];
  7012. colors[cIndex + 10] = colors[cIndex + 4];
  7013. colors[cIndex + 11] = colors[cIndex + 5];
  7014. colors[cIndex + 12] = colors[cIndex + 6];
  7015. colors[cIndex + 13] = colors[cIndex + 7];
  7016. colors[cIndex + 14] = colors[cIndex + 8];
  7017. colors[cIndex + 15] = colorsMap[cs[offset]];
  7018. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  7019. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  7020. pIndex += 12;
  7021. cIndex += 18;
  7022. }
  7023. }
  7024. break;
  7025. case 'triangles':
  7026. for (var j = 0, jj = ps.length; j < jj; j++) {
  7027. coords[pIndex] = coordsMap[ps[j]];
  7028. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  7029. colors[cIndex] = colorsMap[cs[i]];
  7030. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  7031. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  7032. pIndex += 2;
  7033. cIndex += 3;
  7034. }
  7035. break;
  7036. }
  7037. }
  7038. // draw
  7039. if (backgroundColor) {
  7040. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  7041. backgroundColor[2] / 255, 1.0);
  7042. } else {
  7043. gl.clearColor(0, 0, 0, 0);
  7044. }
  7045. gl.clear(gl.COLOR_BUFFER_BIT);
  7046. var coordsBuffer = gl.createBuffer();
  7047. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  7048. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  7049. gl.enableVertexAttribArray(cache.positionLocation);
  7050. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  7051. var colorsBuffer = gl.createBuffer();
  7052. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  7053. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  7054. gl.enableVertexAttribArray(cache.colorLocation);
  7055. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  7056. 0, 0);
  7057. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  7058. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  7059. gl.drawArrays(gl.TRIANGLES, 0, count);
  7060. gl.flush();
  7061. gl.deleteBuffer(coordsBuffer);
  7062. gl.deleteBuffer(colorsBuffer);
  7063. return canvas;
  7064. }
  7065. function cleanup() {
  7066. smaskCache = null;
  7067. figuresCache = null;
  7068. }
  7069. return {
  7070. get isEnabled() {
  7071. if (PDFJS.disableWebGL) {
  7072. return false;
  7073. }
  7074. var enabled = false;
  7075. try {
  7076. generageGL();
  7077. enabled = !!currentGL;
  7078. } catch (e) { }
  7079. return shadow(this, 'isEnabled', enabled);
  7080. },
  7081. composeSMask: composeSMask,
  7082. drawFigures: drawFigures,
  7083. clear: cleanup
  7084. };
  7085. })();
  7086. var ShadingIRs = {};
  7087. ShadingIRs.RadialAxial = {
  7088. fromIR: function RadialAxial_fromIR(raw) {
  7089. var type = raw[1];
  7090. var colorStops = raw[2];
  7091. var p0 = raw[3];
  7092. var p1 = raw[4];
  7093. var r0 = raw[5];
  7094. var r1 = raw[6];
  7095. return {
  7096. type: 'Pattern',
  7097. getPattern: function RadialAxial_getPattern(ctx) {
  7098. var grad;
  7099. if (type === 'axial') {
  7100. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  7101. } else if (type === 'radial') {
  7102. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  7103. }
  7104. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  7105. var c = colorStops[i];
  7106. grad.addColorStop(c[0], c[1]);
  7107. }
  7108. return grad;
  7109. }
  7110. };
  7111. }
  7112. };
  7113. var createMeshCanvas = (function createMeshCanvasClosure() {
  7114. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  7115. // Very basic Gouraud-shaded triangle rasterization algorithm.
  7116. var coords = context.coords, colors = context.colors;
  7117. var bytes = data.data, rowSize = data.width * 4;
  7118. var tmp;
  7119. if (coords[p1 + 1] > coords[p2 + 1]) {
  7120. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  7121. }
  7122. if (coords[p2 + 1] > coords[p3 + 1]) {
  7123. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  7124. }
  7125. if (coords[p1 + 1] > coords[p2 + 1]) {
  7126. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  7127. }
  7128. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  7129. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  7130. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  7131. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  7132. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  7133. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  7134. if (y1 >= y3) {
  7135. return;
  7136. }
  7137. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  7138. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  7139. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  7140. var minY = Math.round(y1), maxY = Math.round(y3);
  7141. var xa, car, cag, cab;
  7142. var xb, cbr, cbg, cbb;
  7143. var k;
  7144. for (var y = minY; y <= maxY; y++) {
  7145. if (y < y2) {
  7146. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  7147. xa = x1 - (x1 - x2) * k;
  7148. car = c1r - (c1r - c2r) * k;
  7149. cag = c1g - (c1g - c2g) * k;
  7150. cab = c1b - (c1b - c2b) * k;
  7151. } else {
  7152. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  7153. xa = x2 - (x2 - x3) * k;
  7154. car = c2r - (c2r - c3r) * k;
  7155. cag = c2g - (c2g - c3g) * k;
  7156. cab = c2b - (c2b - c3b) * k;
  7157. }
  7158. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  7159. xb = x1 - (x1 - x3) * k;
  7160. cbr = c1r - (c1r - c3r) * k;
  7161. cbg = c1g - (c1g - c3g) * k;
  7162. cbb = c1b - (c1b - c3b) * k;
  7163. var x1_ = Math.round(Math.min(xa, xb));
  7164. var x2_ = Math.round(Math.max(xa, xb));
  7165. var j = rowSize * y + x1_ * 4;
  7166. for (var x = x1_; x <= x2_; x++) {
  7167. k = (xa - x) / (xa - xb);
  7168. k = k < 0 ? 0 : k > 1 ? 1 : k;
  7169. bytes[j++] = (car - (car - cbr) * k) | 0;
  7170. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  7171. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  7172. bytes[j++] = 255;
  7173. }
  7174. }
  7175. }
  7176. function drawFigure(data, figure, context) {
  7177. var ps = figure.coords;
  7178. var cs = figure.colors;
  7179. var i, ii;
  7180. switch (figure.type) {
  7181. case 'lattice':
  7182. var verticesPerRow = figure.verticesPerRow;
  7183. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  7184. var cols = verticesPerRow - 1;
  7185. for (i = 0; i < rows; i++) {
  7186. var q = i * verticesPerRow;
  7187. for (var j = 0; j < cols; j++, q++) {
  7188. drawTriangle(data, context,
  7189. ps[q], ps[q + 1], ps[q + verticesPerRow],
  7190. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  7191. drawTriangle(data, context,
  7192. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  7193. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  7194. }
  7195. }
  7196. break;
  7197. case 'triangles':
  7198. for (i = 0, ii = ps.length; i < ii; i += 3) {
  7199. drawTriangle(data, context,
  7200. ps[i], ps[i + 1], ps[i + 2],
  7201. cs[i], cs[i + 1], cs[i + 2]);
  7202. }
  7203. break;
  7204. default:
  7205. error('illigal figure');
  7206. break;
  7207. }
  7208. }
  7209. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  7210. backgroundColor) {
  7211. // we will increase scale on some weird factor to let antialiasing take
  7212. // care of "rough" edges
  7213. var EXPECTED_SCALE = 1.1;
  7214. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  7215. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  7216. var offsetX = Math.floor(bounds[0]);
  7217. var offsetY = Math.floor(bounds[1]);
  7218. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  7219. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  7220. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  7221. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7222. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  7223. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  7224. var scaleX = boundsWidth / width;
  7225. var scaleY = boundsHeight / height;
  7226. var context = {
  7227. coords: coords,
  7228. colors: colors,
  7229. offsetX: -offsetX,
  7230. offsetY: -offsetY,
  7231. scaleX: 1 / scaleX,
  7232. scaleY: 1 / scaleY
  7233. };
  7234. var canvas, tmpCanvas, i, ii;
  7235. if (WebGLUtils.isEnabled) {
  7236. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  7237. figures, context);
  7238. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  7239. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  7240. tmpCanvas.context.drawImage(canvas, 0, 0);
  7241. canvas = tmpCanvas.canvas;
  7242. } else {
  7243. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  7244. var tmpCtx = tmpCanvas.context;
  7245. var data = tmpCtx.createImageData(width, height);
  7246. if (backgroundColor) {
  7247. var bytes = data.data;
  7248. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  7249. bytes[i] = backgroundColor[0];
  7250. bytes[i + 1] = backgroundColor[1];
  7251. bytes[i + 2] = backgroundColor[2];
  7252. bytes[i + 3] = 255;
  7253. }
  7254. }
  7255. for (i = 0; i < figures.length; i++) {
  7256. drawFigure(data, figures[i], context);
  7257. }
  7258. tmpCtx.putImageData(data, 0, 0);
  7259. canvas = tmpCanvas.canvas;
  7260. }
  7261. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  7262. scaleX: scaleX, scaleY: scaleY};
  7263. }
  7264. return createMeshCanvas;
  7265. })();
  7266. ShadingIRs.Mesh = {
  7267. fromIR: function Mesh_fromIR(raw) {
  7268. //var type = raw[1];
  7269. var coords = raw[2];
  7270. var colors = raw[3];
  7271. var figures = raw[4];
  7272. var bounds = raw[5];
  7273. var matrix = raw[6];
  7274. //var bbox = raw[7];
  7275. var background = raw[8];
  7276. return {
  7277. type: 'Pattern',
  7278. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  7279. var combinedScale;
  7280. // Obtain scale from matrix and current transformation matrix.
  7281. if (shadingFill) {
  7282. combinedScale = Util.singularValueDecompose2dScale(
  7283. ctx.mozCurrentTransform);
  7284. } else {
  7285. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  7286. var curMatrixScale = Util.singularValueDecompose2dScale(
  7287. owner.baseTransform);
  7288. combinedScale = [matrixScale[0] * curMatrixScale[0],
  7289. matrixScale[1] * curMatrixScale[1]];
  7290. }
  7291. // Rasterizing on the main thread since sending/queue large canvases
  7292. // might cause OOM.
  7293. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,
  7294. coords, colors, figures, shadingFill ? null : background);
  7295. if (!shadingFill) {
  7296. ctx.setTransform.apply(ctx, owner.baseTransform);
  7297. if (matrix) {
  7298. ctx.transform.apply(ctx, matrix);
  7299. }
  7300. }
  7301. ctx.translate(temporaryPatternCanvas.offsetX,
  7302. temporaryPatternCanvas.offsetY);
  7303. ctx.scale(temporaryPatternCanvas.scaleX,
  7304. temporaryPatternCanvas.scaleY);
  7305. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  7306. }
  7307. };
  7308. }
  7309. };
  7310. ShadingIRs.Dummy = {
  7311. fromIR: function Dummy_fromIR() {
  7312. return {
  7313. type: 'Pattern',
  7314. getPattern: function Dummy_fromIR_getPattern() {
  7315. return 'hotpink';
  7316. }
  7317. };
  7318. }
  7319. };
  7320. function getShadingPatternFromIR(raw) {
  7321. var shadingIR = ShadingIRs[raw[0]];
  7322. if (!shadingIR) {
  7323. error('Unknown IR type: ' + raw[0]);
  7324. }
  7325. return shadingIR.fromIR(raw);
  7326. }
  7327. var TilingPattern = (function TilingPatternClosure() {
  7328. var PaintType = {
  7329. COLORED: 1,
  7330. UNCOLORED: 2
  7331. };
  7332. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  7333. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  7334. this.name = IR[1][0].name;
  7335. this.operatorList = IR[2];
  7336. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  7337. this.bbox = IR[4];
  7338. this.xstep = IR[5];
  7339. this.ystep = IR[6];
  7340. this.paintType = IR[7];
  7341. this.tilingType = IR[8];
  7342. this.color = color;
  7343. this.objs = objs;
  7344. this.commonObjs = commonObjs;
  7345. this.baseTransform = baseTransform;
  7346. this.type = 'Pattern';
  7347. this.ctx = ctx;
  7348. }
  7349. TilingPattern.prototype = {
  7350. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  7351. var operatorList = this.operatorList;
  7352. var bbox = this.bbox;
  7353. var xstep = this.xstep;
  7354. var ystep = this.ystep;
  7355. var paintType = this.paintType;
  7356. var tilingType = this.tilingType;
  7357. var color = this.color;
  7358. var objs = this.objs;
  7359. var commonObjs = this.commonObjs;
  7360. info('TilingType: ' + tilingType);
  7361. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  7362. var topLeft = [x0, y0];
  7363. // we want the canvas to be as large as the step size
  7364. var botRight = [x0 + xstep, y0 + ystep];
  7365. var width = botRight[0] - topLeft[0];
  7366. var height = botRight[1] - topLeft[1];
  7367. // Obtain scale from matrix and current transformation matrix.
  7368. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  7369. var curMatrixScale = Util.singularValueDecompose2dScale(
  7370. this.baseTransform);
  7371. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  7372. matrixScale[1] * curMatrixScale[1]];
  7373. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  7374. // Use width and height values that are as close as possible to the end
  7375. // result when the pattern is used. Too low value makes the pattern look
  7376. // blurry. Too large value makes it look too crispy.
  7377. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  7378. MAX_PATTERN_SIZE);
  7379. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  7380. MAX_PATTERN_SIZE);
  7381. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  7382. var tmpCtx = tmpCanvas.context;
  7383. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  7384. graphics.groupLevel = owner.groupLevel;
  7385. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  7386. this.setScale(width, height, xstep, ystep);
  7387. this.transformToScale(graphics);
  7388. // transform coordinates to pattern space
  7389. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  7390. graphics.transform.apply(graphics, tmpTranslate);
  7391. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  7392. graphics.executeOperatorList(operatorList);
  7393. return tmpCanvas.canvas;
  7394. },
  7395. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  7396. this.scale = [width / xstep, height / ystep];
  7397. },
  7398. transformToScale: function TilingPattern_transformToScale(graphics) {
  7399. var scale = this.scale;
  7400. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  7401. graphics.transform.apply(graphics, tmpScale);
  7402. },
  7403. scaleToContext: function TilingPattern_scaleToContext() {
  7404. var scale = this.scale;
  7405. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  7406. },
  7407. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  7408. if (bbox && isArray(bbox) && 4 == bbox.length) {
  7409. var bboxWidth = x1 - x0;
  7410. var bboxHeight = y1 - y0;
  7411. graphics.rectangle(x0, y0, bboxWidth, bboxHeight);
  7412. graphics.clip();
  7413. graphics.endPath();
  7414. }
  7415. },
  7416. setFillAndStrokeStyleToContext:
  7417. function setFillAndStrokeStyleToContext(context, paintType, color) {
  7418. switch (paintType) {
  7419. case PaintType.COLORED:
  7420. var ctx = this.ctx;
  7421. context.fillStyle = ctx.fillStyle;
  7422. context.strokeStyle = ctx.strokeStyle;
  7423. break;
  7424. case PaintType.UNCOLORED:
  7425. var rgbColor = ColorSpace.singletons.rgb.getRgb(color, 0);
  7426. var cssColor = Util.makeCssRgb(rgbColor);
  7427. context.fillStyle = cssColor;
  7428. context.strokeStyle = cssColor;
  7429. break;
  7430. default:
  7431. error('Unsupported paint type: ' + paintType);
  7432. }
  7433. },
  7434. getPattern: function TilingPattern_getPattern(ctx, owner) {
  7435. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  7436. ctx = this.ctx;
  7437. ctx.setTransform.apply(ctx, this.baseTransform);
  7438. ctx.transform.apply(ctx, this.matrix);
  7439. this.scaleToContext();
  7440. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  7441. }
  7442. };
  7443. return TilingPattern;
  7444. })();
  7445. PDFJS.disableFontFace = false;
  7446. var FontLoader = {
  7447. insertRule: function fontLoaderInsertRule(rule) {
  7448. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  7449. if (!styleElement) {
  7450. styleElement = document.createElement('style');
  7451. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  7452. document.documentElement.getElementsByTagName('head')[0].appendChild(
  7453. styleElement);
  7454. }
  7455. var styleSheet = styleElement.sheet;
  7456. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  7457. },
  7458. clear: function fontLoaderClear() {
  7459. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  7460. if (styleElement) {
  7461. styleElement.parentNode.removeChild(styleElement);
  7462. }
  7463. },
  7464. get loadTestFont() {
  7465. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  7466. // height.
  7467. return shadow(this, 'loadTestFont', atob(
  7468. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  7469. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  7470. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  7471. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  7472. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  7473. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  7474. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  7475. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  7476. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  7477. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  7478. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  7479. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  7480. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  7481. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7482. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7483. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  7484. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  7485. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  7486. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  7487. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  7488. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  7489. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  7490. ));
  7491. },
  7492. loadTestFontId: 0,
  7493. loadingContext: {
  7494. requests: [],
  7495. nextRequestId: 0
  7496. },
  7497. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  7498. if (isWorker) {
  7499. return false;
  7500. }
  7501. // User agent string sniffing is bad, but there is no reliable way to tell
  7502. // if font is fully loaded and ready to be used with canvas.
  7503. var userAgent = window.navigator.userAgent;
  7504. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  7505. if (m && m[1] >= 14) {
  7506. return true;
  7507. }
  7508. // TODO other browsers
  7509. return false;
  7510. })(),
  7511. bind: function fontLoaderBind(fonts, callback) {
  7512. assert(!isWorker, 'bind() shall be called from main thread');
  7513. var rules = [], fontsToLoad = [];
  7514. for (var i = 0, ii = fonts.length; i < ii; i++) {
  7515. var font = fonts[i];
  7516. // Add the font to the DOM only once or skip if the font
  7517. // is already loaded.
  7518. if (font.attached || font.loading === false) {
  7519. continue;
  7520. }
  7521. font.attached = true;
  7522. var rule = font.bindDOM();
  7523. if (rule) {
  7524. rules.push(rule);
  7525. fontsToLoad.push(font);
  7526. }
  7527. }
  7528. var request = FontLoader.queueLoadingCallback(callback);
  7529. if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  7530. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  7531. } else {
  7532. request.complete();
  7533. }
  7534. },
  7535. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  7536. function LoadLoader_completeRequest() {
  7537. assert(!request.end, 'completeRequest() cannot be called twice');
  7538. request.end = Date.now();
  7539. // sending all completed requests in order how they were queued
  7540. while (context.requests.length > 0 && context.requests[0].end) {
  7541. var otherRequest = context.requests.shift();
  7542. setTimeout(otherRequest.callback, 0);
  7543. }
  7544. }
  7545. var context = FontLoader.loadingContext;
  7546. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  7547. var request = {
  7548. id: requestId,
  7549. complete: LoadLoader_completeRequest,
  7550. callback: callback,
  7551. started: Date.now()
  7552. };
  7553. context.requests.push(request);
  7554. return request;
  7555. },
  7556. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  7557. fonts,
  7558. request) {
  7559. /** Hack begin */
  7560. // There's currently no event when a font has finished downloading so the
  7561. // following code is a dirty hack to 'guess' when a font is
  7562. // ready. It's assumed fonts are loaded in order, so add a known test
  7563. // font after the desired fonts and then test for the loading of that
  7564. // test font.
  7565. function int32(data, offset) {
  7566. return (data.charCodeAt(offset) << 24) |
  7567. (data.charCodeAt(offset + 1) << 16) |
  7568. (data.charCodeAt(offset + 2) << 8) |
  7569. (data.charCodeAt(offset + 3) & 0xff);
  7570. }
  7571. function spliceString(s, offset, remove, insert) {
  7572. var chunk1 = s.substr(0, offset);
  7573. var chunk2 = s.substr(offset + remove);
  7574. return chunk1 + insert + chunk2;
  7575. }
  7576. var i, ii;
  7577. var canvas = document.createElement('canvas');
  7578. canvas.width = 1;
  7579. canvas.height = 1;
  7580. var ctx = canvas.getContext('2d');
  7581. var called = 0;
  7582. function isFontReady(name, callback) {
  7583. called++;
  7584. // With setTimeout clamping this gives the font ~100ms to load.
  7585. if(called > 30) {
  7586. warn('Load test font never loaded.');
  7587. callback();
  7588. return;
  7589. }
  7590. ctx.font = '30px ' + name;
  7591. ctx.fillText('.', 0, 20);
  7592. var imageData = ctx.getImageData(0, 0, 1, 1);
  7593. if (imageData.data[3] > 0) {
  7594. callback();
  7595. return;
  7596. }
  7597. setTimeout(isFontReady.bind(null, name, callback));
  7598. }
  7599. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  7600. // Chromium seems to cache fonts based on a hash of the actual font data,
  7601. // so the font must be modified for each load test else it will appear to
  7602. // be loaded already.
  7603. // TODO: This could maybe be made faster by avoiding the btoa of the full
  7604. // font by splitting it in chunks before hand and padding the font id.
  7605. var data = this.loadTestFont;
  7606. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  7607. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  7608. loadTestFontId);
  7609. // CFF checksum is important for IE, adjusting it
  7610. var CFF_CHECKSUM_OFFSET = 16;
  7611. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  7612. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  7613. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  7614. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  7615. }
  7616. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  7617. checksum = (checksum - XXXX_VALUE +
  7618. int32(loadTestFontId + 'XXX', i)) | 0;
  7619. }
  7620. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  7621. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  7622. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  7623. url + '}';
  7624. FontLoader.insertRule(rule);
  7625. var names = [];
  7626. for (i = 0, ii = fonts.length; i < ii; i++) {
  7627. names.push(fonts[i].loadedName);
  7628. }
  7629. names.push(loadTestFontId);
  7630. var div = document.createElement('div');
  7631. div.setAttribute('style',
  7632. 'visibility: hidden;' +
  7633. 'width: 10px; height: 10px;' +
  7634. 'position: absolute; top: 0px; left: 0px;');
  7635. for (i = 0, ii = names.length; i < ii; ++i) {
  7636. var span = document.createElement('span');
  7637. span.textContent = 'Hi';
  7638. span.style.fontFamily = names[i];
  7639. div.appendChild(span);
  7640. }
  7641. document.body.appendChild(div);
  7642. isFontReady(loadTestFontId, function() {
  7643. document.body.removeChild(div);
  7644. request.complete();
  7645. });
  7646. /** Hack end */
  7647. }
  7648. };
  7649. var FontFace = (function FontFaceClosure() {
  7650. function FontFace(name, file, properties) {
  7651. this.compiledGlyphs = {};
  7652. if (arguments.length === 1) {
  7653. // importing translated data
  7654. var data = arguments[0];
  7655. for (var i in data) {
  7656. this[i] = data[i];
  7657. }
  7658. return;
  7659. }
  7660. }
  7661. FontFace.prototype = {
  7662. bindDOM: function FontFace_bindDOM() {
  7663. if (!this.data) {
  7664. return null;
  7665. }
  7666. if (PDFJS.disableFontFace) {
  7667. this.disableFontFace = true;
  7668. return null;
  7669. }
  7670. var data = bytesToString(new Uint8Array(this.data));
  7671. var fontName = this.loadedName;
  7672. // Add the font-face rule to the document
  7673. var url = ('url(data:' + this.mimetype + ';base64,' +
  7674. window.btoa(data) + ');');
  7675. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  7676. FontLoader.insertRule(rule);
  7677. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  7678. globalScope['FontInspector'].enabled) {
  7679. globalScope['FontInspector'].fontAdded(this, url);
  7680. }
  7681. return rule;
  7682. },
  7683. getPathGenerator: function (objs, character) {
  7684. if (!(character in this.compiledGlyphs)) {
  7685. var js = objs.get(this.loadedName + '_path_' + character);
  7686. /*jshint -W054 */
  7687. this.compiledGlyphs[character] = new Function('c', 'size', js);
  7688. }
  7689. return this.compiledGlyphs[character];
  7690. }
  7691. };
  7692. return FontFace;
  7693. })();
  7694. }).call((typeof window === 'undefined') ? this : window);
  7695. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  7696. // workerSrc is not set -- using last script url to define default location
  7697. PDFJS.workerSrc = (function () {
  7698. 'use strict';
  7699. var scriptTagContainer = document.body ||
  7700. document.getElementsByTagName('head')[0];
  7701. var pdfjsSrc = scriptTagContainer.lastChild.src;
  7702. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  7703. })();
  7704. }