pdf.js 206 KB

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