pdf.js 223 KB

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