pdf.js 275 KB

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