pdf.js 262 KB

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