pdf.js 247 KB

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