pdf.js 263 KB

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